From 0e85d3514c84fd3e37c9beebc794f338da47c21e Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 23 Jul 2021 21:29:34 +0000 Subject: [PATCH 1/2] fix: enable self signed jwt for grpc chore: use gapic-generator-python 0.50.5 PiperOrigin-RevId: 386504689 Source-Link: https://github.com/googleapis/googleapis/commit/762094a99ac6e03a17516b13dfbef37927267a70 Source-Link: https://github.com/googleapis/googleapis-gen/commit/6bfc480e1a161d5de121c2bcc3745885d33b265a --- owl-bot-staging/v1/.coveragerc | 17 + owl-bot-staging/v1/MANIFEST.in | 2 + owl-bot-staging/v1/README.rst | 49 + .../docs/appengine_admin_v1/applications.rst | 6 + .../authorized_certificates.rst | 10 + .../appengine_admin_v1/authorized_domains.rst | 10 + .../appengine_admin_v1/domain_mappings.rst | 10 + .../v1/docs/appengine_admin_v1/firewall.rst | 10 + .../v1/docs/appengine_admin_v1/instances.rst | 10 + .../v1/docs/appengine_admin_v1/services.rst | 13 + .../v1/docs/appengine_admin_v1/types.rst | 7 + .../v1/docs/appengine_admin_v1/versions.rst | 10 + owl-bot-staging/v1/docs/conf.py | 376 +++ owl-bot-staging/v1/docs/index.rst | 7 + .../google/cloud/appengine_admin/__init__.py | 253 ++ .../v1/google/cloud/appengine_admin/py.typed | 2 + .../cloud/appengine_admin_v1/__init__.py | 254 ++ .../appengine_admin_v1/gapic_metadata.json | 461 ++++ .../google/cloud/appengine_admin_v1/py.typed | 2 + .../appengine_admin_v1/services/__init__.py | 15 + .../services/applications/__init__.py | 22 + .../services/applications/async_client.py | 434 ++++ .../services/applications/client.py | 620 +++++ .../applications/transports/__init__.py | 33 + .../services/applications/transports/base.py | 220 ++ .../services/applications/transports/grpc.py | 376 +++ .../applications/transports/grpc_asyncio.py | 380 +++ .../authorized_certificates/__init__.py | 22 + .../authorized_certificates/async_client.py | 459 ++++ .../authorized_certificates/client.py | 646 ++++++ .../authorized_certificates/pagers.py | 141 ++ .../transports/__init__.py | 33 + .../transports/base.py | 228 ++ .../transports/grpc.py | 366 +++ .../transports/grpc_asyncio.py | 370 +++ .../services/authorized_domains/__init__.py | 22 + .../authorized_domains/async_client.py | 233 ++ .../services/authorized_domains/client.py | 416 ++++ .../services/authorized_domains/pagers.py | 141 ++ .../authorized_domains/transports/__init__.py | 33 + .../authorized_domains/transports/base.py | 170 ++ .../authorized_domains/transports/grpc.py | 255 ++ .../transports/grpc_asyncio.py | 259 +++ .../services/domain_mappings/__init__.py | 22 + .../services/domain_mappings/async_client.py | 504 ++++ .../services/domain_mappings/client.py | 691 ++++++ .../services/domain_mappings/pagers.py | 141 ++ .../domain_mappings/transports/__init__.py | 33 + .../domain_mappings/transports/base.py | 234 ++ .../domain_mappings/transports/grpc.py | 385 ++++ .../transports/grpc_asyncio.py | 389 ++++ .../services/firewall/__init__.py | 22 + .../services/firewall/async_client.py | 515 +++++ .../services/firewall/client.py | 703 ++++++ .../services/firewall/pagers.py | 141 ++ .../services/firewall/transports/__init__.py | 33 + .../services/firewall/transports/base.py | 242 ++ .../services/firewall/transports/grpc.py | 400 ++++ .../firewall/transports/grpc_asyncio.py | 404 ++++ .../services/instances/__init__.py | 22 + .../services/instances/async_client.py | 459 ++++ .../services/instances/client.py | 654 ++++++ .../services/instances/pagers.py | 141 ++ .../services/instances/transports/__init__.py | 33 + .../services/instances/transports/base.py | 220 ++ .../services/instances/transports/grpc.py | 377 +++ .../instances/transports/grpc_asyncio.py | 381 +++ .../services/services/__init__.py | 22 + .../services/services/async_client.py | 448 ++++ .../services/services/client.py | 634 +++++ .../services/services/pagers.py | 141 ++ .../services/services/transports/__init__.py | 33 + .../services/services/transports/base.py | 220 ++ .../services/services/transports/grpc.py | 352 +++ .../services/transports/grpc_asyncio.py | 356 +++ .../services/versions/__init__.py | 22 + .../services/versions/async_client.py | 535 +++++ .../services/versions/client.py | 722 ++++++ .../services/versions/pagers.py | 141 ++ .../services/versions/transports/__init__.py | 33 + .../services/versions/transports/base.py | 234 ++ .../services/versions/transports/grpc.py | 413 ++++ .../versions/transports/grpc_asyncio.py | 417 ++++ .../appengine_admin_v1/types/__init__.py | 250 ++ .../appengine_admin_v1/types/app_yaml.py | 539 +++++ .../appengine_admin_v1/types/appengine.py | 1103 +++++++++ .../appengine_admin_v1/types/application.py | 284 +++ .../appengine_admin_v1/types/audit_data.py | 84 + .../appengine_admin_v1/types/certificate.py | 229 ++ .../cloud/appengine_admin_v1/types/deploy.py | 191 ++ .../types/deployed_files.py | 25 + .../cloud/appengine_admin_v1/types/domain.py | 53 + .../types/domain_mapping.py | 161 ++ .../appengine_admin_v1/types/firewall.py | 86 + .../appengine_admin_v1/types/instance.py | 183 ++ .../appengine_admin_v1/types/location.py | 60 + .../types/network_settings.py | 49 + .../appengine_admin_v1/types/operation.py | 120 + .../cloud/appengine_admin_v1/types/service.py | 121 + .../cloud/appengine_admin_v1/types/version.py | 973 ++++++++ owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 132 ++ .../fixup_appengine_admin_v1_keywords.py | 209 ++ owl-bot-staging/v1/setup.py | 54 + owl-bot-staging/v1/tests/__init__.py | 16 + owl-bot-staging/v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/appengine_admin_v1/__init__.py | 16 + .../appengine_admin_v1/test_applications.py | 1539 +++++++++++++ .../test_authorized_certificates.py | 1927 ++++++++++++++++ .../test_authorized_domains.py | 1264 ++++++++++ .../test_domain_mappings.py | 1908 +++++++++++++++ .../gapic/appengine_admin_v1/test_firewall.py | 2050 +++++++++++++++++ .../appengine_admin_v1/test_instances.py | 1839 +++++++++++++++ .../gapic/appengine_admin_v1/test_services.py | 1761 ++++++++++++++ .../gapic/appengine_admin_v1/test_versions.py | 1977 ++++++++++++++++ 116 files changed, 38510 insertions(+) create mode 100644 owl-bot-staging/v1/.coveragerc create mode 100644 owl-bot-staging/v1/MANIFEST.in create mode 100644 owl-bot-staging/v1/README.rst create mode 100644 owl-bot-staging/v1/docs/appengine_admin_v1/applications.rst create mode 100644 owl-bot-staging/v1/docs/appengine_admin_v1/authorized_certificates.rst create mode 100644 owl-bot-staging/v1/docs/appengine_admin_v1/authorized_domains.rst create mode 100644 owl-bot-staging/v1/docs/appengine_admin_v1/domain_mappings.rst create mode 100644 owl-bot-staging/v1/docs/appengine_admin_v1/firewall.rst create mode 100644 owl-bot-staging/v1/docs/appengine_admin_v1/instances.rst create mode 100644 owl-bot-staging/v1/docs/appengine_admin_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/appengine_admin_v1/types.rst create mode 100644 owl-bot-staging/v1/docs/appengine_admin_v1/versions.rst create mode 100644 owl-bot-staging/v1/docs/conf.py create mode 100644 owl-bot-staging/v1/docs/index.rst create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/client.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/client.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/client.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/client.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/client.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/client.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/client.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/client.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/app_yaml.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/appengine.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/application.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/audit_data.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/certificate.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/deploy.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/deployed_files.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/domain.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/domain_mapping.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/firewall.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/instance.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/location.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/network_settings.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/operation.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/service.py create mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/version.py create mode 100644 owl-bot-staging/v1/mypy.ini create mode 100644 owl-bot-staging/v1/noxfile.py create mode 100644 owl-bot-staging/v1/scripts/fixup_appengine_admin_v1_keywords.py create mode 100644 owl-bot-staging/v1/setup.py create mode 100644 owl-bot-staging/v1/tests/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_applications.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_firewall.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_instances.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_services.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_versions.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 0000000..44c6382 --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/appengine_admin/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in new file mode 100644 index 0000000..6103ec7 --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/appengine_admin *.py +recursive-include google/cloud/appengine_admin_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 0000000..f6231b8 --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Appengine Admin API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Appengine Admin API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/appengine_admin_v1/applications.rst b/owl-bot-staging/v1/docs/appengine_admin_v1/applications.rst new file mode 100644 index 0000000..8afb1c7 --- /dev/null +++ b/owl-bot-staging/v1/docs/appengine_admin_v1/applications.rst @@ -0,0 +1,6 @@ +Applications +------------------------------ + +.. automodule:: google.cloud.appengine_admin_v1.services.applications + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/appengine_admin_v1/authorized_certificates.rst b/owl-bot-staging/v1/docs/appengine_admin_v1/authorized_certificates.rst new file mode 100644 index 0000000..03ac310 --- /dev/null +++ b/owl-bot-staging/v1/docs/appengine_admin_v1/authorized_certificates.rst @@ -0,0 +1,10 @@ +AuthorizedCertificates +---------------------------------------- + +.. automodule:: google.cloud.appengine_admin_v1.services.authorized_certificates + :members: + :inherited-members: + +.. automodule:: google.cloud.appengine_admin_v1.services.authorized_certificates.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/appengine_admin_v1/authorized_domains.rst b/owl-bot-staging/v1/docs/appengine_admin_v1/authorized_domains.rst new file mode 100644 index 0000000..d02102a --- /dev/null +++ b/owl-bot-staging/v1/docs/appengine_admin_v1/authorized_domains.rst @@ -0,0 +1,10 @@ +AuthorizedDomains +----------------------------------- + +.. automodule:: google.cloud.appengine_admin_v1.services.authorized_domains + :members: + :inherited-members: + +.. automodule:: google.cloud.appengine_admin_v1.services.authorized_domains.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/appengine_admin_v1/domain_mappings.rst b/owl-bot-staging/v1/docs/appengine_admin_v1/domain_mappings.rst new file mode 100644 index 0000000..89af15b --- /dev/null +++ b/owl-bot-staging/v1/docs/appengine_admin_v1/domain_mappings.rst @@ -0,0 +1,10 @@ +DomainMappings +-------------------------------- + +.. automodule:: google.cloud.appengine_admin_v1.services.domain_mappings + :members: + :inherited-members: + +.. automodule:: google.cloud.appengine_admin_v1.services.domain_mappings.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/appengine_admin_v1/firewall.rst b/owl-bot-staging/v1/docs/appengine_admin_v1/firewall.rst new file mode 100644 index 0000000..ce343d1 --- /dev/null +++ b/owl-bot-staging/v1/docs/appengine_admin_v1/firewall.rst @@ -0,0 +1,10 @@ +Firewall +-------------------------- + +.. automodule:: google.cloud.appengine_admin_v1.services.firewall + :members: + :inherited-members: + +.. automodule:: google.cloud.appengine_admin_v1.services.firewall.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/appengine_admin_v1/instances.rst b/owl-bot-staging/v1/docs/appengine_admin_v1/instances.rst new file mode 100644 index 0000000..57f5079 --- /dev/null +++ b/owl-bot-staging/v1/docs/appengine_admin_v1/instances.rst @@ -0,0 +1,10 @@ +Instances +--------------------------- + +.. automodule:: google.cloud.appengine_admin_v1.services.instances + :members: + :inherited-members: + +.. automodule:: google.cloud.appengine_admin_v1.services.instances.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/appengine_admin_v1/services.rst b/owl-bot-staging/v1/docs/appengine_admin_v1/services.rst new file mode 100644 index 0000000..ebe1b56 --- /dev/null +++ b/owl-bot-staging/v1/docs/appengine_admin_v1/services.rst @@ -0,0 +1,13 @@ +Services for Google Cloud Appengine Admin v1 API +================================================ +.. toctree:: + :maxdepth: 2 + + applications + authorized_certificates + authorized_domains + domain_mappings + firewall + instances + services + versions diff --git a/owl-bot-staging/v1/docs/appengine_admin_v1/types.rst b/owl-bot-staging/v1/docs/appengine_admin_v1/types.rst new file mode 100644 index 0000000..cc6979e --- /dev/null +++ b/owl-bot-staging/v1/docs/appengine_admin_v1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Appengine Admin v1 API +============================================= + +.. automodule:: google.cloud.appengine_admin_v1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1/docs/appengine_admin_v1/versions.rst b/owl-bot-staging/v1/docs/appengine_admin_v1/versions.rst new file mode 100644 index 0000000..58a0f63 --- /dev/null +++ b/owl-bot-staging/v1/docs/appengine_admin_v1/versions.rst @@ -0,0 +1,10 @@ +Versions +-------------------------- + +.. automodule:: google.cloud.appengine_admin_v1.services.versions + :members: + :inherited-members: + +.. automodule:: google.cloud.appengine_admin_v1.services.versions.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py new file mode 100644 index 0000000..2aafff4 --- /dev/null +++ b/owl-bot-staging/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-appengine-admin documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.6.3" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-appengine-admin" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-appengine-admin-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "google-cloud-appengine-admin.tex", + u"google-cloud-appengine-admin Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "google-cloud-appengine-admin", + u"Google Cloud Appengine Admin Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "google-cloud-appengine-admin", + u"google-cloud-appengine-admin Documentation", + author, + "google-cloud-appengine-admin", + "GAPIC library for Google Cloud Appengine Admin API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 0000000..75f0698 --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + appengine_admin_v1/services + appengine_admin_v1/types diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin/__init__.py new file mode 100644 index 0000000..e0b30cc --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin/__init__.py @@ -0,0 +1,253 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.cloud.appengine_admin_v1.services.applications.client import ApplicationsClient +from google.cloud.appengine_admin_v1.services.applications.async_client import ApplicationsAsyncClient +from google.cloud.appengine_admin_v1.services.authorized_certificates.client import AuthorizedCertificatesClient +from google.cloud.appengine_admin_v1.services.authorized_certificates.async_client import AuthorizedCertificatesAsyncClient +from google.cloud.appengine_admin_v1.services.authorized_domains.client import AuthorizedDomainsClient +from google.cloud.appengine_admin_v1.services.authorized_domains.async_client import AuthorizedDomainsAsyncClient +from google.cloud.appengine_admin_v1.services.domain_mappings.client import DomainMappingsClient +from google.cloud.appengine_admin_v1.services.domain_mappings.async_client import DomainMappingsAsyncClient +from google.cloud.appengine_admin_v1.services.firewall.client import FirewallClient +from google.cloud.appengine_admin_v1.services.firewall.async_client import FirewallAsyncClient +from google.cloud.appengine_admin_v1.services.instances.client import InstancesClient +from google.cloud.appengine_admin_v1.services.instances.async_client import InstancesAsyncClient +from google.cloud.appengine_admin_v1.services.services.client import ServicesClient +from google.cloud.appengine_admin_v1.services.services.async_client import ServicesAsyncClient +from google.cloud.appengine_admin_v1.services.versions.client import VersionsClient +from google.cloud.appengine_admin_v1.services.versions.async_client import VersionsAsyncClient + +from google.cloud.appengine_admin_v1.types.app_yaml import ApiConfigHandler +from google.cloud.appengine_admin_v1.types.app_yaml import ApiEndpointHandler +from google.cloud.appengine_admin_v1.types.app_yaml import ErrorHandler +from google.cloud.appengine_admin_v1.types.app_yaml import HealthCheck +from google.cloud.appengine_admin_v1.types.app_yaml import Library +from google.cloud.appengine_admin_v1.types.app_yaml import LivenessCheck +from google.cloud.appengine_admin_v1.types.app_yaml import ReadinessCheck +from google.cloud.appengine_admin_v1.types.app_yaml import ScriptHandler +from google.cloud.appengine_admin_v1.types.app_yaml import StaticFilesHandler +from google.cloud.appengine_admin_v1.types.app_yaml import UrlMap +from google.cloud.appengine_admin_v1.types.app_yaml import AuthFailAction +from google.cloud.appengine_admin_v1.types.app_yaml import LoginRequirement +from google.cloud.appengine_admin_v1.types.app_yaml import SecurityLevel +from google.cloud.appengine_admin_v1.types.appengine import BatchUpdateIngressRulesRequest +from google.cloud.appengine_admin_v1.types.appengine import BatchUpdateIngressRulesResponse +from google.cloud.appengine_admin_v1.types.appengine import CreateApplicationRequest +from google.cloud.appengine_admin_v1.types.appengine import CreateAuthorizedCertificateRequest +from google.cloud.appengine_admin_v1.types.appengine import CreateDomainMappingRequest +from google.cloud.appengine_admin_v1.types.appengine import CreateIngressRuleRequest +from google.cloud.appengine_admin_v1.types.appengine import CreateVersionRequest +from google.cloud.appengine_admin_v1.types.appengine import DebugInstanceRequest +from google.cloud.appengine_admin_v1.types.appengine import DeleteAuthorizedCertificateRequest +from google.cloud.appengine_admin_v1.types.appengine import DeleteDomainMappingRequest +from google.cloud.appengine_admin_v1.types.appengine import DeleteIngressRuleRequest +from google.cloud.appengine_admin_v1.types.appengine import DeleteInstanceRequest +from google.cloud.appengine_admin_v1.types.appengine import DeleteServiceRequest +from google.cloud.appengine_admin_v1.types.appengine import DeleteVersionRequest +from google.cloud.appengine_admin_v1.types.appengine import GetApplicationRequest +from google.cloud.appengine_admin_v1.types.appengine import GetAuthorizedCertificateRequest +from google.cloud.appengine_admin_v1.types.appengine import GetDomainMappingRequest +from google.cloud.appengine_admin_v1.types.appengine import GetIngressRuleRequest +from google.cloud.appengine_admin_v1.types.appengine import GetInstanceRequest +from google.cloud.appengine_admin_v1.types.appengine import GetServiceRequest +from google.cloud.appengine_admin_v1.types.appengine import GetVersionRequest +from google.cloud.appengine_admin_v1.types.appengine import ListAuthorizedCertificatesRequest +from google.cloud.appengine_admin_v1.types.appengine import ListAuthorizedCertificatesResponse +from google.cloud.appengine_admin_v1.types.appengine import ListAuthorizedDomainsRequest +from google.cloud.appengine_admin_v1.types.appengine import ListAuthorizedDomainsResponse +from google.cloud.appengine_admin_v1.types.appengine import ListDomainMappingsRequest +from google.cloud.appengine_admin_v1.types.appengine import ListDomainMappingsResponse +from google.cloud.appengine_admin_v1.types.appengine import ListIngressRulesRequest +from google.cloud.appengine_admin_v1.types.appengine import ListIngressRulesResponse +from google.cloud.appengine_admin_v1.types.appengine import ListInstancesRequest +from google.cloud.appengine_admin_v1.types.appengine import ListInstancesResponse +from google.cloud.appengine_admin_v1.types.appengine import ListServicesRequest +from google.cloud.appengine_admin_v1.types.appengine import ListServicesResponse +from google.cloud.appengine_admin_v1.types.appengine import ListVersionsRequest +from google.cloud.appengine_admin_v1.types.appengine import ListVersionsResponse +from google.cloud.appengine_admin_v1.types.appengine import RepairApplicationRequest +from google.cloud.appengine_admin_v1.types.appengine import UpdateApplicationRequest +from google.cloud.appengine_admin_v1.types.appengine import UpdateAuthorizedCertificateRequest +from google.cloud.appengine_admin_v1.types.appengine import UpdateDomainMappingRequest +from google.cloud.appengine_admin_v1.types.appengine import UpdateIngressRuleRequest +from google.cloud.appengine_admin_v1.types.appengine import UpdateServiceRequest +from google.cloud.appengine_admin_v1.types.appengine import UpdateVersionRequest +from google.cloud.appengine_admin_v1.types.appengine import AuthorizedCertificateView +from google.cloud.appengine_admin_v1.types.appengine import DomainOverrideStrategy +from google.cloud.appengine_admin_v1.types.appengine import VersionView +from google.cloud.appengine_admin_v1.types.application import Application +from google.cloud.appengine_admin_v1.types.application import UrlDispatchRule +from google.cloud.appengine_admin_v1.types.audit_data import AuditData +from google.cloud.appengine_admin_v1.types.audit_data import CreateVersionMethod +from google.cloud.appengine_admin_v1.types.audit_data import UpdateServiceMethod +from google.cloud.appengine_admin_v1.types.certificate import AuthorizedCertificate +from google.cloud.appengine_admin_v1.types.certificate import CertificateRawData +from google.cloud.appengine_admin_v1.types.certificate import ManagedCertificate +from google.cloud.appengine_admin_v1.types.certificate import ManagementStatus +from google.cloud.appengine_admin_v1.types.deploy import CloudBuildOptions +from google.cloud.appengine_admin_v1.types.deploy import ContainerInfo +from google.cloud.appengine_admin_v1.types.deploy import Deployment +from google.cloud.appengine_admin_v1.types.deploy import FileInfo +from google.cloud.appengine_admin_v1.types.deploy import ZipInfo +from google.cloud.appengine_admin_v1.types.domain import AuthorizedDomain +from google.cloud.appengine_admin_v1.types.domain_mapping import DomainMapping +from google.cloud.appengine_admin_v1.types.domain_mapping import ResourceRecord +from google.cloud.appengine_admin_v1.types.domain_mapping import SslSettings +from google.cloud.appengine_admin_v1.types.firewall import FirewallRule +from google.cloud.appengine_admin_v1.types.instance import Instance +from google.cloud.appengine_admin_v1.types.location import LocationMetadata +from google.cloud.appengine_admin_v1.types.network_settings import NetworkSettings +from google.cloud.appengine_admin_v1.types.operation import CreateVersionMetadataV1 +from google.cloud.appengine_admin_v1.types.operation import OperationMetadataV1 +from google.cloud.appengine_admin_v1.types.service import Service +from google.cloud.appengine_admin_v1.types.service import TrafficSplit +from google.cloud.appengine_admin_v1.types.version import AutomaticScaling +from google.cloud.appengine_admin_v1.types.version import BasicScaling +from google.cloud.appengine_admin_v1.types.version import CpuUtilization +from google.cloud.appengine_admin_v1.types.version import DiskUtilization +from google.cloud.appengine_admin_v1.types.version import EndpointsApiService +from google.cloud.appengine_admin_v1.types.version import Entrypoint +from google.cloud.appengine_admin_v1.types.version import ManualScaling +from google.cloud.appengine_admin_v1.types.version import Network +from google.cloud.appengine_admin_v1.types.version import NetworkUtilization +from google.cloud.appengine_admin_v1.types.version import RequestUtilization +from google.cloud.appengine_admin_v1.types.version import Resources +from google.cloud.appengine_admin_v1.types.version import StandardSchedulerSettings +from google.cloud.appengine_admin_v1.types.version import Version +from google.cloud.appengine_admin_v1.types.version import Volume +from google.cloud.appengine_admin_v1.types.version import VpcAccessConnector +from google.cloud.appengine_admin_v1.types.version import InboundServiceType +from google.cloud.appengine_admin_v1.types.version import ServingStatus + +__all__ = ('ApplicationsClient', + 'ApplicationsAsyncClient', + 'AuthorizedCertificatesClient', + 'AuthorizedCertificatesAsyncClient', + 'AuthorizedDomainsClient', + 'AuthorizedDomainsAsyncClient', + 'DomainMappingsClient', + 'DomainMappingsAsyncClient', + 'FirewallClient', + 'FirewallAsyncClient', + 'InstancesClient', + 'InstancesAsyncClient', + 'ServicesClient', + 'ServicesAsyncClient', + 'VersionsClient', + 'VersionsAsyncClient', + 'ApiConfigHandler', + 'ApiEndpointHandler', + 'ErrorHandler', + 'HealthCheck', + 'Library', + 'LivenessCheck', + 'ReadinessCheck', + 'ScriptHandler', + 'StaticFilesHandler', + 'UrlMap', + 'AuthFailAction', + 'LoginRequirement', + 'SecurityLevel', + 'BatchUpdateIngressRulesRequest', + 'BatchUpdateIngressRulesResponse', + 'CreateApplicationRequest', + 'CreateAuthorizedCertificateRequest', + 'CreateDomainMappingRequest', + 'CreateIngressRuleRequest', + 'CreateVersionRequest', + 'DebugInstanceRequest', + 'DeleteAuthorizedCertificateRequest', + 'DeleteDomainMappingRequest', + 'DeleteIngressRuleRequest', + 'DeleteInstanceRequest', + 'DeleteServiceRequest', + 'DeleteVersionRequest', + 'GetApplicationRequest', + 'GetAuthorizedCertificateRequest', + 'GetDomainMappingRequest', + 'GetIngressRuleRequest', + 'GetInstanceRequest', + 'GetServiceRequest', + 'GetVersionRequest', + 'ListAuthorizedCertificatesRequest', + 'ListAuthorizedCertificatesResponse', + 'ListAuthorizedDomainsRequest', + 'ListAuthorizedDomainsResponse', + 'ListDomainMappingsRequest', + 'ListDomainMappingsResponse', + 'ListIngressRulesRequest', + 'ListIngressRulesResponse', + 'ListInstancesRequest', + 'ListInstancesResponse', + 'ListServicesRequest', + 'ListServicesResponse', + 'ListVersionsRequest', + 'ListVersionsResponse', + 'RepairApplicationRequest', + 'UpdateApplicationRequest', + 'UpdateAuthorizedCertificateRequest', + 'UpdateDomainMappingRequest', + 'UpdateIngressRuleRequest', + 'UpdateServiceRequest', + 'UpdateVersionRequest', + 'AuthorizedCertificateView', + 'DomainOverrideStrategy', + 'VersionView', + 'Application', + 'UrlDispatchRule', + 'AuditData', + 'CreateVersionMethod', + 'UpdateServiceMethod', + 'AuthorizedCertificate', + 'CertificateRawData', + 'ManagedCertificate', + 'ManagementStatus', + 'CloudBuildOptions', + 'ContainerInfo', + 'Deployment', + 'FileInfo', + 'ZipInfo', + 'AuthorizedDomain', + 'DomainMapping', + 'ResourceRecord', + 'SslSettings', + 'FirewallRule', + 'Instance', + 'LocationMetadata', + 'NetworkSettings', + 'CreateVersionMetadataV1', + 'OperationMetadataV1', + 'Service', + 'TrafficSplit', + 'AutomaticScaling', + 'BasicScaling', + 'CpuUtilization', + 'DiskUtilization', + 'EndpointsApiService', + 'Entrypoint', + 'ManualScaling', + 'Network', + 'NetworkUtilization', + 'RequestUtilization', + 'Resources', + 'StandardSchedulerSettings', + 'Version', + 'Volume', + 'VpcAccessConnector', + 'InboundServiceType', + 'ServingStatus', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin/py.typed b/owl-bot-staging/v1/google/cloud/appengine_admin/py.typed new file mode 100644 index 0000000..f846732 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-appengine-admin package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/__init__.py new file mode 100644 index 0000000..d72b66e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/__init__.py @@ -0,0 +1,254 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.applications import ApplicationsClient +from .services.applications import ApplicationsAsyncClient +from .services.authorized_certificates import AuthorizedCertificatesClient +from .services.authorized_certificates import AuthorizedCertificatesAsyncClient +from .services.authorized_domains import AuthorizedDomainsClient +from .services.authorized_domains import AuthorizedDomainsAsyncClient +from .services.domain_mappings import DomainMappingsClient +from .services.domain_mappings import DomainMappingsAsyncClient +from .services.firewall import FirewallClient +from .services.firewall import FirewallAsyncClient +from .services.instances import InstancesClient +from .services.instances import InstancesAsyncClient +from .services.services import ServicesClient +from .services.services import ServicesAsyncClient +from .services.versions import VersionsClient +from .services.versions import VersionsAsyncClient + +from .types.app_yaml import ApiConfigHandler +from .types.app_yaml import ApiEndpointHandler +from .types.app_yaml import ErrorHandler +from .types.app_yaml import HealthCheck +from .types.app_yaml import Library +from .types.app_yaml import LivenessCheck +from .types.app_yaml import ReadinessCheck +from .types.app_yaml import ScriptHandler +from .types.app_yaml import StaticFilesHandler +from .types.app_yaml import UrlMap +from .types.app_yaml import AuthFailAction +from .types.app_yaml import LoginRequirement +from .types.app_yaml import SecurityLevel +from .types.appengine import BatchUpdateIngressRulesRequest +from .types.appengine import BatchUpdateIngressRulesResponse +from .types.appengine import CreateApplicationRequest +from .types.appengine import CreateAuthorizedCertificateRequest +from .types.appengine import CreateDomainMappingRequest +from .types.appengine import CreateIngressRuleRequest +from .types.appengine import CreateVersionRequest +from .types.appengine import DebugInstanceRequest +from .types.appengine import DeleteAuthorizedCertificateRequest +from .types.appengine import DeleteDomainMappingRequest +from .types.appengine import DeleteIngressRuleRequest +from .types.appengine import DeleteInstanceRequest +from .types.appengine import DeleteServiceRequest +from .types.appengine import DeleteVersionRequest +from .types.appengine import GetApplicationRequest +from .types.appengine import GetAuthorizedCertificateRequest +from .types.appengine import GetDomainMappingRequest +from .types.appengine import GetIngressRuleRequest +from .types.appengine import GetInstanceRequest +from .types.appengine import GetServiceRequest +from .types.appengine import GetVersionRequest +from .types.appengine import ListAuthorizedCertificatesRequest +from .types.appengine import ListAuthorizedCertificatesResponse +from .types.appengine import ListAuthorizedDomainsRequest +from .types.appengine import ListAuthorizedDomainsResponse +from .types.appengine import ListDomainMappingsRequest +from .types.appengine import ListDomainMappingsResponse +from .types.appengine import ListIngressRulesRequest +from .types.appengine import ListIngressRulesResponse +from .types.appengine import ListInstancesRequest +from .types.appengine import ListInstancesResponse +from .types.appengine import ListServicesRequest +from .types.appengine import ListServicesResponse +from .types.appengine import ListVersionsRequest +from .types.appengine import ListVersionsResponse +from .types.appengine import RepairApplicationRequest +from .types.appengine import UpdateApplicationRequest +from .types.appengine import UpdateAuthorizedCertificateRequest +from .types.appengine import UpdateDomainMappingRequest +from .types.appengine import UpdateIngressRuleRequest +from .types.appengine import UpdateServiceRequest +from .types.appengine import UpdateVersionRequest +from .types.appengine import AuthorizedCertificateView +from .types.appengine import DomainOverrideStrategy +from .types.appengine import VersionView +from .types.application import Application +from .types.application import UrlDispatchRule +from .types.audit_data import AuditData +from .types.audit_data import CreateVersionMethod +from .types.audit_data import UpdateServiceMethod +from .types.certificate import AuthorizedCertificate +from .types.certificate import CertificateRawData +from .types.certificate import ManagedCertificate +from .types.certificate import ManagementStatus +from .types.deploy import CloudBuildOptions +from .types.deploy import ContainerInfo +from .types.deploy import Deployment +from .types.deploy import FileInfo +from .types.deploy import ZipInfo +from .types.domain import AuthorizedDomain +from .types.domain_mapping import DomainMapping +from .types.domain_mapping import ResourceRecord +from .types.domain_mapping import SslSettings +from .types.firewall import FirewallRule +from .types.instance import Instance +from .types.location import LocationMetadata +from .types.network_settings import NetworkSettings +from .types.operation import CreateVersionMetadataV1 +from .types.operation import OperationMetadataV1 +from .types.service import Service +from .types.service import TrafficSplit +from .types.version import AutomaticScaling +from .types.version import BasicScaling +from .types.version import CpuUtilization +from .types.version import DiskUtilization +from .types.version import EndpointsApiService +from .types.version import Entrypoint +from .types.version import ManualScaling +from .types.version import Network +from .types.version import NetworkUtilization +from .types.version import RequestUtilization +from .types.version import Resources +from .types.version import StandardSchedulerSettings +from .types.version import Version +from .types.version import Volume +from .types.version import VpcAccessConnector +from .types.version import InboundServiceType +from .types.version import ServingStatus + +__all__ = ( + 'ApplicationsAsyncClient', + 'AuthorizedCertificatesAsyncClient', + 'AuthorizedDomainsAsyncClient', + 'DomainMappingsAsyncClient', + 'FirewallAsyncClient', + 'InstancesAsyncClient', + 'ServicesAsyncClient', + 'VersionsAsyncClient', +'ApiConfigHandler', +'ApiEndpointHandler', +'Application', +'ApplicationsClient', +'AuditData', +'AuthFailAction', +'AuthorizedCertificate', +'AuthorizedCertificateView', +'AuthorizedCertificatesClient', +'AuthorizedDomain', +'AuthorizedDomainsClient', +'AutomaticScaling', +'BasicScaling', +'BatchUpdateIngressRulesRequest', +'BatchUpdateIngressRulesResponse', +'CertificateRawData', +'CloudBuildOptions', +'ContainerInfo', +'CpuUtilization', +'CreateApplicationRequest', +'CreateAuthorizedCertificateRequest', +'CreateDomainMappingRequest', +'CreateIngressRuleRequest', +'CreateVersionMetadataV1', +'CreateVersionMethod', +'CreateVersionRequest', +'DebugInstanceRequest', +'DeleteAuthorizedCertificateRequest', +'DeleteDomainMappingRequest', +'DeleteIngressRuleRequest', +'DeleteInstanceRequest', +'DeleteServiceRequest', +'DeleteVersionRequest', +'Deployment', +'DiskUtilization', +'DomainMapping', +'DomainMappingsClient', +'DomainOverrideStrategy', +'EndpointsApiService', +'Entrypoint', +'ErrorHandler', +'FileInfo', +'FirewallClient', +'FirewallRule', +'GetApplicationRequest', +'GetAuthorizedCertificateRequest', +'GetDomainMappingRequest', +'GetIngressRuleRequest', +'GetInstanceRequest', +'GetServiceRequest', +'GetVersionRequest', +'HealthCheck', +'InboundServiceType', +'Instance', +'InstancesClient', +'Library', +'ListAuthorizedCertificatesRequest', +'ListAuthorizedCertificatesResponse', +'ListAuthorizedDomainsRequest', +'ListAuthorizedDomainsResponse', +'ListDomainMappingsRequest', +'ListDomainMappingsResponse', +'ListIngressRulesRequest', +'ListIngressRulesResponse', +'ListInstancesRequest', +'ListInstancesResponse', +'ListServicesRequest', +'ListServicesResponse', +'ListVersionsRequest', +'ListVersionsResponse', +'LivenessCheck', +'LocationMetadata', +'LoginRequirement', +'ManagedCertificate', +'ManagementStatus', +'ManualScaling', +'Network', +'NetworkSettings', +'NetworkUtilization', +'OperationMetadataV1', +'ReadinessCheck', +'RepairApplicationRequest', +'RequestUtilization', +'ResourceRecord', +'Resources', +'ScriptHandler', +'SecurityLevel', +'Service', +'ServicesClient', +'ServingStatus', +'SslSettings', +'StandardSchedulerSettings', +'StaticFilesHandler', +'TrafficSplit', +'UpdateApplicationRequest', +'UpdateAuthorizedCertificateRequest', +'UpdateDomainMappingRequest', +'UpdateIngressRuleRequest', +'UpdateServiceMethod', +'UpdateServiceRequest', +'UpdateVersionRequest', +'UrlDispatchRule', +'UrlMap', +'Version', +'VersionView', +'VersionsClient', +'Volume', +'VpcAccessConnector', +'ZipInfo', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/gapic_metadata.json new file mode 100644 index 0000000..0bb6583 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/gapic_metadata.json @@ -0,0 +1,461 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.appengine_admin_v1", + "protoPackage": "google.appengine.v1", + "schema": "1.0", + "services": { + "Applications": { + "clients": { + "grpc": { + "libraryClient": "ApplicationsClient", + "rpcs": { + "CreateApplication": { + "methods": [ + "create_application" + ] + }, + "GetApplication": { + "methods": [ + "get_application" + ] + }, + "RepairApplication": { + "methods": [ + "repair_application" + ] + }, + "UpdateApplication": { + "methods": [ + "update_application" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ApplicationsAsyncClient", + "rpcs": { + "CreateApplication": { + "methods": [ + "create_application" + ] + }, + "GetApplication": { + "methods": [ + "get_application" + ] + }, + "RepairApplication": { + "methods": [ + "repair_application" + ] + }, + "UpdateApplication": { + "methods": [ + "update_application" + ] + } + } + } + } + }, + "AuthorizedCertificates": { + "clients": { + "grpc": { + "libraryClient": "AuthorizedCertificatesClient", + "rpcs": { + "CreateAuthorizedCertificate": { + "methods": [ + "create_authorized_certificate" + ] + }, + "DeleteAuthorizedCertificate": { + "methods": [ + "delete_authorized_certificate" + ] + }, + "GetAuthorizedCertificate": { + "methods": [ + "get_authorized_certificate" + ] + }, + "ListAuthorizedCertificates": { + "methods": [ + "list_authorized_certificates" + ] + }, + "UpdateAuthorizedCertificate": { + "methods": [ + "update_authorized_certificate" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AuthorizedCertificatesAsyncClient", + "rpcs": { + "CreateAuthorizedCertificate": { + "methods": [ + "create_authorized_certificate" + ] + }, + "DeleteAuthorizedCertificate": { + "methods": [ + "delete_authorized_certificate" + ] + }, + "GetAuthorizedCertificate": { + "methods": [ + "get_authorized_certificate" + ] + }, + "ListAuthorizedCertificates": { + "methods": [ + "list_authorized_certificates" + ] + }, + "UpdateAuthorizedCertificate": { + "methods": [ + "update_authorized_certificate" + ] + } + } + } + } + }, + "AuthorizedDomains": { + "clients": { + "grpc": { + "libraryClient": "AuthorizedDomainsClient", + "rpcs": { + "ListAuthorizedDomains": { + "methods": [ + "list_authorized_domains" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AuthorizedDomainsAsyncClient", + "rpcs": { + "ListAuthorizedDomains": { + "methods": [ + "list_authorized_domains" + ] + } + } + } + } + }, + "DomainMappings": { + "clients": { + "grpc": { + "libraryClient": "DomainMappingsClient", + "rpcs": { + "CreateDomainMapping": { + "methods": [ + "create_domain_mapping" + ] + }, + "DeleteDomainMapping": { + "methods": [ + "delete_domain_mapping" + ] + }, + "GetDomainMapping": { + "methods": [ + "get_domain_mapping" + ] + }, + "ListDomainMappings": { + "methods": [ + "list_domain_mappings" + ] + }, + "UpdateDomainMapping": { + "methods": [ + "update_domain_mapping" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DomainMappingsAsyncClient", + "rpcs": { + "CreateDomainMapping": { + "methods": [ + "create_domain_mapping" + ] + }, + "DeleteDomainMapping": { + "methods": [ + "delete_domain_mapping" + ] + }, + "GetDomainMapping": { + "methods": [ + "get_domain_mapping" + ] + }, + "ListDomainMappings": { + "methods": [ + "list_domain_mappings" + ] + }, + "UpdateDomainMapping": { + "methods": [ + "update_domain_mapping" + ] + } + } + } + } + }, + "Firewall": { + "clients": { + "grpc": { + "libraryClient": "FirewallClient", + "rpcs": { + "BatchUpdateIngressRules": { + "methods": [ + "batch_update_ingress_rules" + ] + }, + "CreateIngressRule": { + "methods": [ + "create_ingress_rule" + ] + }, + "DeleteIngressRule": { + "methods": [ + "delete_ingress_rule" + ] + }, + "GetIngressRule": { + "methods": [ + "get_ingress_rule" + ] + }, + "ListIngressRules": { + "methods": [ + "list_ingress_rules" + ] + }, + "UpdateIngressRule": { + "methods": [ + "update_ingress_rule" + ] + } + } + }, + "grpc-async": { + "libraryClient": "FirewallAsyncClient", + "rpcs": { + "BatchUpdateIngressRules": { + "methods": [ + "batch_update_ingress_rules" + ] + }, + "CreateIngressRule": { + "methods": [ + "create_ingress_rule" + ] + }, + "DeleteIngressRule": { + "methods": [ + "delete_ingress_rule" + ] + }, + "GetIngressRule": { + "methods": [ + "get_ingress_rule" + ] + }, + "ListIngressRules": { + "methods": [ + "list_ingress_rules" + ] + }, + "UpdateIngressRule": { + "methods": [ + "update_ingress_rule" + ] + } + } + } + } + }, + "Instances": { + "clients": { + "grpc": { + "libraryClient": "InstancesClient", + "rpcs": { + "DebugInstance": { + "methods": [ + "debug_instance" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + } + } + }, + "grpc-async": { + "libraryClient": "InstancesAsyncClient", + "rpcs": { + "DebugInstance": { + "methods": [ + "debug_instance" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + } + } + } + } + }, + "Services": { + "clients": { + "grpc": { + "libraryClient": "ServicesClient", + "rpcs": { + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ServicesAsyncClient", + "rpcs": { + "DeleteService": { + "methods": [ + "delete_service" + ] + }, + "GetService": { + "methods": [ + "get_service" + ] + }, + "ListServices": { + "methods": [ + "list_services" + ] + }, + "UpdateService": { + "methods": [ + "update_service" + ] + } + } + } + } + }, + "Versions": { + "clients": { + "grpc": { + "libraryClient": "VersionsClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + }, + "grpc-async": { + "libraryClient": "VersionsAsyncClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/py.typed b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/py.typed new file mode 100644 index 0000000..f846732 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-appengine-admin package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/__init__.py new file mode 100644 index 0000000..4de6597 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/__init__.py new file mode 100644 index 0000000..4da2040 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ApplicationsClient +from .async_client import ApplicationsAsyncClient + +__all__ = ( + 'ApplicationsClient', + 'ApplicationsAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/async_client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/async_client.py new file mode 100644 index 0000000..9e0a567 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/async_client.py @@ -0,0 +1,434 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation as gac_operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import application +from google.cloud.appengine_admin_v1.types import operation as ga_operation +from google.protobuf import duration_pb2 # type: ignore +from .transports.base import ApplicationsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ApplicationsGrpcAsyncIOTransport +from .client import ApplicationsClient + + +class ApplicationsAsyncClient: + """Manages App Engine applications.""" + + _client: ApplicationsClient + + DEFAULT_ENDPOINT = ApplicationsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ApplicationsClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(ApplicationsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ApplicationsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ApplicationsClient.common_folder_path) + parse_common_folder_path = staticmethod(ApplicationsClient.parse_common_folder_path) + common_organization_path = staticmethod(ApplicationsClient.common_organization_path) + parse_common_organization_path = staticmethod(ApplicationsClient.parse_common_organization_path) + common_project_path = staticmethod(ApplicationsClient.common_project_path) + parse_common_project_path = staticmethod(ApplicationsClient.parse_common_project_path) + common_location_path = staticmethod(ApplicationsClient.common_location_path) + parse_common_location_path = staticmethod(ApplicationsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ApplicationsAsyncClient: The constructed client. + """ + return ApplicationsClient.from_service_account_info.__func__(ApplicationsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ApplicationsAsyncClient: The constructed client. + """ + return ApplicationsClient.from_service_account_file.__func__(ApplicationsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ApplicationsTransport: + """Returns the transport used by the client instance. + + Returns: + ApplicationsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ApplicationsClient).get_transport_class, type(ApplicationsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ApplicationsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the applications client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ApplicationsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ApplicationsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_application(self, + request: appengine.GetApplicationRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> application.Application: + r"""Gets information about an application. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.GetApplicationRequest`): + The request object. Request message for + `Applications.GetApplication`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.Application: + An Application resource contains the + top-level configuration of an App Engine + application. + + """ + # Create or coerce a protobuf request object. + request = appengine.GetApplicationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_application, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_application(self, + request: appengine.CreateApplicationRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates an App Engine application for a Google Cloud Platform + project. Required fields: + + - ``id`` - The ID of the target Cloud Platform project. + - *location* - The + `region `__ + where you want the App Engine application located. + + For more information about App Engine applications, see + `Managing Projects, Applications, and + Billing `__. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.CreateApplicationRequest`): + The request object. Request message for + `Applications.CreateApplication`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Application` An Application resource contains the top-level configuration of an App + Engine application. + + """ + # Create or coerce a protobuf request object. + request = appengine.CreateApplicationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_application, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + application.Application, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + async def update_application(self, + request: appengine.UpdateApplicationRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the specified Application resource. You can update the + following fields: + + - ``auth_domain`` - Google authentication domain for + controlling user access to the application. + - ``default_cookie_expiration`` - Cookie expiration policy for + the application. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.UpdateApplicationRequest`): + The request object. Request message for + `Applications.UpdateApplication`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Application` An Application resource contains the top-level configuration of an App + Engine application. + + """ + # Create or coerce a protobuf request object. + request = appengine.UpdateApplicationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_application, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + application.Application, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + async def repair_application(self, + request: appengine.RepairApplicationRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Recreates the required App Engine features for the specified App + Engine application, for example a Cloud Storage bucket or App + Engine service account. Use this method if you receive an error + message about a missing feature, for example, *Error retrieving + the App Engine service account*. If you have deleted your App + Engine service account, this will not be able to recreate it. + Instead, you should attempt to use the IAM undelete API if + possible at + https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params=%7B"name"%3A"projects%2F-%2FserviceAccounts%2Funique_id"%2C"resource"%3A%7B%7D%7D + . If the deletion was recent, the numeric ID can be found in the + Cloud Console Activity Log. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.RepairApplicationRequest`): + The request object. Request message for + 'Applications.RepairApplication'. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Application` An Application resource contains the top-level configuration of an App + Engine application. + + """ + # Create or coerce a protobuf request object. + request = appengine.RepairApplicationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.repair_application, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + application.Application, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-appengine-admin", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ApplicationsAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/client.py new file mode 100644 index 0000000..909612f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/client.py @@ -0,0 +1,620 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation as gac_operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import application +from google.cloud.appengine_admin_v1.types import operation as ga_operation +from google.protobuf import duration_pb2 # type: ignore +from .transports.base import ApplicationsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ApplicationsGrpcTransport +from .transports.grpc_asyncio import ApplicationsGrpcAsyncIOTransport + + +class ApplicationsClientMeta(type): + """Metaclass for the Applications client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[ApplicationsTransport]] + _transport_registry["grpc"] = ApplicationsGrpcTransport + _transport_registry["grpc_asyncio"] = ApplicationsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ApplicationsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class ApplicationsClient(metaclass=ApplicationsClientMeta): + """Manages App Engine applications.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "appengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ApplicationsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ApplicationsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ApplicationsTransport: + """Returns the transport used by the client instance. + + Returns: + ApplicationsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ApplicationsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the applications client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ApplicationsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ApplicationsTransport): + # transport is a ApplicationsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), + ) + + def get_application(self, + request: appengine.GetApplicationRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> application.Application: + r"""Gets information about an application. + + Args: + request (google.cloud.appengine_admin_v1.types.GetApplicationRequest): + The request object. Request message for + `Applications.GetApplication`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.Application: + An Application resource contains the + top-level configuration of an App Engine + application. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.GetApplicationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.GetApplicationRequest): + request = appengine.GetApplicationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_application] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_application(self, + request: appengine.CreateApplicationRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gac_operation.Operation: + r"""Creates an App Engine application for a Google Cloud Platform + project. Required fields: + + - ``id`` - The ID of the target Cloud Platform project. + - *location* - The + `region `__ + where you want the App Engine application located. + + For more information about App Engine applications, see + `Managing Projects, Applications, and + Billing `__. + + Args: + request (google.cloud.appengine_admin_v1.types.CreateApplicationRequest): + The request object. Request message for + `Applications.CreateApplication`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Application` An Application resource contains the top-level configuration of an App + Engine application. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.CreateApplicationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.CreateApplicationRequest): + request = appengine.CreateApplicationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_application] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = gac_operation.from_gapic( + response, + self._transport.operations_client, + application.Application, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + def update_application(self, + request: appengine.UpdateApplicationRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gac_operation.Operation: + r"""Updates the specified Application resource. You can update the + following fields: + + - ``auth_domain`` - Google authentication domain for + controlling user access to the application. + - ``default_cookie_expiration`` - Cookie expiration policy for + the application. + + Args: + request (google.cloud.appengine_admin_v1.types.UpdateApplicationRequest): + The request object. Request message for + `Applications.UpdateApplication`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Application` An Application resource contains the top-level configuration of an App + Engine application. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.UpdateApplicationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.UpdateApplicationRequest): + request = appengine.UpdateApplicationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_application] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = gac_operation.from_gapic( + response, + self._transport.operations_client, + application.Application, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + def repair_application(self, + request: appengine.RepairApplicationRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gac_operation.Operation: + r"""Recreates the required App Engine features for the specified App + Engine application, for example a Cloud Storage bucket or App + Engine service account. Use this method if you receive an error + message about a missing feature, for example, *Error retrieving + the App Engine service account*. If you have deleted your App + Engine service account, this will not be able to recreate it. + Instead, you should attempt to use the IAM undelete API if + possible at + https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params=%7B"name"%3A"projects%2F-%2FserviceAccounts%2Funique_id"%2C"resource"%3A%7B%7D%7D + . If the deletion was recent, the numeric ID can be found in the + Cloud Console Activity Log. + + Args: + request (google.cloud.appengine_admin_v1.types.RepairApplicationRequest): + The request object. Request message for + 'Applications.RepairApplication'. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Application` An Application resource contains the top-level configuration of an App + Engine application. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.RepairApplicationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.RepairApplicationRequest): + request = appengine.RepairApplicationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.repair_application] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = gac_operation.from_gapic( + response, + self._transport.operations_client, + application.Application, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-appengine-admin", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ApplicationsClient", +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/__init__.py new file mode 100644 index 0000000..ec29c43 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ApplicationsTransport +from .grpc import ApplicationsGrpcTransport +from .grpc_asyncio import ApplicationsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ApplicationsTransport]] +_transport_registry['grpc'] = ApplicationsGrpcTransport +_transport_registry['grpc_asyncio'] = ApplicationsGrpcAsyncIOTransport + +__all__ = ( + 'ApplicationsTransport', + 'ApplicationsGrpcTransport', + 'ApplicationsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/base.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/base.py new file mode 100644 index 0000000..7254922 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/base.py @@ -0,0 +1,220 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import application +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-appengine-admin', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class ApplicationsTransport(abc.ABC): + """Abstract transport class for Applications.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ) + + DEFAULT_HOST: str = 'appengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials is service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_application: gapic_v1.method.wrap_method( + self.get_application, + default_timeout=None, + client_info=client_info, + ), + self.create_application: gapic_v1.method.wrap_method( + self.create_application, + default_timeout=None, + client_info=client_info, + ), + self.update_application: gapic_v1.method.wrap_method( + self.update_application, + default_timeout=None, + client_info=client_info, + ), + self.repair_application: gapic_v1.method.wrap_method( + self.repair_application, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def get_application(self) -> Callable[ + [appengine.GetApplicationRequest], + Union[ + application.Application, + Awaitable[application.Application] + ]]: + raise NotImplementedError() + + @property + def create_application(self) -> Callable[ + [appengine.CreateApplicationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_application(self) -> Callable[ + [appengine.UpdateApplicationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def repair_application(self) -> Callable[ + [appengine.RepairApplicationRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'ApplicationsTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/grpc.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/grpc.py new file mode 100644 index 0000000..b79e293 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/grpc.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import application +from google.longrunning import operations_pb2 # type: ignore +from .base import ApplicationsTransport, DEFAULT_CLIENT_INFO + + +class ApplicationsGrpcTransport(ApplicationsTransport): + """gRPC backend transport for Applications. + + Manages App Engine applications. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_application(self) -> Callable[ + [appengine.GetApplicationRequest], + application.Application]: + r"""Return a callable for the get application method over gRPC. + + Gets information about an application. + + Returns: + Callable[[~.GetApplicationRequest], + ~.Application]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_application' not in self._stubs: + self._stubs['get_application'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Applications/GetApplication', + request_serializer=appengine.GetApplicationRequest.serialize, + response_deserializer=application.Application.deserialize, + ) + return self._stubs['get_application'] + + @property + def create_application(self) -> Callable[ + [appengine.CreateApplicationRequest], + operations_pb2.Operation]: + r"""Return a callable for the create application method over gRPC. + + Creates an App Engine application for a Google Cloud Platform + project. Required fields: + + - ``id`` - The ID of the target Cloud Platform project. + - *location* - The + `region `__ + where you want the App Engine application located. + + For more information about App Engine applications, see + `Managing Projects, Applications, and + Billing `__. + + Returns: + Callable[[~.CreateApplicationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_application' not in self._stubs: + self._stubs['create_application'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Applications/CreateApplication', + request_serializer=appengine.CreateApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_application'] + + @property + def update_application(self) -> Callable[ + [appengine.UpdateApplicationRequest], + operations_pb2.Operation]: + r"""Return a callable for the update application method over gRPC. + + Updates the specified Application resource. You can update the + following fields: + + - ``auth_domain`` - Google authentication domain for + controlling user access to the application. + - ``default_cookie_expiration`` - Cookie expiration policy for + the application. + + Returns: + Callable[[~.UpdateApplicationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_application' not in self._stubs: + self._stubs['update_application'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Applications/UpdateApplication', + request_serializer=appengine.UpdateApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_application'] + + @property + def repair_application(self) -> Callable[ + [appengine.RepairApplicationRequest], + operations_pb2.Operation]: + r"""Return a callable for the repair application method over gRPC. + + Recreates the required App Engine features for the specified App + Engine application, for example a Cloud Storage bucket or App + Engine service account. Use this method if you receive an error + message about a missing feature, for example, *Error retrieving + the App Engine service account*. If you have deleted your App + Engine service account, this will not be able to recreate it. + Instead, you should attempt to use the IAM undelete API if + possible at + https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params=%7B"name"%3A"projects%2F-%2FserviceAccounts%2Funique_id"%2C"resource"%3A%7B%7D%7D + . If the deletion was recent, the numeric ID can be found in the + Cloud Console Activity Log. + + Returns: + Callable[[~.RepairApplicationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'repair_application' not in self._stubs: + self._stubs['repair_application'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Applications/RepairApplication', + request_serializer=appengine.RepairApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['repair_application'] + + +__all__ = ( + 'ApplicationsGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/grpc_asyncio.py new file mode 100644 index 0000000..fb68688 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/grpc_asyncio.py @@ -0,0 +1,380 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import application +from google.longrunning import operations_pb2 # type: ignore +from .base import ApplicationsTransport, DEFAULT_CLIENT_INFO +from .grpc import ApplicationsGrpcTransport + + +class ApplicationsGrpcAsyncIOTransport(ApplicationsTransport): + """gRPC AsyncIO backend transport for Applications. + + Manages App Engine applications. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_application(self) -> Callable[ + [appengine.GetApplicationRequest], + Awaitable[application.Application]]: + r"""Return a callable for the get application method over gRPC. + + Gets information about an application. + + Returns: + Callable[[~.GetApplicationRequest], + Awaitable[~.Application]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_application' not in self._stubs: + self._stubs['get_application'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Applications/GetApplication', + request_serializer=appengine.GetApplicationRequest.serialize, + response_deserializer=application.Application.deserialize, + ) + return self._stubs['get_application'] + + @property + def create_application(self) -> Callable[ + [appengine.CreateApplicationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create application method over gRPC. + + Creates an App Engine application for a Google Cloud Platform + project. Required fields: + + - ``id`` - The ID of the target Cloud Platform project. + - *location* - The + `region `__ + where you want the App Engine application located. + + For more information about App Engine applications, see + `Managing Projects, Applications, and + Billing `__. + + Returns: + Callable[[~.CreateApplicationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_application' not in self._stubs: + self._stubs['create_application'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Applications/CreateApplication', + request_serializer=appengine.CreateApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_application'] + + @property + def update_application(self) -> Callable[ + [appengine.UpdateApplicationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update application method over gRPC. + + Updates the specified Application resource. You can update the + following fields: + + - ``auth_domain`` - Google authentication domain for + controlling user access to the application. + - ``default_cookie_expiration`` - Cookie expiration policy for + the application. + + Returns: + Callable[[~.UpdateApplicationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_application' not in self._stubs: + self._stubs['update_application'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Applications/UpdateApplication', + request_serializer=appengine.UpdateApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_application'] + + @property + def repair_application(self) -> Callable[ + [appengine.RepairApplicationRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the repair application method over gRPC. + + Recreates the required App Engine features for the specified App + Engine application, for example a Cloud Storage bucket or App + Engine service account. Use this method if you receive an error + message about a missing feature, for example, *Error retrieving + the App Engine service account*. If you have deleted your App + Engine service account, this will not be able to recreate it. + Instead, you should attempt to use the IAM undelete API if + possible at + https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params=%7B"name"%3A"projects%2F-%2FserviceAccounts%2Funique_id"%2C"resource"%3A%7B%7D%7D + . If the deletion was recent, the numeric ID can be found in the + Cloud Console Activity Log. + + Returns: + Callable[[~.RepairApplicationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'repair_application' not in self._stubs: + self._stubs['repair_application'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Applications/RepairApplication', + request_serializer=appengine.RepairApplicationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['repair_application'] + + +__all__ = ( + 'ApplicationsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/__init__.py new file mode 100644 index 0000000..5a113af --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import AuthorizedCertificatesClient +from .async_client import AuthorizedCertificatesAsyncClient + +__all__ = ( + 'AuthorizedCertificatesClient', + 'AuthorizedCertificatesAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/async_client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/async_client.py new file mode 100644 index 0000000..85b96ce --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/async_client.py @@ -0,0 +1,459 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.appengine_admin_v1.services.authorized_certificates import pagers +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import certificate +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import AuthorizedCertificatesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AuthorizedCertificatesGrpcAsyncIOTransport +from .client import AuthorizedCertificatesClient + + +class AuthorizedCertificatesAsyncClient: + """Manages SSL certificates a user is authorized to administer. + A user can administer any SSL certificates applicable to their + authorized domains. + """ + + _client: AuthorizedCertificatesClient + + DEFAULT_ENDPOINT = AuthorizedCertificatesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AuthorizedCertificatesClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(AuthorizedCertificatesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AuthorizedCertificatesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AuthorizedCertificatesClient.common_folder_path) + parse_common_folder_path = staticmethod(AuthorizedCertificatesClient.parse_common_folder_path) + common_organization_path = staticmethod(AuthorizedCertificatesClient.common_organization_path) + parse_common_organization_path = staticmethod(AuthorizedCertificatesClient.parse_common_organization_path) + common_project_path = staticmethod(AuthorizedCertificatesClient.common_project_path) + parse_common_project_path = staticmethod(AuthorizedCertificatesClient.parse_common_project_path) + common_location_path = staticmethod(AuthorizedCertificatesClient.common_location_path) + parse_common_location_path = staticmethod(AuthorizedCertificatesClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AuthorizedCertificatesAsyncClient: The constructed client. + """ + return AuthorizedCertificatesClient.from_service_account_info.__func__(AuthorizedCertificatesAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AuthorizedCertificatesAsyncClient: The constructed client. + """ + return AuthorizedCertificatesClient.from_service_account_file.__func__(AuthorizedCertificatesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> AuthorizedCertificatesTransport: + """Returns the transport used by the client instance. + + Returns: + AuthorizedCertificatesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(AuthorizedCertificatesClient).get_transport_class, type(AuthorizedCertificatesClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, AuthorizedCertificatesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the authorized certificates client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.AuthorizedCertificatesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = AuthorizedCertificatesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_authorized_certificates(self, + request: appengine.ListAuthorizedCertificatesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAuthorizedCertificatesAsyncPager: + r"""Lists all SSL certificates the user is authorized to + administer. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesRequest`): + The request object. Request message for + `AuthorizedCertificates.ListAuthorizedCertificates`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.services.authorized_certificates.pagers.ListAuthorizedCertificatesAsyncPager: + Response message for + AuthorizedCertificates.ListAuthorizedCertificates. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = appengine.ListAuthorizedCertificatesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_authorized_certificates, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAuthorizedCertificatesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_authorized_certificate(self, + request: appengine.GetAuthorizedCertificateRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> certificate.AuthorizedCertificate: + r"""Gets the specified SSL certificate. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.GetAuthorizedCertificateRequest`): + The request object. Request message for + `AuthorizedCertificates.GetAuthorizedCertificate`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.AuthorizedCertificate: + An SSL certificate that a user has + been authorized to administer. A user is + authorized to administer any certificate + that applies to one of their authorized + domains. + + """ + # Create or coerce a protobuf request object. + request = appengine.GetAuthorizedCertificateRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_authorized_certificate, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_authorized_certificate(self, + request: appengine.CreateAuthorizedCertificateRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> certificate.AuthorizedCertificate: + r"""Uploads the specified SSL certificate. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.CreateAuthorizedCertificateRequest`): + The request object. Request message for + `AuthorizedCertificates.CreateAuthorizedCertificate`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.AuthorizedCertificate: + An SSL certificate that a user has + been authorized to administer. A user is + authorized to administer any certificate + that applies to one of their authorized + domains. + + """ + # Create or coerce a protobuf request object. + request = appengine.CreateAuthorizedCertificateRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_authorized_certificate, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_authorized_certificate(self, + request: appengine.UpdateAuthorizedCertificateRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> certificate.AuthorizedCertificate: + r"""Updates the specified SSL certificate. To renew a certificate + and maintain its existing domain mappings, update + ``certificate_data`` with a new certificate. The new certificate + must be applicable to the same domains as the original + certificate. The certificate ``display_name`` may also be + updated. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.UpdateAuthorizedCertificateRequest`): + The request object. Request message for + `AuthorizedCertificates.UpdateAuthorizedCertificate`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.AuthorizedCertificate: + An SSL certificate that a user has + been authorized to administer. A user is + authorized to administer any certificate + that applies to one of their authorized + domains. + + """ + # Create or coerce a protobuf request object. + request = appengine.UpdateAuthorizedCertificateRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_authorized_certificate, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_authorized_certificate(self, + request: appengine.DeleteAuthorizedCertificateRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified SSL certificate. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.DeleteAuthorizedCertificateRequest`): + The request object. Request message for + `AuthorizedCertificates.DeleteAuthorizedCertificate`. + 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. + """ + # Create or coerce a protobuf request object. + request = appengine.DeleteAuthorizedCertificateRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_authorized_certificate, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-appengine-admin", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AuthorizedCertificatesAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/client.py new file mode 100644 index 0000000..c313304 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/client.py @@ -0,0 +1,646 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.appengine_admin_v1.services.authorized_certificates import pagers +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import certificate +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import AuthorizedCertificatesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AuthorizedCertificatesGrpcTransport +from .transports.grpc_asyncio import AuthorizedCertificatesGrpcAsyncIOTransport + + +class AuthorizedCertificatesClientMeta(type): + """Metaclass for the AuthorizedCertificates client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[AuthorizedCertificatesTransport]] + _transport_registry["grpc"] = AuthorizedCertificatesGrpcTransport + _transport_registry["grpc_asyncio"] = AuthorizedCertificatesGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[AuthorizedCertificatesTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class AuthorizedCertificatesClient(metaclass=AuthorizedCertificatesClientMeta): + """Manages SSL certificates a user is authorized to administer. + A user can administer any SSL certificates applicable to their + authorized domains. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "appengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AuthorizedCertificatesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AuthorizedCertificatesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> AuthorizedCertificatesTransport: + """Returns the transport used by the client instance. + + Returns: + AuthorizedCertificatesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, AuthorizedCertificatesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the authorized certificates client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, AuthorizedCertificatesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, AuthorizedCertificatesTransport): + # transport is a AuthorizedCertificatesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), + ) + + def list_authorized_certificates(self, + request: appengine.ListAuthorizedCertificatesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAuthorizedCertificatesPager: + r"""Lists all SSL certificates the user is authorized to + administer. + + Args: + request (google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesRequest): + The request object. Request message for + `AuthorizedCertificates.ListAuthorizedCertificates`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.services.authorized_certificates.pagers.ListAuthorizedCertificatesPager: + Response message for + AuthorizedCertificates.ListAuthorizedCertificates. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.ListAuthorizedCertificatesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.ListAuthorizedCertificatesRequest): + request = appengine.ListAuthorizedCertificatesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_authorized_certificates] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAuthorizedCertificatesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_authorized_certificate(self, + request: appengine.GetAuthorizedCertificateRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> certificate.AuthorizedCertificate: + r"""Gets the specified SSL certificate. + + Args: + request (google.cloud.appengine_admin_v1.types.GetAuthorizedCertificateRequest): + The request object. Request message for + `AuthorizedCertificates.GetAuthorizedCertificate`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.AuthorizedCertificate: + An SSL certificate that a user has + been authorized to administer. A user is + authorized to administer any certificate + that applies to one of their authorized + domains. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.GetAuthorizedCertificateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.GetAuthorizedCertificateRequest): + request = appengine.GetAuthorizedCertificateRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_authorized_certificate] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_authorized_certificate(self, + request: appengine.CreateAuthorizedCertificateRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> certificate.AuthorizedCertificate: + r"""Uploads the specified SSL certificate. + + Args: + request (google.cloud.appengine_admin_v1.types.CreateAuthorizedCertificateRequest): + The request object. Request message for + `AuthorizedCertificates.CreateAuthorizedCertificate`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.AuthorizedCertificate: + An SSL certificate that a user has + been authorized to administer. A user is + authorized to administer any certificate + that applies to one of their authorized + domains. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.CreateAuthorizedCertificateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.CreateAuthorizedCertificateRequest): + request = appengine.CreateAuthorizedCertificateRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_authorized_certificate] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_authorized_certificate(self, + request: appengine.UpdateAuthorizedCertificateRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> certificate.AuthorizedCertificate: + r"""Updates the specified SSL certificate. To renew a certificate + and maintain its existing domain mappings, update + ``certificate_data`` with a new certificate. The new certificate + must be applicable to the same domains as the original + certificate. The certificate ``display_name`` may also be + updated. + + Args: + request (google.cloud.appengine_admin_v1.types.UpdateAuthorizedCertificateRequest): + The request object. Request message for + `AuthorizedCertificates.UpdateAuthorizedCertificate`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.AuthorizedCertificate: + An SSL certificate that a user has + been authorized to administer. A user is + authorized to administer any certificate + that applies to one of their authorized + domains. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.UpdateAuthorizedCertificateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.UpdateAuthorizedCertificateRequest): + request = appengine.UpdateAuthorizedCertificateRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_authorized_certificate] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_authorized_certificate(self, + request: appengine.DeleteAuthorizedCertificateRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified SSL certificate. + + Args: + request (google.cloud.appengine_admin_v1.types.DeleteAuthorizedCertificateRequest): + The request object. Request message for + `AuthorizedCertificates.DeleteAuthorizedCertificate`. + 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. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.DeleteAuthorizedCertificateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.DeleteAuthorizedCertificateRequest): + request = appengine.DeleteAuthorizedCertificateRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_authorized_certificate] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-appengine-admin", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AuthorizedCertificatesClient", +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/pagers.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/pagers.py new file mode 100644 index 0000000..2da15e4 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/pagers.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import certificate + + +class ListAuthorizedCertificatesPager: + """A pager for iterating through ``list_authorized_certificates`` requests. + + This class thinly wraps an initial + :class:`google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``certificates`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAuthorizedCertificates`` requests and continue to iterate + through the ``certificates`` field on the + corresponding responses. + + All the usual :class:`google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., appengine.ListAuthorizedCertificatesResponse], + request: appengine.ListAuthorizedCertificatesRequest, + response: appengine.ListAuthorizedCertificatesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesRequest): + The initial request object. + response (google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = appengine.ListAuthorizedCertificatesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[appengine.ListAuthorizedCertificatesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[certificate.AuthorizedCertificate]: + for page in self.pages: + yield from page.certificates + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAuthorizedCertificatesAsyncPager: + """A pager for iterating through ``list_authorized_certificates`` requests. + + This class thinly wraps an initial + :class:`google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``certificates`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAuthorizedCertificates`` requests and continue to iterate + through the ``certificates`` field on the + corresponding responses. + + All the usual :class:`google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[appengine.ListAuthorizedCertificatesResponse]], + request: appengine.ListAuthorizedCertificatesRequest, + response: appengine.ListAuthorizedCertificatesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesRequest): + The initial request object. + response (google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = appengine.ListAuthorizedCertificatesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[appengine.ListAuthorizedCertificatesResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[certificate.AuthorizedCertificate]: + async def async_generator(): + async for page in self.pages: + for response in page.certificates: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/__init__.py new file mode 100644 index 0000000..03a834e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AuthorizedCertificatesTransport +from .grpc import AuthorizedCertificatesGrpcTransport +from .grpc_asyncio import AuthorizedCertificatesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AuthorizedCertificatesTransport]] +_transport_registry['grpc'] = AuthorizedCertificatesGrpcTransport +_transport_registry['grpc_asyncio'] = AuthorizedCertificatesGrpcAsyncIOTransport + +__all__ = ( + 'AuthorizedCertificatesTransport', + 'AuthorizedCertificatesGrpcTransport', + 'AuthorizedCertificatesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/base.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/base.py new file mode 100644 index 0000000..4935474 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/base.py @@ -0,0 +1,228 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import certificate +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-appengine-admin', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class AuthorizedCertificatesTransport(abc.ABC): + """Abstract transport class for AuthorizedCertificates.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ) + + DEFAULT_HOST: str = 'appengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials is service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_authorized_certificates: gapic_v1.method.wrap_method( + self.list_authorized_certificates, + default_timeout=None, + client_info=client_info, + ), + self.get_authorized_certificate: gapic_v1.method.wrap_method( + self.get_authorized_certificate, + default_timeout=None, + client_info=client_info, + ), + self.create_authorized_certificate: gapic_v1.method.wrap_method( + self.create_authorized_certificate, + default_timeout=None, + client_info=client_info, + ), + self.update_authorized_certificate: gapic_v1.method.wrap_method( + self.update_authorized_certificate, + default_timeout=None, + client_info=client_info, + ), + self.delete_authorized_certificate: gapic_v1.method.wrap_method( + self.delete_authorized_certificate, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def list_authorized_certificates(self) -> Callable[ + [appengine.ListAuthorizedCertificatesRequest], + Union[ + appengine.ListAuthorizedCertificatesResponse, + Awaitable[appengine.ListAuthorizedCertificatesResponse] + ]]: + raise NotImplementedError() + + @property + def get_authorized_certificate(self) -> Callable[ + [appengine.GetAuthorizedCertificateRequest], + Union[ + certificate.AuthorizedCertificate, + Awaitable[certificate.AuthorizedCertificate] + ]]: + raise NotImplementedError() + + @property + def create_authorized_certificate(self) -> Callable[ + [appengine.CreateAuthorizedCertificateRequest], + Union[ + certificate.AuthorizedCertificate, + Awaitable[certificate.AuthorizedCertificate] + ]]: + raise NotImplementedError() + + @property + def update_authorized_certificate(self) -> Callable[ + [appengine.UpdateAuthorizedCertificateRequest], + Union[ + certificate.AuthorizedCertificate, + Awaitable[certificate.AuthorizedCertificate] + ]]: + raise NotImplementedError() + + @property + def delete_authorized_certificate(self) -> Callable[ + [appengine.DeleteAuthorizedCertificateRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'AuthorizedCertificatesTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc.py new file mode 100644 index 0000000..f747f56 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc.py @@ -0,0 +1,366 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import certificate +from google.protobuf import empty_pb2 # type: ignore +from .base import AuthorizedCertificatesTransport, DEFAULT_CLIENT_INFO + + +class AuthorizedCertificatesGrpcTransport(AuthorizedCertificatesTransport): + """gRPC backend transport for AuthorizedCertificates. + + Manages SSL certificates a user is authorized to administer. + A user can administer any SSL certificates applicable to their + authorized domains. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_authorized_certificates(self) -> Callable[ + [appengine.ListAuthorizedCertificatesRequest], + appengine.ListAuthorizedCertificatesResponse]: + r"""Return a callable for the list authorized certificates method over gRPC. + + Lists all SSL certificates the user is authorized to + administer. + + Returns: + Callable[[~.ListAuthorizedCertificatesRequest], + ~.ListAuthorizedCertificatesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_authorized_certificates' not in self._stubs: + self._stubs['list_authorized_certificates'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.AuthorizedCertificates/ListAuthorizedCertificates', + request_serializer=appengine.ListAuthorizedCertificatesRequest.serialize, + response_deserializer=appengine.ListAuthorizedCertificatesResponse.deserialize, + ) + return self._stubs['list_authorized_certificates'] + + @property + def get_authorized_certificate(self) -> Callable[ + [appengine.GetAuthorizedCertificateRequest], + certificate.AuthorizedCertificate]: + r"""Return a callable for the get authorized certificate method over gRPC. + + Gets the specified SSL certificate. + + Returns: + Callable[[~.GetAuthorizedCertificateRequest], + ~.AuthorizedCertificate]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_authorized_certificate' not in self._stubs: + self._stubs['get_authorized_certificate'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.AuthorizedCertificates/GetAuthorizedCertificate', + request_serializer=appengine.GetAuthorizedCertificateRequest.serialize, + response_deserializer=certificate.AuthorizedCertificate.deserialize, + ) + return self._stubs['get_authorized_certificate'] + + @property + def create_authorized_certificate(self) -> Callable[ + [appengine.CreateAuthorizedCertificateRequest], + certificate.AuthorizedCertificate]: + r"""Return a callable for the create authorized certificate method over gRPC. + + Uploads the specified SSL certificate. + + Returns: + Callable[[~.CreateAuthorizedCertificateRequest], + ~.AuthorizedCertificate]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_authorized_certificate' not in self._stubs: + self._stubs['create_authorized_certificate'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.AuthorizedCertificates/CreateAuthorizedCertificate', + request_serializer=appengine.CreateAuthorizedCertificateRequest.serialize, + response_deserializer=certificate.AuthorizedCertificate.deserialize, + ) + return self._stubs['create_authorized_certificate'] + + @property + def update_authorized_certificate(self) -> Callable[ + [appengine.UpdateAuthorizedCertificateRequest], + certificate.AuthorizedCertificate]: + r"""Return a callable for the update authorized certificate method over gRPC. + + Updates the specified SSL certificate. To renew a certificate + and maintain its existing domain mappings, update + ``certificate_data`` with a new certificate. The new certificate + must be applicable to the same domains as the original + certificate. The certificate ``display_name`` may also be + updated. + + Returns: + Callable[[~.UpdateAuthorizedCertificateRequest], + ~.AuthorizedCertificate]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_authorized_certificate' not in self._stubs: + self._stubs['update_authorized_certificate'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.AuthorizedCertificates/UpdateAuthorizedCertificate', + request_serializer=appengine.UpdateAuthorizedCertificateRequest.serialize, + response_deserializer=certificate.AuthorizedCertificate.deserialize, + ) + return self._stubs['update_authorized_certificate'] + + @property + def delete_authorized_certificate(self) -> Callable[ + [appengine.DeleteAuthorizedCertificateRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete authorized certificate method over gRPC. + + Deletes the specified SSL certificate. + + Returns: + Callable[[~.DeleteAuthorizedCertificateRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_authorized_certificate' not in self._stubs: + self._stubs['delete_authorized_certificate'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.AuthorizedCertificates/DeleteAuthorizedCertificate', + request_serializer=appengine.DeleteAuthorizedCertificateRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_authorized_certificate'] + + +__all__ = ( + 'AuthorizedCertificatesGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc_asyncio.py new file mode 100644 index 0000000..7b34f97 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc_asyncio.py @@ -0,0 +1,370 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import certificate +from google.protobuf import empty_pb2 # type: ignore +from .base import AuthorizedCertificatesTransport, DEFAULT_CLIENT_INFO +from .grpc import AuthorizedCertificatesGrpcTransport + + +class AuthorizedCertificatesGrpcAsyncIOTransport(AuthorizedCertificatesTransport): + """gRPC AsyncIO backend transport for AuthorizedCertificates. + + Manages SSL certificates a user is authorized to administer. + A user can administer any SSL certificates applicable to their + authorized domains. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_authorized_certificates(self) -> Callable[ + [appengine.ListAuthorizedCertificatesRequest], + Awaitable[appengine.ListAuthorizedCertificatesResponse]]: + r"""Return a callable for the list authorized certificates method over gRPC. + + Lists all SSL certificates the user is authorized to + administer. + + Returns: + Callable[[~.ListAuthorizedCertificatesRequest], + Awaitable[~.ListAuthorizedCertificatesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_authorized_certificates' not in self._stubs: + self._stubs['list_authorized_certificates'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.AuthorizedCertificates/ListAuthorizedCertificates', + request_serializer=appengine.ListAuthorizedCertificatesRequest.serialize, + response_deserializer=appengine.ListAuthorizedCertificatesResponse.deserialize, + ) + return self._stubs['list_authorized_certificates'] + + @property + def get_authorized_certificate(self) -> Callable[ + [appengine.GetAuthorizedCertificateRequest], + Awaitable[certificate.AuthorizedCertificate]]: + r"""Return a callable for the get authorized certificate method over gRPC. + + Gets the specified SSL certificate. + + Returns: + Callable[[~.GetAuthorizedCertificateRequest], + Awaitable[~.AuthorizedCertificate]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_authorized_certificate' not in self._stubs: + self._stubs['get_authorized_certificate'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.AuthorizedCertificates/GetAuthorizedCertificate', + request_serializer=appengine.GetAuthorizedCertificateRequest.serialize, + response_deserializer=certificate.AuthorizedCertificate.deserialize, + ) + return self._stubs['get_authorized_certificate'] + + @property + def create_authorized_certificate(self) -> Callable[ + [appengine.CreateAuthorizedCertificateRequest], + Awaitable[certificate.AuthorizedCertificate]]: + r"""Return a callable for the create authorized certificate method over gRPC. + + Uploads the specified SSL certificate. + + Returns: + Callable[[~.CreateAuthorizedCertificateRequest], + Awaitable[~.AuthorizedCertificate]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_authorized_certificate' not in self._stubs: + self._stubs['create_authorized_certificate'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.AuthorizedCertificates/CreateAuthorizedCertificate', + request_serializer=appengine.CreateAuthorizedCertificateRequest.serialize, + response_deserializer=certificate.AuthorizedCertificate.deserialize, + ) + return self._stubs['create_authorized_certificate'] + + @property + def update_authorized_certificate(self) -> Callable[ + [appengine.UpdateAuthorizedCertificateRequest], + Awaitable[certificate.AuthorizedCertificate]]: + r"""Return a callable for the update authorized certificate method over gRPC. + + Updates the specified SSL certificate. To renew a certificate + and maintain its existing domain mappings, update + ``certificate_data`` with a new certificate. The new certificate + must be applicable to the same domains as the original + certificate. The certificate ``display_name`` may also be + updated. + + Returns: + Callable[[~.UpdateAuthorizedCertificateRequest], + Awaitable[~.AuthorizedCertificate]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_authorized_certificate' not in self._stubs: + self._stubs['update_authorized_certificate'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.AuthorizedCertificates/UpdateAuthorizedCertificate', + request_serializer=appengine.UpdateAuthorizedCertificateRequest.serialize, + response_deserializer=certificate.AuthorizedCertificate.deserialize, + ) + return self._stubs['update_authorized_certificate'] + + @property + def delete_authorized_certificate(self) -> Callable[ + [appengine.DeleteAuthorizedCertificateRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete authorized certificate method over gRPC. + + Deletes the specified SSL certificate. + + Returns: + Callable[[~.DeleteAuthorizedCertificateRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_authorized_certificate' not in self._stubs: + self._stubs['delete_authorized_certificate'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.AuthorizedCertificates/DeleteAuthorizedCertificate', + request_serializer=appengine.DeleteAuthorizedCertificateRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_authorized_certificate'] + + +__all__ = ( + 'AuthorizedCertificatesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/__init__.py new file mode 100644 index 0000000..2cc1a32 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import AuthorizedDomainsClient +from .async_client import AuthorizedDomainsAsyncClient + +__all__ = ( + 'AuthorizedDomainsClient', + 'AuthorizedDomainsAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/async_client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/async_client.py new file mode 100644 index 0000000..186d938 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/async_client.py @@ -0,0 +1,233 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.appengine_admin_v1.services.authorized_domains import pagers +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import domain +from .transports.base import AuthorizedDomainsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AuthorizedDomainsGrpcAsyncIOTransport +from .client import AuthorizedDomainsClient + + +class AuthorizedDomainsAsyncClient: + """Manages domains a user is authorized to administer. To authorize use + of a domain, verify ownership via `Webmaster + Central `__. + """ + + _client: AuthorizedDomainsClient + + DEFAULT_ENDPOINT = AuthorizedDomainsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AuthorizedDomainsClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(AuthorizedDomainsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AuthorizedDomainsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AuthorizedDomainsClient.common_folder_path) + parse_common_folder_path = staticmethod(AuthorizedDomainsClient.parse_common_folder_path) + common_organization_path = staticmethod(AuthorizedDomainsClient.common_organization_path) + parse_common_organization_path = staticmethod(AuthorizedDomainsClient.parse_common_organization_path) + common_project_path = staticmethod(AuthorizedDomainsClient.common_project_path) + parse_common_project_path = staticmethod(AuthorizedDomainsClient.parse_common_project_path) + common_location_path = staticmethod(AuthorizedDomainsClient.common_location_path) + parse_common_location_path = staticmethod(AuthorizedDomainsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AuthorizedDomainsAsyncClient: The constructed client. + """ + return AuthorizedDomainsClient.from_service_account_info.__func__(AuthorizedDomainsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AuthorizedDomainsAsyncClient: The constructed client. + """ + return AuthorizedDomainsClient.from_service_account_file.__func__(AuthorizedDomainsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> AuthorizedDomainsTransport: + """Returns the transport used by the client instance. + + Returns: + AuthorizedDomainsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(AuthorizedDomainsClient).get_transport_class, type(AuthorizedDomainsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, AuthorizedDomainsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the authorized domains client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.AuthorizedDomainsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = AuthorizedDomainsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_authorized_domains(self, + request: appengine.ListAuthorizedDomainsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAuthorizedDomainsAsyncPager: + r"""Lists all domains the user is authorized to + administer. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsRequest`): + The request object. Request message for + `AuthorizedDomains.ListAuthorizedDomains`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.services.authorized_domains.pagers.ListAuthorizedDomainsAsyncPager: + Response message for + AuthorizedDomains.ListAuthorizedDomains. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = appengine.ListAuthorizedDomainsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_authorized_domains, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAuthorizedDomainsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-appengine-admin", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AuthorizedDomainsAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/client.py new file mode 100644 index 0000000..b5fd82b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/client.py @@ -0,0 +1,416 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.appengine_admin_v1.services.authorized_domains import pagers +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import domain +from .transports.base import AuthorizedDomainsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AuthorizedDomainsGrpcTransport +from .transports.grpc_asyncio import AuthorizedDomainsGrpcAsyncIOTransport + + +class AuthorizedDomainsClientMeta(type): + """Metaclass for the AuthorizedDomains client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[AuthorizedDomainsTransport]] + _transport_registry["grpc"] = AuthorizedDomainsGrpcTransport + _transport_registry["grpc_asyncio"] = AuthorizedDomainsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[AuthorizedDomainsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class AuthorizedDomainsClient(metaclass=AuthorizedDomainsClientMeta): + """Manages domains a user is authorized to administer. To authorize use + of a domain, verify ownership via `Webmaster + Central `__. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "appengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AuthorizedDomainsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AuthorizedDomainsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> AuthorizedDomainsTransport: + """Returns the transport used by the client instance. + + Returns: + AuthorizedDomainsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, AuthorizedDomainsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the authorized domains client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, AuthorizedDomainsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, AuthorizedDomainsTransport): + # transport is a AuthorizedDomainsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), + ) + + def list_authorized_domains(self, + request: appengine.ListAuthorizedDomainsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAuthorizedDomainsPager: + r"""Lists all domains the user is authorized to + administer. + + Args: + request (google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsRequest): + The request object. Request message for + `AuthorizedDomains.ListAuthorizedDomains`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.services.authorized_domains.pagers.ListAuthorizedDomainsPager: + Response message for + AuthorizedDomains.ListAuthorizedDomains. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.ListAuthorizedDomainsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.ListAuthorizedDomainsRequest): + request = appengine.ListAuthorizedDomainsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_authorized_domains] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAuthorizedDomainsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-appengine-admin", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AuthorizedDomainsClient", +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/pagers.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/pagers.py new file mode 100644 index 0000000..1a037ec --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/pagers.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import domain + + +class ListAuthorizedDomainsPager: + """A pager for iterating through ``list_authorized_domains`` requests. + + This class thinly wraps an initial + :class:`google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``domains`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAuthorizedDomains`` requests and continue to iterate + through the ``domains`` field on the + corresponding responses. + + All the usual :class:`google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., appengine.ListAuthorizedDomainsResponse], + request: appengine.ListAuthorizedDomainsRequest, + response: appengine.ListAuthorizedDomainsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsRequest): + The initial request object. + response (google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = appengine.ListAuthorizedDomainsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[appengine.ListAuthorizedDomainsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[domain.AuthorizedDomain]: + for page in self.pages: + yield from page.domains + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAuthorizedDomainsAsyncPager: + """A pager for iterating through ``list_authorized_domains`` requests. + + This class thinly wraps an initial + :class:`google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``domains`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAuthorizedDomains`` requests and continue to iterate + through the ``domains`` field on the + corresponding responses. + + All the usual :class:`google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[appengine.ListAuthorizedDomainsResponse]], + request: appengine.ListAuthorizedDomainsRequest, + response: appengine.ListAuthorizedDomainsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsRequest): + The initial request object. + response (google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = appengine.ListAuthorizedDomainsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[appengine.ListAuthorizedDomainsResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[domain.AuthorizedDomain]: + async def async_generator(): + async for page in self.pages: + for response in page.domains: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/__init__.py new file mode 100644 index 0000000..6334caa --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AuthorizedDomainsTransport +from .grpc import AuthorizedDomainsGrpcTransport +from .grpc_asyncio import AuthorizedDomainsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AuthorizedDomainsTransport]] +_transport_registry['grpc'] = AuthorizedDomainsGrpcTransport +_transport_registry['grpc_asyncio'] = AuthorizedDomainsGrpcAsyncIOTransport + +__all__ = ( + 'AuthorizedDomainsTransport', + 'AuthorizedDomainsGrpcTransport', + 'AuthorizedDomainsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/base.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/base.py new file mode 100644 index 0000000..d59d717 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/base.py @@ -0,0 +1,170 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-appengine-admin', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class AuthorizedDomainsTransport(abc.ABC): + """Abstract transport class for AuthorizedDomains.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ) + + DEFAULT_HOST: str = 'appengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials is service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_authorized_domains: gapic_v1.method.wrap_method( + self.list_authorized_domains, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def list_authorized_domains(self) -> Callable[ + [appengine.ListAuthorizedDomainsRequest], + Union[ + appengine.ListAuthorizedDomainsResponse, + Awaitable[appengine.ListAuthorizedDomainsResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'AuthorizedDomainsTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc.py new file mode 100644 index 0000000..f868356 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc.py @@ -0,0 +1,255 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from .base import AuthorizedDomainsTransport, DEFAULT_CLIENT_INFO + + +class AuthorizedDomainsGrpcTransport(AuthorizedDomainsTransport): + """gRPC backend transport for AuthorizedDomains. + + Manages domains a user is authorized to administer. To authorize use + of a domain, verify ownership via `Webmaster + Central `__. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_authorized_domains(self) -> Callable[ + [appengine.ListAuthorizedDomainsRequest], + appengine.ListAuthorizedDomainsResponse]: + r"""Return a callable for the list authorized domains method over gRPC. + + Lists all domains the user is authorized to + administer. + + Returns: + Callable[[~.ListAuthorizedDomainsRequest], + ~.ListAuthorizedDomainsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_authorized_domains' not in self._stubs: + self._stubs['list_authorized_domains'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.AuthorizedDomains/ListAuthorizedDomains', + request_serializer=appengine.ListAuthorizedDomainsRequest.serialize, + response_deserializer=appengine.ListAuthorizedDomainsResponse.deserialize, + ) + return self._stubs['list_authorized_domains'] + + +__all__ = ( + 'AuthorizedDomainsGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc_asyncio.py new file mode 100644 index 0000000..21976cd --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc_asyncio.py @@ -0,0 +1,259 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from .base import AuthorizedDomainsTransport, DEFAULT_CLIENT_INFO +from .grpc import AuthorizedDomainsGrpcTransport + + +class AuthorizedDomainsGrpcAsyncIOTransport(AuthorizedDomainsTransport): + """gRPC AsyncIO backend transport for AuthorizedDomains. + + Manages domains a user is authorized to administer. To authorize use + of a domain, verify ownership via `Webmaster + Central `__. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_authorized_domains(self) -> Callable[ + [appengine.ListAuthorizedDomainsRequest], + Awaitable[appengine.ListAuthorizedDomainsResponse]]: + r"""Return a callable for the list authorized domains method over gRPC. + + Lists all domains the user is authorized to + administer. + + Returns: + Callable[[~.ListAuthorizedDomainsRequest], + Awaitable[~.ListAuthorizedDomainsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_authorized_domains' not in self._stubs: + self._stubs['list_authorized_domains'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.AuthorizedDomains/ListAuthorizedDomains', + request_serializer=appengine.ListAuthorizedDomainsRequest.serialize, + response_deserializer=appengine.ListAuthorizedDomainsResponse.deserialize, + ) + return self._stubs['list_authorized_domains'] + + +__all__ = ( + 'AuthorizedDomainsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/__init__.py new file mode 100644 index 0000000..ddd8876 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import DomainMappingsClient +from .async_client import DomainMappingsAsyncClient + +__all__ = ( + 'DomainMappingsClient', + 'DomainMappingsAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/async_client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/async_client.py new file mode 100644 index 0000000..4dfb7bd --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/async_client.py @@ -0,0 +1,504 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation as gac_operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.appengine_admin_v1.services.domain_mappings import pagers +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import domain_mapping +from google.cloud.appengine_admin_v1.types import operation as ga_operation +from google.protobuf import empty_pb2 # type: ignore +from .transports.base import DomainMappingsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DomainMappingsGrpcAsyncIOTransport +from .client import DomainMappingsClient + + +class DomainMappingsAsyncClient: + """Manages domains serving an application.""" + + _client: DomainMappingsClient + + DEFAULT_ENDPOINT = DomainMappingsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DomainMappingsClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(DomainMappingsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DomainMappingsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DomainMappingsClient.common_folder_path) + parse_common_folder_path = staticmethod(DomainMappingsClient.parse_common_folder_path) + common_organization_path = staticmethod(DomainMappingsClient.common_organization_path) + parse_common_organization_path = staticmethod(DomainMappingsClient.parse_common_organization_path) + common_project_path = staticmethod(DomainMappingsClient.common_project_path) + parse_common_project_path = staticmethod(DomainMappingsClient.parse_common_project_path) + common_location_path = staticmethod(DomainMappingsClient.common_location_path) + parse_common_location_path = staticmethod(DomainMappingsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DomainMappingsAsyncClient: The constructed client. + """ + return DomainMappingsClient.from_service_account_info.__func__(DomainMappingsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DomainMappingsAsyncClient: The constructed client. + """ + return DomainMappingsClient.from_service_account_file.__func__(DomainMappingsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> DomainMappingsTransport: + """Returns the transport used by the client instance. + + Returns: + DomainMappingsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DomainMappingsClient).get_transport_class, type(DomainMappingsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, DomainMappingsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the domain mappings client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.DomainMappingsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = DomainMappingsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_domain_mappings(self, + request: appengine.ListDomainMappingsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDomainMappingsAsyncPager: + r"""Lists the domain mappings on an application. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.ListDomainMappingsRequest`): + The request object. Request message for + `DomainMappings.ListDomainMappings`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.services.domain_mappings.pagers.ListDomainMappingsAsyncPager: + Response message for DomainMappings.ListDomainMappings. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = appengine.ListDomainMappingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_domain_mappings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDomainMappingsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_domain_mapping(self, + request: appengine.GetDomainMappingRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> domain_mapping.DomainMapping: + r"""Gets the specified domain mapping. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.GetDomainMappingRequest`): + The request object. Request message for + `DomainMappings.GetDomainMapping`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.DomainMapping: + A domain serving an App Engine + application. + + """ + # Create or coerce a protobuf request object. + request = appengine.GetDomainMappingRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_domain_mapping, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_domain_mapping(self, + request: appengine.CreateDomainMappingRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Maps a domain to an application. A user must be authorized to + administer a domain in order to map it to an application. For a + list of available authorized domains, see + ```AuthorizedDomains.ListAuthorizedDomains`` <>`__. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.CreateDomainMappingRequest`): + The request object. Request message for + `DomainMappings.CreateDomainMapping`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.appengine_admin_v1.types.DomainMapping` + A domain serving an App Engine application. + + """ + # Create or coerce a protobuf request object. + request = appengine.CreateDomainMappingRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_domain_mapping, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + domain_mapping.DomainMapping, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + async def update_domain_mapping(self, + request: appengine.UpdateDomainMappingRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the specified domain mapping. To map an SSL certificate + to a domain mapping, update ``certificate_id`` to point to an + ``AuthorizedCertificate`` resource. A user must be authorized to + administer the associated domain in order to update a + ``DomainMapping`` resource. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.UpdateDomainMappingRequest`): + The request object. Request message for + `DomainMappings.UpdateDomainMapping`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.appengine_admin_v1.types.DomainMapping` + A domain serving an App Engine application. + + """ + # Create or coerce a protobuf request object. + request = appengine.UpdateDomainMappingRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_domain_mapping, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + domain_mapping.DomainMapping, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + async def delete_domain_mapping(self, + request: appengine.DeleteDomainMappingRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified domain mapping. A user must be authorized + to administer the associated domain in order to delete a + ``DomainMapping`` resource. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.DeleteDomainMappingRequest`): + The request object. Request message for + `DomainMappings.DeleteDomainMapping`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + request = appengine.DeleteDomainMappingRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_domain_mapping, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-appengine-admin", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "DomainMappingsAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/client.py new file mode 100644 index 0000000..45a1b8a --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/client.py @@ -0,0 +1,691 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation as gac_operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.appengine_admin_v1.services.domain_mappings import pagers +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import domain_mapping +from google.cloud.appengine_admin_v1.types import operation as ga_operation +from google.protobuf import empty_pb2 # type: ignore +from .transports.base import DomainMappingsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DomainMappingsGrpcTransport +from .transports.grpc_asyncio import DomainMappingsGrpcAsyncIOTransport + + +class DomainMappingsClientMeta(type): + """Metaclass for the DomainMappings client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[DomainMappingsTransport]] + _transport_registry["grpc"] = DomainMappingsGrpcTransport + _transport_registry["grpc_asyncio"] = DomainMappingsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[DomainMappingsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class DomainMappingsClient(metaclass=DomainMappingsClientMeta): + """Manages domains serving an application.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "appengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DomainMappingsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DomainMappingsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> DomainMappingsTransport: + """Returns the transport used by the client instance. + + Returns: + DomainMappingsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DomainMappingsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the domain mappings client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, DomainMappingsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, DomainMappingsTransport): + # transport is a DomainMappingsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), + ) + + def list_domain_mappings(self, + request: appengine.ListDomainMappingsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDomainMappingsPager: + r"""Lists the domain mappings on an application. + + Args: + request (google.cloud.appengine_admin_v1.types.ListDomainMappingsRequest): + The request object. Request message for + `DomainMappings.ListDomainMappings`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.services.domain_mappings.pagers.ListDomainMappingsPager: + Response message for DomainMappings.ListDomainMappings. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.ListDomainMappingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.ListDomainMappingsRequest): + request = appengine.ListDomainMappingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_domain_mappings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDomainMappingsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_domain_mapping(self, + request: appengine.GetDomainMappingRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> domain_mapping.DomainMapping: + r"""Gets the specified domain mapping. + + Args: + request (google.cloud.appengine_admin_v1.types.GetDomainMappingRequest): + The request object. Request message for + `DomainMappings.GetDomainMapping`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.DomainMapping: + A domain serving an App Engine + application. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.GetDomainMappingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.GetDomainMappingRequest): + request = appengine.GetDomainMappingRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_domain_mapping] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_domain_mapping(self, + request: appengine.CreateDomainMappingRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gac_operation.Operation: + r"""Maps a domain to an application. A user must be authorized to + administer a domain in order to map it to an application. For a + list of available authorized domains, see + ```AuthorizedDomains.ListAuthorizedDomains`` <>`__. + + Args: + request (google.cloud.appengine_admin_v1.types.CreateDomainMappingRequest): + The request object. Request message for + `DomainMappings.CreateDomainMapping`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.appengine_admin_v1.types.DomainMapping` + A domain serving an App Engine application. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.CreateDomainMappingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.CreateDomainMappingRequest): + request = appengine.CreateDomainMappingRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_domain_mapping] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = gac_operation.from_gapic( + response, + self._transport.operations_client, + domain_mapping.DomainMapping, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + def update_domain_mapping(self, + request: appengine.UpdateDomainMappingRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gac_operation.Operation: + r"""Updates the specified domain mapping. To map an SSL certificate + to a domain mapping, update ``certificate_id`` to point to an + ``AuthorizedCertificate`` resource. A user must be authorized to + administer the associated domain in order to update a + ``DomainMapping`` resource. + + Args: + request (google.cloud.appengine_admin_v1.types.UpdateDomainMappingRequest): + The request object. Request message for + `DomainMappings.UpdateDomainMapping`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.appengine_admin_v1.types.DomainMapping` + A domain serving an App Engine application. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.UpdateDomainMappingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.UpdateDomainMappingRequest): + request = appengine.UpdateDomainMappingRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_domain_mapping] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = gac_operation.from_gapic( + response, + self._transport.operations_client, + domain_mapping.DomainMapping, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + def delete_domain_mapping(self, + request: appengine.DeleteDomainMappingRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gac_operation.Operation: + r"""Deletes the specified domain mapping. A user must be authorized + to administer the associated domain in order to delete a + ``DomainMapping`` resource. + + Args: + request (google.cloud.appengine_admin_v1.types.DeleteDomainMappingRequest): + The request object. Request message for + `DomainMappings.DeleteDomainMapping`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.DeleteDomainMappingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.DeleteDomainMappingRequest): + request = appengine.DeleteDomainMappingRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_domain_mapping] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = gac_operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-appengine-admin", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "DomainMappingsClient", +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/pagers.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/pagers.py new file mode 100644 index 0000000..ab3b9e0 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/pagers.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import domain_mapping + + +class ListDomainMappingsPager: + """A pager for iterating through ``list_domain_mappings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.appengine_admin_v1.types.ListDomainMappingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``domain_mappings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDomainMappings`` requests and continue to iterate + through the ``domain_mappings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.appengine_admin_v1.types.ListDomainMappingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., appengine.ListDomainMappingsResponse], + request: appengine.ListDomainMappingsRequest, + response: appengine.ListDomainMappingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.appengine_admin_v1.types.ListDomainMappingsRequest): + The initial request object. + response (google.cloud.appengine_admin_v1.types.ListDomainMappingsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = appengine.ListDomainMappingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[appengine.ListDomainMappingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[domain_mapping.DomainMapping]: + for page in self.pages: + yield from page.domain_mappings + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDomainMappingsAsyncPager: + """A pager for iterating through ``list_domain_mappings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.appengine_admin_v1.types.ListDomainMappingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``domain_mappings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDomainMappings`` requests and continue to iterate + through the ``domain_mappings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.appengine_admin_v1.types.ListDomainMappingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[appengine.ListDomainMappingsResponse]], + request: appengine.ListDomainMappingsRequest, + response: appengine.ListDomainMappingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.appengine_admin_v1.types.ListDomainMappingsRequest): + The initial request object. + response (google.cloud.appengine_admin_v1.types.ListDomainMappingsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = appengine.ListDomainMappingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[appengine.ListDomainMappingsResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[domain_mapping.DomainMapping]: + async def async_generator(): + async for page in self.pages: + for response in page.domain_mappings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/__init__.py new file mode 100644 index 0000000..486f6a7 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import DomainMappingsTransport +from .grpc import DomainMappingsGrpcTransport +from .grpc_asyncio import DomainMappingsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DomainMappingsTransport]] +_transport_registry['grpc'] = DomainMappingsGrpcTransport +_transport_registry['grpc_asyncio'] = DomainMappingsGrpcAsyncIOTransport + +__all__ = ( + 'DomainMappingsTransport', + 'DomainMappingsGrpcTransport', + 'DomainMappingsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/base.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/base.py new file mode 100644 index 0000000..0f72811 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/base.py @@ -0,0 +1,234 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import domain_mapping +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-appengine-admin', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class DomainMappingsTransport(abc.ABC): + """Abstract transport class for DomainMappings.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ) + + DEFAULT_HOST: str = 'appengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials is service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_domain_mappings: gapic_v1.method.wrap_method( + self.list_domain_mappings, + default_timeout=None, + client_info=client_info, + ), + self.get_domain_mapping: gapic_v1.method.wrap_method( + self.get_domain_mapping, + default_timeout=None, + client_info=client_info, + ), + self.create_domain_mapping: gapic_v1.method.wrap_method( + self.create_domain_mapping, + default_timeout=None, + client_info=client_info, + ), + self.update_domain_mapping: gapic_v1.method.wrap_method( + self.update_domain_mapping, + default_timeout=None, + client_info=client_info, + ), + self.delete_domain_mapping: gapic_v1.method.wrap_method( + self.delete_domain_mapping, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_domain_mappings(self) -> Callable[ + [appengine.ListDomainMappingsRequest], + Union[ + appengine.ListDomainMappingsResponse, + Awaitable[appengine.ListDomainMappingsResponse] + ]]: + raise NotImplementedError() + + @property + def get_domain_mapping(self) -> Callable[ + [appengine.GetDomainMappingRequest], + Union[ + domain_mapping.DomainMapping, + Awaitable[domain_mapping.DomainMapping] + ]]: + raise NotImplementedError() + + @property + def create_domain_mapping(self) -> Callable[ + [appengine.CreateDomainMappingRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_domain_mapping(self) -> Callable[ + [appengine.UpdateDomainMappingRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_domain_mapping(self) -> Callable[ + [appengine.DeleteDomainMappingRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'DomainMappingsTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc.py new file mode 100644 index 0000000..4ae1052 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc.py @@ -0,0 +1,385 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import domain_mapping +from google.longrunning import operations_pb2 # type: ignore +from .base import DomainMappingsTransport, DEFAULT_CLIENT_INFO + + +class DomainMappingsGrpcTransport(DomainMappingsTransport): + """gRPC backend transport for DomainMappings. + + Manages domains serving an application. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_domain_mappings(self) -> Callable[ + [appengine.ListDomainMappingsRequest], + appengine.ListDomainMappingsResponse]: + r"""Return a callable for the list domain mappings method over gRPC. + + Lists the domain mappings on an application. + + Returns: + Callable[[~.ListDomainMappingsRequest], + ~.ListDomainMappingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_domain_mappings' not in self._stubs: + self._stubs['list_domain_mappings'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.DomainMappings/ListDomainMappings', + request_serializer=appengine.ListDomainMappingsRequest.serialize, + response_deserializer=appengine.ListDomainMappingsResponse.deserialize, + ) + return self._stubs['list_domain_mappings'] + + @property + def get_domain_mapping(self) -> Callable[ + [appengine.GetDomainMappingRequest], + domain_mapping.DomainMapping]: + r"""Return a callable for the get domain mapping method over gRPC. + + Gets the specified domain mapping. + + Returns: + Callable[[~.GetDomainMappingRequest], + ~.DomainMapping]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_domain_mapping' not in self._stubs: + self._stubs['get_domain_mapping'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.DomainMappings/GetDomainMapping', + request_serializer=appengine.GetDomainMappingRequest.serialize, + response_deserializer=domain_mapping.DomainMapping.deserialize, + ) + return self._stubs['get_domain_mapping'] + + @property + def create_domain_mapping(self) -> Callable[ + [appengine.CreateDomainMappingRequest], + operations_pb2.Operation]: + r"""Return a callable for the create domain mapping method over gRPC. + + Maps a domain to an application. A user must be authorized to + administer a domain in order to map it to an application. For a + list of available authorized domains, see + ```AuthorizedDomains.ListAuthorizedDomains`` <>`__. + + Returns: + Callable[[~.CreateDomainMappingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_domain_mapping' not in self._stubs: + self._stubs['create_domain_mapping'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.DomainMappings/CreateDomainMapping', + request_serializer=appengine.CreateDomainMappingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_domain_mapping'] + + @property + def update_domain_mapping(self) -> Callable[ + [appengine.UpdateDomainMappingRequest], + operations_pb2.Operation]: + r"""Return a callable for the update domain mapping method over gRPC. + + Updates the specified domain mapping. To map an SSL certificate + to a domain mapping, update ``certificate_id`` to point to an + ``AuthorizedCertificate`` resource. A user must be authorized to + administer the associated domain in order to update a + ``DomainMapping`` resource. + + Returns: + Callable[[~.UpdateDomainMappingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_domain_mapping' not in self._stubs: + self._stubs['update_domain_mapping'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.DomainMappings/UpdateDomainMapping', + request_serializer=appengine.UpdateDomainMappingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_domain_mapping'] + + @property + def delete_domain_mapping(self) -> Callable[ + [appengine.DeleteDomainMappingRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete domain mapping method over gRPC. + + Deletes the specified domain mapping. A user must be authorized + to administer the associated domain in order to delete a + ``DomainMapping`` resource. + + Returns: + Callable[[~.DeleteDomainMappingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_domain_mapping' not in self._stubs: + self._stubs['delete_domain_mapping'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.DomainMappings/DeleteDomainMapping', + request_serializer=appengine.DeleteDomainMappingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_domain_mapping'] + + +__all__ = ( + 'DomainMappingsGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc_asyncio.py new file mode 100644 index 0000000..b68101f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc_asyncio.py @@ -0,0 +1,389 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import domain_mapping +from google.longrunning import operations_pb2 # type: ignore +from .base import DomainMappingsTransport, DEFAULT_CLIENT_INFO +from .grpc import DomainMappingsGrpcTransport + + +class DomainMappingsGrpcAsyncIOTransport(DomainMappingsTransport): + """gRPC AsyncIO backend transport for DomainMappings. + + Manages domains serving an application. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_domain_mappings(self) -> Callable[ + [appengine.ListDomainMappingsRequest], + Awaitable[appengine.ListDomainMappingsResponse]]: + r"""Return a callable for the list domain mappings method over gRPC. + + Lists the domain mappings on an application. + + Returns: + Callable[[~.ListDomainMappingsRequest], + Awaitable[~.ListDomainMappingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_domain_mappings' not in self._stubs: + self._stubs['list_domain_mappings'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.DomainMappings/ListDomainMappings', + request_serializer=appengine.ListDomainMappingsRequest.serialize, + response_deserializer=appengine.ListDomainMappingsResponse.deserialize, + ) + return self._stubs['list_domain_mappings'] + + @property + def get_domain_mapping(self) -> Callable[ + [appengine.GetDomainMappingRequest], + Awaitable[domain_mapping.DomainMapping]]: + r"""Return a callable for the get domain mapping method over gRPC. + + Gets the specified domain mapping. + + Returns: + Callable[[~.GetDomainMappingRequest], + Awaitable[~.DomainMapping]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_domain_mapping' not in self._stubs: + self._stubs['get_domain_mapping'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.DomainMappings/GetDomainMapping', + request_serializer=appengine.GetDomainMappingRequest.serialize, + response_deserializer=domain_mapping.DomainMapping.deserialize, + ) + return self._stubs['get_domain_mapping'] + + @property + def create_domain_mapping(self) -> Callable[ + [appengine.CreateDomainMappingRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create domain mapping method over gRPC. + + Maps a domain to an application. A user must be authorized to + administer a domain in order to map it to an application. For a + list of available authorized domains, see + ```AuthorizedDomains.ListAuthorizedDomains`` <>`__. + + Returns: + Callable[[~.CreateDomainMappingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_domain_mapping' not in self._stubs: + self._stubs['create_domain_mapping'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.DomainMappings/CreateDomainMapping', + request_serializer=appengine.CreateDomainMappingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_domain_mapping'] + + @property + def update_domain_mapping(self) -> Callable[ + [appengine.UpdateDomainMappingRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update domain mapping method over gRPC. + + Updates the specified domain mapping. To map an SSL certificate + to a domain mapping, update ``certificate_id`` to point to an + ``AuthorizedCertificate`` resource. A user must be authorized to + administer the associated domain in order to update a + ``DomainMapping`` resource. + + Returns: + Callable[[~.UpdateDomainMappingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_domain_mapping' not in self._stubs: + self._stubs['update_domain_mapping'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.DomainMappings/UpdateDomainMapping', + request_serializer=appengine.UpdateDomainMappingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_domain_mapping'] + + @property + def delete_domain_mapping(self) -> Callable[ + [appengine.DeleteDomainMappingRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete domain mapping method over gRPC. + + Deletes the specified domain mapping. A user must be authorized + to administer the associated domain in order to delete a + ``DomainMapping`` resource. + + Returns: + Callable[[~.DeleteDomainMappingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_domain_mapping' not in self._stubs: + self._stubs['delete_domain_mapping'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.DomainMappings/DeleteDomainMapping', + request_serializer=appengine.DeleteDomainMappingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_domain_mapping'] + + +__all__ = ( + 'DomainMappingsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/__init__.py new file mode 100644 index 0000000..56728f7 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import FirewallClient +from .async_client import FirewallAsyncClient + +__all__ = ( + 'FirewallClient', + 'FirewallAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/async_client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/async_client.py new file mode 100644 index 0000000..3784ac7 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/async_client.py @@ -0,0 +1,515 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.appengine_admin_v1.services.firewall import pagers +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import firewall +from .transports.base import FirewallTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import FirewallGrpcAsyncIOTransport +from .client import FirewallClient + + +class FirewallAsyncClient: + """Firewall resources are used to define a collection of access + control rules for an Application. Each rule is defined with a + position which specifies the rule's order in the sequence of + rules, an IP range to be matched against requests, and an action + to take upon matching requests. + Every request is evaluated against the Firewall rules in + priority order. Processesing stops at the first rule which + matches the request's IP address. A final rule always specifies + an action that applies to all remaining IP addresses. The + default final rule for a newly-created application will be set + to "allow" if not otherwise specified by the user. + """ + + _client: FirewallClient + + DEFAULT_ENDPOINT = FirewallClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = FirewallClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(FirewallClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(FirewallClient.parse_common_billing_account_path) + common_folder_path = staticmethod(FirewallClient.common_folder_path) + parse_common_folder_path = staticmethod(FirewallClient.parse_common_folder_path) + common_organization_path = staticmethod(FirewallClient.common_organization_path) + parse_common_organization_path = staticmethod(FirewallClient.parse_common_organization_path) + common_project_path = staticmethod(FirewallClient.common_project_path) + parse_common_project_path = staticmethod(FirewallClient.parse_common_project_path) + common_location_path = staticmethod(FirewallClient.common_location_path) + parse_common_location_path = staticmethod(FirewallClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FirewallAsyncClient: The constructed client. + """ + return FirewallClient.from_service_account_info.__func__(FirewallAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FirewallAsyncClient: The constructed client. + """ + return FirewallClient.from_service_account_file.__func__(FirewallAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> FirewallTransport: + """Returns the transport used by the client instance. + + Returns: + FirewallTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(FirewallClient).get_transport_class, type(FirewallClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, FirewallTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the firewall client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.FirewallTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = FirewallClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_ingress_rules(self, + request: appengine.ListIngressRulesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListIngressRulesAsyncPager: + r"""Lists the firewall rules of an application. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.ListIngressRulesRequest`): + The request object. Request message for + `Firewall.ListIngressRules`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.services.firewall.pagers.ListIngressRulesAsyncPager: + Response message for Firewall.ListIngressRules. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = appengine.ListIngressRulesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_ingress_rules, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListIngressRulesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_update_ingress_rules(self, + request: appengine.BatchUpdateIngressRulesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> appengine.BatchUpdateIngressRulesResponse: + r"""Replaces the entire firewall ruleset in one bulk operation. This + overrides and replaces the rules of an existing firewall with + the new rules. + + If the final rule does not match traffic with the '*' wildcard + IP range, then an "allow all" rule is explicitly added to the + end of the list. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.BatchUpdateIngressRulesRequest`): + The request object. Request message for + `Firewall.BatchUpdateIngressRules`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.BatchUpdateIngressRulesResponse: + Response message for Firewall.UpdateAllIngressRules. + """ + # Create or coerce a protobuf request object. + request = appengine.BatchUpdateIngressRulesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_update_ingress_rules, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_ingress_rule(self, + request: appengine.CreateIngressRuleRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> firewall.FirewallRule: + r"""Creates a firewall rule for the application. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.CreateIngressRuleRequest`): + The request object. Request message for + `Firewall.CreateIngressRule`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.FirewallRule: + A single firewall rule that is + evaluated against incoming traffic and + provides an action to take on matched + requests. + + """ + # Create or coerce a protobuf request object. + request = appengine.CreateIngressRuleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_ingress_rule, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_ingress_rule(self, + request: appengine.GetIngressRuleRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> firewall.FirewallRule: + r"""Gets the specified firewall rule. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.GetIngressRuleRequest`): + The request object. Request message for + `Firewall.GetIngressRule`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.FirewallRule: + A single firewall rule that is + evaluated against incoming traffic and + provides an action to take on matched + requests. + + """ + # Create or coerce a protobuf request object. + request = appengine.GetIngressRuleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_ingress_rule, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_ingress_rule(self, + request: appengine.UpdateIngressRuleRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> firewall.FirewallRule: + r"""Updates the specified firewall rule. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.UpdateIngressRuleRequest`): + The request object. Request message for + `Firewall.UpdateIngressRule`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.FirewallRule: + A single firewall rule that is + evaluated against incoming traffic and + provides an action to take on matched + requests. + + """ + # Create or coerce a protobuf request object. + request = appengine.UpdateIngressRuleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_ingress_rule, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_ingress_rule(self, + request: appengine.DeleteIngressRuleRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified firewall rule. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.DeleteIngressRuleRequest`): + The request object. Request message for + `Firewall.DeleteIngressRule`. + 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. + """ + # Create or coerce a protobuf request object. + request = appengine.DeleteIngressRuleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_ingress_rule, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-appengine-admin", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "FirewallAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/client.py new file mode 100644 index 0000000..9ff6406 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/client.py @@ -0,0 +1,703 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.appengine_admin_v1.services.firewall import pagers +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import firewall +from .transports.base import FirewallTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import FirewallGrpcTransport +from .transports.grpc_asyncio import FirewallGrpcAsyncIOTransport + + +class FirewallClientMeta(type): + """Metaclass for the Firewall client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[FirewallTransport]] + _transport_registry["grpc"] = FirewallGrpcTransport + _transport_registry["grpc_asyncio"] = FirewallGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[FirewallTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class FirewallClient(metaclass=FirewallClientMeta): + """Firewall resources are used to define a collection of access + control rules for an Application. Each rule is defined with a + position which specifies the rule's order in the sequence of + rules, an IP range to be matched against requests, and an action + to take upon matching requests. + Every request is evaluated against the Firewall rules in + priority order. Processesing stops at the first rule which + matches the request's IP address. A final rule always specifies + an action that applies to all remaining IP addresses. The + default final rule for a newly-created application will be set + to "allow" if not otherwise specified by the user. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "appengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FirewallClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FirewallClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> FirewallTransport: + """Returns the transport used by the client instance. + + Returns: + FirewallTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, FirewallTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the firewall client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, FirewallTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, FirewallTransport): + # transport is a FirewallTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), + ) + + def list_ingress_rules(self, + request: appengine.ListIngressRulesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListIngressRulesPager: + r"""Lists the firewall rules of an application. + + Args: + request (google.cloud.appengine_admin_v1.types.ListIngressRulesRequest): + The request object. Request message for + `Firewall.ListIngressRules`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.services.firewall.pagers.ListIngressRulesPager: + Response message for Firewall.ListIngressRules. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.ListIngressRulesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.ListIngressRulesRequest): + request = appengine.ListIngressRulesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_ingress_rules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListIngressRulesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_update_ingress_rules(self, + request: appengine.BatchUpdateIngressRulesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> appengine.BatchUpdateIngressRulesResponse: + r"""Replaces the entire firewall ruleset in one bulk operation. This + overrides and replaces the rules of an existing firewall with + the new rules. + + If the final rule does not match traffic with the '*' wildcard + IP range, then an "allow all" rule is explicitly added to the + end of the list. + + Args: + request (google.cloud.appengine_admin_v1.types.BatchUpdateIngressRulesRequest): + The request object. Request message for + `Firewall.BatchUpdateIngressRules`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.BatchUpdateIngressRulesResponse: + Response message for Firewall.UpdateAllIngressRules. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.BatchUpdateIngressRulesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.BatchUpdateIngressRulesRequest): + request = appengine.BatchUpdateIngressRulesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_update_ingress_rules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_ingress_rule(self, + request: appengine.CreateIngressRuleRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> firewall.FirewallRule: + r"""Creates a firewall rule for the application. + + Args: + request (google.cloud.appengine_admin_v1.types.CreateIngressRuleRequest): + The request object. Request message for + `Firewall.CreateIngressRule`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.FirewallRule: + A single firewall rule that is + evaluated against incoming traffic and + provides an action to take on matched + requests. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.CreateIngressRuleRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.CreateIngressRuleRequest): + request = appengine.CreateIngressRuleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_ingress_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_ingress_rule(self, + request: appengine.GetIngressRuleRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> firewall.FirewallRule: + r"""Gets the specified firewall rule. + + Args: + request (google.cloud.appengine_admin_v1.types.GetIngressRuleRequest): + The request object. Request message for + `Firewall.GetIngressRule`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.FirewallRule: + A single firewall rule that is + evaluated against incoming traffic and + provides an action to take on matched + requests. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.GetIngressRuleRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.GetIngressRuleRequest): + request = appengine.GetIngressRuleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_ingress_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_ingress_rule(self, + request: appengine.UpdateIngressRuleRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> firewall.FirewallRule: + r"""Updates the specified firewall rule. + + Args: + request (google.cloud.appengine_admin_v1.types.UpdateIngressRuleRequest): + The request object. Request message for + `Firewall.UpdateIngressRule`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.FirewallRule: + A single firewall rule that is + evaluated against incoming traffic and + provides an action to take on matched + requests. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.UpdateIngressRuleRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.UpdateIngressRuleRequest): + request = appengine.UpdateIngressRuleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_ingress_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_ingress_rule(self, + request: appengine.DeleteIngressRuleRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified firewall rule. + + Args: + request (google.cloud.appengine_admin_v1.types.DeleteIngressRuleRequest): + The request object. Request message for + `Firewall.DeleteIngressRule`. + 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. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.DeleteIngressRuleRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.DeleteIngressRuleRequest): + request = appengine.DeleteIngressRuleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_ingress_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-appengine-admin", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "FirewallClient", +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/pagers.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/pagers.py new file mode 100644 index 0000000..eb8440d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/pagers.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import firewall + + +class ListIngressRulesPager: + """A pager for iterating through ``list_ingress_rules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.appengine_admin_v1.types.ListIngressRulesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``ingress_rules`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListIngressRules`` requests and continue to iterate + through the ``ingress_rules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.appengine_admin_v1.types.ListIngressRulesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., appengine.ListIngressRulesResponse], + request: appengine.ListIngressRulesRequest, + response: appengine.ListIngressRulesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.appengine_admin_v1.types.ListIngressRulesRequest): + The initial request object. + response (google.cloud.appengine_admin_v1.types.ListIngressRulesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = appengine.ListIngressRulesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[appengine.ListIngressRulesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[firewall.FirewallRule]: + for page in self.pages: + yield from page.ingress_rules + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListIngressRulesAsyncPager: + """A pager for iterating through ``list_ingress_rules`` requests. + + This class thinly wraps an initial + :class:`google.cloud.appengine_admin_v1.types.ListIngressRulesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``ingress_rules`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListIngressRules`` requests and continue to iterate + through the ``ingress_rules`` field on the + corresponding responses. + + All the usual :class:`google.cloud.appengine_admin_v1.types.ListIngressRulesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[appengine.ListIngressRulesResponse]], + request: appengine.ListIngressRulesRequest, + response: appengine.ListIngressRulesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.appengine_admin_v1.types.ListIngressRulesRequest): + The initial request object. + response (google.cloud.appengine_admin_v1.types.ListIngressRulesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = appengine.ListIngressRulesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[appengine.ListIngressRulesResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[firewall.FirewallRule]: + async def async_generator(): + async for page in self.pages: + for response in page.ingress_rules: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/__init__.py new file mode 100644 index 0000000..cdbfc05 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import FirewallTransport +from .grpc import FirewallGrpcTransport +from .grpc_asyncio import FirewallGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[FirewallTransport]] +_transport_registry['grpc'] = FirewallGrpcTransport +_transport_registry['grpc_asyncio'] = FirewallGrpcAsyncIOTransport + +__all__ = ( + 'FirewallTransport', + 'FirewallGrpcTransport', + 'FirewallGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/base.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/base.py new file mode 100644 index 0000000..f3ea7b6 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/base.py @@ -0,0 +1,242 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import firewall +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-appengine-admin', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class FirewallTransport(abc.ABC): + """Abstract transport class for Firewall.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ) + + DEFAULT_HOST: str = 'appengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials is service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_ingress_rules: gapic_v1.method.wrap_method( + self.list_ingress_rules, + default_timeout=None, + client_info=client_info, + ), + self.batch_update_ingress_rules: gapic_v1.method.wrap_method( + self.batch_update_ingress_rules, + default_timeout=None, + client_info=client_info, + ), + self.create_ingress_rule: gapic_v1.method.wrap_method( + self.create_ingress_rule, + default_timeout=None, + client_info=client_info, + ), + self.get_ingress_rule: gapic_v1.method.wrap_method( + self.get_ingress_rule, + default_timeout=None, + client_info=client_info, + ), + self.update_ingress_rule: gapic_v1.method.wrap_method( + self.update_ingress_rule, + default_timeout=None, + client_info=client_info, + ), + self.delete_ingress_rule: gapic_v1.method.wrap_method( + self.delete_ingress_rule, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def list_ingress_rules(self) -> Callable[ + [appengine.ListIngressRulesRequest], + Union[ + appengine.ListIngressRulesResponse, + Awaitable[appengine.ListIngressRulesResponse] + ]]: + raise NotImplementedError() + + @property + def batch_update_ingress_rules(self) -> Callable[ + [appengine.BatchUpdateIngressRulesRequest], + Union[ + appengine.BatchUpdateIngressRulesResponse, + Awaitable[appengine.BatchUpdateIngressRulesResponse] + ]]: + raise NotImplementedError() + + @property + def create_ingress_rule(self) -> Callable[ + [appengine.CreateIngressRuleRequest], + Union[ + firewall.FirewallRule, + Awaitable[firewall.FirewallRule] + ]]: + raise NotImplementedError() + + @property + def get_ingress_rule(self) -> Callable[ + [appengine.GetIngressRuleRequest], + Union[ + firewall.FirewallRule, + Awaitable[firewall.FirewallRule] + ]]: + raise NotImplementedError() + + @property + def update_ingress_rule(self) -> Callable[ + [appengine.UpdateIngressRuleRequest], + Union[ + firewall.FirewallRule, + Awaitable[firewall.FirewallRule] + ]]: + raise NotImplementedError() + + @property + def delete_ingress_rule(self) -> Callable[ + [appengine.DeleteIngressRuleRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'FirewallTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/grpc.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/grpc.py new file mode 100644 index 0000000..2b0ca92 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/grpc.py @@ -0,0 +1,400 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import firewall +from google.protobuf import empty_pb2 # type: ignore +from .base import FirewallTransport, DEFAULT_CLIENT_INFO + + +class FirewallGrpcTransport(FirewallTransport): + """gRPC backend transport for Firewall. + + Firewall resources are used to define a collection of access + control rules for an Application. Each rule is defined with a + position which specifies the rule's order in the sequence of + rules, an IP range to be matched against requests, and an action + to take upon matching requests. + Every request is evaluated against the Firewall rules in + priority order. Processesing stops at the first rule which + matches the request's IP address. A final rule always specifies + an action that applies to all remaining IP addresses. The + default final rule for a newly-created application will be set + to "allow" if not otherwise specified by the user. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_ingress_rules(self) -> Callable[ + [appengine.ListIngressRulesRequest], + appengine.ListIngressRulesResponse]: + r"""Return a callable for the list ingress rules method over gRPC. + + Lists the firewall rules of an application. + + Returns: + Callable[[~.ListIngressRulesRequest], + ~.ListIngressRulesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_ingress_rules' not in self._stubs: + self._stubs['list_ingress_rules'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Firewall/ListIngressRules', + request_serializer=appengine.ListIngressRulesRequest.serialize, + response_deserializer=appengine.ListIngressRulesResponse.deserialize, + ) + return self._stubs['list_ingress_rules'] + + @property + def batch_update_ingress_rules(self) -> Callable[ + [appengine.BatchUpdateIngressRulesRequest], + appengine.BatchUpdateIngressRulesResponse]: + r"""Return a callable for the batch update ingress rules method over gRPC. + + Replaces the entire firewall ruleset in one bulk operation. This + overrides and replaces the rules of an existing firewall with + the new rules. + + If the final rule does not match traffic with the '*' wildcard + IP range, then an "allow all" rule is explicitly added to the + end of the list. + + Returns: + Callable[[~.BatchUpdateIngressRulesRequest], + ~.BatchUpdateIngressRulesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_update_ingress_rules' not in self._stubs: + self._stubs['batch_update_ingress_rules'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Firewall/BatchUpdateIngressRules', + request_serializer=appengine.BatchUpdateIngressRulesRequest.serialize, + response_deserializer=appengine.BatchUpdateIngressRulesResponse.deserialize, + ) + return self._stubs['batch_update_ingress_rules'] + + @property + def create_ingress_rule(self) -> Callable[ + [appengine.CreateIngressRuleRequest], + firewall.FirewallRule]: + r"""Return a callable for the create ingress rule method over gRPC. + + Creates a firewall rule for the application. + + Returns: + Callable[[~.CreateIngressRuleRequest], + ~.FirewallRule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_ingress_rule' not in self._stubs: + self._stubs['create_ingress_rule'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Firewall/CreateIngressRule', + request_serializer=appengine.CreateIngressRuleRequest.serialize, + response_deserializer=firewall.FirewallRule.deserialize, + ) + return self._stubs['create_ingress_rule'] + + @property + def get_ingress_rule(self) -> Callable[ + [appengine.GetIngressRuleRequest], + firewall.FirewallRule]: + r"""Return a callable for the get ingress rule method over gRPC. + + Gets the specified firewall rule. + + Returns: + Callable[[~.GetIngressRuleRequest], + ~.FirewallRule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_ingress_rule' not in self._stubs: + self._stubs['get_ingress_rule'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Firewall/GetIngressRule', + request_serializer=appengine.GetIngressRuleRequest.serialize, + response_deserializer=firewall.FirewallRule.deserialize, + ) + return self._stubs['get_ingress_rule'] + + @property + def update_ingress_rule(self) -> Callable[ + [appengine.UpdateIngressRuleRequest], + firewall.FirewallRule]: + r"""Return a callable for the update ingress rule method over gRPC. + + Updates the specified firewall rule. + + Returns: + Callable[[~.UpdateIngressRuleRequest], + ~.FirewallRule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_ingress_rule' not in self._stubs: + self._stubs['update_ingress_rule'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Firewall/UpdateIngressRule', + request_serializer=appengine.UpdateIngressRuleRequest.serialize, + response_deserializer=firewall.FirewallRule.deserialize, + ) + return self._stubs['update_ingress_rule'] + + @property + def delete_ingress_rule(self) -> Callable[ + [appengine.DeleteIngressRuleRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete ingress rule method over gRPC. + + Deletes the specified firewall rule. + + Returns: + Callable[[~.DeleteIngressRuleRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_ingress_rule' not in self._stubs: + self._stubs['delete_ingress_rule'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Firewall/DeleteIngressRule', + request_serializer=appengine.DeleteIngressRuleRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_ingress_rule'] + + +__all__ = ( + 'FirewallGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/grpc_asyncio.py new file mode 100644 index 0000000..1ce6dda --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/grpc_asyncio.py @@ -0,0 +1,404 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import firewall +from google.protobuf import empty_pb2 # type: ignore +from .base import FirewallTransport, DEFAULT_CLIENT_INFO +from .grpc import FirewallGrpcTransport + + +class FirewallGrpcAsyncIOTransport(FirewallTransport): + """gRPC AsyncIO backend transport for Firewall. + + Firewall resources are used to define a collection of access + control rules for an Application. Each rule is defined with a + position which specifies the rule's order in the sequence of + rules, an IP range to be matched against requests, and an action + to take upon matching requests. + Every request is evaluated against the Firewall rules in + priority order. Processesing stops at the first rule which + matches the request's IP address. A final rule always specifies + an action that applies to all remaining IP addresses. The + default final rule for a newly-created application will be set + to "allow" if not otherwise specified by the user. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_ingress_rules(self) -> Callable[ + [appengine.ListIngressRulesRequest], + Awaitable[appengine.ListIngressRulesResponse]]: + r"""Return a callable for the list ingress rules method over gRPC. + + Lists the firewall rules of an application. + + Returns: + Callable[[~.ListIngressRulesRequest], + Awaitable[~.ListIngressRulesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_ingress_rules' not in self._stubs: + self._stubs['list_ingress_rules'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Firewall/ListIngressRules', + request_serializer=appengine.ListIngressRulesRequest.serialize, + response_deserializer=appengine.ListIngressRulesResponse.deserialize, + ) + return self._stubs['list_ingress_rules'] + + @property + def batch_update_ingress_rules(self) -> Callable[ + [appengine.BatchUpdateIngressRulesRequest], + Awaitable[appengine.BatchUpdateIngressRulesResponse]]: + r"""Return a callable for the batch update ingress rules method over gRPC. + + Replaces the entire firewall ruleset in one bulk operation. This + overrides and replaces the rules of an existing firewall with + the new rules. + + If the final rule does not match traffic with the '*' wildcard + IP range, then an "allow all" rule is explicitly added to the + end of the list. + + Returns: + Callable[[~.BatchUpdateIngressRulesRequest], + Awaitable[~.BatchUpdateIngressRulesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_update_ingress_rules' not in self._stubs: + self._stubs['batch_update_ingress_rules'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Firewall/BatchUpdateIngressRules', + request_serializer=appengine.BatchUpdateIngressRulesRequest.serialize, + response_deserializer=appengine.BatchUpdateIngressRulesResponse.deserialize, + ) + return self._stubs['batch_update_ingress_rules'] + + @property + def create_ingress_rule(self) -> Callable[ + [appengine.CreateIngressRuleRequest], + Awaitable[firewall.FirewallRule]]: + r"""Return a callable for the create ingress rule method over gRPC. + + Creates a firewall rule for the application. + + Returns: + Callable[[~.CreateIngressRuleRequest], + Awaitable[~.FirewallRule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_ingress_rule' not in self._stubs: + self._stubs['create_ingress_rule'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Firewall/CreateIngressRule', + request_serializer=appengine.CreateIngressRuleRequest.serialize, + response_deserializer=firewall.FirewallRule.deserialize, + ) + return self._stubs['create_ingress_rule'] + + @property + def get_ingress_rule(self) -> Callable[ + [appengine.GetIngressRuleRequest], + Awaitable[firewall.FirewallRule]]: + r"""Return a callable for the get ingress rule method over gRPC. + + Gets the specified firewall rule. + + Returns: + Callable[[~.GetIngressRuleRequest], + Awaitable[~.FirewallRule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_ingress_rule' not in self._stubs: + self._stubs['get_ingress_rule'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Firewall/GetIngressRule', + request_serializer=appengine.GetIngressRuleRequest.serialize, + response_deserializer=firewall.FirewallRule.deserialize, + ) + return self._stubs['get_ingress_rule'] + + @property + def update_ingress_rule(self) -> Callable[ + [appengine.UpdateIngressRuleRequest], + Awaitable[firewall.FirewallRule]]: + r"""Return a callable for the update ingress rule method over gRPC. + + Updates the specified firewall rule. + + Returns: + Callable[[~.UpdateIngressRuleRequest], + Awaitable[~.FirewallRule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_ingress_rule' not in self._stubs: + self._stubs['update_ingress_rule'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Firewall/UpdateIngressRule', + request_serializer=appengine.UpdateIngressRuleRequest.serialize, + response_deserializer=firewall.FirewallRule.deserialize, + ) + return self._stubs['update_ingress_rule'] + + @property + def delete_ingress_rule(self) -> Callable[ + [appengine.DeleteIngressRuleRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete ingress rule method over gRPC. + + Deletes the specified firewall rule. + + Returns: + Callable[[~.DeleteIngressRuleRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_ingress_rule' not in self._stubs: + self._stubs['delete_ingress_rule'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Firewall/DeleteIngressRule', + request_serializer=appengine.DeleteIngressRuleRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_ingress_rule'] + + +__all__ = ( + 'FirewallGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/__init__.py new file mode 100644 index 0000000..0567e49 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import InstancesClient +from .async_client import InstancesAsyncClient + +__all__ = ( + 'InstancesClient', + 'InstancesAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/async_client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/async_client.py new file mode 100644 index 0000000..b48b6d1 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/async_client.py @@ -0,0 +1,459 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation as gac_operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.appengine_admin_v1.services.instances import pagers +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import instance +from google.cloud.appengine_admin_v1.types import operation as ga_operation +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import InstancesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import InstancesGrpcAsyncIOTransport +from .client import InstancesClient + + +class InstancesAsyncClient: + """Manages instances of a version.""" + + _client: InstancesClient + + DEFAULT_ENDPOINT = InstancesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = InstancesClient.DEFAULT_MTLS_ENDPOINT + + instance_path = staticmethod(InstancesClient.instance_path) + parse_instance_path = staticmethod(InstancesClient.parse_instance_path) + common_billing_account_path = staticmethod(InstancesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(InstancesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(InstancesClient.common_folder_path) + parse_common_folder_path = staticmethod(InstancesClient.parse_common_folder_path) + common_organization_path = staticmethod(InstancesClient.common_organization_path) + parse_common_organization_path = staticmethod(InstancesClient.parse_common_organization_path) + common_project_path = staticmethod(InstancesClient.common_project_path) + parse_common_project_path = staticmethod(InstancesClient.parse_common_project_path) + common_location_path = staticmethod(InstancesClient.common_location_path) + parse_common_location_path = staticmethod(InstancesClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + InstancesAsyncClient: The constructed client. + """ + return InstancesClient.from_service_account_info.__func__(InstancesAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + InstancesAsyncClient: The constructed client. + """ + return InstancesClient.from_service_account_file.__func__(InstancesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> InstancesTransport: + """Returns the transport used by the client instance. + + Returns: + InstancesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(InstancesClient).get_transport_class, type(InstancesClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, InstancesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the instances client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.InstancesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = InstancesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_instances(self, + request: appengine.ListInstancesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListInstancesAsyncPager: + r"""Lists the instances of a version. + + Tip: To aggregate details about instances over time, see the + `Stackdriver Monitoring + API `__. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.ListInstancesRequest`): + The request object. Request message for + `Instances.ListInstances`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.services.instances.pagers.ListInstancesAsyncPager: + Response message for Instances.ListInstances. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = appengine.ListInstancesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_instances, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListInstancesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_instance(self, + request: appengine.GetInstanceRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> instance.Instance: + r"""Gets instance information. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.GetInstanceRequest`): + The request object. Request message for + `Instances.GetInstance`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.Instance: + An Instance resource is the computing + unit that App Engine uses to + automatically scale an application. + + """ + # Create or coerce a protobuf request object. + request = appengine.GetInstanceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_instance, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_instance(self, + request: appengine.DeleteInstanceRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Stops a running instance. + + The instance might be automatically recreated based on the + scaling settings of the version. For more information, see "How + Instances are Managed" (`standard + environment `__ + \| `flexible + environment `__). + + To ensure that instances are not re-created and avoid getting + billed, you can stop all instances within the target version by + changing the serving status of the version to ``STOPPED`` with + the + ```apps.services.versions.patch`` `__ + method. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.DeleteInstanceRequest`): + The request object. Request message for + `Instances.DeleteInstance`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + request = appengine.DeleteInstanceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_instance, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + async def debug_instance(self, + request: appengine.DebugInstanceRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Enables debugging on a VM instance. This allows you + to use the SSH command to connect to the virtual machine + where the instance lives. While in "debug mode", the + instance continues to serve live traffic. You should + delete the instance when you are done debugging and then + allow the system to take over and determine if another + instance should be started. + + Only applicable for instances in App Engine flexible + environment. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.DebugInstanceRequest`): + The request object. Request message for + `Instances.DebugInstance`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Instance` An Instance resource is the computing unit that App Engine uses to + automatically scale an application. + + """ + # Create or coerce a protobuf request object. + request = appengine.DebugInstanceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.debug_instance, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + instance.Instance, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-appengine-admin", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "InstancesAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/client.py new file mode 100644 index 0000000..f510d7e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/client.py @@ -0,0 +1,654 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation as gac_operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.appengine_admin_v1.services.instances import pagers +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import instance +from google.cloud.appengine_admin_v1.types import operation as ga_operation +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import InstancesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import InstancesGrpcTransport +from .transports.grpc_asyncio import InstancesGrpcAsyncIOTransport + + +class InstancesClientMeta(type): + """Metaclass for the Instances client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[InstancesTransport]] + _transport_registry["grpc"] = InstancesGrpcTransport + _transport_registry["grpc_asyncio"] = InstancesGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[InstancesTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class InstancesClient(metaclass=InstancesClientMeta): + """Manages instances of a version.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "appengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + InstancesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + InstancesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> InstancesTransport: + """Returns the transport used by the client instance. + + Returns: + InstancesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def instance_path(app: str,service: str,version: str,instance: str,) -> str: + """Returns a fully-qualified instance string.""" + return "apps/{app}/services/{service}/versions/{version}/instances/{instance}".format(app=app, service=service, version=version, instance=instance, ) + + @staticmethod + def parse_instance_path(path: str) -> Dict[str,str]: + """Parses a instance path into its component segments.""" + m = re.match(r"^apps/(?P.+?)/services/(?P.+?)/versions/(?P.+?)/instances/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, InstancesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the instances client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, InstancesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, InstancesTransport): + # transport is a InstancesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), + ) + + def list_instances(self, + request: appengine.ListInstancesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListInstancesPager: + r"""Lists the instances of a version. + + Tip: To aggregate details about instances over time, see the + `Stackdriver Monitoring + API `__. + + Args: + request (google.cloud.appengine_admin_v1.types.ListInstancesRequest): + The request object. Request message for + `Instances.ListInstances`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.services.instances.pagers.ListInstancesPager: + Response message for Instances.ListInstances. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.ListInstancesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.ListInstancesRequest): + request = appengine.ListInstancesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_instances] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListInstancesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_instance(self, + request: appengine.GetInstanceRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> instance.Instance: + r"""Gets instance information. + + Args: + request (google.cloud.appengine_admin_v1.types.GetInstanceRequest): + The request object. Request message for + `Instances.GetInstance`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.Instance: + An Instance resource is the computing + unit that App Engine uses to + automatically scale an application. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.GetInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.GetInstanceRequest): + request = appengine.GetInstanceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_instance] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_instance(self, + request: appengine.DeleteInstanceRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gac_operation.Operation: + r"""Stops a running instance. + + The instance might be automatically recreated based on the + scaling settings of the version. For more information, see "How + Instances are Managed" (`standard + environment `__ + \| `flexible + environment `__). + + To ensure that instances are not re-created and avoid getting + billed, you can stop all instances within the target version by + changing the serving status of the version to ``STOPPED`` with + the + ```apps.services.versions.patch`` `__ + method. + + Args: + request (google.cloud.appengine_admin_v1.types.DeleteInstanceRequest): + The request object. Request message for + `Instances.DeleteInstance`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.DeleteInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.DeleteInstanceRequest): + request = appengine.DeleteInstanceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_instance] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = gac_operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + def debug_instance(self, + request: appengine.DebugInstanceRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gac_operation.Operation: + r"""Enables debugging on a VM instance. This allows you + to use the SSH command to connect to the virtual machine + where the instance lives. While in "debug mode", the + instance continues to serve live traffic. You should + delete the instance when you are done debugging and then + allow the system to take over and determine if another + instance should be started. + + Only applicable for instances in App Engine flexible + environment. + + Args: + request (google.cloud.appengine_admin_v1.types.DebugInstanceRequest): + The request object. Request message for + `Instances.DebugInstance`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Instance` An Instance resource is the computing unit that App Engine uses to + automatically scale an application. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.DebugInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.DebugInstanceRequest): + request = appengine.DebugInstanceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.debug_instance] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = gac_operation.from_gapic( + response, + self._transport.operations_client, + instance.Instance, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-appengine-admin", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "InstancesClient", +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/pagers.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/pagers.py new file mode 100644 index 0000000..08a248d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/pagers.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import instance + + +class ListInstancesPager: + """A pager for iterating through ``list_instances`` requests. + + This class thinly wraps an initial + :class:`google.cloud.appengine_admin_v1.types.ListInstancesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``instances`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListInstances`` requests and continue to iterate + through the ``instances`` field on the + corresponding responses. + + All the usual :class:`google.cloud.appengine_admin_v1.types.ListInstancesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., appengine.ListInstancesResponse], + request: appengine.ListInstancesRequest, + response: appengine.ListInstancesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.appengine_admin_v1.types.ListInstancesRequest): + The initial request object. + response (google.cloud.appengine_admin_v1.types.ListInstancesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = appengine.ListInstancesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[appengine.ListInstancesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[instance.Instance]: + for page in self.pages: + yield from page.instances + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListInstancesAsyncPager: + """A pager for iterating through ``list_instances`` requests. + + This class thinly wraps an initial + :class:`google.cloud.appengine_admin_v1.types.ListInstancesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``instances`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListInstances`` requests and continue to iterate + through the ``instances`` field on the + corresponding responses. + + All the usual :class:`google.cloud.appengine_admin_v1.types.ListInstancesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[appengine.ListInstancesResponse]], + request: appengine.ListInstancesRequest, + response: appengine.ListInstancesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.appengine_admin_v1.types.ListInstancesRequest): + The initial request object. + response (google.cloud.appengine_admin_v1.types.ListInstancesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = appengine.ListInstancesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[appengine.ListInstancesResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[instance.Instance]: + async def async_generator(): + async for page in self.pages: + for response in page.instances: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/__init__.py new file mode 100644 index 0000000..f8f9921 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import InstancesTransport +from .grpc import InstancesGrpcTransport +from .grpc_asyncio import InstancesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[InstancesTransport]] +_transport_registry['grpc'] = InstancesGrpcTransport +_transport_registry['grpc_asyncio'] = InstancesGrpcAsyncIOTransport + +__all__ = ( + 'InstancesTransport', + 'InstancesGrpcTransport', + 'InstancesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/base.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/base.py new file mode 100644 index 0000000..94e4717 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/base.py @@ -0,0 +1,220 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import instance +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-appengine-admin', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class InstancesTransport(abc.ABC): + """Abstract transport class for Instances.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ) + + DEFAULT_HOST: str = 'appengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials is service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_instances: gapic_v1.method.wrap_method( + self.list_instances, + default_timeout=None, + client_info=client_info, + ), + self.get_instance: gapic_v1.method.wrap_method( + self.get_instance, + default_timeout=None, + client_info=client_info, + ), + self.delete_instance: gapic_v1.method.wrap_method( + self.delete_instance, + default_timeout=None, + client_info=client_info, + ), + self.debug_instance: gapic_v1.method.wrap_method( + self.debug_instance, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_instances(self) -> Callable[ + [appengine.ListInstancesRequest], + Union[ + appengine.ListInstancesResponse, + Awaitable[appengine.ListInstancesResponse] + ]]: + raise NotImplementedError() + + @property + def get_instance(self) -> Callable[ + [appengine.GetInstanceRequest], + Union[ + instance.Instance, + Awaitable[instance.Instance] + ]]: + raise NotImplementedError() + + @property + def delete_instance(self) -> Callable[ + [appengine.DeleteInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def debug_instance(self) -> Callable[ + [appengine.DebugInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'InstancesTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/grpc.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/grpc.py new file mode 100644 index 0000000..d46b857 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/grpc.py @@ -0,0 +1,377 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import instance +from google.longrunning import operations_pb2 # type: ignore +from .base import InstancesTransport, DEFAULT_CLIENT_INFO + + +class InstancesGrpcTransport(InstancesTransport): + """gRPC backend transport for Instances. + + Manages instances of a version. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_instances(self) -> Callable[ + [appengine.ListInstancesRequest], + appengine.ListInstancesResponse]: + r"""Return a callable for the list instances method over gRPC. + + Lists the instances of a version. + + Tip: To aggregate details about instances over time, see the + `Stackdriver Monitoring + API `__. + + Returns: + Callable[[~.ListInstancesRequest], + ~.ListInstancesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_instances' not in self._stubs: + self._stubs['list_instances'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Instances/ListInstances', + request_serializer=appengine.ListInstancesRequest.serialize, + response_deserializer=appengine.ListInstancesResponse.deserialize, + ) + return self._stubs['list_instances'] + + @property + def get_instance(self) -> Callable[ + [appengine.GetInstanceRequest], + instance.Instance]: + r"""Return a callable for the get instance method over gRPC. + + Gets instance information. + + Returns: + Callable[[~.GetInstanceRequest], + ~.Instance]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_instance' not in self._stubs: + self._stubs['get_instance'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Instances/GetInstance', + request_serializer=appengine.GetInstanceRequest.serialize, + response_deserializer=instance.Instance.deserialize, + ) + return self._stubs['get_instance'] + + @property + def delete_instance(self) -> Callable[ + [appengine.DeleteInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete instance method over gRPC. + + Stops a running instance. + + The instance might be automatically recreated based on the + scaling settings of the version. For more information, see "How + Instances are Managed" (`standard + environment `__ + \| `flexible + environment `__). + + To ensure that instances are not re-created and avoid getting + billed, you can stop all instances within the target version by + changing the serving status of the version to ``STOPPED`` with + the + ```apps.services.versions.patch`` `__ + method. + + Returns: + Callable[[~.DeleteInstanceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_instance' not in self._stubs: + self._stubs['delete_instance'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Instances/DeleteInstance', + request_serializer=appengine.DeleteInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_instance'] + + @property + def debug_instance(self) -> Callable[ + [appengine.DebugInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the debug instance method over gRPC. + + Enables debugging on a VM instance. This allows you + to use the SSH command to connect to the virtual machine + where the instance lives. While in "debug mode", the + instance continues to serve live traffic. You should + delete the instance when you are done debugging and then + allow the system to take over and determine if another + instance should be started. + + Only applicable for instances in App Engine flexible + environment. + + Returns: + Callable[[~.DebugInstanceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'debug_instance' not in self._stubs: + self._stubs['debug_instance'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Instances/DebugInstance', + request_serializer=appengine.DebugInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['debug_instance'] + + +__all__ = ( + 'InstancesGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/grpc_asyncio.py new file mode 100644 index 0000000..b695723 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/grpc_asyncio.py @@ -0,0 +1,381 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import instance +from google.longrunning import operations_pb2 # type: ignore +from .base import InstancesTransport, DEFAULT_CLIENT_INFO +from .grpc import InstancesGrpcTransport + + +class InstancesGrpcAsyncIOTransport(InstancesTransport): + """gRPC AsyncIO backend transport for Instances. + + Manages instances of a version. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_instances(self) -> Callable[ + [appengine.ListInstancesRequest], + Awaitable[appengine.ListInstancesResponse]]: + r"""Return a callable for the list instances method over gRPC. + + Lists the instances of a version. + + Tip: To aggregate details about instances over time, see the + `Stackdriver Monitoring + API `__. + + Returns: + Callable[[~.ListInstancesRequest], + Awaitable[~.ListInstancesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_instances' not in self._stubs: + self._stubs['list_instances'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Instances/ListInstances', + request_serializer=appengine.ListInstancesRequest.serialize, + response_deserializer=appengine.ListInstancesResponse.deserialize, + ) + return self._stubs['list_instances'] + + @property + def get_instance(self) -> Callable[ + [appengine.GetInstanceRequest], + Awaitable[instance.Instance]]: + r"""Return a callable for the get instance method over gRPC. + + Gets instance information. + + Returns: + Callable[[~.GetInstanceRequest], + Awaitable[~.Instance]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_instance' not in self._stubs: + self._stubs['get_instance'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Instances/GetInstance', + request_serializer=appengine.GetInstanceRequest.serialize, + response_deserializer=instance.Instance.deserialize, + ) + return self._stubs['get_instance'] + + @property + def delete_instance(self) -> Callable[ + [appengine.DeleteInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete instance method over gRPC. + + Stops a running instance. + + The instance might be automatically recreated based on the + scaling settings of the version. For more information, see "How + Instances are Managed" (`standard + environment `__ + \| `flexible + environment `__). + + To ensure that instances are not re-created and avoid getting + billed, you can stop all instances within the target version by + changing the serving status of the version to ``STOPPED`` with + the + ```apps.services.versions.patch`` `__ + method. + + Returns: + Callable[[~.DeleteInstanceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_instance' not in self._stubs: + self._stubs['delete_instance'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Instances/DeleteInstance', + request_serializer=appengine.DeleteInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_instance'] + + @property + def debug_instance(self) -> Callable[ + [appengine.DebugInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the debug instance method over gRPC. + + Enables debugging on a VM instance. This allows you + to use the SSH command to connect to the virtual machine + where the instance lives. While in "debug mode", the + instance continues to serve live traffic. You should + delete the instance when you are done debugging and then + allow the system to take over and determine if another + instance should be started. + + Only applicable for instances in App Engine flexible + environment. + + Returns: + Callable[[~.DebugInstanceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'debug_instance' not in self._stubs: + self._stubs['debug_instance'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Instances/DebugInstance', + request_serializer=appengine.DebugInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['debug_instance'] + + +__all__ = ( + 'InstancesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/__init__.py new file mode 100644 index 0000000..f4257d7 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ServicesClient +from .async_client import ServicesAsyncClient + +__all__ = ( + 'ServicesClient', + 'ServicesAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/async_client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/async_client.py new file mode 100644 index 0000000..95c9965 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/async_client.py @@ -0,0 +1,448 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation as gac_operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.appengine_admin_v1.services.services import pagers +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import network_settings +from google.cloud.appengine_admin_v1.types import operation as ga_operation +from google.cloud.appengine_admin_v1.types import service +from google.protobuf import empty_pb2 # type: ignore +from .transports.base import ServicesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ServicesGrpcAsyncIOTransport +from .client import ServicesClient + + +class ServicesAsyncClient: + """Manages services of an application.""" + + _client: ServicesClient + + DEFAULT_ENDPOINT = ServicesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ServicesClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(ServicesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ServicesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ServicesClient.common_folder_path) + parse_common_folder_path = staticmethod(ServicesClient.parse_common_folder_path) + common_organization_path = staticmethod(ServicesClient.common_organization_path) + parse_common_organization_path = staticmethod(ServicesClient.parse_common_organization_path) + common_project_path = staticmethod(ServicesClient.common_project_path) + parse_common_project_path = staticmethod(ServicesClient.parse_common_project_path) + common_location_path = staticmethod(ServicesClient.common_location_path) + parse_common_location_path = staticmethod(ServicesClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ServicesAsyncClient: The constructed client. + """ + return ServicesClient.from_service_account_info.__func__(ServicesAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ServicesAsyncClient: The constructed client. + """ + return ServicesClient.from_service_account_file.__func__(ServicesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ServicesTransport: + """Returns the transport used by the client instance. + + Returns: + ServicesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ServicesClient).get_transport_class, type(ServicesClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ServicesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the services client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ServicesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ServicesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_services(self, + request: appengine.ListServicesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServicesAsyncPager: + r"""Lists all the services in the application. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.ListServicesRequest`): + The request object. Request message for + `Services.ListServices`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.services.services.pagers.ListServicesAsyncPager: + Response message for Services.ListServices. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = appengine.ListServicesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_services, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListServicesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_service(self, + request: appengine.GetServiceRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Service: + r"""Gets the current configuration of the specified + service. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.GetServiceRequest`): + The request object. Request message for + `Services.GetService`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.Service: + A Service resource is a logical + component of an application that can + share state and communicate in a secure + fashion with other services. For + example, an application that handles + customer requests might include separate + services to handle tasks such as backend + data analysis or API requests from + mobile devices. Each service has a + collection of versions that define a + specific set of code used to implement + the functionality of that service. + + """ + # Create or coerce a protobuf request object. + request = appengine.GetServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_service(self, + request: appengine.UpdateServiceRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the configuration of the specified service. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.UpdateServiceRequest`): + The request object. Request message for + `Services.UpdateService`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Service` A Service resource is a logical component of an application that can share + state and communicate in a secure fashion with other + services. For example, an application that handles + customer requests might include separate services to + handle tasks such as backend data analysis or API + requests from mobile devices. Each service has a + collection of versions that define a specific set of + code used to implement the functionality of that + service. + + """ + # Create or coerce a protobuf request object. + request = appengine.UpdateServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + service.Service, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + async def delete_service(self, + request: appengine.DeleteServiceRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified service and all enclosed + versions. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.DeleteServiceRequest`): + The request object. Request message for + `Services.DeleteService`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + request = appengine.DeleteServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-appengine-admin", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ServicesAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/client.py new file mode 100644 index 0000000..6778b93 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/client.py @@ -0,0 +1,634 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation as gac_operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.appengine_admin_v1.services.services import pagers +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import network_settings +from google.cloud.appengine_admin_v1.types import operation as ga_operation +from google.cloud.appengine_admin_v1.types import service +from google.protobuf import empty_pb2 # type: ignore +from .transports.base import ServicesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ServicesGrpcTransport +from .transports.grpc_asyncio import ServicesGrpcAsyncIOTransport + + +class ServicesClientMeta(type): + """Metaclass for the Services client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[ServicesTransport]] + _transport_registry["grpc"] = ServicesGrpcTransport + _transport_registry["grpc_asyncio"] = ServicesGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ServicesTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class ServicesClient(metaclass=ServicesClientMeta): + """Manages services of an application.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "appengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ServicesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ServicesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ServicesTransport: + """Returns the transport used by the client instance. + + Returns: + ServicesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ServicesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the services client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ServicesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ServicesTransport): + # transport is a ServicesTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), + ) + + def list_services(self, + request: appengine.ListServicesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServicesPager: + r"""Lists all the services in the application. + + Args: + request (google.cloud.appengine_admin_v1.types.ListServicesRequest): + The request object. Request message for + `Services.ListServices`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.services.services.pagers.ListServicesPager: + Response message for Services.ListServices. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.ListServicesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.ListServicesRequest): + request = appengine.ListServicesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_services] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListServicesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_service(self, + request: appengine.GetServiceRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Service: + r"""Gets the current configuration of the specified + service. + + Args: + request (google.cloud.appengine_admin_v1.types.GetServiceRequest): + The request object. Request message for + `Services.GetService`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.Service: + A Service resource is a logical + component of an application that can + share state and communicate in a secure + fashion with other services. For + example, an application that handles + customer requests might include separate + services to handle tasks such as backend + data analysis or API requests from + mobile devices. Each service has a + collection of versions that define a + specific set of code used to implement + the functionality of that service. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.GetServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.GetServiceRequest): + request = appengine.GetServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_service(self, + request: appengine.UpdateServiceRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gac_operation.Operation: + r"""Updates the configuration of the specified service. + + Args: + request (google.cloud.appengine_admin_v1.types.UpdateServiceRequest): + The request object. Request message for + `Services.UpdateService`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Service` A Service resource is a logical component of an application that can share + state and communicate in a secure fashion with other + services. For example, an application that handles + customer requests might include separate services to + handle tasks such as backend data analysis or API + requests from mobile devices. Each service has a + collection of versions that define a specific set of + code used to implement the functionality of that + service. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.UpdateServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.UpdateServiceRequest): + request = appengine.UpdateServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = gac_operation.from_gapic( + response, + self._transport.operations_client, + service.Service, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + def delete_service(self, + request: appengine.DeleteServiceRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gac_operation.Operation: + r"""Deletes the specified service and all enclosed + versions. + + Args: + request (google.cloud.appengine_admin_v1.types.DeleteServiceRequest): + The request object. Request message for + `Services.DeleteService`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.DeleteServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.DeleteServiceRequest): + request = appengine.DeleteServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = gac_operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-appengine-admin", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ServicesClient", +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/pagers.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/pagers.py new file mode 100644 index 0000000..ce295d1 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/pagers.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import service + + +class ListServicesPager: + """A pager for iterating through ``list_services`` requests. + + This class thinly wraps an initial + :class:`google.cloud.appengine_admin_v1.types.ListServicesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``services`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListServices`` requests and continue to iterate + through the ``services`` field on the + corresponding responses. + + All the usual :class:`google.cloud.appengine_admin_v1.types.ListServicesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., appengine.ListServicesResponse], + request: appengine.ListServicesRequest, + response: appengine.ListServicesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.appengine_admin_v1.types.ListServicesRequest): + The initial request object. + response (google.cloud.appengine_admin_v1.types.ListServicesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = appengine.ListServicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[appengine.ListServicesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[service.Service]: + for page in self.pages: + yield from page.services + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServicesAsyncPager: + """A pager for iterating through ``list_services`` requests. + + This class thinly wraps an initial + :class:`google.cloud.appengine_admin_v1.types.ListServicesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``services`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListServices`` requests and continue to iterate + through the ``services`` field on the + corresponding responses. + + All the usual :class:`google.cloud.appengine_admin_v1.types.ListServicesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[appengine.ListServicesResponse]], + request: appengine.ListServicesRequest, + response: appengine.ListServicesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.appengine_admin_v1.types.ListServicesRequest): + The initial request object. + response (google.cloud.appengine_admin_v1.types.ListServicesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = appengine.ListServicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[appengine.ListServicesResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[service.Service]: + async def async_generator(): + async for page in self.pages: + for response in page.services: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/__init__.py new file mode 100644 index 0000000..919f871 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ServicesTransport +from .grpc import ServicesGrpcTransport +from .grpc_asyncio import ServicesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ServicesTransport]] +_transport_registry['grpc'] = ServicesGrpcTransport +_transport_registry['grpc_asyncio'] = ServicesGrpcAsyncIOTransport + +__all__ = ( + 'ServicesTransport', + 'ServicesGrpcTransport', + 'ServicesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/base.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/base.py new file mode 100644 index 0000000..b5523fc --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/base.py @@ -0,0 +1,220 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import service +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-appengine-admin', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class ServicesTransport(abc.ABC): + """Abstract transport class for Services.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ) + + DEFAULT_HOST: str = 'appengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials is service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_services: gapic_v1.method.wrap_method( + self.list_services, + default_timeout=None, + client_info=client_info, + ), + self.get_service: gapic_v1.method.wrap_method( + self.get_service, + default_timeout=None, + client_info=client_info, + ), + self.update_service: gapic_v1.method.wrap_method( + self.update_service, + default_timeout=None, + client_info=client_info, + ), + self.delete_service: gapic_v1.method.wrap_method( + self.delete_service, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_services(self) -> Callable[ + [appengine.ListServicesRequest], + Union[ + appengine.ListServicesResponse, + Awaitable[appengine.ListServicesResponse] + ]]: + raise NotImplementedError() + + @property + def get_service(self) -> Callable[ + [appengine.GetServiceRequest], + Union[ + service.Service, + Awaitable[service.Service] + ]]: + raise NotImplementedError() + + @property + def update_service(self) -> Callable[ + [appengine.UpdateServiceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_service(self) -> Callable[ + [appengine.DeleteServiceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'ServicesTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/grpc.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/grpc.py new file mode 100644 index 0000000..eac4202 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/grpc.py @@ -0,0 +1,352 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import service +from google.longrunning import operations_pb2 # type: ignore +from .base import ServicesTransport, DEFAULT_CLIENT_INFO + + +class ServicesGrpcTransport(ServicesTransport): + """gRPC backend transport for Services. + + Manages services of an application. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_services(self) -> Callable[ + [appengine.ListServicesRequest], + appengine.ListServicesResponse]: + r"""Return a callable for the list services method over gRPC. + + Lists all the services in the application. + + Returns: + Callable[[~.ListServicesRequest], + ~.ListServicesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_services' not in self._stubs: + self._stubs['list_services'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Services/ListServices', + request_serializer=appengine.ListServicesRequest.serialize, + response_deserializer=appengine.ListServicesResponse.deserialize, + ) + return self._stubs['list_services'] + + @property + def get_service(self) -> Callable[ + [appengine.GetServiceRequest], + service.Service]: + r"""Return a callable for the get service method over gRPC. + + Gets the current configuration of the specified + service. + + Returns: + Callable[[~.GetServiceRequest], + ~.Service]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_service' not in self._stubs: + self._stubs['get_service'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Services/GetService', + request_serializer=appengine.GetServiceRequest.serialize, + response_deserializer=service.Service.deserialize, + ) + return self._stubs['get_service'] + + @property + def update_service(self) -> Callable[ + [appengine.UpdateServiceRequest], + operations_pb2.Operation]: + r"""Return a callable for the update service method over gRPC. + + Updates the configuration of the specified service. + + Returns: + Callable[[~.UpdateServiceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_service' not in self._stubs: + self._stubs['update_service'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Services/UpdateService', + request_serializer=appengine.UpdateServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_service'] + + @property + def delete_service(self) -> Callable[ + [appengine.DeleteServiceRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete service method over gRPC. + + Deletes the specified service and all enclosed + versions. + + Returns: + Callable[[~.DeleteServiceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_service' not in self._stubs: + self._stubs['delete_service'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Services/DeleteService', + request_serializer=appengine.DeleteServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_service'] + + +__all__ = ( + 'ServicesGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/grpc_asyncio.py new file mode 100644 index 0000000..b54bff0 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/grpc_asyncio.py @@ -0,0 +1,356 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import service +from google.longrunning import operations_pb2 # type: ignore +from .base import ServicesTransport, DEFAULT_CLIENT_INFO +from .grpc import ServicesGrpcTransport + + +class ServicesGrpcAsyncIOTransport(ServicesTransport): + """gRPC AsyncIO backend transport for Services. + + Manages services of an application. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_services(self) -> Callable[ + [appengine.ListServicesRequest], + Awaitable[appengine.ListServicesResponse]]: + r"""Return a callable for the list services method over gRPC. + + Lists all the services in the application. + + Returns: + Callable[[~.ListServicesRequest], + Awaitable[~.ListServicesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_services' not in self._stubs: + self._stubs['list_services'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Services/ListServices', + request_serializer=appengine.ListServicesRequest.serialize, + response_deserializer=appengine.ListServicesResponse.deserialize, + ) + return self._stubs['list_services'] + + @property + def get_service(self) -> Callable[ + [appengine.GetServiceRequest], + Awaitable[service.Service]]: + r"""Return a callable for the get service method over gRPC. + + Gets the current configuration of the specified + service. + + Returns: + Callable[[~.GetServiceRequest], + Awaitable[~.Service]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_service' not in self._stubs: + self._stubs['get_service'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Services/GetService', + request_serializer=appengine.GetServiceRequest.serialize, + response_deserializer=service.Service.deserialize, + ) + return self._stubs['get_service'] + + @property + def update_service(self) -> Callable[ + [appengine.UpdateServiceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update service method over gRPC. + + Updates the configuration of the specified service. + + Returns: + Callable[[~.UpdateServiceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_service' not in self._stubs: + self._stubs['update_service'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Services/UpdateService', + request_serializer=appengine.UpdateServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_service'] + + @property + def delete_service(self) -> Callable[ + [appengine.DeleteServiceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete service method over gRPC. + + Deletes the specified service and all enclosed + versions. + + Returns: + Callable[[~.DeleteServiceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_service' not in self._stubs: + self._stubs['delete_service'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Services/DeleteService', + request_serializer=appengine.DeleteServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_service'] + + +__all__ = ( + 'ServicesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/__init__.py new file mode 100644 index 0000000..630246b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import VersionsClient +from .async_client import VersionsAsyncClient + +__all__ = ( + 'VersionsClient', + 'VersionsAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/async_client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/async_client.py new file mode 100644 index 0000000..07674aa --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/async_client.py @@ -0,0 +1,535 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation as gac_operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.appengine_admin_v1.services.versions import pagers +from google.cloud.appengine_admin_v1.types import app_yaml +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import deploy +from google.cloud.appengine_admin_v1.types import operation as ga_operation +from google.cloud.appengine_admin_v1.types import version +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport +from .client import VersionsClient + + +class VersionsAsyncClient: + """Manages versions of a service.""" + + _client: VersionsClient + + DEFAULT_ENDPOINT = VersionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = VersionsClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(VersionsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(VersionsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(VersionsClient.common_folder_path) + parse_common_folder_path = staticmethod(VersionsClient.parse_common_folder_path) + common_organization_path = staticmethod(VersionsClient.common_organization_path) + parse_common_organization_path = staticmethod(VersionsClient.parse_common_organization_path) + common_project_path = staticmethod(VersionsClient.common_project_path) + parse_common_project_path = staticmethod(VersionsClient.parse_common_project_path) + common_location_path = staticmethod(VersionsClient.common_location_path) + parse_common_location_path = staticmethod(VersionsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VersionsAsyncClient: The constructed client. + """ + return VersionsClient.from_service_account_info.__func__(VersionsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VersionsAsyncClient: The constructed client. + """ + return VersionsClient.from_service_account_file.__func__(VersionsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VersionsTransport: + """Returns the transport used by the client instance. + + Returns: + VersionsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(VersionsClient).get_transport_class, type(VersionsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, VersionsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the versions client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.VersionsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = VersionsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_versions(self, + request: appengine.ListVersionsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVersionsAsyncPager: + r"""Lists the versions of a service. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.ListVersionsRequest`): + The request object. Request message for + `Versions.ListVersions`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.services.versions.pagers.ListVersionsAsyncPager: + Response message for Versions.ListVersions. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = appengine.ListVersionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_versions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListVersionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_version(self, + request: appengine.GetVersionRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.Version: + r"""Gets the specified Version resource. By default, only a + ``BASIC_VIEW`` will be returned. Specify the ``FULL_VIEW`` + parameter to get the full resource. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.GetVersionRequest`): + The request object. Request message for + `Versions.GetVersion`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.Version: + A Version resource is a specific set + of source code and configuration files + that are deployed into a service. + + """ + # Create or coerce a protobuf request object. + request = appengine.GetVersionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_version(self, + request: appengine.CreateVersionRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deploys code and resource files to a new version. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.CreateVersionRequest`): + The request object. Request message for + `Versions.CreateVersion`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Version` A Version resource is a specific set of source code and configuration files + that are deployed into a service. + + """ + # Create or coerce a protobuf request object. + request = appengine.CreateVersionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + version.Version, + metadata_type=ga_operation.CreateVersionMetadataV1, + ) + + # Done; return the response. + return response + + async def update_version(self, + request: appengine.UpdateVersionRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the specified Version resource. You can specify the + following fields depending on the App Engine environment and + type of scaling that the version resource uses: + + **Standard environment** + + - ```instance_class`` `__ + + *automatic scaling* in the standard environment: + + - ```automatic_scaling.min_idle_instances`` `__ + - ```automatic_scaling.max_idle_instances`` `__ + - ```automaticScaling.standard_scheduler_settings.max_instances`` `__ + - ```automaticScaling.standard_scheduler_settings.min_instances`` `__ + - ```automaticScaling.standard_scheduler_settings.target_cpu_utilization`` `__ + - ```automaticScaling.standard_scheduler_settings.target_throughput_utilization`` `__ + + *basic scaling* or *manual scaling* in the standard environment: + + - ```serving_status`` `__ + - ```manual_scaling.instances`` `__ + + **Flexible environment** + + - ```serving_status`` `__ + + *automatic scaling* in the flexible environment: + + - ```automatic_scaling.min_total_instances`` `__ + - ```automatic_scaling.max_total_instances`` `__ + - ```automatic_scaling.cool_down_period_sec`` `__ + - ```automatic_scaling.cpu_utilization.target_utilization`` `__ + + *manual scaling* in the flexible environment: + + - ```manual_scaling.instances`` `__ + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.UpdateVersionRequest`): + The request object. Request message for + `Versions.UpdateVersion`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Version` A Version resource is a specific set of source code and configuration files + that are deployed into a service. + + """ + # Create or coerce a protobuf request object. + request = appengine.UpdateVersionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + version.Version, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + async def delete_version(self, + request: appengine.DeleteVersionRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes an existing Version resource. + + Args: + request (:class:`google.cloud.appengine_admin_v1.types.DeleteVersionRequest`): + The request object. Request message for + `Versions.DeleteVersion`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + request = appengine.DeleteVersionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-appengine-admin", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VersionsAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/client.py new file mode 100644 index 0000000..b5c1817 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/client.py @@ -0,0 +1,722 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation as gac_operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.appengine_admin_v1.services.versions import pagers +from google.cloud.appengine_admin_v1.types import app_yaml +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import deploy +from google.cloud.appengine_admin_v1.types import operation as ga_operation +from google.cloud.appengine_admin_v1.types import version +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import VersionsGrpcTransport +from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport + + +class VersionsClientMeta(type): + """Metaclass for the Versions client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] + _transport_registry["grpc"] = VersionsGrpcTransport + _transport_registry["grpc_asyncio"] = VersionsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[VersionsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class VersionsClient(metaclass=VersionsClientMeta): + """Manages versions of a service.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "appengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VersionsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VersionsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VersionsTransport: + """Returns the transport used by the client instance. + + Returns: + VersionsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, VersionsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the versions client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, VersionsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, VersionsTransport): + # transport is a VersionsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), + ) + + def list_versions(self, + request: appengine.ListVersionsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVersionsPager: + r"""Lists the versions of a service. + + Args: + request (google.cloud.appengine_admin_v1.types.ListVersionsRequest): + The request object. Request message for + `Versions.ListVersions`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.services.versions.pagers.ListVersionsPager: + Response message for Versions.ListVersions. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.ListVersionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.ListVersionsRequest): + request = appengine.ListVersionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_versions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListVersionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_version(self, + request: appengine.GetVersionRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.Version: + r"""Gets the specified Version resource. By default, only a + ``BASIC_VIEW`` will be returned. Specify the ``FULL_VIEW`` + parameter to get the full resource. + + Args: + request (google.cloud.appengine_admin_v1.types.GetVersionRequest): + The request object. Request message for + `Versions.GetVersion`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.appengine_admin_v1.types.Version: + A Version resource is a specific set + of source code and configuration files + that are deployed into a service. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.GetVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.GetVersionRequest): + request = appengine.GetVersionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_version(self, + request: appengine.CreateVersionRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gac_operation.Operation: + r"""Deploys code and resource files to a new version. + + Args: + request (google.cloud.appengine_admin_v1.types.CreateVersionRequest): + The request object. Request message for + `Versions.CreateVersion`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Version` A Version resource is a specific set of source code and configuration files + that are deployed into a service. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.CreateVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.CreateVersionRequest): + request = appengine.CreateVersionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = gac_operation.from_gapic( + response, + self._transport.operations_client, + version.Version, + metadata_type=ga_operation.CreateVersionMetadataV1, + ) + + # Done; return the response. + return response + + def update_version(self, + request: appengine.UpdateVersionRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gac_operation.Operation: + r"""Updates the specified Version resource. You can specify the + following fields depending on the App Engine environment and + type of scaling that the version resource uses: + + **Standard environment** + + - ```instance_class`` `__ + + *automatic scaling* in the standard environment: + + - ```automatic_scaling.min_idle_instances`` `__ + - ```automatic_scaling.max_idle_instances`` `__ + - ```automaticScaling.standard_scheduler_settings.max_instances`` `__ + - ```automaticScaling.standard_scheduler_settings.min_instances`` `__ + - ```automaticScaling.standard_scheduler_settings.target_cpu_utilization`` `__ + - ```automaticScaling.standard_scheduler_settings.target_throughput_utilization`` `__ + + *basic scaling* or *manual scaling* in the standard environment: + + - ```serving_status`` `__ + - ```manual_scaling.instances`` `__ + + **Flexible environment** + + - ```serving_status`` `__ + + *automatic scaling* in the flexible environment: + + - ```automatic_scaling.min_total_instances`` `__ + - ```automatic_scaling.max_total_instances`` `__ + - ```automatic_scaling.cool_down_period_sec`` `__ + - ```automatic_scaling.cpu_utilization.target_utilization`` `__ + + *manual scaling* in the flexible environment: + + - ```manual_scaling.instances`` `__ + + Args: + request (google.cloud.appengine_admin_v1.types.UpdateVersionRequest): + The request object. Request message for + `Versions.UpdateVersion`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Version` A Version resource is a specific set of source code and configuration files + that are deployed into a service. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.UpdateVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.UpdateVersionRequest): + request = appengine.UpdateVersionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = gac_operation.from_gapic( + response, + self._transport.operations_client, + version.Version, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + def delete_version(self, + request: appengine.DeleteVersionRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gac_operation.Operation: + r"""Deletes an existing Version resource. + + Args: + request (google.cloud.appengine_admin_v1.types.DeleteVersionRequest): + The request object. Request message for + `Versions.DeleteVersion`. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a appengine.DeleteVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, appengine.DeleteVersionRequest): + request = appengine.DeleteVersionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = gac_operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=ga_operation.OperationMetadataV1, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-appengine-admin", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VersionsClient", +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/pagers.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/pagers.py new file mode 100644 index 0000000..b32c743 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/pagers.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import version + + +class ListVersionsPager: + """A pager for iterating through ``list_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.appengine_admin_v1.types.ListVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListVersions`` requests and continue to iterate + through the ``versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.appengine_admin_v1.types.ListVersionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., appengine.ListVersionsResponse], + request: appengine.ListVersionsRequest, + response: appengine.ListVersionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.appengine_admin_v1.types.ListVersionsRequest): + The initial request object. + response (google.cloud.appengine_admin_v1.types.ListVersionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = appengine.ListVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[appengine.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, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[version.Version]: + for page in self.pages: + yield from page.versions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListVersionsAsyncPager: + """A pager for iterating through ``list_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.appengine_admin_v1.types.ListVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListVersions`` requests and continue to iterate + through the ``versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.appengine_admin_v1.types.ListVersionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[appengine.ListVersionsResponse]], + request: appengine.ListVersionsRequest, + response: appengine.ListVersionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.appengine_admin_v1.types.ListVersionsRequest): + The initial request object. + response (google.cloud.appengine_admin_v1.types.ListVersionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = appengine.ListVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[appengine.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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[version.Version]: + async def async_generator(): + async for page in self.pages: + for response in page.versions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/__init__.py new file mode 100644 index 0000000..dfb70ce --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import VersionsTransport +from .grpc import VersionsGrpcTransport +from .grpc_asyncio import VersionsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] +_transport_registry['grpc'] = VersionsGrpcTransport +_transport_registry['grpc_asyncio'] = VersionsGrpcAsyncIOTransport + +__all__ = ( + 'VersionsTransport', + 'VersionsGrpcTransport', + 'VersionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/base.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/base.py new file mode 100644 index 0000000..e907f17 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/base.py @@ -0,0 +1,234 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import version +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-appengine-admin', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class VersionsTransport(abc.ABC): + """Abstract transport class for Versions.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ) + + DEFAULT_HOST: str = 'appengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials is service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_versions: gapic_v1.method.wrap_method( + self.list_versions, + default_timeout=None, + client_info=client_info, + ), + self.get_version: gapic_v1.method.wrap_method( + self.get_version, + default_timeout=None, + client_info=client_info, + ), + self.create_version: gapic_v1.method.wrap_method( + self.create_version, + default_timeout=None, + client_info=client_info, + ), + self.update_version: gapic_v1.method.wrap_method( + self.update_version, + default_timeout=None, + client_info=client_info, + ), + self.delete_version: gapic_v1.method.wrap_method( + self.delete_version, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_versions(self) -> Callable[ + [appengine.ListVersionsRequest], + Union[ + appengine.ListVersionsResponse, + Awaitable[appengine.ListVersionsResponse] + ]]: + raise NotImplementedError() + + @property + def get_version(self) -> Callable[ + [appengine.GetVersionRequest], + Union[ + version.Version, + Awaitable[version.Version] + ]]: + raise NotImplementedError() + + @property + def create_version(self) -> Callable[ + [appengine.CreateVersionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_version(self) -> Callable[ + [appengine.UpdateVersionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_version(self) -> Callable[ + [appengine.DeleteVersionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'VersionsTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/grpc.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/grpc.py new file mode 100644 index 0000000..15e5f11 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/grpc.py @@ -0,0 +1,413 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import version +from google.longrunning import operations_pb2 # type: ignore +from .base import VersionsTransport, DEFAULT_CLIENT_INFO + + +class VersionsGrpcTransport(VersionsTransport): + """gRPC backend transport for Versions. + + Manages versions of a service. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_versions(self) -> Callable[ + [appengine.ListVersionsRequest], + appengine.ListVersionsResponse]: + r"""Return a callable for the list versions method over gRPC. + + Lists the versions of a service. + + Returns: + Callable[[~.ListVersionsRequest], + ~.ListVersionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_versions' not in self._stubs: + self._stubs['list_versions'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Versions/ListVersions', + request_serializer=appengine.ListVersionsRequest.serialize, + response_deserializer=appengine.ListVersionsResponse.deserialize, + ) + return self._stubs['list_versions'] + + @property + def get_version(self) -> Callable[ + [appengine.GetVersionRequest], + version.Version]: + r"""Return a callable for the get version method over gRPC. + + Gets the specified Version resource. By default, only a + ``BASIC_VIEW`` will be returned. Specify the ``FULL_VIEW`` + parameter to get the full resource. + + Returns: + Callable[[~.GetVersionRequest], + ~.Version]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_version' not in self._stubs: + self._stubs['get_version'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Versions/GetVersion', + request_serializer=appengine.GetVersionRequest.serialize, + response_deserializer=version.Version.deserialize, + ) + return self._stubs['get_version'] + + @property + def create_version(self) -> Callable[ + [appengine.CreateVersionRequest], + operations_pb2.Operation]: + r"""Return a callable for the create version method over gRPC. + + Deploys code and resource files to a new version. + + Returns: + Callable[[~.CreateVersionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_version' not in self._stubs: + self._stubs['create_version'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Versions/CreateVersion', + request_serializer=appengine.CreateVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_version'] + + @property + def update_version(self) -> Callable[ + [appengine.UpdateVersionRequest], + operations_pb2.Operation]: + r"""Return a callable for the update version method over gRPC. + + Updates the specified Version resource. You can specify the + following fields depending on the App Engine environment and + type of scaling that the version resource uses: + + **Standard environment** + + - ```instance_class`` `__ + + *automatic scaling* in the standard environment: + + - ```automatic_scaling.min_idle_instances`` `__ + - ```automatic_scaling.max_idle_instances`` `__ + - ```automaticScaling.standard_scheduler_settings.max_instances`` `__ + - ```automaticScaling.standard_scheduler_settings.min_instances`` `__ + - ```automaticScaling.standard_scheduler_settings.target_cpu_utilization`` `__ + - ```automaticScaling.standard_scheduler_settings.target_throughput_utilization`` `__ + + *basic scaling* or *manual scaling* in the standard environment: + + - ```serving_status`` `__ + - ```manual_scaling.instances`` `__ + + **Flexible environment** + + - ```serving_status`` `__ + + *automatic scaling* in the flexible environment: + + - ```automatic_scaling.min_total_instances`` `__ + - ```automatic_scaling.max_total_instances`` `__ + - ```automatic_scaling.cool_down_period_sec`` `__ + - ```automatic_scaling.cpu_utilization.target_utilization`` `__ + + *manual scaling* in the flexible environment: + + - ```manual_scaling.instances`` `__ + + Returns: + Callable[[~.UpdateVersionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_version' not in self._stubs: + self._stubs['update_version'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Versions/UpdateVersion', + request_serializer=appengine.UpdateVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_version'] + + @property + def delete_version(self) -> Callable[ + [appengine.DeleteVersionRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete version method over gRPC. + + Deletes an existing Version resource. + + Returns: + Callable[[~.DeleteVersionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_version' not in self._stubs: + self._stubs['delete_version'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Versions/DeleteVersion', + request_serializer=appengine.DeleteVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_version'] + + +__all__ = ( + 'VersionsGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/grpc_asyncio.py new file mode 100644 index 0000000..011f072 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/grpc_asyncio.py @@ -0,0 +1,417 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import version +from google.longrunning import operations_pb2 # type: ignore +from .base import VersionsTransport, DEFAULT_CLIENT_INFO +from .grpc import VersionsGrpcTransport + + +class VersionsGrpcAsyncIOTransport(VersionsTransport): + """gRPC AsyncIO backend transport for Versions. + + Manages versions of a service. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'appengine.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_versions(self) -> Callable[ + [appengine.ListVersionsRequest], + Awaitable[appengine.ListVersionsResponse]]: + r"""Return a callable for the list versions method over gRPC. + + Lists the versions of a service. + + Returns: + Callable[[~.ListVersionsRequest], + Awaitable[~.ListVersionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_versions' not in self._stubs: + self._stubs['list_versions'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Versions/ListVersions', + request_serializer=appengine.ListVersionsRequest.serialize, + response_deserializer=appengine.ListVersionsResponse.deserialize, + ) + return self._stubs['list_versions'] + + @property + def get_version(self) -> Callable[ + [appengine.GetVersionRequest], + Awaitable[version.Version]]: + r"""Return a callable for the get version method over gRPC. + + Gets the specified Version resource. By default, only a + ``BASIC_VIEW`` will be returned. Specify the ``FULL_VIEW`` + parameter to get the full resource. + + Returns: + Callable[[~.GetVersionRequest], + Awaitable[~.Version]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_version' not in self._stubs: + self._stubs['get_version'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Versions/GetVersion', + request_serializer=appengine.GetVersionRequest.serialize, + response_deserializer=version.Version.deserialize, + ) + return self._stubs['get_version'] + + @property + def create_version(self) -> Callable[ + [appengine.CreateVersionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create version method over gRPC. + + Deploys code and resource files to a new version. + + Returns: + Callable[[~.CreateVersionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_version' not in self._stubs: + self._stubs['create_version'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Versions/CreateVersion', + request_serializer=appengine.CreateVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_version'] + + @property + def update_version(self) -> Callable[ + [appengine.UpdateVersionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update version method over gRPC. + + Updates the specified Version resource. You can specify the + following fields depending on the App Engine environment and + type of scaling that the version resource uses: + + **Standard environment** + + - ```instance_class`` `__ + + *automatic scaling* in the standard environment: + + - ```automatic_scaling.min_idle_instances`` `__ + - ```automatic_scaling.max_idle_instances`` `__ + - ```automaticScaling.standard_scheduler_settings.max_instances`` `__ + - ```automaticScaling.standard_scheduler_settings.min_instances`` `__ + - ```automaticScaling.standard_scheduler_settings.target_cpu_utilization`` `__ + - ```automaticScaling.standard_scheduler_settings.target_throughput_utilization`` `__ + + *basic scaling* or *manual scaling* in the standard environment: + + - ```serving_status`` `__ + - ```manual_scaling.instances`` `__ + + **Flexible environment** + + - ```serving_status`` `__ + + *automatic scaling* in the flexible environment: + + - ```automatic_scaling.min_total_instances`` `__ + - ```automatic_scaling.max_total_instances`` `__ + - ```automatic_scaling.cool_down_period_sec`` `__ + - ```automatic_scaling.cpu_utilization.target_utilization`` `__ + + *manual scaling* in the flexible environment: + + - ```manual_scaling.instances`` `__ + + Returns: + Callable[[~.UpdateVersionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_version' not in self._stubs: + self._stubs['update_version'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Versions/UpdateVersion', + request_serializer=appengine.UpdateVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_version'] + + @property + def delete_version(self) -> Callable[ + [appengine.DeleteVersionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete version method over gRPC. + + Deletes an existing Version resource. + + Returns: + Callable[[~.DeleteVersionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_version' not in self._stubs: + self._stubs['delete_version'] = self.grpc_channel.unary_unary( + '/google.appengine.v1.Versions/DeleteVersion', + request_serializer=appengine.DeleteVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_version'] + + +__all__ = ( + 'VersionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/__init__.py new file mode 100644 index 0000000..2152b04 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/__init__.py @@ -0,0 +1,250 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .app_yaml import ( + ApiConfigHandler, + ApiEndpointHandler, + ErrorHandler, + HealthCheck, + Library, + LivenessCheck, + ReadinessCheck, + ScriptHandler, + StaticFilesHandler, + UrlMap, + AuthFailAction, + LoginRequirement, + SecurityLevel, +) +from .appengine import ( + BatchUpdateIngressRulesRequest, + BatchUpdateIngressRulesResponse, + CreateApplicationRequest, + CreateAuthorizedCertificateRequest, + CreateDomainMappingRequest, + CreateIngressRuleRequest, + CreateVersionRequest, + DebugInstanceRequest, + DeleteAuthorizedCertificateRequest, + DeleteDomainMappingRequest, + DeleteIngressRuleRequest, + DeleteInstanceRequest, + DeleteServiceRequest, + DeleteVersionRequest, + GetApplicationRequest, + GetAuthorizedCertificateRequest, + GetDomainMappingRequest, + GetIngressRuleRequest, + GetInstanceRequest, + GetServiceRequest, + GetVersionRequest, + ListAuthorizedCertificatesRequest, + ListAuthorizedCertificatesResponse, + ListAuthorizedDomainsRequest, + ListAuthorizedDomainsResponse, + ListDomainMappingsRequest, + ListDomainMappingsResponse, + ListIngressRulesRequest, + ListIngressRulesResponse, + ListInstancesRequest, + ListInstancesResponse, + ListServicesRequest, + ListServicesResponse, + ListVersionsRequest, + ListVersionsResponse, + RepairApplicationRequest, + UpdateApplicationRequest, + UpdateAuthorizedCertificateRequest, + UpdateDomainMappingRequest, + UpdateIngressRuleRequest, + UpdateServiceRequest, + UpdateVersionRequest, + AuthorizedCertificateView, + DomainOverrideStrategy, + VersionView, +) +from .application import ( + Application, + UrlDispatchRule, +) +from .audit_data import ( + AuditData, + CreateVersionMethod, + UpdateServiceMethod, +) +from .certificate import ( + AuthorizedCertificate, + CertificateRawData, + ManagedCertificate, + ManagementStatus, +) +from .deploy import ( + CloudBuildOptions, + ContainerInfo, + Deployment, + FileInfo, + ZipInfo, +) +from .domain import ( + AuthorizedDomain, +) +from .domain_mapping import ( + DomainMapping, + ResourceRecord, + SslSettings, +) +from .firewall import ( + FirewallRule, +) +from .instance import ( + Instance, +) +from .location import ( + LocationMetadata, +) +from .network_settings import ( + NetworkSettings, +) +from .operation import ( + CreateVersionMetadataV1, + OperationMetadataV1, +) +from .service import ( + Service, + TrafficSplit, +) +from .version import ( + AutomaticScaling, + BasicScaling, + CpuUtilization, + DiskUtilization, + EndpointsApiService, + Entrypoint, + ManualScaling, + Network, + NetworkUtilization, + RequestUtilization, + Resources, + StandardSchedulerSettings, + Version, + Volume, + VpcAccessConnector, + InboundServiceType, + ServingStatus, +) + +__all__ = ( + 'ApiConfigHandler', + 'ApiEndpointHandler', + 'ErrorHandler', + 'HealthCheck', + 'Library', + 'LivenessCheck', + 'ReadinessCheck', + 'ScriptHandler', + 'StaticFilesHandler', + 'UrlMap', + 'AuthFailAction', + 'LoginRequirement', + 'SecurityLevel', + 'BatchUpdateIngressRulesRequest', + 'BatchUpdateIngressRulesResponse', + 'CreateApplicationRequest', + 'CreateAuthorizedCertificateRequest', + 'CreateDomainMappingRequest', + 'CreateIngressRuleRequest', + 'CreateVersionRequest', + 'DebugInstanceRequest', + 'DeleteAuthorizedCertificateRequest', + 'DeleteDomainMappingRequest', + 'DeleteIngressRuleRequest', + 'DeleteInstanceRequest', + 'DeleteServiceRequest', + 'DeleteVersionRequest', + 'GetApplicationRequest', + 'GetAuthorizedCertificateRequest', + 'GetDomainMappingRequest', + 'GetIngressRuleRequest', + 'GetInstanceRequest', + 'GetServiceRequest', + 'GetVersionRequest', + 'ListAuthorizedCertificatesRequest', + 'ListAuthorizedCertificatesResponse', + 'ListAuthorizedDomainsRequest', + 'ListAuthorizedDomainsResponse', + 'ListDomainMappingsRequest', + 'ListDomainMappingsResponse', + 'ListIngressRulesRequest', + 'ListIngressRulesResponse', + 'ListInstancesRequest', + 'ListInstancesResponse', + 'ListServicesRequest', + 'ListServicesResponse', + 'ListVersionsRequest', + 'ListVersionsResponse', + 'RepairApplicationRequest', + 'UpdateApplicationRequest', + 'UpdateAuthorizedCertificateRequest', + 'UpdateDomainMappingRequest', + 'UpdateIngressRuleRequest', + 'UpdateServiceRequest', + 'UpdateVersionRequest', + 'AuthorizedCertificateView', + 'DomainOverrideStrategy', + 'VersionView', + 'Application', + 'UrlDispatchRule', + 'AuditData', + 'CreateVersionMethod', + 'UpdateServiceMethod', + 'AuthorizedCertificate', + 'CertificateRawData', + 'ManagedCertificate', + 'ManagementStatus', + 'CloudBuildOptions', + 'ContainerInfo', + 'Deployment', + 'FileInfo', + 'ZipInfo', + 'AuthorizedDomain', + 'DomainMapping', + 'ResourceRecord', + 'SslSettings', + 'FirewallRule', + 'Instance', + 'LocationMetadata', + 'NetworkSettings', + 'CreateVersionMetadataV1', + 'OperationMetadataV1', + 'Service', + 'TrafficSplit', + 'AutomaticScaling', + 'BasicScaling', + 'CpuUtilization', + 'DiskUtilization', + 'EndpointsApiService', + 'Entrypoint', + 'ManualScaling', + 'Network', + 'NetworkUtilization', + 'RequestUtilization', + 'Resources', + 'StandardSchedulerSettings', + 'Version', + 'Volume', + 'VpcAccessConnector', + 'InboundServiceType', + 'ServingStatus', +) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/app_yaml.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/app_yaml.py new file mode 100644 index 0000000..a5b49e2 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/app_yaml.py @@ -0,0 +1,539 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.appengine.v1', + manifest={ + 'AuthFailAction', + 'LoginRequirement', + 'SecurityLevel', + 'ApiConfigHandler', + 'ErrorHandler', + 'UrlMap', + 'StaticFilesHandler', + 'ScriptHandler', + 'ApiEndpointHandler', + 'HealthCheck', + 'ReadinessCheck', + 'LivenessCheck', + 'Library', + }, +) + + +class AuthFailAction(proto.Enum): + r"""Actions to take when the user is not logged in.""" + AUTH_FAIL_ACTION_UNSPECIFIED = 0 + AUTH_FAIL_ACTION_REDIRECT = 1 + AUTH_FAIL_ACTION_UNAUTHORIZED = 2 + + +class LoginRequirement(proto.Enum): + r"""Methods to restrict access to a URL based on login status.""" + LOGIN_UNSPECIFIED = 0 + LOGIN_OPTIONAL = 1 + LOGIN_ADMIN = 2 + LOGIN_REQUIRED = 3 + + +class SecurityLevel(proto.Enum): + r"""Methods to enforce security (HTTPS) on a URL.""" + _pb_options = {'allow_alias': True} + SECURE_UNSPECIFIED = 0 + SECURE_DEFAULT = 0 + SECURE_NEVER = 1 + SECURE_OPTIONAL = 2 + SECURE_ALWAYS = 3 + + +class ApiConfigHandler(proto.Message): + r"""`Google Cloud + Endpoints `__ + configuration for API handlers. + + Attributes: + auth_fail_action (google.cloud.appengine_admin_v1.types.AuthFailAction): + Action to take when users access resources that require + authentication. Defaults to ``redirect``. + login (google.cloud.appengine_admin_v1.types.LoginRequirement): + Level of login required to access this resource. Defaults to + ``optional``. + script (str): + Path to the script from the application root + directory. + security_level (google.cloud.appengine_admin_v1.types.SecurityLevel): + Security (HTTPS) enforcement for this URL. + url (str): + URL to serve the endpoint at. + """ + + auth_fail_action = proto.Field( + proto.ENUM, + number=1, + enum='AuthFailAction', + ) + login = proto.Field( + proto.ENUM, + number=2, + enum='LoginRequirement', + ) + script = proto.Field( + proto.STRING, + number=3, + ) + security_level = proto.Field( + proto.ENUM, + number=4, + enum='SecurityLevel', + ) + url = proto.Field( + proto.STRING, + number=5, + ) + + +class ErrorHandler(proto.Message): + r"""Custom static error page to be served when an error occurs. + Attributes: + error_code (google.cloud.appengine_admin_v1.types.ErrorHandler.ErrorCode): + Error condition this handler applies to. + static_file (str): + Static file content to be served for this + error. + mime_type (str): + MIME type of file. Defaults to ``text/html``. + """ + class ErrorCode(proto.Enum): + r"""Error codes.""" + _pb_options = {'allow_alias': True} + ERROR_CODE_UNSPECIFIED = 0 + ERROR_CODE_DEFAULT = 0 + ERROR_CODE_OVER_QUOTA = 1 + ERROR_CODE_DOS_API_DENIAL = 2 + ERROR_CODE_TIMEOUT = 3 + + error_code = proto.Field( + proto.ENUM, + number=1, + enum=ErrorCode, + ) + static_file = proto.Field( + proto.STRING, + number=2, + ) + mime_type = proto.Field( + proto.STRING, + number=3, + ) + + +class UrlMap(proto.Message): + r"""URL pattern and description of how the URL should be handled. + App Engine can handle URLs by executing application code or by + serving static files uploaded with the version, such as images, + CSS, or JavaScript. + + Attributes: + url_regex (str): + URL prefix. Uses regular expression syntax, + which means regexp special characters must be + escaped, but should not contain groupings. All + URLs that begin with this prefix are handled by + this handler, using the portion of the URL after + the prefix as part of the file path. + static_files (google.cloud.appengine_admin_v1.types.StaticFilesHandler): + Returns the contents of a file, such as an + image, as the response. + script (google.cloud.appengine_admin_v1.types.ScriptHandler): + Executes a script to handle the requests that match this URL + pattern. Only the ``auto`` value is supported for Node.js in + the App Engine standard environment, for example + ``"script": "auto"``. + api_endpoint (google.cloud.appengine_admin_v1.types.ApiEndpointHandler): + Uses API Endpoints to handle requests. + security_level (google.cloud.appengine_admin_v1.types.SecurityLevel): + Security (HTTPS) enforcement for this URL. + login (google.cloud.appengine_admin_v1.types.LoginRequirement): + Level of login required to access this + resource. Not supported for Node.js in the App + Engine standard environment. + auth_fail_action (google.cloud.appengine_admin_v1.types.AuthFailAction): + Action to take when users access resources that require + authentication. Defaults to ``redirect``. + redirect_http_response_code (google.cloud.appengine_admin_v1.types.UrlMap.RedirectHttpResponseCode): + ``30x`` code to use when performing redirects for the + ``secure`` field. Defaults to ``302``. + """ + class RedirectHttpResponseCode(proto.Enum): + r"""Redirect codes.""" + REDIRECT_HTTP_RESPONSE_CODE_UNSPECIFIED = 0 + REDIRECT_HTTP_RESPONSE_CODE_301 = 1 + REDIRECT_HTTP_RESPONSE_CODE_302 = 2 + REDIRECT_HTTP_RESPONSE_CODE_303 = 3 + REDIRECT_HTTP_RESPONSE_CODE_307 = 4 + + url_regex = proto.Field( + proto.STRING, + number=1, + ) + static_files = proto.Field( + proto.MESSAGE, + number=2, + oneof='handler_type', + message='StaticFilesHandler', + ) + script = proto.Field( + proto.MESSAGE, + number=3, + oneof='handler_type', + message='ScriptHandler', + ) + api_endpoint = proto.Field( + proto.MESSAGE, + number=4, + oneof='handler_type', + message='ApiEndpointHandler', + ) + security_level = proto.Field( + proto.ENUM, + number=5, + enum='SecurityLevel', + ) + login = proto.Field( + proto.ENUM, + number=6, + enum='LoginRequirement', + ) + auth_fail_action = proto.Field( + proto.ENUM, + number=7, + enum='AuthFailAction', + ) + redirect_http_response_code = proto.Field( + proto.ENUM, + number=8, + enum=RedirectHttpResponseCode, + ) + + +class StaticFilesHandler(proto.Message): + r"""Files served directly to the user for a given URL, such as + images, CSS stylesheets, or JavaScript source files. Static file + handlers describe which files in the application directory are + static files, and which URLs serve them. + + Attributes: + path (str): + Path to the static files matched by the URL + pattern, from the application root directory. + The path can refer to text matched in groupings + in the URL pattern. + upload_path_regex (str): + Regular expression that matches the file + paths for all files that should be referenced by + this handler. + http_headers (Sequence[google.cloud.appengine_admin_v1.types.StaticFilesHandler.HttpHeadersEntry]): + HTTP headers to use for all responses from + these URLs. + mime_type (str): + MIME type used to serve all files served by + this handler. + Defaults to file-specific MIME types, which are + derived from each file's filename extension. + expiration (google.protobuf.duration_pb2.Duration): + Time a static file served by this handler + should be cached by web proxies and browsers. + require_matching_file (bool): + Whether this handler should match the request + if the file referenced by the handler does not + exist. + application_readable (bool): + Whether files should also be uploaded as code + data. By default, files declared in static file + handlers are uploaded as static data and are + only served to end users; they cannot be read by + the application. If enabled, uploads are charged + against both your code and static data storage + resource quotas. + """ + + path = proto.Field( + proto.STRING, + number=1, + ) + upload_path_regex = proto.Field( + proto.STRING, + number=2, + ) + http_headers = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + mime_type = proto.Field( + proto.STRING, + number=4, + ) + expiration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + require_matching_file = proto.Field( + proto.BOOL, + number=6, + ) + application_readable = proto.Field( + proto.BOOL, + number=7, + ) + + +class ScriptHandler(proto.Message): + r"""Executes a script to handle the request that matches the URL + pattern. + + Attributes: + script_path (str): + Path to the script from the application root + directory. + """ + + script_path = proto.Field( + proto.STRING, + number=1, + ) + + +class ApiEndpointHandler(proto.Message): + r"""Uses Google Cloud Endpoints to handle requests. + Attributes: + script_path (str): + Path to the script from the application root + directory. + """ + + script_path = proto.Field( + proto.STRING, + number=1, + ) + + +class HealthCheck(proto.Message): + r"""Health checking configuration for VM instances. Unhealthy + instances are killed and replaced with new instances. Only + applicable for instances in App Engine flexible environment. + + Attributes: + disable_health_check (bool): + Whether to explicitly disable health checks + for this instance. + host (str): + Host header to send when performing an HTTP + health check. Example: "myapp.appspot.com". + healthy_threshold (int): + Number of consecutive successful health + checks required before receiving traffic. + unhealthy_threshold (int): + Number of consecutive failed health checks + required before removing traffic. + restart_threshold (int): + Number of consecutive failed health checks + required before an instance is restarted. + check_interval (google.protobuf.duration_pb2.Duration): + Interval between health checks. + timeout (google.protobuf.duration_pb2.Duration): + Time before the health check is considered + failed. + """ + + disable_health_check = proto.Field( + proto.BOOL, + number=1, + ) + host = proto.Field( + proto.STRING, + number=2, + ) + healthy_threshold = proto.Field( + proto.UINT32, + number=3, + ) + unhealthy_threshold = proto.Field( + proto.UINT32, + number=4, + ) + restart_threshold = proto.Field( + proto.UINT32, + number=5, + ) + check_interval = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + timeout = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + + +class ReadinessCheck(proto.Message): + r"""Readiness checking configuration for VM instances. Unhealthy + instances are removed from traffic rotation. + + Attributes: + path (str): + The request path. + host (str): + Host header to send when performing a HTTP + Readiness check. Example: "myapp.appspot.com". + failure_threshold (int): + Number of consecutive failed checks required + before removing traffic. + success_threshold (int): + Number of consecutive successful checks + required before receiving traffic. + check_interval (google.protobuf.duration_pb2.Duration): + Interval between health checks. + timeout (google.protobuf.duration_pb2.Duration): + Time before the check is considered failed. + app_start_timeout (google.protobuf.duration_pb2.Duration): + A maximum time limit on application + initialization, measured from moment the + application successfully replies to a + healthcheck until it is ready to serve traffic. + """ + + path = proto.Field( + proto.STRING, + number=1, + ) + host = proto.Field( + proto.STRING, + number=2, + ) + failure_threshold = proto.Field( + proto.UINT32, + number=3, + ) + success_threshold = proto.Field( + proto.UINT32, + number=4, + ) + check_interval = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + timeout = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + app_start_timeout = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + + +class LivenessCheck(proto.Message): + r"""Health checking configuration for VM instances. Unhealthy + instances are killed and replaced with new instances. + + Attributes: + path (str): + The request path. + host (str): + Host header to send when performing a HTTP + Liveness check. Example: "myapp.appspot.com". + failure_threshold (int): + Number of consecutive failed checks required + before considering the VM unhealthy. + success_threshold (int): + Number of consecutive successful checks + required before considering the VM healthy. + check_interval (google.protobuf.duration_pb2.Duration): + Interval between health checks. + timeout (google.protobuf.duration_pb2.Duration): + Time before the check is considered failed. + initial_delay (google.protobuf.duration_pb2.Duration): + The initial delay before starting to execute + the checks. + """ + + path = proto.Field( + proto.STRING, + number=1, + ) + host = proto.Field( + proto.STRING, + number=2, + ) + failure_threshold = proto.Field( + proto.UINT32, + number=3, + ) + success_threshold = proto.Field( + proto.UINT32, + number=4, + ) + check_interval = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + timeout = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + initial_delay = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + + +class Library(proto.Message): + r"""Third-party Python runtime library that is required by the + application. + + Attributes: + name (str): + Name of the library. Example: "django". + version (str): + Version of the library to select, or + "latest". + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + version = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/appengine.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/appengine.py new file mode 100644 index 0000000..815b78d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/appengine.py @@ -0,0 +1,1103 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.appengine_admin_v1.types import application as ga_application +from google.cloud.appengine_admin_v1.types import certificate as ga_certificate +from google.cloud.appengine_admin_v1.types import domain +from google.cloud.appengine_admin_v1.types import domain_mapping as ga_domain_mapping +from google.cloud.appengine_admin_v1.types import firewall +from google.cloud.appengine_admin_v1.types import instance +from google.cloud.appengine_admin_v1.types import service as ga_service +from google.cloud.appengine_admin_v1.types import version as ga_version +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.appengine.v1', + manifest={ + 'VersionView', + 'AuthorizedCertificateView', + 'DomainOverrideStrategy', + 'GetApplicationRequest', + 'CreateApplicationRequest', + 'UpdateApplicationRequest', + 'RepairApplicationRequest', + 'ListServicesRequest', + 'ListServicesResponse', + 'GetServiceRequest', + 'UpdateServiceRequest', + 'DeleteServiceRequest', + 'ListVersionsRequest', + 'ListVersionsResponse', + 'GetVersionRequest', + 'CreateVersionRequest', + 'UpdateVersionRequest', + 'DeleteVersionRequest', + 'ListInstancesRequest', + 'ListInstancesResponse', + 'GetInstanceRequest', + 'DeleteInstanceRequest', + 'DebugInstanceRequest', + 'ListIngressRulesRequest', + 'ListIngressRulesResponse', + 'BatchUpdateIngressRulesRequest', + 'BatchUpdateIngressRulesResponse', + 'CreateIngressRuleRequest', + 'GetIngressRuleRequest', + 'UpdateIngressRuleRequest', + 'DeleteIngressRuleRequest', + 'ListAuthorizedDomainsRequest', + 'ListAuthorizedDomainsResponse', + 'ListAuthorizedCertificatesRequest', + 'ListAuthorizedCertificatesResponse', + 'GetAuthorizedCertificateRequest', + 'CreateAuthorizedCertificateRequest', + 'UpdateAuthorizedCertificateRequest', + 'DeleteAuthorizedCertificateRequest', + 'ListDomainMappingsRequest', + 'ListDomainMappingsResponse', + 'GetDomainMappingRequest', + 'CreateDomainMappingRequest', + 'UpdateDomainMappingRequest', + 'DeleteDomainMappingRequest', + }, +) + + +class VersionView(proto.Enum): + r"""Fields that should be returned when + [Version][google.appengine.v1.Version] resources are retrieved. + """ + BASIC = 0 + FULL = 1 + + +class AuthorizedCertificateView(proto.Enum): + r"""Fields that should be returned when an AuthorizedCertificate + resource is retrieved. + """ + BASIC_CERTIFICATE = 0 + FULL_CERTIFICATE = 1 + + +class DomainOverrideStrategy(proto.Enum): + r"""Override strategy for mutating an existing mapping.""" + UNSPECIFIED_DOMAIN_OVERRIDE_STRATEGY = 0 + STRICT = 1 + OVERRIDE = 2 + + +class GetApplicationRequest(proto.Message): + r"""Request message for ``Applications.GetApplication``. + Attributes: + name (str): + Name of the Application resource to get. Example: + ``apps/myapp``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateApplicationRequest(proto.Message): + r"""Request message for ``Applications.CreateApplication``. + Attributes: + application (google.cloud.appengine_admin_v1.types.Application): + Application configuration. + """ + + application = proto.Field( + proto.MESSAGE, + number=2, + message=ga_application.Application, + ) + + +class UpdateApplicationRequest(proto.Message): + r"""Request message for ``Applications.UpdateApplication``. + Attributes: + name (str): + Name of the Application resource to update. Example: + ``apps/myapp``. + application (google.cloud.appengine_admin_v1.types.Application): + An Application containing the updated + resource. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Standard field mask for the set of fields to + be updated. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + application = proto.Field( + proto.MESSAGE, + number=2, + message=ga_application.Application, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class RepairApplicationRequest(proto.Message): + r"""Request message for 'Applications.RepairApplication'. + Attributes: + name (str): + Name of the application to repair. Example: ``apps/myapp`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListServicesRequest(proto.Message): + r"""Request message for ``Services.ListServices``. + Attributes: + parent (str): + Name of the parent Application resource. Example: + ``apps/myapp``. + page_size (int): + Maximum results to return per page. + page_token (str): + Continuation token for fetching the next page + of results. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListServicesResponse(proto.Message): + r"""Response message for ``Services.ListServices``. + Attributes: + services (Sequence[google.cloud.appengine_admin_v1.types.Service]): + The services belonging to the requested + application. + next_page_token (str): + Continuation token for fetching the next page + of results. + """ + + @property + def raw_page(self): + return self + + services = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ga_service.Service, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetServiceRequest(proto.Message): + r"""Request message for ``Services.GetService``. + Attributes: + name (str): + Name of the resource requested. Example: + ``apps/myapp/services/default``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateServiceRequest(proto.Message): + r"""Request message for ``Services.UpdateService``. + Attributes: + name (str): + Name of the resource to update. Example: + ``apps/myapp/services/default``. + service (google.cloud.appengine_admin_v1.types.Service): + A Service resource containing the updated + service. Only fields set in the field mask will + be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Standard field mask for the set of fields to + be updated. + migrate_traffic (bool): + Set to ``true`` to gradually shift traffic to one or more + versions that you specify. By default, traffic is shifted + immediately. For gradual traffic migration, the target + versions must be located within instances that are + configured for both `warmup + requests `__ + and `automatic + scaling `__. + You must specify the + ```shardBy`` `__ + field in the Service resource. Gradual traffic migration is + not supported in the App Engine flexible environment. For + examples, see `Migrating and Splitting + Traffic `__. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + service = proto.Field( + proto.MESSAGE, + number=2, + message=ga_service.Service, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + migrate_traffic = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteServiceRequest(proto.Message): + r"""Request message for ``Services.DeleteService``. + Attributes: + name (str): + Name of the resource requested. Example: + ``apps/myapp/services/default``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListVersionsRequest(proto.Message): + r"""Request message for ``Versions.ListVersions``. + Attributes: + parent (str): + Name of the parent Service resource. Example: + ``apps/myapp/services/default``. + view (google.cloud.appengine_admin_v1.types.VersionView): + Controls the set of fields returned in the ``List`` + response. + page_size (int): + Maximum results to return per page. + page_token (str): + Continuation token for fetching the next page + of results. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + view = proto.Field( + proto.ENUM, + number=2, + enum='VersionView', + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListVersionsResponse(proto.Message): + r"""Response message for ``Versions.ListVersions``. + Attributes: + versions (Sequence[google.cloud.appengine_admin_v1.types.Version]): + The versions belonging to the requested + service. + next_page_token (str): + Continuation token for fetching the next page + of results. + """ + + @property + def raw_page(self): + return self + + versions = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ga_version.Version, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetVersionRequest(proto.Message): + r"""Request message for ``Versions.GetVersion``. + Attributes: + name (str): + Name of the resource requested. Example: + ``apps/myapp/services/default/versions/v1``. + view (google.cloud.appengine_admin_v1.types.VersionView): + Controls the set of fields returned in the ``Get`` response. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + view = proto.Field( + proto.ENUM, + number=2, + enum='VersionView', + ) + + +class CreateVersionRequest(proto.Message): + r"""Request message for ``Versions.CreateVersion``. + Attributes: + parent (str): + Name of the parent resource to create this version under. + Example: ``apps/myapp/services/default``. + version (google.cloud.appengine_admin_v1.types.Version): + Application deployment configuration. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + version = proto.Field( + proto.MESSAGE, + number=2, + message=ga_version.Version, + ) + + +class UpdateVersionRequest(proto.Message): + r"""Request message for ``Versions.UpdateVersion``. + Attributes: + name (str): + Name of the resource to update. Example: + ``apps/myapp/services/default/versions/1``. + version (google.cloud.appengine_admin_v1.types.Version): + A Version containing the updated resource. + Only fields set in the field mask will be + updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Standard field mask for the set of fields to + be updated. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + version = proto.Field( + proto.MESSAGE, + number=2, + message=ga_version.Version, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteVersionRequest(proto.Message): + r"""Request message for ``Versions.DeleteVersion``. + Attributes: + name (str): + Name of the resource requested. Example: + ``apps/myapp/services/default/versions/v1``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListInstancesRequest(proto.Message): + r"""Request message for ``Instances.ListInstances``. + Attributes: + parent (str): + Name of the parent Version resource. Example: + ``apps/myapp/services/default/versions/v1``. + page_size (int): + Maximum results to return per page. + page_token (str): + Continuation token for fetching the next page + of results. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListInstancesResponse(proto.Message): + r"""Response message for ``Instances.ListInstances``. + Attributes: + instances (Sequence[google.cloud.appengine_admin_v1.types.Instance]): + The instances belonging to the requested + version. + next_page_token (str): + Continuation token for fetching the next page + of results. + """ + + @property + def raw_page(self): + return self + + instances = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=instance.Instance, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetInstanceRequest(proto.Message): + r"""Request message for ``Instances.GetInstance``. + Attributes: + name (str): + Name of the resource requested. Example: + ``apps/myapp/services/default/versions/v1/instances/instance-1``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteInstanceRequest(proto.Message): + r"""Request message for ``Instances.DeleteInstance``. + Attributes: + name (str): + Name of the resource requested. Example: + ``apps/myapp/services/default/versions/v1/instances/instance-1``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class DebugInstanceRequest(proto.Message): + r"""Request message for ``Instances.DebugInstance``. + Attributes: + name (str): + Name of the resource requested. Example: + ``apps/myapp/services/default/versions/v1/instances/instance-1``. + ssh_key (str): + Public SSH key to add to the instance. Examples: + + - ``[USERNAME]:ssh-rsa [KEY_VALUE] [USERNAME]`` + - ``[USERNAME]:ssh-rsa [KEY_VALUE] google-ssh {"userName":"[USERNAME]","expireOn":"[EXPIRE_TIME]"}`` + + For more information, see `Adding and Removing SSH + Keys `__. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + ssh_key = proto.Field( + proto.STRING, + number=2, + ) + + +class ListIngressRulesRequest(proto.Message): + r"""Request message for ``Firewall.ListIngressRules``. + Attributes: + parent (str): + Name of the Firewall collection to retrieve. Example: + ``apps/myapp/firewall/ingressRules``. + page_size (int): + Maximum results to return per page. + page_token (str): + Continuation token for fetching the next page + of results. + matching_address (str): + A valid IP Address. If set, only rules + matching this address will be returned. The + first returned rule will be the rule that fires + on requests from this IP. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + matching_address = proto.Field( + proto.STRING, + number=4, + ) + + +class ListIngressRulesResponse(proto.Message): + r"""Response message for ``Firewall.ListIngressRules``. + Attributes: + ingress_rules (Sequence[google.cloud.appengine_admin_v1.types.FirewallRule]): + The ingress FirewallRules for this + application. + next_page_token (str): + Continuation token for fetching the next page + of results. + """ + + @property + def raw_page(self): + return self + + ingress_rules = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=firewall.FirewallRule, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class BatchUpdateIngressRulesRequest(proto.Message): + r"""Request message for ``Firewall.BatchUpdateIngressRules``. + Attributes: + name (str): + Name of the Firewall collection to set. Example: + ``apps/myapp/firewall/ingressRules``. + ingress_rules (Sequence[google.cloud.appengine_admin_v1.types.FirewallRule]): + A list of FirewallRules to replace the + existing set. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + ingress_rules = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=firewall.FirewallRule, + ) + + +class BatchUpdateIngressRulesResponse(proto.Message): + r"""Response message for ``Firewall.UpdateAllIngressRules``. + Attributes: + ingress_rules (Sequence[google.cloud.appengine_admin_v1.types.FirewallRule]): + The full list of ingress FirewallRules for + this application. + """ + + ingress_rules = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=firewall.FirewallRule, + ) + + +class CreateIngressRuleRequest(proto.Message): + r"""Request message for ``Firewall.CreateIngressRule``. + Attributes: + parent (str): + Name of the parent Firewall collection in which to create a + new rule. Example: ``apps/myapp/firewall/ingressRules``. + rule (google.cloud.appengine_admin_v1.types.FirewallRule): + A FirewallRule containing the new resource. + The user may optionally provide a position at + which the new rule will be placed. The positions + define a sequential list starting at 1. If a + rule already exists at the given position, rules + greater than the provided position will be moved + forward by one. + + If no position is provided, the server will + place the rule as the second to last rule in the + sequence before the required default allow-all + or deny-all rule. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + rule = proto.Field( + proto.MESSAGE, + number=2, + message=firewall.FirewallRule, + ) + + +class GetIngressRuleRequest(proto.Message): + r"""Request message for ``Firewall.GetIngressRule``. + Attributes: + name (str): + Name of the Firewall resource to retrieve. Example: + ``apps/myapp/firewall/ingressRules/100``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateIngressRuleRequest(proto.Message): + r"""Request message for ``Firewall.UpdateIngressRule``. + Attributes: + name (str): + Name of the Firewall resource to update. Example: + ``apps/myapp/firewall/ingressRules/100``. + rule (google.cloud.appengine_admin_v1.types.FirewallRule): + A FirewallRule containing the updated + resource + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Standard field mask for the set of fields to + be updated. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + rule = proto.Field( + proto.MESSAGE, + number=2, + message=firewall.FirewallRule, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteIngressRuleRequest(proto.Message): + r"""Request message for ``Firewall.DeleteIngressRule``. + Attributes: + name (str): + Name of the Firewall resource to delete. Example: + ``apps/myapp/firewall/ingressRules/100``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAuthorizedDomainsRequest(proto.Message): + r"""Request message for ``AuthorizedDomains.ListAuthorizedDomains``. + Attributes: + parent (str): + Name of the parent Application resource. Example: + ``apps/myapp``. + page_size (int): + Maximum results to return per page. + page_token (str): + Continuation token for fetching the next page + of results. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAuthorizedDomainsResponse(proto.Message): + r"""Response message for ``AuthorizedDomains.ListAuthorizedDomains``. + Attributes: + domains (Sequence[google.cloud.appengine_admin_v1.types.AuthorizedDomain]): + The authorized domains belonging to the user. + next_page_token (str): + Continuation token for fetching the next page + of results. + """ + + @property + def raw_page(self): + return self + + domains = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=domain.AuthorizedDomain, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ListAuthorizedCertificatesRequest(proto.Message): + r"""Request message for + ``AuthorizedCertificates.ListAuthorizedCertificates``. + + Attributes: + parent (str): + Name of the parent ``Application`` resource. Example: + ``apps/myapp``. + view (google.cloud.appengine_admin_v1.types.AuthorizedCertificateView): + Controls the set of fields returned in the ``LIST`` + response. + page_size (int): + Maximum results to return per page. + page_token (str): + Continuation token for fetching the next page + of results. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + view = proto.Field( + proto.ENUM, + number=4, + enum='AuthorizedCertificateView', + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAuthorizedCertificatesResponse(proto.Message): + r"""Response message for + ``AuthorizedCertificates.ListAuthorizedCertificates``. + + Attributes: + certificates (Sequence[google.cloud.appengine_admin_v1.types.AuthorizedCertificate]): + The SSL certificates the user is authorized + to administer. + next_page_token (str): + Continuation token for fetching the next page + of results. + """ + + @property + def raw_page(self): + return self + + certificates = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ga_certificate.AuthorizedCertificate, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetAuthorizedCertificateRequest(proto.Message): + r"""Request message for + ``AuthorizedCertificates.GetAuthorizedCertificate``. + + Attributes: + name (str): + Name of the resource requested. Example: + ``apps/myapp/authorizedCertificates/12345``. + view (google.cloud.appengine_admin_v1.types.AuthorizedCertificateView): + Controls the set of fields returned in the ``GET`` response. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + view = proto.Field( + proto.ENUM, + number=2, + enum='AuthorizedCertificateView', + ) + + +class CreateAuthorizedCertificateRequest(proto.Message): + r"""Request message for + ``AuthorizedCertificates.CreateAuthorizedCertificate``. + + Attributes: + parent (str): + Name of the parent ``Application`` resource. Example: + ``apps/myapp``. + certificate (google.cloud.appengine_admin_v1.types.AuthorizedCertificate): + SSL certificate data. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + certificate = proto.Field( + proto.MESSAGE, + number=2, + message=ga_certificate.AuthorizedCertificate, + ) + + +class UpdateAuthorizedCertificateRequest(proto.Message): + r"""Request message for + ``AuthorizedCertificates.UpdateAuthorizedCertificate``. + + Attributes: + name (str): + Name of the resource to update. Example: + ``apps/myapp/authorizedCertificates/12345``. + certificate (google.cloud.appengine_admin_v1.types.AuthorizedCertificate): + An ``AuthorizedCertificate`` containing the updated + resource. Only fields set in the field mask will be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Standard field mask for the set of fields to be updated. + Updates are only supported on the ``certificate_raw_data`` + and ``display_name`` fields. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + certificate = proto.Field( + proto.MESSAGE, + number=2, + message=ga_certificate.AuthorizedCertificate, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteAuthorizedCertificateRequest(proto.Message): + r"""Request message for + ``AuthorizedCertificates.DeleteAuthorizedCertificate``. + + Attributes: + name (str): + Name of the resource to delete. Example: + ``apps/myapp/authorizedCertificates/12345``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDomainMappingsRequest(proto.Message): + r"""Request message for ``DomainMappings.ListDomainMappings``. + Attributes: + parent (str): + Name of the parent Application resource. Example: + ``apps/myapp``. + page_size (int): + Maximum results to return per page. + page_token (str): + Continuation token for fetching the next page + of results. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class ListDomainMappingsResponse(proto.Message): + r"""Response message for ``DomainMappings.ListDomainMappings``. + Attributes: + domain_mappings (Sequence[google.cloud.appengine_admin_v1.types.DomainMapping]): + The domain mappings for the application. + next_page_token (str): + Continuation token for fetching the next page + of results. + """ + + @property + def raw_page(self): + return self + + domain_mappings = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ga_domain_mapping.DomainMapping, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetDomainMappingRequest(proto.Message): + r"""Request message for ``DomainMappings.GetDomainMapping``. + Attributes: + name (str): + Name of the resource requested. Example: + ``apps/myapp/domainMappings/example.com``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateDomainMappingRequest(proto.Message): + r"""Request message for ``DomainMappings.CreateDomainMapping``. + Attributes: + parent (str): + Name of the parent Application resource. Example: + ``apps/myapp``. + domain_mapping (google.cloud.appengine_admin_v1.types.DomainMapping): + Domain mapping configuration. + override_strategy (google.cloud.appengine_admin_v1.types.DomainOverrideStrategy): + Whether the domain creation should override + any existing mappings for this domain. By + default, overrides are rejected. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + domain_mapping = proto.Field( + proto.MESSAGE, + number=2, + message=ga_domain_mapping.DomainMapping, + ) + override_strategy = proto.Field( + proto.ENUM, + number=4, + enum='DomainOverrideStrategy', + ) + + +class UpdateDomainMappingRequest(proto.Message): + r"""Request message for ``DomainMappings.UpdateDomainMapping``. + Attributes: + name (str): + Name of the resource to update. Example: + ``apps/myapp/domainMappings/example.com``. + domain_mapping (google.cloud.appengine_admin_v1.types.DomainMapping): + A domain mapping containing the updated + resource. Only fields set in the field mask will + be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Standard field mask for the set of fields to + be updated. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + domain_mapping = proto.Field( + proto.MESSAGE, + number=2, + message=ga_domain_mapping.DomainMapping, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteDomainMappingRequest(proto.Message): + r"""Request message for ``DomainMappings.DeleteDomainMapping``. + Attributes: + name (str): + Name of the resource to delete. Example: + ``apps/myapp/domainMappings/example.com``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/application.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/application.py new file mode 100644 index 0000000..dbcf39d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/application.py @@ -0,0 +1,284 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.appengine.v1', + manifest={ + 'Application', + 'UrlDispatchRule', + }, +) + + +class Application(proto.Message): + r"""An Application resource contains the top-level configuration + of an App Engine application. + + Attributes: + name (str): + Full path to the Application resource in the API. Example: + ``apps/myapp``. + + @OutputOnly + id (str): + Identifier of the Application resource. This identifier is + equivalent to the project ID of the Google Cloud Platform + project where you want to deploy your application. Example: + ``myapp``. + dispatch_rules (Sequence[google.cloud.appengine_admin_v1.types.UrlDispatchRule]): + HTTP path dispatch rules for requests to the + application that do not explicitly target a + service or version. Rules are order-dependent. + Up to 20 dispatch rules can be supported. + auth_domain (str): + Google Apps authentication domain that + controls which users can access this + application. + Defaults to open access for any Google Account. + location_id (str): + Location from which this application runs. Application + instances run out of the data centers in the specified + location, which is also where all of the application's end + user content is stored. + + Defaults to ``us-central``. + + View the list of `supported + locations `__. + code_bucket (str): + Google Cloud Storage bucket that can be used + for storing files associated with this + application. This bucket is associated with the + application and can be used by the gcloud + deployment commands. + @OutputOnly + default_cookie_expiration (google.protobuf.duration_pb2.Duration): + Cookie expiration policy for this + application. + serving_status (google.cloud.appengine_admin_v1.types.Application.ServingStatus): + Serving status of this application. + default_hostname (str): + Hostname used to reach this application, as + resolved by App Engine. + @OutputOnly + default_bucket (str): + Google Cloud Storage bucket that can be used + by this application to store content. + + @OutputOnly + iap (google.cloud.appengine_admin_v1.types.Application.IdentityAwareProxy): + + gcr_domain (str): + The Google Container Registry domain used for + storing managed build docker images for this + application. + database_type (google.cloud.appengine_admin_v1.types.Application.DatabaseType): + The type of the Cloud Firestore or Cloud + Datastore database associated with this + application. + feature_settings (google.cloud.appengine_admin_v1.types.Application.FeatureSettings): + The feature specific settings to be used in + the application. + """ + class ServingStatus(proto.Enum): + r"""""" + UNSPECIFIED = 0 + SERVING = 1 + USER_DISABLED = 2 + SYSTEM_DISABLED = 3 + + class DatabaseType(proto.Enum): + r"""""" + DATABASE_TYPE_UNSPECIFIED = 0 + CLOUD_DATASTORE = 1 + CLOUD_FIRESTORE = 2 + CLOUD_DATASTORE_COMPATIBILITY = 3 + + class IdentityAwareProxy(proto.Message): + r"""Identity-Aware Proxy + Attributes: + enabled (bool): + Whether the serving infrastructure will authenticate and + authorize all incoming requests. + + If true, the ``oauth2_client_id`` and + ``oauth2_client_secret`` fields must be non-empty. + oauth2_client_id (str): + OAuth2 client ID to use for the + authentication flow. + oauth2_client_secret (str): + OAuth2 client secret to use for the authentication flow. + + For security reasons, this value cannot be retrieved via the + API. Instead, the SHA-256 hash of the value is returned in + the ``oauth2_client_secret_sha256`` field. + + @InputOnly + oauth2_client_secret_sha256 (str): + Hex-encoded SHA-256 hash of the client + secret. + @OutputOnly + """ + + enabled = proto.Field( + proto.BOOL, + number=1, + ) + oauth2_client_id = proto.Field( + proto.STRING, + number=2, + ) + oauth2_client_secret = proto.Field( + proto.STRING, + number=3, + ) + oauth2_client_secret_sha256 = proto.Field( + proto.STRING, + number=4, + ) + + class FeatureSettings(proto.Message): + r"""The feature specific settings to be used in the application. + These define behaviors that are user configurable. + + Attributes: + split_health_checks (bool): + Boolean value indicating if split health checks should be + used instead of the legacy health checks. At an app.yaml + level, this means defaulting to 'readiness_check' and + 'liveness_check' values instead of 'health_check' ones. Once + the legacy 'health_check' behavior is deprecated, and this + value is always true, this setting can be removed. + use_container_optimized_os (bool): + If true, use `Container-Optimized + OS `__ + base image for VMs, rather than a base Debian image. + """ + + split_health_checks = proto.Field( + proto.BOOL, + number=1, + ) + use_container_optimized_os = proto.Field( + proto.BOOL, + number=2, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + id = proto.Field( + proto.STRING, + number=2, + ) + dispatch_rules = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='UrlDispatchRule', + ) + auth_domain = proto.Field( + proto.STRING, + number=6, + ) + location_id = proto.Field( + proto.STRING, + number=7, + ) + code_bucket = proto.Field( + proto.STRING, + number=8, + ) + default_cookie_expiration = proto.Field( + proto.MESSAGE, + number=9, + message=duration_pb2.Duration, + ) + serving_status = proto.Field( + proto.ENUM, + number=10, + enum=ServingStatus, + ) + default_hostname = proto.Field( + proto.STRING, + number=11, + ) + default_bucket = proto.Field( + proto.STRING, + number=12, + ) + iap = proto.Field( + proto.MESSAGE, + number=14, + message=IdentityAwareProxy, + ) + gcr_domain = proto.Field( + proto.STRING, + number=16, + ) + database_type = proto.Field( + proto.ENUM, + number=17, + enum=DatabaseType, + ) + feature_settings = proto.Field( + proto.MESSAGE, + number=18, + message=FeatureSettings, + ) + + +class UrlDispatchRule(proto.Message): + r"""Rules to match an HTTP request and dispatch that request to a + service. + + Attributes: + domain (str): + Domain name to match against. The wildcard "``*``" is + supported if specified before a period: "``*.``". + + Defaults to matching all domains: "``*``". + path (str): + Pathname within the host. Must start with a "``/``". A + single "``*``" can be included at the end of the path. + + The sum of the lengths of the domain and path may not exceed + 100 characters. + service (str): + Resource ID of a service in this application that should + serve the matched request. The service must already exist. + Example: ``default``. + """ + + domain = proto.Field( + proto.STRING, + number=1, + ) + path = proto.Field( + proto.STRING, + number=2, + ) + service = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/audit_data.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/audit_data.py new file mode 100644 index 0000000..9dbb7e8 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/audit_data.py @@ -0,0 +1,84 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.appengine_admin_v1.types import appengine + + +__protobuf__ = proto.module( + package='google.appengine.v1', + manifest={ + 'AuditData', + 'UpdateServiceMethod', + 'CreateVersionMethod', + }, +) + + +class AuditData(proto.Message): + r"""App Engine admin service audit log. + Attributes: + update_service (google.cloud.appengine_admin_v1.types.UpdateServiceMethod): + Detailed information about UpdateService + call. + create_version (google.cloud.appengine_admin_v1.types.CreateVersionMethod): + Detailed information about CreateVersion + call. + """ + + update_service = proto.Field( + proto.MESSAGE, + number=1, + oneof='method', + message='UpdateServiceMethod', + ) + create_version = proto.Field( + proto.MESSAGE, + number=2, + oneof='method', + message='CreateVersionMethod', + ) + + +class UpdateServiceMethod(proto.Message): + r"""Detailed information about UpdateService call. + Attributes: + request (google.cloud.appengine_admin_v1.types.UpdateServiceRequest): + Update service request. + """ + + request = proto.Field( + proto.MESSAGE, + number=1, + message=appengine.UpdateServiceRequest, + ) + + +class CreateVersionMethod(proto.Message): + r"""Detailed information about CreateVersion call. + Attributes: + request (google.cloud.appengine_admin_v1.types.CreateVersionRequest): + Create version request. + """ + + request = proto.Field( + proto.MESSAGE, + number=1, + message=appengine.CreateVersionRequest, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/certificate.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/certificate.py new file mode 100644 index 0000000..72c6776 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/certificate.py @@ -0,0 +1,229 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.appengine.v1', + manifest={ + 'ManagementStatus', + 'AuthorizedCertificate', + 'CertificateRawData', + 'ManagedCertificate', + }, +) + + +class ManagementStatus(proto.Enum): + r"""State of certificate management. Refers to the most recent + certificate acquisition or renewal attempt. + """ + MANAGEMENT_STATUS_UNSPECIFIED = 0 + OK = 1 + PENDING = 2 + FAILED_RETRYING_NOT_VISIBLE = 4 + FAILED_PERMANENT = 6 + FAILED_RETRYING_CAA_FORBIDDEN = 7 + FAILED_RETRYING_CAA_CHECKING = 8 + + +class AuthorizedCertificate(proto.Message): + r"""An SSL certificate that a user has been authorized to + administer. A user is authorized to administer any certificate + that applies to one of their authorized domains. + + Attributes: + name (str): + Full path to the ``AuthorizedCertificate`` resource in the + API. Example: ``apps/myapp/authorizedCertificates/12345``. + + @OutputOnly + id (str): + Relative name of the certificate. This is a unique value + autogenerated on ``AuthorizedCertificate`` resource + creation. Example: ``12345``. + + @OutputOnly + display_name (str): + The user-specified display name of the certificate. This is + not guaranteed to be unique. Example: ``My Certificate``. + domain_names (Sequence[str]): + Topmost applicable domains of this certificate. This + certificate applies to these domains and their subdomains. + Example: ``example.com``. + + @OutputOnly + expire_time (google.protobuf.timestamp_pb2.Timestamp): + The time when this certificate expires. To update the + renewal time on this certificate, upload an SSL certificate + with a different expiration time using + ```AuthorizedCertificates.UpdateAuthorizedCertificate`` <>`__. + + @OutputOnly + certificate_raw_data (google.cloud.appengine_admin_v1.types.CertificateRawData): + The SSL certificate serving the ``AuthorizedCertificate`` + resource. This must be obtained independently from a + certificate authority. + managed_certificate (google.cloud.appengine_admin_v1.types.ManagedCertificate): + Only applicable if this certificate is managed by App + Engine. Managed certificates are tied to the lifecycle of a + ``DomainMapping`` and cannot be updated or deleted via the + ``AuthorizedCertificates`` API. If this certificate is + manually administered by the user, this field will be empty. + + @OutputOnly + visible_domain_mappings (Sequence[str]): + The full paths to user visible Domain Mapping resources that + have this certificate mapped. Example: + ``apps/myapp/domainMappings/example.com``. + + This may not represent the full list of mapped domain + mappings if the user does not have ``VIEWER`` permissions on + all of the applications that have this certificate mapped. + See ``domain_mappings_count`` for a complete count. + + Only returned by ``GET`` or ``LIST`` requests when + specifically requested by the ``view=FULL_CERTIFICATE`` + option. + + @OutputOnly + domain_mappings_count (int): + Aggregate count of the domain mappings with this certificate + mapped. This count includes domain mappings on applications + for which the user does not have ``VIEWER`` permissions. + + Only returned by ``GET`` or ``LIST`` requests when + specifically requested by the ``view=FULL_CERTIFICATE`` + option. + + @OutputOnly + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + id = proto.Field( + proto.STRING, + number=2, + ) + display_name = proto.Field( + proto.STRING, + number=3, + ) + domain_names = proto.RepeatedField( + proto.STRING, + number=4, + ) + expire_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + certificate_raw_data = proto.Field( + proto.MESSAGE, + number=6, + message='CertificateRawData', + ) + managed_certificate = proto.Field( + proto.MESSAGE, + number=7, + message='ManagedCertificate', + ) + visible_domain_mappings = proto.RepeatedField( + proto.STRING, + number=8, + ) + domain_mappings_count = proto.Field( + proto.INT32, + number=9, + ) + + +class CertificateRawData(proto.Message): + r"""An SSL certificate obtained from a certificate authority. + Attributes: + public_certificate (str): + PEM encoded x.509 public key certificate. This field is set + once on certificate creation. Must include the header and + footer. Example: + + .. raw:: html + +
+                -----BEGIN CERTIFICATE-----
+                
+                -----END CERTIFICATE-----
+                
+ private_key (str): + Unencrypted PEM encoded RSA private key. This field is set + once on certificate creation and then encrypted. The key + size must be 2048 bits or fewer. Must include the header and + footer. Example: + + .. raw:: html + +
+                -----BEGIN RSA PRIVATE KEY-----
+                
+                -----END RSA PRIVATE KEY-----
+                
+ + @InputOnly + """ + + public_certificate = proto.Field( + proto.STRING, + number=1, + ) + private_key = proto.Field( + proto.STRING, + number=2, + ) + + +class ManagedCertificate(proto.Message): + r"""A certificate managed by App Engine. + Attributes: + last_renewal_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which the certificate was last renewed. The renewal + process is fully managed. Certificate renewal will + automatically occur before the certificate expires. Renewal + errors can be tracked via ``ManagementStatus``. + + @OutputOnly + status (google.cloud.appengine_admin_v1.types.ManagementStatus): + Status of certificate management. Refers to + the most recent certificate acquisition or + renewal attempt. + @OutputOnly + """ + + last_renewal_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + status = proto.Field( + proto.ENUM, + number=2, + enum='ManagementStatus', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/deploy.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/deploy.py new file mode 100644 index 0000000..175cc77 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/deploy.py @@ -0,0 +1,191 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.appengine.v1', + manifest={ + 'Deployment', + 'FileInfo', + 'ContainerInfo', + 'CloudBuildOptions', + 'ZipInfo', + }, +) + + +class Deployment(proto.Message): + r"""Code and application artifacts used to deploy a version to + App Engine. + + Attributes: + files (Sequence[google.cloud.appengine_admin_v1.types.Deployment.FilesEntry]): + Manifest of the files stored in Google Cloud + Storage that are included as part of this + version. All files must be readable using the + credentials supplied with this call. + container (google.cloud.appengine_admin_v1.types.ContainerInfo): + The Docker image for the container that runs + the version. Only applicable for instances + running in the App Engine flexible environment. + zip_ (google.cloud.appengine_admin_v1.types.ZipInfo): + The zip file for this deployment, if this is + a zip deployment. + cloud_build_options (google.cloud.appengine_admin_v1.types.CloudBuildOptions): + Options for any Google Cloud Build builds + created as a part of this deployment. + + These options will only be used if a new build + is created, such as when deploying to the App + Engine flexible environment using files or zip. + """ + + files = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message='FileInfo', + ) + container = proto.Field( + proto.MESSAGE, + number=2, + message='ContainerInfo', + ) + zip_ = proto.Field( + proto.MESSAGE, + number=3, + message='ZipInfo', + ) + cloud_build_options = proto.Field( + proto.MESSAGE, + number=6, + message='CloudBuildOptions', + ) + + +class FileInfo(proto.Message): + r"""Single source file that is part of the version to be + deployed. Each source file that is deployed must be specified + separately. + + Attributes: + source_url (str): + URL source to use to fetch this file. Must be + a URL to a resource in Google Cloud Storage in + the form + 'http(s)://storage.googleapis.com/\/\'. + sha1_sum (str): + The SHA1 hash of the file, in hex. + mime_type (str): + The MIME type of the file. + Defaults to the value from Google Cloud Storage. + """ + + source_url = proto.Field( + proto.STRING, + number=1, + ) + sha1_sum = proto.Field( + proto.STRING, + number=2, + ) + mime_type = proto.Field( + proto.STRING, + number=3, + ) + + +class ContainerInfo(proto.Message): + r"""Docker image that is used to create a container and start a + VM instance for the version that you deploy. Only applicable for + instances running in the App Engine flexible environment. + + Attributes: + image (str): + URI to the hosted container image in Google + Container Registry. The URI must be fully + qualified and include a tag or digest. Examples: + "gcr.io/my-project/image:tag" or "gcr.io/my- + project/image@digest". + """ + + image = proto.Field( + proto.STRING, + number=1, + ) + + +class CloudBuildOptions(proto.Message): + r"""Options for the build operations performed as a part of the + version deployment. Only applicable for App Engine flexible + environment when creating a version using source code directly. + + Attributes: + app_yaml_path (str): + Path to the yaml file used in deployment, + used to determine runtime configuration details. + Required for flexible environment builds. + + See + https://cloud.google.com/appengine/docs/standard/python/config/appref + for more details. + cloud_build_timeout (google.protobuf.duration_pb2.Duration): + The Cloud Build timeout used as part of any + dependent builds performed by version creation. + Defaults to 10 minutes. + """ + + app_yaml_path = proto.Field( + proto.STRING, + number=1, + ) + cloud_build_timeout = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class ZipInfo(proto.Message): + r"""The zip file information for a zip deployment. + Attributes: + source_url (str): + URL of the zip file to deploy from. Must be a + URL to a resource in Google Cloud Storage in the + form + 'http(s)://storage.googleapis.com/\/\'. + files_count (int): + An estimate of the number of files in a zip + for a zip deployment. If set, must be greater + than or equal to the actual number of files. + Used for optimizing performance; if not + provided, deployment may be slow. + """ + + source_url = proto.Field( + proto.STRING, + number=3, + ) + files_count = proto.Field( + proto.INT32, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/deployed_files.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/deployed_files.py new file mode 100644 index 0000000..e9fa874 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/deployed_files.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + + +__protobuf__ = proto.module( + package='google.appengine.v1', + manifest={ + }, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/domain.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/domain.py new file mode 100644 index 0000000..d237853 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/domain.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.appengine.v1', + manifest={ + 'AuthorizedDomain', + }, +) + + +class AuthorizedDomain(proto.Message): + r"""A domain that a user has been authorized to administer. To authorize + use of a domain, verify ownership via `Webmaster + Central `__. + + Attributes: + name (str): + Full path to the ``AuthorizedDomain`` resource in the API. + Example: ``apps/myapp/authorizedDomains/example.com``. + + @OutputOnly + id (str): + Fully qualified domain name of the domain authorized for + use. Example: ``example.com``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + id = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/domain_mapping.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/domain_mapping.py new file mode 100644 index 0000000..1f0e515 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/domain_mapping.py @@ -0,0 +1,161 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.appengine.v1', + manifest={ + 'DomainMapping', + 'SslSettings', + 'ResourceRecord', + }, +) + + +class DomainMapping(proto.Message): + r"""A domain serving an App Engine application. + Attributes: + name (str): + Full path to the ``DomainMapping`` resource in the API. + Example: ``apps/myapp/domainMapping/example.com``. + + @OutputOnly + id (str): + Relative name of the domain serving the application. + Example: ``example.com``. + ssl_settings (google.cloud.appengine_admin_v1.types.SslSettings): + SSL configuration for this domain. If + unconfigured, this domain will not serve with + SSL. + resource_records (Sequence[google.cloud.appengine_admin_v1.types.ResourceRecord]): + The resource records required to configure + this domain mapping. These records must be added + to the domain's DNS configuration in order to + serve the application via this domain mapping. + @OutputOnly + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + id = proto.Field( + proto.STRING, + number=2, + ) + ssl_settings = proto.Field( + proto.MESSAGE, + number=3, + message='SslSettings', + ) + resource_records = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='ResourceRecord', + ) + + +class SslSettings(proto.Message): + r"""SSL configuration for a ``DomainMapping`` resource. + Attributes: + certificate_id (str): + ID of the ``AuthorizedCertificate`` resource configuring SSL + for the application. Clearing this field will remove SSL + support. + + By default, a managed certificate is automatically created + for every domain mapping. To omit SSL support or to + configure SSL manually, specify ``SslManagementType.MANUAL`` + on a ``CREATE`` or ``UPDATE`` request. You must be + authorized to administer the ``AuthorizedCertificate`` + resource to manually map it to a ``DomainMapping`` resource. + Example: ``12345``. + ssl_management_type (google.cloud.appengine_admin_v1.types.SslSettings.SslManagementType): + SSL management type for this domain. If ``AUTOMATIC``, a + managed certificate is automatically provisioned. If + ``MANUAL``, ``certificate_id`` must be manually specified in + order to configure SSL for this domain. + pending_managed_certificate_id (str): + ID of the managed ``AuthorizedCertificate`` resource + currently being provisioned, if applicable. Until the new + managed certificate has been successfully provisioned, the + previous SSL state will be preserved. Once the provisioning + process completes, the ``certificate_id`` field will reflect + the new managed certificate and this field will be left + empty. To remove SSL support while there is still a pending + managed certificate, clear the ``certificate_id`` field with + an ``UpdateDomainMappingRequest``. + + @OutputOnly + """ + class SslManagementType(proto.Enum): + r"""The SSL management type for this domain.""" + SSL_MANAGEMENT_TYPE_UNSPECIFIED = 0 + AUTOMATIC = 1 + MANUAL = 2 + + certificate_id = proto.Field( + proto.STRING, + number=1, + ) + ssl_management_type = proto.Field( + proto.ENUM, + number=3, + enum=SslManagementType, + ) + pending_managed_certificate_id = proto.Field( + proto.STRING, + number=4, + ) + + +class ResourceRecord(proto.Message): + r"""A DNS resource record. + Attributes: + name (str): + Relative name of the object affected by this record. Only + applicable for ``CNAME`` records. Example: 'www'. + rrdata (str): + Data for this record. Values vary by record + type, as defined in RFC 1035 (section 5) and RFC + 1034 (section 3.6.1). + type_ (google.cloud.appengine_admin_v1.types.ResourceRecord.RecordType): + Resource record type. Example: ``AAAA``. + """ + class RecordType(proto.Enum): + r"""A resource record type.""" + RECORD_TYPE_UNSPECIFIED = 0 + A = 1 + AAAA = 2 + CNAME = 3 + + name = proto.Field( + proto.STRING, + number=1, + ) + rrdata = proto.Field( + proto.STRING, + number=2, + ) + type_ = proto.Field( + proto.ENUM, + number=3, + enum=RecordType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/firewall.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/firewall.py new file mode 100644 index 0000000..f426b35 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/firewall.py @@ -0,0 +1,86 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.appengine.v1', + manifest={ + 'FirewallRule', + }, +) + + +class FirewallRule(proto.Message): + r"""A single firewall rule that is evaluated against incoming + traffic and provides an action to take on matched requests. + + Attributes: + priority (int): + A positive integer between [1, Int32.MaxValue-1] that + defines the order of rule evaluation. Rules with the lowest + priority are evaluated first. + + A default rule at priority Int32.MaxValue matches all IPv4 + and IPv6 traffic when no previous rule matches. Only the + action of this rule can be modified by the user. + action (google.cloud.appengine_admin_v1.types.FirewallRule.Action): + The action to take on matched requests. + source_range (str): + IP address or range, defined using CIDR notation, of + requests that this rule applies to. You can use the wildcard + character "*" to match all IPs equivalent to "0/0" and + "::/0" together. Examples: ``192.168.1.1`` or + ``192.168.0.0/16`` or ``2001:db8::/32`` or + ``2001:0db8:0000:0042:0000:8a2e:0370:7334``. + + .. raw:: html + +

Truncation will be silently performed on addresses which are not + properly truncated. For example, `1.2.3.4/24` is accepted as the same + address as `1.2.3.0/24`. Similarly, for IPv6, `2001:db8::1/32` is accepted + as the same address as `2001:db8::/32`. + description (str): + An optional string description of this rule. + This field has a maximum length of 100 + characters. + """ + class Action(proto.Enum): + r"""Available actions to take on matching requests.""" + UNSPECIFIED_ACTION = 0 + ALLOW = 1 + DENY = 2 + + priority = proto.Field( + proto.INT32, + number=1, + ) + action = proto.Field( + proto.ENUM, + number=2, + enum=Action, + ) + source_range = proto.Field( + proto.STRING, + number=3, + ) + description = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/instance.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/instance.py new file mode 100644 index 0000000..8a02aa3 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/instance.py @@ -0,0 +1,183 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.appengine.v1', + manifest={ + 'Instance', + }, +) + + +class Instance(proto.Message): + r"""An Instance resource is the computing unit that App Engine + uses to automatically scale an application. + + Attributes: + name (str): + Output only. Full path to the Instance resource in the API. + Example: + ``apps/myapp/services/default/versions/v1/instances/instance-1``. + id (str): + Output only. Relative name of the instance within the + version. Example: ``instance-1``. + app_engine_release (str): + Output only. App Engine release this instance + is running on. + availability (google.cloud.appengine_admin_v1.types.Instance.Availability): + Output only. Availability of the instance. + vm_name (str): + Output only. Name of the virtual machine + where this instance lives. Only applicable for + instances in App Engine flexible environment. + vm_zone_name (str): + Output only. Zone where the virtual machine + is located. Only applicable for instances in App + Engine flexible environment. + vm_id (str): + Output only. Virtual machine ID of this + instance. Only applicable for instances in App + Engine flexible environment. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time that this instance was + started. + @OutputOnly + requests (int): + Output only. Number of requests since this + instance was started. + errors (int): + Output only. Number of errors since this + instance was started. + qps (float): + Output only. Average queries per second (QPS) + over the last minute. + average_latency (int): + Output only. Average latency (ms) over the + last minute. + memory_usage (int): + Output only. Total memory in use (bytes). + vm_status (str): + Output only. Status of the virtual machine + where this instance lives. Only applicable for + instances in App Engine flexible environment. + vm_debug_enabled (bool): + Output only. Whether this instance is in + debug mode. Only applicable for instances in App + Engine flexible environment. + vm_ip (str): + Output only. The IP address of this instance. + Only applicable for instances in App Engine + flexible environment. + vm_liveness (google.cloud.appengine_admin_v1.types.Instance.Liveness.LivenessState): + Output only. The liveness health check of + this instance. Only applicable for instances in + App Engine flexible environment. + """ + class Availability(proto.Enum): + r"""Availability of the instance.""" + UNSPECIFIED = 0 + RESIDENT = 1 + DYNAMIC = 2 + + class Liveness(proto.Message): + r"""Wrapper for LivenessState enum. """ + class LivenessState(proto.Enum): + r"""Liveness health check status for Flex instances.""" + LIVENESS_STATE_UNSPECIFIED = 0 + UNKNOWN = 1 + HEALTHY = 2 + UNHEALTHY = 3 + DRAINING = 4 + TIMEOUT = 5 + + name = proto.Field( + proto.STRING, + number=1, + ) + id = proto.Field( + proto.STRING, + number=2, + ) + app_engine_release = proto.Field( + proto.STRING, + number=3, + ) + availability = proto.Field( + proto.ENUM, + number=4, + enum=Availability, + ) + vm_name = proto.Field( + proto.STRING, + number=5, + ) + vm_zone_name = proto.Field( + proto.STRING, + number=6, + ) + vm_id = proto.Field( + proto.STRING, + number=7, + ) + start_time = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + requests = proto.Field( + proto.INT32, + number=9, + ) + errors = proto.Field( + proto.INT32, + number=10, + ) + qps = proto.Field( + proto.FLOAT, + number=11, + ) + average_latency = proto.Field( + proto.INT32, + number=12, + ) + memory_usage = proto.Field( + proto.INT64, + number=13, + ) + vm_status = proto.Field( + proto.STRING, + number=14, + ) + vm_debug_enabled = proto.Field( + proto.BOOL, + number=15, + ) + vm_ip = proto.Field( + proto.STRING, + number=16, + ) + vm_liveness = proto.Field( + proto.ENUM, + number=17, + enum=Liveness.LivenessState, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/location.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/location.py new file mode 100644 index 0000000..73a0dd3 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/location.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.appengine.v1', + manifest={ + 'LocationMetadata', + }, +) + + +class LocationMetadata(proto.Message): + r"""Metadata for the given + [google.cloud.location.Location][google.cloud.location.Location]. + + Attributes: + standard_environment_available (bool): + App Engine standard environment is available + in the given location. + @OutputOnly + flexible_environment_available (bool): + App Engine flexible environment is available + in the given location. + @OutputOnly + search_api_available (bool): + Output only. `Search + API `__ + is available in the given location. + """ + + standard_environment_available = proto.Field( + proto.BOOL, + number=2, + ) + flexible_environment_available = proto.Field( + proto.BOOL, + number=4, + ) + search_api_available = proto.Field( + proto.BOOL, + number=6, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/network_settings.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/network_settings.py new file mode 100644 index 0000000..dd6950e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/network_settings.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.appengine.v1', + manifest={ + 'NetworkSettings', + }, +) + + +class NetworkSettings(proto.Message): + r"""A NetworkSettings resource is a container for ingress + settings for a version or service. + + Attributes: + ingress_traffic_allowed (google.cloud.appengine_admin_v1.types.NetworkSettings.IngressTrafficAllowed): + The ingress settings for version or service. + """ + class IngressTrafficAllowed(proto.Enum): + r"""If unspecified, INGRESS_TRAFFIC_ALLOWED_ALL will be used.""" + INGRESS_TRAFFIC_ALLOWED_UNSPECIFIED = 0 + INGRESS_TRAFFIC_ALLOWED_ALL = 1 + INGRESS_TRAFFIC_ALLOWED_INTERNAL_ONLY = 2 + INGRESS_TRAFFIC_ALLOWED_INTERNAL_AND_LB = 3 + + ingress_traffic_allowed = proto.Field( + proto.ENUM, + number=1, + enum=IngressTrafficAllowed, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/operation.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/operation.py new file mode 100644 index 0000000..1cedf75 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/operation.py @@ -0,0 +1,120 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.appengine.v1', + manifest={ + 'OperationMetadataV1', + 'CreateVersionMetadataV1', + }, +) + + +class OperationMetadataV1(proto.Message): + r"""Metadata for the given + [google.longrunning.Operation][google.longrunning.Operation]. + + Attributes: + method (str): + API method that initiated this operation. Example: + ``google.appengine.v1.Versions.CreateVersion``. + + @OutputOnly + insert_time (google.protobuf.timestamp_pb2.Timestamp): + Time that this operation was created. + @OutputOnly + end_time (google.protobuf.timestamp_pb2.Timestamp): + Time that this operation completed. + @OutputOnly + user (str): + User who requested this operation. + @OutputOnly + target (str): + Name of the resource that this operation is acting on. + Example: ``apps/myapp/services/default``. + + @OutputOnly + ephemeral_message (str): + Ephemeral message that may change every time + the operation is polled. @OutputOnly + warning (Sequence[str]): + Durable messages that persist on every + operation poll. @OutputOnly + create_version_metadata (google.cloud.appengine_admin_v1.types.CreateVersionMetadataV1): + + """ + + method = proto.Field( + proto.STRING, + number=1, + ) + insert_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + user = proto.Field( + proto.STRING, + number=4, + ) + target = proto.Field( + proto.STRING, + number=5, + ) + ephemeral_message = proto.Field( + proto.STRING, + number=6, + ) + warning = proto.RepeatedField( + proto.STRING, + number=7, + ) + create_version_metadata = proto.Field( + proto.MESSAGE, + number=8, + oneof='method_metadata', + message='CreateVersionMetadataV1', + ) + + +class CreateVersionMetadataV1(proto.Message): + r"""Metadata for the given + [google.longrunning.Operation][google.longrunning.Operation] during + a + [google.appengine.v1.CreateVersionRequest][google.appengine.v1.CreateVersionRequest]. + + Attributes: + cloud_build_id (str): + The Cloud Build ID if one was created as part + of the version create. @OutputOnly + """ + + cloud_build_id = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/service.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/service.py new file mode 100644 index 0000000..2fe2fdd --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/service.py @@ -0,0 +1,121 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.appengine_admin_v1.types import network_settings as ga_network_settings + + +__protobuf__ = proto.module( + package='google.appengine.v1', + manifest={ + 'Service', + 'TrafficSplit', + }, +) + + +class Service(proto.Message): + r"""A Service resource is a logical component of an application + that can share state and communicate in a secure fashion with + other services. For example, an application that handles + customer requests might include separate services to handle + tasks such as backend data analysis or API requests from mobile + devices. Each service has a collection of versions that define a + specific set of code used to implement the functionality of that + service. + + Attributes: + name (str): + Full path to the Service resource in the API. Example: + ``apps/myapp/services/default``. + + @OutputOnly + id (str): + Relative name of the service within the application. + Example: ``default``. + + @OutputOnly + split (google.cloud.appengine_admin_v1.types.TrafficSplit): + Mapping that defines fractional HTTP traffic + diversion to different versions within the + service. + network_settings (google.cloud.appengine_admin_v1.types.NetworkSettings): + Ingress settings for this service. Will apply + to all versions. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + id = proto.Field( + proto.STRING, + number=2, + ) + split = proto.Field( + proto.MESSAGE, + number=3, + message='TrafficSplit', + ) + network_settings = proto.Field( + proto.MESSAGE, + number=6, + message=ga_network_settings.NetworkSettings, + ) + + +class TrafficSplit(proto.Message): + r"""Traffic routing configuration for versions within a single + service. Traffic splits define how traffic directed to the + service is assigned to versions. + + Attributes: + shard_by (google.cloud.appengine_admin_v1.types.TrafficSplit.ShardBy): + Mechanism used to determine which version a + request is sent to. The traffic selection + algorithm will be stable for either type until + allocations are changed. + allocations (Sequence[google.cloud.appengine_admin_v1.types.TrafficSplit.AllocationsEntry]): + Mapping from version IDs within the service to fractional + (0.000, 1] allocations of traffic for that version. Each + version can be specified only once, but some versions in the + service may not have any traffic allocation. Services that + have traffic allocated cannot be deleted until either the + service is deleted or their traffic allocation is removed. + Allocations must sum to 1. Up to two decimal place precision + is supported for IP-based splits and up to three decimal + places is supported for cookie-based splits. + """ + class ShardBy(proto.Enum): + r"""Available sharding mechanisms.""" + UNSPECIFIED = 0 + COOKIE = 1 + IP = 2 + RANDOM = 3 + + shard_by = proto.Field( + proto.ENUM, + number=1, + enum=ShardBy, + ) + allocations = proto.MapField( + proto.STRING, + proto.DOUBLE, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/version.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/version.py new file mode 100644 index 0000000..03a31ef --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/version.py @@ -0,0 +1,973 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.appengine_admin_v1.types import app_yaml +from google.cloud.appengine_admin_v1.types import deploy +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.appengine.v1', + manifest={ + 'InboundServiceType', + 'ServingStatus', + 'Version', + 'EndpointsApiService', + 'AutomaticScaling', + 'BasicScaling', + 'ManualScaling', + 'CpuUtilization', + 'RequestUtilization', + 'DiskUtilization', + 'NetworkUtilization', + 'StandardSchedulerSettings', + 'Network', + 'Volume', + 'Resources', + 'VpcAccessConnector', + 'Entrypoint', + }, +) + + +class InboundServiceType(proto.Enum): + r"""Available inbound services.""" + INBOUND_SERVICE_UNSPECIFIED = 0 + INBOUND_SERVICE_MAIL = 1 + INBOUND_SERVICE_MAIL_BOUNCE = 2 + INBOUND_SERVICE_XMPP_ERROR = 3 + INBOUND_SERVICE_XMPP_MESSAGE = 4 + INBOUND_SERVICE_XMPP_SUBSCRIBE = 5 + INBOUND_SERVICE_XMPP_PRESENCE = 6 + INBOUND_SERVICE_CHANNEL_PRESENCE = 7 + INBOUND_SERVICE_WARMUP = 9 + + +class ServingStatus(proto.Enum): + r"""Run states of a version.""" + SERVING_STATUS_UNSPECIFIED = 0 + SERVING = 1 + STOPPED = 2 + + +class Version(proto.Message): + r"""A Version resource is a specific set of source code and + configuration files that are deployed into a service. + + Attributes: + name (str): + Full path to the Version resource in the API. Example: + ``apps/myapp/services/default/versions/v1``. + + @OutputOnly + id (str): + Relative name of the version within the service. Example: + ``v1``. Version names can contain only lowercase letters, + numbers, or hyphens. Reserved names: "default", "latest", + and any name with the prefix "ah-". + automatic_scaling (google.cloud.appengine_admin_v1.types.AutomaticScaling): + Automatic scaling is based on request rate, + response latencies, and other application + metrics. Instances are dynamically created and + destroyed as needed in order to handle traffic. + basic_scaling (google.cloud.appengine_admin_v1.types.BasicScaling): + A service with basic scaling will create an + instance when the application receives a + request. The instance will be turned down when + the app becomes idle. Basic scaling is ideal for + work that is intermittent or driven by user + activity. + manual_scaling (google.cloud.appengine_admin_v1.types.ManualScaling): + A service with manual scaling runs + continuously, allowing you to perform complex + initialization and rely on the state of its + memory over time. Manually scaled versions are + sometimes referred to as "backends". + inbound_services (Sequence[google.cloud.appengine_admin_v1.types.InboundServiceType]): + Before an application can receive email or + XMPP messages, the application must be + configured to enable the service. + instance_class (str): + Instance class that is used to run this version. Valid + values are: + + - AutomaticScaling: ``F1``, ``F2``, ``F4``, ``F4_1G`` + - ManualScaling or BasicScaling: ``B1``, ``B2``, ``B4``, + ``B8``, ``B4_1G`` + + Defaults to ``F1`` for AutomaticScaling and ``B1`` for + ManualScaling or BasicScaling. + network (google.cloud.appengine_admin_v1.types.Network): + Extra network settings. + Only applicable in the App Engine flexible + environment. + zones (Sequence[str]): + The Google Compute Engine zones that are + supported by this version in the App Engine + flexible environment. Deprecated. + resources (google.cloud.appengine_admin_v1.types.Resources): + Machine resources for this version. + Only applicable in the App Engine flexible + environment. + runtime (str): + Desired runtime. Example: ``python27``. + runtime_channel (str): + The channel of the runtime to use. Only available for some + runtimes. Defaults to the ``default`` channel. + threadsafe (bool): + Whether multiple requests can be dispatched + to this version at once. + vm (bool): + Whether to deploy this version in a container + on a virtual machine. + beta_settings (Sequence[google.cloud.appengine_admin_v1.types.Version.BetaSettingsEntry]): + Metadata settings that are supplied to this + version to enable beta runtime features. + env (str): + App Engine execution environment for this version. + + Defaults to ``standard``. + serving_status (google.cloud.appengine_admin_v1.types.ServingStatus): + Current serving status of this version. Only the versions + with a ``SERVING`` status create instances and can be + billed. + + ``SERVING_STATUS_UNSPECIFIED`` is an invalid value. Defaults + to ``SERVING``. + created_by (str): + Email address of the user who created this + version. + @OutputOnly + create_time (google.protobuf.timestamp_pb2.Timestamp): + Time that this version was created. + @OutputOnly + disk_usage_bytes (int): + Total size in bytes of all the files that are + included in this version and currently hosted on + the App Engine disk. + @OutputOnly + runtime_api_version (str): + The version of the API in the given runtime + environment. Please see the app.yaml reference + for valid values at + https://cloud.google.com/appengine/docs/standard//config/appref + runtime_main_executable_path (str): + The path or name of the app's main + executable. + service_account (str): + The identity that the deployed version will + run as. Admin API will use the App Engine + Appspot service account as default if this field + is neither provided in app.yaml file nor through + CLI flag. + handlers (Sequence[google.cloud.appengine_admin_v1.types.UrlMap]): + An ordered list of URL-matching patterns that should be + applied to incoming requests. The first matching URL handles + the request and other request handlers are not attempted. + + Only returned in ``GET`` requests if ``view=FULL`` is set. + error_handlers (Sequence[google.cloud.appengine_admin_v1.types.ErrorHandler]): + Custom static error pages. Limited to 10KB per page. + + Only returned in ``GET`` requests if ``view=FULL`` is set. + libraries (Sequence[google.cloud.appengine_admin_v1.types.Library]): + Configuration for third-party Python runtime libraries that + are required by the application. + + Only returned in ``GET`` requests if ``view=FULL`` is set. + api_config (google.cloud.appengine_admin_v1.types.ApiConfigHandler): + Serving configuration for `Google Cloud + Endpoints `__. + + Only returned in ``GET`` requests if ``view=FULL`` is set. + env_variables (Sequence[google.cloud.appengine_admin_v1.types.Version.EnvVariablesEntry]): + Environment variables available to the application. + + Only returned in ``GET`` requests if ``view=FULL`` is set. + build_env_variables (Sequence[google.cloud.appengine_admin_v1.types.Version.BuildEnvVariablesEntry]): + Environment variables available to the build environment. + + Only returned in ``GET`` requests if ``view=FULL`` is set. + default_expiration (google.protobuf.duration_pb2.Duration): + Duration that static files should be cached by web proxies + and browsers. Only applicable if the corresponding + `StaticFilesHandler `__ + does not specify its own expiration time. + + Only returned in ``GET`` requests if ``view=FULL`` is set. + health_check (google.cloud.appengine_admin_v1.types.HealthCheck): + Configures health checking for instances. Unhealthy + instances are stopped and replaced with new instances. Only + applicable in the App Engine flexible environment. + + Only returned in ``GET`` requests if ``view=FULL`` is set. + readiness_check (google.cloud.appengine_admin_v1.types.ReadinessCheck): + Configures readiness health checking for instances. + Unhealthy instances are not put into the backend traffic + rotation. + + Only returned in ``GET`` requests if ``view=FULL`` is set. + liveness_check (google.cloud.appengine_admin_v1.types.LivenessCheck): + Configures liveness health checking for instances. Unhealthy + instances are stopped and replaced with new instances + + Only returned in ``GET`` requests if ``view=FULL`` is set. + nobuild_files_regex (str): + Files that match this pattern will not be built into this + version. Only applicable for Go runtimes. + + Only returned in ``GET`` requests if ``view=FULL`` is set. + deployment (google.cloud.appengine_admin_v1.types.Deployment): + Code and application artifacts that make up this version. + + Only returned in ``GET`` requests if ``view=FULL`` is set. + version_url (str): + Serving URL for this version. Example: + "https://myversion-dot-myservice-dot- + myapp.appspot.com" + @OutputOnly + endpoints_api_service (google.cloud.appengine_admin_v1.types.EndpointsApiService): + Cloud Endpoints configuration. + + If endpoints_api_service is set, the Cloud Endpoints + Extensible Service Proxy will be provided to serve the API + implemented by the app. + entrypoint (google.cloud.appengine_admin_v1.types.Entrypoint): + The entrypoint for the application. + vpc_access_connector (google.cloud.appengine_admin_v1.types.VpcAccessConnector): + Enables VPC connectivity for standard apps. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + id = proto.Field( + proto.STRING, + number=2, + ) + automatic_scaling = proto.Field( + proto.MESSAGE, + number=3, + oneof='scaling', + message='AutomaticScaling', + ) + basic_scaling = proto.Field( + proto.MESSAGE, + number=4, + oneof='scaling', + message='BasicScaling', + ) + manual_scaling = proto.Field( + proto.MESSAGE, + number=5, + oneof='scaling', + message='ManualScaling', + ) + inbound_services = proto.RepeatedField( + proto.ENUM, + number=6, + enum='InboundServiceType', + ) + instance_class = proto.Field( + proto.STRING, + number=7, + ) + network = proto.Field( + proto.MESSAGE, + number=8, + message='Network', + ) + zones = proto.RepeatedField( + proto.STRING, + number=118, + ) + resources = proto.Field( + proto.MESSAGE, + number=9, + message='Resources', + ) + runtime = proto.Field( + proto.STRING, + number=10, + ) + runtime_channel = proto.Field( + proto.STRING, + number=117, + ) + threadsafe = proto.Field( + proto.BOOL, + number=11, + ) + vm = proto.Field( + proto.BOOL, + number=12, + ) + beta_settings = proto.MapField( + proto.STRING, + proto.STRING, + number=13, + ) + env = proto.Field( + proto.STRING, + number=14, + ) + serving_status = proto.Field( + proto.ENUM, + number=15, + enum='ServingStatus', + ) + created_by = proto.Field( + proto.STRING, + number=16, + ) + create_time = proto.Field( + proto.MESSAGE, + number=17, + message=timestamp_pb2.Timestamp, + ) + disk_usage_bytes = proto.Field( + proto.INT64, + number=18, + ) + runtime_api_version = proto.Field( + proto.STRING, + number=21, + ) + runtime_main_executable_path = proto.Field( + proto.STRING, + number=22, + ) + service_account = proto.Field( + proto.STRING, + number=127, + ) + handlers = proto.RepeatedField( + proto.MESSAGE, + number=100, + message=app_yaml.UrlMap, + ) + error_handlers = proto.RepeatedField( + proto.MESSAGE, + number=101, + message=app_yaml.ErrorHandler, + ) + libraries = proto.RepeatedField( + proto.MESSAGE, + number=102, + message=app_yaml.Library, + ) + api_config = proto.Field( + proto.MESSAGE, + number=103, + message=app_yaml.ApiConfigHandler, + ) + env_variables = proto.MapField( + proto.STRING, + proto.STRING, + number=104, + ) + build_env_variables = proto.MapField( + proto.STRING, + proto.STRING, + number=125, + ) + default_expiration = proto.Field( + proto.MESSAGE, + number=105, + message=duration_pb2.Duration, + ) + health_check = proto.Field( + proto.MESSAGE, + number=106, + message=app_yaml.HealthCheck, + ) + readiness_check = proto.Field( + proto.MESSAGE, + number=112, + message=app_yaml.ReadinessCheck, + ) + liveness_check = proto.Field( + proto.MESSAGE, + number=113, + message=app_yaml.LivenessCheck, + ) + nobuild_files_regex = proto.Field( + proto.STRING, + number=107, + ) + deployment = proto.Field( + proto.MESSAGE, + number=108, + message=deploy.Deployment, + ) + version_url = proto.Field( + proto.STRING, + number=109, + ) + endpoints_api_service = proto.Field( + proto.MESSAGE, + number=110, + message='EndpointsApiService', + ) + entrypoint = proto.Field( + proto.MESSAGE, + number=122, + message='Entrypoint', + ) + vpc_access_connector = proto.Field( + proto.MESSAGE, + number=121, + message='VpcAccessConnector', + ) + + +class EndpointsApiService(proto.Message): + r"""`Cloud Endpoints `__ + configuration. The Endpoints API Service provides tooling for + serving Open API and gRPC endpoints via an NGINX proxy. Only valid + for App Engine Flexible environment deployments. + + The fields here refer to the name and configuration ID of a + "service" resource in the `Service Management + API `__. + + Attributes: + name (str): + Endpoints service name which is the name of + the "service" resource in the Service Management + API. For example + "myapi.endpoints.myproject.cloud.goog". + config_id (str): + Endpoints service configuration ID as specified by the + Service Management API. For example "2016-09-19r1". + + By default, the rollout strategy for Endpoints is + ``RolloutStrategy.FIXED``. This means that Endpoints starts + up with a particular configuration ID. When a new + configuration is rolled out, Endpoints must be given the new + configuration ID. The ``config_id`` field is used to give + the configuration ID and is required in this case. + + Endpoints also has a rollout strategy called + ``RolloutStrategy.MANAGED``. When using this, Endpoints + fetches the latest configuration and does not need the + configuration ID. In this case, ``config_id`` must be + omitted. + rollout_strategy (google.cloud.appengine_admin_v1.types.EndpointsApiService.RolloutStrategy): + Endpoints rollout strategy. If ``FIXED``, ``config_id`` must + be specified. If ``MANAGED``, ``config_id`` must be omitted. + disable_trace_sampling (bool): + Enable or disable trace sampling. By default, + this is set to false for enabled. + """ + class RolloutStrategy(proto.Enum): + r"""Available rollout strategies.""" + UNSPECIFIED_ROLLOUT_STRATEGY = 0 + FIXED = 1 + MANAGED = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + config_id = proto.Field( + proto.STRING, + number=2, + ) + rollout_strategy = proto.Field( + proto.ENUM, + number=3, + enum=RolloutStrategy, + ) + disable_trace_sampling = proto.Field( + proto.BOOL, + number=4, + ) + + +class AutomaticScaling(proto.Message): + r"""Automatic scaling is based on request rate, response + latencies, and other application metrics. + + Attributes: + cool_down_period (google.protobuf.duration_pb2.Duration): + The time period that the + `Autoscaler `__ + should wait before it starts collecting information from a + new instance. This prevents the autoscaler from collecting + information when the instance is initializing, during which + the collected usage would not be reliable. Only applicable + in the App Engine flexible environment. + cpu_utilization (google.cloud.appengine_admin_v1.types.CpuUtilization): + Target scaling by CPU usage. + max_concurrent_requests (int): + Number of concurrent requests an automatic + scaling instance can accept before the scheduler + spawns a new instance. + Defaults to a runtime-specific value. + max_idle_instances (int): + Maximum number of idle instances that should + be maintained for this version. + max_total_instances (int): + Maximum number of instances that should be + started to handle requests for this version. + max_pending_latency (google.protobuf.duration_pb2.Duration): + Maximum amount of time that a request should + wait in the pending queue before starting a new + instance to handle it. + min_idle_instances (int): + Minimum number of idle instances that should + be maintained for this version. Only applicable + for the default version of a service. + min_total_instances (int): + Minimum number of running instances that + should be maintained for this version. + min_pending_latency (google.protobuf.duration_pb2.Duration): + Minimum amount of time a request should wait + in the pending queue before starting a new + instance to handle it. + request_utilization (google.cloud.appengine_admin_v1.types.RequestUtilization): + Target scaling by request utilization. + disk_utilization (google.cloud.appengine_admin_v1.types.DiskUtilization): + Target scaling by disk usage. + network_utilization (google.cloud.appengine_admin_v1.types.NetworkUtilization): + Target scaling by network usage. + standard_scheduler_settings (google.cloud.appengine_admin_v1.types.StandardSchedulerSettings): + Scheduler settings for standard environment. + """ + + cool_down_period = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + cpu_utilization = proto.Field( + proto.MESSAGE, + number=2, + message='CpuUtilization', + ) + max_concurrent_requests = proto.Field( + proto.INT32, + number=3, + ) + max_idle_instances = proto.Field( + proto.INT32, + number=4, + ) + max_total_instances = proto.Field( + proto.INT32, + number=5, + ) + max_pending_latency = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + min_idle_instances = proto.Field( + proto.INT32, + number=7, + ) + min_total_instances = proto.Field( + proto.INT32, + number=8, + ) + min_pending_latency = proto.Field( + proto.MESSAGE, + number=9, + message=duration_pb2.Duration, + ) + request_utilization = proto.Field( + proto.MESSAGE, + number=10, + message='RequestUtilization', + ) + disk_utilization = proto.Field( + proto.MESSAGE, + number=11, + message='DiskUtilization', + ) + network_utilization = proto.Field( + proto.MESSAGE, + number=12, + message='NetworkUtilization', + ) + standard_scheduler_settings = proto.Field( + proto.MESSAGE, + number=20, + message='StandardSchedulerSettings', + ) + + +class BasicScaling(proto.Message): + r"""A service with basic scaling will create an instance when the + application receives a request. The instance will be turned down + when the app becomes idle. Basic scaling is ideal for work that + is intermittent or driven by user activity. + + Attributes: + idle_timeout (google.protobuf.duration_pb2.Duration): + Duration of time after the last request that + an instance must wait before the instance is + shut down. + max_instances (int): + Maximum number of instances to create for + this version. + """ + + idle_timeout = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + max_instances = proto.Field( + proto.INT32, + number=2, + ) + + +class ManualScaling(proto.Message): + r"""A service with manual scaling runs continuously, allowing you + to perform complex initialization and rely on the state of its + memory over time. + + Attributes: + instances (int): + Number of instances to assign to the service at the start. + This number can later be altered by using the `Modules + API `__ + ``set_num_instances()`` function. + """ + + instances = proto.Field( + proto.INT32, + number=1, + ) + + +class CpuUtilization(proto.Message): + r"""Target scaling by CPU usage. + Attributes: + aggregation_window_length (google.protobuf.duration_pb2.Duration): + Period of time over which CPU utilization is + calculated. + target_utilization (float): + Target CPU utilization ratio to maintain when + scaling. Must be between 0 and 1. + """ + + aggregation_window_length = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + target_utilization = proto.Field( + proto.DOUBLE, + number=2, + ) + + +class RequestUtilization(proto.Message): + r"""Target scaling by request utilization. + Only applicable in the App Engine flexible environment. + + Attributes: + target_request_count_per_second (int): + Target requests per second. + target_concurrent_requests (int): + Target number of concurrent requests. + """ + + target_request_count_per_second = proto.Field( + proto.INT32, + number=1, + ) + target_concurrent_requests = proto.Field( + proto.INT32, + number=2, + ) + + +class DiskUtilization(proto.Message): + r"""Target scaling by disk usage. + Only applicable in the App Engine flexible environment. + + Attributes: + target_write_bytes_per_second (int): + Target bytes written per second. + target_write_ops_per_second (int): + Target ops written per second. + target_read_bytes_per_second (int): + Target bytes read per second. + target_read_ops_per_second (int): + Target ops read per seconds. + """ + + target_write_bytes_per_second = proto.Field( + proto.INT32, + number=14, + ) + target_write_ops_per_second = proto.Field( + proto.INT32, + number=15, + ) + target_read_bytes_per_second = proto.Field( + proto.INT32, + number=16, + ) + target_read_ops_per_second = proto.Field( + proto.INT32, + number=17, + ) + + +class NetworkUtilization(proto.Message): + r"""Target scaling by network usage. + Only applicable in the App Engine flexible environment. + + Attributes: + target_sent_bytes_per_second (int): + Target bytes sent per second. + target_sent_packets_per_second (int): + Target packets sent per second. + target_received_bytes_per_second (int): + Target bytes received per second. + target_received_packets_per_second (int): + Target packets received per second. + """ + + target_sent_bytes_per_second = proto.Field( + proto.INT32, + number=1, + ) + target_sent_packets_per_second = proto.Field( + proto.INT32, + number=11, + ) + target_received_bytes_per_second = proto.Field( + proto.INT32, + number=12, + ) + target_received_packets_per_second = proto.Field( + proto.INT32, + number=13, + ) + + +class StandardSchedulerSettings(proto.Message): + r"""Scheduler settings for standard environment. + Attributes: + target_cpu_utilization (float): + Target CPU utilization ratio to maintain when + scaling. + target_throughput_utilization (float): + Target throughput utilization ratio to + maintain when scaling + min_instances (int): + Minimum number of instances to run for this version. Set to + zero to disable ``min_instances`` configuration. + max_instances (int): + Maximum number of instances to run for this version. Set to + zero to disable ``max_instances`` configuration. + """ + + target_cpu_utilization = proto.Field( + proto.DOUBLE, + number=1, + ) + target_throughput_utilization = proto.Field( + proto.DOUBLE, + number=2, + ) + min_instances = proto.Field( + proto.INT32, + number=3, + ) + max_instances = proto.Field( + proto.INT32, + number=4, + ) + + +class Network(proto.Message): + r"""Extra network settings. + Only applicable in the App Engine flexible environment. + + Attributes: + forwarded_ports (Sequence[str]): + List of ports, or port pairs, to forward from + the virtual machine to the application + container. Only applicable in the App Engine + flexible environment. + instance_tag (str): + Tag to apply to the instance during creation. + Only applicable in the App Engine flexible + environment. + name (str): + Google Compute Engine network where the virtual machines are + created. Specify the short name, not the resource path. + + Defaults to ``default``. + subnetwork_name (str): + Google Cloud Platform sub-network where the virtual machines + are created. Specify the short name, not the resource path. + + If a subnetwork name is specified, a network name will also + be required unless it is for the default network. + + - If the network that the instance is being created in is a + Legacy network, then the IP address is allocated from the + IPv4Range. + - If the network that the instance is being created in is + an auto Subnet Mode Network, then only network name + should be specified (not the subnetwork_name) and the IP + address is created from the IPCidrRange of the subnetwork + that exists in that zone for that network. + - If the network that the instance is being created in is a + custom Subnet Mode Network, then the subnetwork_name must + be specified and the IP address is created from the + IPCidrRange of the subnetwork. + + If specified, the subnetwork must exist in the same region + as the App Engine flexible environment application. + session_affinity (bool): + Enable session affinity. + Only applicable in the App Engine flexible + environment. + """ + + forwarded_ports = proto.RepeatedField( + proto.STRING, + number=1, + ) + instance_tag = proto.Field( + proto.STRING, + number=2, + ) + name = proto.Field( + proto.STRING, + number=3, + ) + subnetwork_name = proto.Field( + proto.STRING, + number=4, + ) + session_affinity = proto.Field( + proto.BOOL, + number=5, + ) + + +class Volume(proto.Message): + r"""Volumes mounted within the app container. + Only applicable in the App Engine flexible environment. + + Attributes: + name (str): + Unique name for the volume. + volume_type (str): + Underlying volume type, e.g. 'tmpfs'. + size_gb (float): + Volume size in gigabytes. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + volume_type = proto.Field( + proto.STRING, + number=2, + ) + size_gb = proto.Field( + proto.DOUBLE, + number=3, + ) + + +class Resources(proto.Message): + r"""Machine resources for a version. + Attributes: + cpu (float): + Number of CPU cores needed. + disk_gb (float): + Disk size (GB) needed. + memory_gb (float): + Memory (GB) needed. + volumes (Sequence[google.cloud.appengine_admin_v1.types.Volume]): + User specified volumes. + kms_key_reference (str): + The name of the encryption key that is stored + in Google Cloud KMS. Only should be used by + Cloud Composer to encrypt the vm disk + """ + + cpu = proto.Field( + proto.DOUBLE, + number=1, + ) + disk_gb = proto.Field( + proto.DOUBLE, + number=2, + ) + memory_gb = proto.Field( + proto.DOUBLE, + number=3, + ) + volumes = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Volume', + ) + kms_key_reference = proto.Field( + proto.STRING, + number=5, + ) + + +class VpcAccessConnector(proto.Message): + r"""VPC access connector specification. + Attributes: + name (str): + Full Serverless VPC Access Connector name + e.g. /projects/my-project/locations/us- + central1/connectors/c1. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class Entrypoint(proto.Message): + r"""The entrypoint for the application. + Attributes: + shell (str): + The format should be a shell command that can be fed to + ``bash -c``. + """ + + shell = proto.Field( + proto.STRING, + number=1, + oneof='command', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini new file mode 100644 index 0000000..4505b48 --- /dev/null +++ b/owl-bot-staging/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py new file mode 100644 index 0000000..f447519 --- /dev/null +++ b/owl-bot-staging/v1/noxfile.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/appengine_admin_v1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/owl-bot-staging/v1/scripts/fixup_appengine_admin_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_appengine_admin_v1_keywords.py new file mode 100644 index 0000000..977426f --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_appengine_admin_v1_keywords.py @@ -0,0 +1,209 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class appengine_adminCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_update_ingress_rules': ('name', 'ingress_rules', ), + 'create_application': ('application', ), + 'create_authorized_certificate': ('parent', 'certificate', ), + 'create_domain_mapping': ('parent', 'domain_mapping', 'override_strategy', ), + 'create_ingress_rule': ('parent', 'rule', ), + 'create_version': ('parent', 'version', ), + 'debug_instance': ('name', 'ssh_key', ), + 'delete_authorized_certificate': ('name', ), + 'delete_domain_mapping': ('name', ), + 'delete_ingress_rule': ('name', ), + 'delete_instance': ('name', ), + 'delete_service': ('name', ), + 'delete_version': ('name', ), + 'get_application': ('name', ), + 'get_authorized_certificate': ('name', 'view', ), + 'get_domain_mapping': ('name', ), + 'get_ingress_rule': ('name', ), + 'get_instance': ('name', ), + 'get_service': ('name', ), + 'get_version': ('name', 'view', ), + 'list_authorized_certificates': ('parent', 'view', 'page_size', 'page_token', ), + 'list_authorized_domains': ('parent', 'page_size', 'page_token', ), + 'list_domain_mappings': ('parent', 'page_size', 'page_token', ), + 'list_ingress_rules': ('parent', 'page_size', 'page_token', 'matching_address', ), + 'list_instances': ('parent', 'page_size', 'page_token', ), + 'list_services': ('parent', 'page_size', 'page_token', ), + 'list_versions': ('parent', 'view', 'page_size', 'page_token', ), + 'repair_application': ('name', ), + 'update_application': ('name', 'application', 'update_mask', ), + 'update_authorized_certificate': ('name', 'certificate', 'update_mask', ), + 'update_domain_mapping': ('name', 'domain_mapping', 'update_mask', ), + 'update_ingress_rule': ('name', 'rule', 'update_mask', ), + 'update_service': ('name', 'service', 'update_mask', 'migrate_traffic', ), + 'update_version': ('name', 'version', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=appengine_adminCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the appengine_admin client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py new file mode 100644 index 0000000..e549b9d --- /dev/null +++ b/owl-bot-staging/v1/setup.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-appengine-admin', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/__init__.py new file mode 100644 index 0000000..b54a5fc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_applications.py b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_applications.py new file mode 100644 index 0000000..4365fbb --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_applications.py @@ -0,0 +1,1539 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.appengine_admin_v1.services.applications import ApplicationsAsyncClient +from google.cloud.appengine_admin_v1.services.applications import ApplicationsClient +from google.cloud.appengine_admin_v1.services.applications import transports +from google.cloud.appengine_admin_v1.services.applications.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import application +from google.cloud.appengine_admin_v1.types import operation as ga_operation +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ApplicationsClient._get_default_mtls_endpoint(None) is None + assert ApplicationsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ApplicationsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ApplicationsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ApplicationsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ApplicationsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + ApplicationsClient, + ApplicationsAsyncClient, +]) +def test_applications_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'appengine.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ApplicationsGrpcTransport, "grpc"), + (transports.ApplicationsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_applications_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + ApplicationsClient, + ApplicationsAsyncClient, +]) +def test_applications_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'appengine.googleapis.com:443' + + +def test_applications_client_get_transport_class(): + transport = ApplicationsClient.get_transport_class() + available_transports = [ + transports.ApplicationsGrpcTransport, + ] + assert transport in available_transports + + transport = ApplicationsClient.get_transport_class("grpc") + assert transport == transports.ApplicationsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ApplicationsClient, transports.ApplicationsGrpcTransport, "grpc"), + (ApplicationsAsyncClient, transports.ApplicationsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ApplicationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ApplicationsClient)) +@mock.patch.object(ApplicationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ApplicationsAsyncClient)) +def test_applications_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(ApplicationsClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(ApplicationsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ApplicationsClient, transports.ApplicationsGrpcTransport, "grpc", "true"), + (ApplicationsAsyncClient, transports.ApplicationsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ApplicationsClient, transports.ApplicationsGrpcTransport, "grpc", "false"), + (ApplicationsAsyncClient, transports.ApplicationsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ApplicationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ApplicationsClient)) +@mock.patch.object(ApplicationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ApplicationsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_applications_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ApplicationsClient, transports.ApplicationsGrpcTransport, "grpc"), + (ApplicationsAsyncClient, transports.ApplicationsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_applications_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ApplicationsClient, transports.ApplicationsGrpcTransport, "grpc"), + (ApplicationsAsyncClient, transports.ApplicationsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_applications_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_applications_client_client_options_from_dict(): + with mock.patch('google.cloud.appengine_admin_v1.services.applications.transports.ApplicationsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ApplicationsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_get_application(transport: str = 'grpc', request_type=appengine.GetApplicationRequest): + client = ApplicationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = application.Application( + name='name_value', + id='id_value', + auth_domain='auth_domain_value', + location_id='location_id_value', + code_bucket='code_bucket_value', + serving_status=application.Application.ServingStatus.SERVING, + default_hostname='default_hostname_value', + default_bucket='default_bucket_value', + gcr_domain='gcr_domain_value', + database_type=application.Application.DatabaseType.CLOUD_DATASTORE, + ) + response = client.get_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetApplicationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, application.Application) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.auth_domain == 'auth_domain_value' + assert response.location_id == 'location_id_value' + assert response.code_bucket == 'code_bucket_value' + assert response.serving_status == application.Application.ServingStatus.SERVING + assert response.default_hostname == 'default_hostname_value' + assert response.default_bucket == 'default_bucket_value' + assert response.gcr_domain == 'gcr_domain_value' + assert response.database_type == application.Application.DatabaseType.CLOUD_DATASTORE + + +def test_get_application_from_dict(): + test_get_application(request_type=dict) + + +def test_get_application_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ApplicationsClient( + credentials=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_application), + '__call__') as call: + client.get_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetApplicationRequest() + + +@pytest.mark.asyncio +async def test_get_application_async(transport: str = 'grpc_asyncio', request_type=appengine.GetApplicationRequest): + client = ApplicationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(application.Application( + name='name_value', + id='id_value', + auth_domain='auth_domain_value', + location_id='location_id_value', + code_bucket='code_bucket_value', + serving_status=application.Application.ServingStatus.SERVING, + default_hostname='default_hostname_value', + default_bucket='default_bucket_value', + gcr_domain='gcr_domain_value', + database_type=application.Application.DatabaseType.CLOUD_DATASTORE, + )) + response = await client.get_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetApplicationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, application.Application) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.auth_domain == 'auth_domain_value' + assert response.location_id == 'location_id_value' + assert response.code_bucket == 'code_bucket_value' + assert response.serving_status == application.Application.ServingStatus.SERVING + assert response.default_hostname == 'default_hostname_value' + assert response.default_bucket == 'default_bucket_value' + assert response.gcr_domain == 'gcr_domain_value' + assert response.database_type == application.Application.DatabaseType.CLOUD_DATASTORE + + +@pytest.mark.asyncio +async def test_get_application_async_from_dict(): + await test_get_application_async(request_type=dict) + + +def test_get_application_field_headers(): + client = ApplicationsClient( + credentials=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. + request = appengine.GetApplicationRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_application), + '__call__') as call: + call.return_value = application.Application() + client.get_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_application_field_headers_async(): + client = ApplicationsAsyncClient( + credentials=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. + request = appengine.GetApplicationRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_application), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(application.Application()) + await client.get_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_create_application(transport: str = 'grpc', request_type=appengine.CreateApplicationRequest): + client = ApplicationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.CreateApplicationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_application_from_dict(): + test_create_application(request_type=dict) + + +def test_create_application_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ApplicationsClient( + credentials=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_application), + '__call__') as call: + client.create_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.CreateApplicationRequest() + + +@pytest.mark.asyncio +async def test_create_application_async(transport: str = 'grpc_asyncio', request_type=appengine.CreateApplicationRequest): + client = ApplicationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.CreateApplicationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_application_async_from_dict(): + await test_create_application_async(request_type=dict) + + +def test_update_application(transport: str = 'grpc', request_type=appengine.UpdateApplicationRequest): + client = ApplicationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.UpdateApplicationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_application_from_dict(): + test_update_application(request_type=dict) + + +def test_update_application_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ApplicationsClient( + credentials=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_application), + '__call__') as call: + client.update_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.UpdateApplicationRequest() + + +@pytest.mark.asyncio +async def test_update_application_async(transport: str = 'grpc_asyncio', request_type=appengine.UpdateApplicationRequest): + client = ApplicationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.UpdateApplicationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_application_async_from_dict(): + await test_update_application_async(request_type=dict) + + +def test_update_application_field_headers(): + client = ApplicationsClient( + credentials=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. + request = appengine.UpdateApplicationRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_application_field_headers_async(): + client = ApplicationsAsyncClient( + credentials=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. + request = appengine.UpdateApplicationRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_application), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_repair_application(transport: str = 'grpc', request_type=appengine.RepairApplicationRequest): + client = ApplicationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.repair_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.repair_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.RepairApplicationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_repair_application_from_dict(): + test_repair_application(request_type=dict) + + +def test_repair_application_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ApplicationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.repair_application), + '__call__') as call: + client.repair_application() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.RepairApplicationRequest() + + +@pytest.mark.asyncio +async def test_repair_application_async(transport: str = 'grpc_asyncio', request_type=appengine.RepairApplicationRequest): + client = ApplicationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.repair_application), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.repair_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.RepairApplicationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_repair_application_async_from_dict(): + await test_repair_application_async(request_type=dict) + + +def test_repair_application_field_headers(): + client = ApplicationsClient( + credentials=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. + request = appengine.RepairApplicationRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.repair_application), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.repair_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_repair_application_field_headers_async(): + client = ApplicationsAsyncClient( + credentials=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. + request = appengine.RepairApplicationRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.repair_application), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.repair_application(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ApplicationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ApplicationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ApplicationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ApplicationsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ApplicationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ApplicationsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ApplicationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ApplicationsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ApplicationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ApplicationsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ApplicationsGrpcTransport, + transports.ApplicationsGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ApplicationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ApplicationsGrpcTransport, + ) + +def test_applications_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ApplicationsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_applications_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.appengine_admin_v1.services.applications.transports.ApplicationsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ApplicationsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_application', + 'create_application', + 'update_application', + 'repair_application', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_applications_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.applications.transports.ApplicationsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ApplicationsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_applications_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.applications.transports.ApplicationsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ApplicationsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ), + quota_project_id="octopus", + ) + + +def test_applications_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.appengine_admin_v1.services.applications.transports.ApplicationsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ApplicationsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_applications_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ApplicationsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_applications_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ApplicationsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ApplicationsGrpcTransport, + transports.ApplicationsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_applications_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ApplicationsGrpcTransport, + transports.ApplicationsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_applications_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ApplicationsGrpcTransport, grpc_helpers), + (transports.ApplicationsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_applications_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + scopes=["1", "2"], + default_host="appengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ApplicationsGrpcTransport, transports.ApplicationsGrpcAsyncIOTransport]) +def test_applications_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_applications_host_no_port(): + client = ApplicationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com'), + ) + assert client.transport._host == 'appengine.googleapis.com:443' + + +def test_applications_host_with_port(): + client = ApplicationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com:8000'), + ) + assert client.transport._host == 'appengine.googleapis.com:8000' + +def test_applications_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ApplicationsGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_applications_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ApplicationsGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.ApplicationsGrpcTransport, transports.ApplicationsGrpcAsyncIOTransport]) +def test_applications_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.ApplicationsGrpcTransport, transports.ApplicationsGrpcAsyncIOTransport]) +def test_applications_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_applications_grpc_lro_client(): + client = ApplicationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_applications_grpc_lro_async_client(): + client = ApplicationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ApplicationsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = ApplicationsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ApplicationsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = ApplicationsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = ApplicationsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ApplicationsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ApplicationsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = ApplicationsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ApplicationsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = ApplicationsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = ApplicationsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ApplicationsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ApplicationsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = ApplicationsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ApplicationsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.ApplicationsTransport, '_prep_wrapped_messages') as prep: + client = ApplicationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ApplicationsTransport, '_prep_wrapped_messages') as prep: + transport_class = ApplicationsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py new file mode 100644 index 0000000..5dddcce --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py @@ -0,0 +1,1927 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.appengine_admin_v1.services.authorized_certificates import AuthorizedCertificatesAsyncClient +from google.cloud.appengine_admin_v1.services.authorized_certificates import AuthorizedCertificatesClient +from google.cloud.appengine_admin_v1.services.authorized_certificates import pagers +from google.cloud.appengine_admin_v1.services.authorized_certificates import transports +from google.cloud.appengine_admin_v1.services.authorized_certificates.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import certificate +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert AuthorizedCertificatesClient._get_default_mtls_endpoint(None) is None + assert AuthorizedCertificatesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AuthorizedCertificatesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AuthorizedCertificatesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AuthorizedCertificatesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AuthorizedCertificatesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + AuthorizedCertificatesClient, + AuthorizedCertificatesAsyncClient, +]) +def test_authorized_certificates_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'appengine.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AuthorizedCertificatesGrpcTransport, "grpc"), + (transports.AuthorizedCertificatesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_authorized_certificates_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + AuthorizedCertificatesClient, + AuthorizedCertificatesAsyncClient, +]) +def test_authorized_certificates_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'appengine.googleapis.com:443' + + +def test_authorized_certificates_client_get_transport_class(): + transport = AuthorizedCertificatesClient.get_transport_class() + available_transports = [ + transports.AuthorizedCertificatesGrpcTransport, + ] + assert transport in available_transports + + transport = AuthorizedCertificatesClient.get_transport_class("grpc") + assert transport == transports.AuthorizedCertificatesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AuthorizedCertificatesClient, transports.AuthorizedCertificatesGrpcTransport, "grpc"), + (AuthorizedCertificatesAsyncClient, transports.AuthorizedCertificatesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(AuthorizedCertificatesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AuthorizedCertificatesClient)) +@mock.patch.object(AuthorizedCertificatesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AuthorizedCertificatesAsyncClient)) +def test_authorized_certificates_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(AuthorizedCertificatesClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(AuthorizedCertificatesClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (AuthorizedCertificatesClient, transports.AuthorizedCertificatesGrpcTransport, "grpc", "true"), + (AuthorizedCertificatesAsyncClient, transports.AuthorizedCertificatesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AuthorizedCertificatesClient, transports.AuthorizedCertificatesGrpcTransport, "grpc", "false"), + (AuthorizedCertificatesAsyncClient, transports.AuthorizedCertificatesGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(AuthorizedCertificatesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AuthorizedCertificatesClient)) +@mock.patch.object(AuthorizedCertificatesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AuthorizedCertificatesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_authorized_certificates_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AuthorizedCertificatesClient, transports.AuthorizedCertificatesGrpcTransport, "grpc"), + (AuthorizedCertificatesAsyncClient, transports.AuthorizedCertificatesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_authorized_certificates_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AuthorizedCertificatesClient, transports.AuthorizedCertificatesGrpcTransport, "grpc"), + (AuthorizedCertificatesAsyncClient, transports.AuthorizedCertificatesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_authorized_certificates_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_authorized_certificates_client_client_options_from_dict(): + with mock.patch('google.cloud.appengine_admin_v1.services.authorized_certificates.transports.AuthorizedCertificatesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AuthorizedCertificatesClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_authorized_certificates(transport: str = 'grpc', request_type=appengine.ListAuthorizedCertificatesRequest): + client = AuthorizedCertificatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorized_certificates), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = appengine.ListAuthorizedCertificatesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_authorized_certificates(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListAuthorizedCertificatesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAuthorizedCertificatesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_authorized_certificates_from_dict(): + test_list_authorized_certificates(request_type=dict) + + +def test_list_authorized_certificates_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AuthorizedCertificatesClient( + credentials=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_authorized_certificates), + '__call__') as call: + client.list_authorized_certificates() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListAuthorizedCertificatesRequest() + + +@pytest.mark.asyncio +async def test_list_authorized_certificates_async(transport: str = 'grpc_asyncio', request_type=appengine.ListAuthorizedCertificatesRequest): + client = AuthorizedCertificatesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorized_certificates), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListAuthorizedCertificatesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_authorized_certificates(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListAuthorizedCertificatesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAuthorizedCertificatesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_authorized_certificates_async_from_dict(): + await test_list_authorized_certificates_async(request_type=dict) + + +def test_list_authorized_certificates_field_headers(): + client = AuthorizedCertificatesClient( + credentials=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. + request = appengine.ListAuthorizedCertificatesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorized_certificates), + '__call__') as call: + call.return_value = appengine.ListAuthorizedCertificatesResponse() + client.list_authorized_certificates(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_authorized_certificates_field_headers_async(): + client = AuthorizedCertificatesAsyncClient( + credentials=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. + request = appengine.ListAuthorizedCertificatesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorized_certificates), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListAuthorizedCertificatesResponse()) + await client.list_authorized_certificates(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_list_authorized_certificates_pager(): + client = AuthorizedCertificatesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorized_certificates), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListAuthorizedCertificatesResponse( + certificates=[ + certificate.AuthorizedCertificate(), + certificate.AuthorizedCertificate(), + certificate.AuthorizedCertificate(), + ], + next_page_token='abc', + ), + appengine.ListAuthorizedCertificatesResponse( + certificates=[], + next_page_token='def', + ), + appengine.ListAuthorizedCertificatesResponse( + certificates=[ + certificate.AuthorizedCertificate(), + ], + next_page_token='ghi', + ), + appengine.ListAuthorizedCertificatesResponse( + certificates=[ + certificate.AuthorizedCertificate(), + certificate.AuthorizedCertificate(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_authorized_certificates(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, certificate.AuthorizedCertificate) + for i in results) + +def test_list_authorized_certificates_pages(): + client = AuthorizedCertificatesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorized_certificates), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListAuthorizedCertificatesResponse( + certificates=[ + certificate.AuthorizedCertificate(), + certificate.AuthorizedCertificate(), + certificate.AuthorizedCertificate(), + ], + next_page_token='abc', + ), + appengine.ListAuthorizedCertificatesResponse( + certificates=[], + next_page_token='def', + ), + appengine.ListAuthorizedCertificatesResponse( + certificates=[ + certificate.AuthorizedCertificate(), + ], + next_page_token='ghi', + ), + appengine.ListAuthorizedCertificatesResponse( + certificates=[ + certificate.AuthorizedCertificate(), + certificate.AuthorizedCertificate(), + ], + ), + RuntimeError, + ) + pages = list(client.list_authorized_certificates(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_authorized_certificates_async_pager(): + client = AuthorizedCertificatesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorized_certificates), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListAuthorizedCertificatesResponse( + certificates=[ + certificate.AuthorizedCertificate(), + certificate.AuthorizedCertificate(), + certificate.AuthorizedCertificate(), + ], + next_page_token='abc', + ), + appengine.ListAuthorizedCertificatesResponse( + certificates=[], + next_page_token='def', + ), + appengine.ListAuthorizedCertificatesResponse( + certificates=[ + certificate.AuthorizedCertificate(), + ], + next_page_token='ghi', + ), + appengine.ListAuthorizedCertificatesResponse( + certificates=[ + certificate.AuthorizedCertificate(), + certificate.AuthorizedCertificate(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_authorized_certificates(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, certificate.AuthorizedCertificate) + for i in responses) + +@pytest.mark.asyncio +async def test_list_authorized_certificates_async_pages(): + client = AuthorizedCertificatesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorized_certificates), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListAuthorizedCertificatesResponse( + certificates=[ + certificate.AuthorizedCertificate(), + certificate.AuthorizedCertificate(), + certificate.AuthorizedCertificate(), + ], + next_page_token='abc', + ), + appengine.ListAuthorizedCertificatesResponse( + certificates=[], + next_page_token='def', + ), + appengine.ListAuthorizedCertificatesResponse( + certificates=[ + certificate.AuthorizedCertificate(), + ], + next_page_token='ghi', + ), + appengine.ListAuthorizedCertificatesResponse( + certificates=[ + certificate.AuthorizedCertificate(), + certificate.AuthorizedCertificate(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_authorized_certificates(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_authorized_certificate(transport: str = 'grpc', request_type=appengine.GetAuthorizedCertificateRequest): + client = AuthorizedCertificatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_authorized_certificate), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = certificate.AuthorizedCertificate( + name='name_value', + id='id_value', + display_name='display_name_value', + domain_names=['domain_names_value'], + visible_domain_mappings=['visible_domain_mappings_value'], + domain_mappings_count=2238, + ) + response = client.get_authorized_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetAuthorizedCertificateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, certificate.AuthorizedCertificate) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.display_name == 'display_name_value' + assert response.domain_names == ['domain_names_value'] + assert response.visible_domain_mappings == ['visible_domain_mappings_value'] + assert response.domain_mappings_count == 2238 + + +def test_get_authorized_certificate_from_dict(): + test_get_authorized_certificate(request_type=dict) + + +def test_get_authorized_certificate_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AuthorizedCertificatesClient( + credentials=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_authorized_certificate), + '__call__') as call: + client.get_authorized_certificate() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetAuthorizedCertificateRequest() + + +@pytest.mark.asyncio +async def test_get_authorized_certificate_async(transport: str = 'grpc_asyncio', request_type=appengine.GetAuthorizedCertificateRequest): + client = AuthorizedCertificatesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_authorized_certificate), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(certificate.AuthorizedCertificate( + name='name_value', + id='id_value', + display_name='display_name_value', + domain_names=['domain_names_value'], + visible_domain_mappings=['visible_domain_mappings_value'], + domain_mappings_count=2238, + )) + response = await client.get_authorized_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetAuthorizedCertificateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, certificate.AuthorizedCertificate) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.display_name == 'display_name_value' + assert response.domain_names == ['domain_names_value'] + assert response.visible_domain_mappings == ['visible_domain_mappings_value'] + assert response.domain_mappings_count == 2238 + + +@pytest.mark.asyncio +async def test_get_authorized_certificate_async_from_dict(): + await test_get_authorized_certificate_async(request_type=dict) + + +def test_get_authorized_certificate_field_headers(): + client = AuthorizedCertificatesClient( + credentials=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. + request = appengine.GetAuthorizedCertificateRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_authorized_certificate), + '__call__') as call: + call.return_value = certificate.AuthorizedCertificate() + client.get_authorized_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_authorized_certificate_field_headers_async(): + client = AuthorizedCertificatesAsyncClient( + credentials=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. + request = appengine.GetAuthorizedCertificateRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_authorized_certificate), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(certificate.AuthorizedCertificate()) + await client.get_authorized_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_create_authorized_certificate(transport: str = 'grpc', request_type=appengine.CreateAuthorizedCertificateRequest): + client = AuthorizedCertificatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_authorized_certificate), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = certificate.AuthorizedCertificate( + name='name_value', + id='id_value', + display_name='display_name_value', + domain_names=['domain_names_value'], + visible_domain_mappings=['visible_domain_mappings_value'], + domain_mappings_count=2238, + ) + response = client.create_authorized_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.CreateAuthorizedCertificateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, certificate.AuthorizedCertificate) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.display_name == 'display_name_value' + assert response.domain_names == ['domain_names_value'] + assert response.visible_domain_mappings == ['visible_domain_mappings_value'] + assert response.domain_mappings_count == 2238 + + +def test_create_authorized_certificate_from_dict(): + test_create_authorized_certificate(request_type=dict) + + +def test_create_authorized_certificate_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AuthorizedCertificatesClient( + credentials=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_authorized_certificate), + '__call__') as call: + client.create_authorized_certificate() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.CreateAuthorizedCertificateRequest() + + +@pytest.mark.asyncio +async def test_create_authorized_certificate_async(transport: str = 'grpc_asyncio', request_type=appengine.CreateAuthorizedCertificateRequest): + client = AuthorizedCertificatesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_authorized_certificate), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(certificate.AuthorizedCertificate( + name='name_value', + id='id_value', + display_name='display_name_value', + domain_names=['domain_names_value'], + visible_domain_mappings=['visible_domain_mappings_value'], + domain_mappings_count=2238, + )) + response = await client.create_authorized_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.CreateAuthorizedCertificateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, certificate.AuthorizedCertificate) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.display_name == 'display_name_value' + assert response.domain_names == ['domain_names_value'] + assert response.visible_domain_mappings == ['visible_domain_mappings_value'] + assert response.domain_mappings_count == 2238 + + +@pytest.mark.asyncio +async def test_create_authorized_certificate_async_from_dict(): + await test_create_authorized_certificate_async(request_type=dict) + + +def test_create_authorized_certificate_field_headers(): + client = AuthorizedCertificatesClient( + credentials=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. + request = appengine.CreateAuthorizedCertificateRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_authorized_certificate), + '__call__') as call: + call.return_value = certificate.AuthorizedCertificate() + client.create_authorized_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_authorized_certificate_field_headers_async(): + client = AuthorizedCertificatesAsyncClient( + credentials=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. + request = appengine.CreateAuthorizedCertificateRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_authorized_certificate), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(certificate.AuthorizedCertificate()) + await client.create_authorized_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_update_authorized_certificate(transport: str = 'grpc', request_type=appengine.UpdateAuthorizedCertificateRequest): + client = AuthorizedCertificatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_authorized_certificate), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = certificate.AuthorizedCertificate( + name='name_value', + id='id_value', + display_name='display_name_value', + domain_names=['domain_names_value'], + visible_domain_mappings=['visible_domain_mappings_value'], + domain_mappings_count=2238, + ) + response = client.update_authorized_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.UpdateAuthorizedCertificateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, certificate.AuthorizedCertificate) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.display_name == 'display_name_value' + assert response.domain_names == ['domain_names_value'] + assert response.visible_domain_mappings == ['visible_domain_mappings_value'] + assert response.domain_mappings_count == 2238 + + +def test_update_authorized_certificate_from_dict(): + test_update_authorized_certificate(request_type=dict) + + +def test_update_authorized_certificate_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AuthorizedCertificatesClient( + credentials=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_authorized_certificate), + '__call__') as call: + client.update_authorized_certificate() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.UpdateAuthorizedCertificateRequest() + + +@pytest.mark.asyncio +async def test_update_authorized_certificate_async(transport: str = 'grpc_asyncio', request_type=appengine.UpdateAuthorizedCertificateRequest): + client = AuthorizedCertificatesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_authorized_certificate), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(certificate.AuthorizedCertificate( + name='name_value', + id='id_value', + display_name='display_name_value', + domain_names=['domain_names_value'], + visible_domain_mappings=['visible_domain_mappings_value'], + domain_mappings_count=2238, + )) + response = await client.update_authorized_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.UpdateAuthorizedCertificateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, certificate.AuthorizedCertificate) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.display_name == 'display_name_value' + assert response.domain_names == ['domain_names_value'] + assert response.visible_domain_mappings == ['visible_domain_mappings_value'] + assert response.domain_mappings_count == 2238 + + +@pytest.mark.asyncio +async def test_update_authorized_certificate_async_from_dict(): + await test_update_authorized_certificate_async(request_type=dict) + + +def test_update_authorized_certificate_field_headers(): + client = AuthorizedCertificatesClient( + credentials=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. + request = appengine.UpdateAuthorizedCertificateRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_authorized_certificate), + '__call__') as call: + call.return_value = certificate.AuthorizedCertificate() + client.update_authorized_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_authorized_certificate_field_headers_async(): + client = AuthorizedCertificatesAsyncClient( + credentials=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. + request = appengine.UpdateAuthorizedCertificateRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_authorized_certificate), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(certificate.AuthorizedCertificate()) + await client.update_authorized_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_delete_authorized_certificate(transport: str = 'grpc', request_type=appengine.DeleteAuthorizedCertificateRequest): + client = AuthorizedCertificatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorized_certificate), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_authorized_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DeleteAuthorizedCertificateRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_authorized_certificate_from_dict(): + test_delete_authorized_certificate(request_type=dict) + + +def test_delete_authorized_certificate_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AuthorizedCertificatesClient( + credentials=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_authorized_certificate), + '__call__') as call: + client.delete_authorized_certificate() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DeleteAuthorizedCertificateRequest() + + +@pytest.mark.asyncio +async def test_delete_authorized_certificate_async(transport: str = 'grpc_asyncio', request_type=appengine.DeleteAuthorizedCertificateRequest): + client = AuthorizedCertificatesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorized_certificate), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_authorized_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DeleteAuthorizedCertificateRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_authorized_certificate_async_from_dict(): + await test_delete_authorized_certificate_async(request_type=dict) + + +def test_delete_authorized_certificate_field_headers(): + client = AuthorizedCertificatesClient( + credentials=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. + request = appengine.DeleteAuthorizedCertificateRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorized_certificate), + '__call__') as call: + call.return_value = None + client.delete_authorized_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_authorized_certificate_field_headers_async(): + client = AuthorizedCertificatesAsyncClient( + credentials=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. + request = appengine.DeleteAuthorizedCertificateRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorized_certificate), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_authorized_certificate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AuthorizedCertificatesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AuthorizedCertificatesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AuthorizedCertificatesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AuthorizedCertificatesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AuthorizedCertificatesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AuthorizedCertificatesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AuthorizedCertificatesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AuthorizedCertificatesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AuthorizedCertificatesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AuthorizedCertificatesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AuthorizedCertificatesGrpcTransport, + transports.AuthorizedCertificatesGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AuthorizedCertificatesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AuthorizedCertificatesGrpcTransport, + ) + +def test_authorized_certificates_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AuthorizedCertificatesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_authorized_certificates_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.appengine_admin_v1.services.authorized_certificates.transports.AuthorizedCertificatesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AuthorizedCertificatesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_authorized_certificates', + 'get_authorized_certificate', + 'create_authorized_certificate', + 'update_authorized_certificate', + 'delete_authorized_certificate', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_authorized_certificates_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.authorized_certificates.transports.AuthorizedCertificatesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AuthorizedCertificatesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_authorized_certificates_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.authorized_certificates.transports.AuthorizedCertificatesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AuthorizedCertificatesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ), + quota_project_id="octopus", + ) + + +def test_authorized_certificates_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.appengine_admin_v1.services.authorized_certificates.transports.AuthorizedCertificatesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AuthorizedCertificatesTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_authorized_certificates_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AuthorizedCertificatesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_authorized_certificates_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AuthorizedCertificatesClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AuthorizedCertificatesGrpcTransport, + transports.AuthorizedCertificatesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_authorized_certificates_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AuthorizedCertificatesGrpcTransport, + transports.AuthorizedCertificatesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_authorized_certificates_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AuthorizedCertificatesGrpcTransport, grpc_helpers), + (transports.AuthorizedCertificatesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_authorized_certificates_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + scopes=["1", "2"], + default_host="appengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AuthorizedCertificatesGrpcTransport, transports.AuthorizedCertificatesGrpcAsyncIOTransport]) +def test_authorized_certificates_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_authorized_certificates_host_no_port(): + client = AuthorizedCertificatesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com'), + ) + assert client.transport._host == 'appengine.googleapis.com:443' + + +def test_authorized_certificates_host_with_port(): + client = AuthorizedCertificatesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com:8000'), + ) + assert client.transport._host == 'appengine.googleapis.com:8000' + +def test_authorized_certificates_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AuthorizedCertificatesGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_authorized_certificates_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AuthorizedCertificatesGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.AuthorizedCertificatesGrpcTransport, transports.AuthorizedCertificatesGrpcAsyncIOTransport]) +def test_authorized_certificates_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.AuthorizedCertificatesGrpcTransport, transports.AuthorizedCertificatesGrpcAsyncIOTransport]) +def test_authorized_certificates_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AuthorizedCertificatesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = AuthorizedCertificatesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AuthorizedCertificatesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = AuthorizedCertificatesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = AuthorizedCertificatesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AuthorizedCertificatesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AuthorizedCertificatesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = AuthorizedCertificatesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AuthorizedCertificatesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = AuthorizedCertificatesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = AuthorizedCertificatesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AuthorizedCertificatesClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AuthorizedCertificatesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = AuthorizedCertificatesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AuthorizedCertificatesClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.AuthorizedCertificatesTransport, '_prep_wrapped_messages') as prep: + client = AuthorizedCertificatesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AuthorizedCertificatesTransport, '_prep_wrapped_messages') as prep: + transport_class = AuthorizedCertificatesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py new file mode 100644 index 0000000..9b8b2d3 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py @@ -0,0 +1,1264 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.appengine_admin_v1.services.authorized_domains import AuthorizedDomainsAsyncClient +from google.cloud.appengine_admin_v1.services.authorized_domains import AuthorizedDomainsClient +from google.cloud.appengine_admin_v1.services.authorized_domains import pagers +from google.cloud.appengine_admin_v1.services.authorized_domains import transports +from google.cloud.appengine_admin_v1.services.authorized_domains.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import domain +from google.oauth2 import service_account +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert AuthorizedDomainsClient._get_default_mtls_endpoint(None) is None + assert AuthorizedDomainsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AuthorizedDomainsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AuthorizedDomainsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AuthorizedDomainsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AuthorizedDomainsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + AuthorizedDomainsClient, + AuthorizedDomainsAsyncClient, +]) +def test_authorized_domains_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'appengine.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AuthorizedDomainsGrpcTransport, "grpc"), + (transports.AuthorizedDomainsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_authorized_domains_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + AuthorizedDomainsClient, + AuthorizedDomainsAsyncClient, +]) +def test_authorized_domains_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'appengine.googleapis.com:443' + + +def test_authorized_domains_client_get_transport_class(): + transport = AuthorizedDomainsClient.get_transport_class() + available_transports = [ + transports.AuthorizedDomainsGrpcTransport, + ] + assert transport in available_transports + + transport = AuthorizedDomainsClient.get_transport_class("grpc") + assert transport == transports.AuthorizedDomainsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AuthorizedDomainsClient, transports.AuthorizedDomainsGrpcTransport, "grpc"), + (AuthorizedDomainsAsyncClient, transports.AuthorizedDomainsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(AuthorizedDomainsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AuthorizedDomainsClient)) +@mock.patch.object(AuthorizedDomainsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AuthorizedDomainsAsyncClient)) +def test_authorized_domains_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(AuthorizedDomainsClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(AuthorizedDomainsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (AuthorizedDomainsClient, transports.AuthorizedDomainsGrpcTransport, "grpc", "true"), + (AuthorizedDomainsAsyncClient, transports.AuthorizedDomainsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AuthorizedDomainsClient, transports.AuthorizedDomainsGrpcTransport, "grpc", "false"), + (AuthorizedDomainsAsyncClient, transports.AuthorizedDomainsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(AuthorizedDomainsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AuthorizedDomainsClient)) +@mock.patch.object(AuthorizedDomainsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AuthorizedDomainsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_authorized_domains_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AuthorizedDomainsClient, transports.AuthorizedDomainsGrpcTransport, "grpc"), + (AuthorizedDomainsAsyncClient, transports.AuthorizedDomainsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_authorized_domains_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AuthorizedDomainsClient, transports.AuthorizedDomainsGrpcTransport, "grpc"), + (AuthorizedDomainsAsyncClient, transports.AuthorizedDomainsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_authorized_domains_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_authorized_domains_client_client_options_from_dict(): + with mock.patch('google.cloud.appengine_admin_v1.services.authorized_domains.transports.AuthorizedDomainsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AuthorizedDomainsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_authorized_domains(transport: str = 'grpc', request_type=appengine.ListAuthorizedDomainsRequest): + client = AuthorizedDomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorized_domains), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = appengine.ListAuthorizedDomainsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_authorized_domains(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListAuthorizedDomainsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAuthorizedDomainsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_authorized_domains_from_dict(): + test_list_authorized_domains(request_type=dict) + + +def test_list_authorized_domains_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AuthorizedDomainsClient( + credentials=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_authorized_domains), + '__call__') as call: + client.list_authorized_domains() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListAuthorizedDomainsRequest() + + +@pytest.mark.asyncio +async def test_list_authorized_domains_async(transport: str = 'grpc_asyncio', request_type=appengine.ListAuthorizedDomainsRequest): + client = AuthorizedDomainsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorized_domains), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListAuthorizedDomainsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_authorized_domains(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListAuthorizedDomainsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAuthorizedDomainsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_authorized_domains_async_from_dict(): + await test_list_authorized_domains_async(request_type=dict) + + +def test_list_authorized_domains_field_headers(): + client = AuthorizedDomainsClient( + credentials=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. + request = appengine.ListAuthorizedDomainsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorized_domains), + '__call__') as call: + call.return_value = appengine.ListAuthorizedDomainsResponse() + client.list_authorized_domains(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_authorized_domains_field_headers_async(): + client = AuthorizedDomainsAsyncClient( + credentials=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. + request = appengine.ListAuthorizedDomainsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorized_domains), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListAuthorizedDomainsResponse()) + await client.list_authorized_domains(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_list_authorized_domains_pager(): + client = AuthorizedDomainsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorized_domains), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListAuthorizedDomainsResponse( + domains=[ + domain.AuthorizedDomain(), + domain.AuthorizedDomain(), + domain.AuthorizedDomain(), + ], + next_page_token='abc', + ), + appengine.ListAuthorizedDomainsResponse( + domains=[], + next_page_token='def', + ), + appengine.ListAuthorizedDomainsResponse( + domains=[ + domain.AuthorizedDomain(), + ], + next_page_token='ghi', + ), + appengine.ListAuthorizedDomainsResponse( + domains=[ + domain.AuthorizedDomain(), + domain.AuthorizedDomain(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_authorized_domains(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, domain.AuthorizedDomain) + for i in results) + +def test_list_authorized_domains_pages(): + client = AuthorizedDomainsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorized_domains), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListAuthorizedDomainsResponse( + domains=[ + domain.AuthorizedDomain(), + domain.AuthorizedDomain(), + domain.AuthorizedDomain(), + ], + next_page_token='abc', + ), + appengine.ListAuthorizedDomainsResponse( + domains=[], + next_page_token='def', + ), + appengine.ListAuthorizedDomainsResponse( + domains=[ + domain.AuthorizedDomain(), + ], + next_page_token='ghi', + ), + appengine.ListAuthorizedDomainsResponse( + domains=[ + domain.AuthorizedDomain(), + domain.AuthorizedDomain(), + ], + ), + RuntimeError, + ) + pages = list(client.list_authorized_domains(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_authorized_domains_async_pager(): + client = AuthorizedDomainsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorized_domains), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListAuthorizedDomainsResponse( + domains=[ + domain.AuthorizedDomain(), + domain.AuthorizedDomain(), + domain.AuthorizedDomain(), + ], + next_page_token='abc', + ), + appengine.ListAuthorizedDomainsResponse( + domains=[], + next_page_token='def', + ), + appengine.ListAuthorizedDomainsResponse( + domains=[ + domain.AuthorizedDomain(), + ], + next_page_token='ghi', + ), + appengine.ListAuthorizedDomainsResponse( + domains=[ + domain.AuthorizedDomain(), + domain.AuthorizedDomain(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_authorized_domains(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, domain.AuthorizedDomain) + for i in responses) + +@pytest.mark.asyncio +async def test_list_authorized_domains_async_pages(): + client = AuthorizedDomainsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorized_domains), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListAuthorizedDomainsResponse( + domains=[ + domain.AuthorizedDomain(), + domain.AuthorizedDomain(), + domain.AuthorizedDomain(), + ], + next_page_token='abc', + ), + appengine.ListAuthorizedDomainsResponse( + domains=[], + next_page_token='def', + ), + appengine.ListAuthorizedDomainsResponse( + domains=[ + domain.AuthorizedDomain(), + ], + next_page_token='ghi', + ), + appengine.ListAuthorizedDomainsResponse( + domains=[ + domain.AuthorizedDomain(), + domain.AuthorizedDomain(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_authorized_domains(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AuthorizedDomainsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AuthorizedDomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AuthorizedDomainsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AuthorizedDomainsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AuthorizedDomainsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AuthorizedDomainsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AuthorizedDomainsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AuthorizedDomainsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AuthorizedDomainsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AuthorizedDomainsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AuthorizedDomainsGrpcTransport, + transports.AuthorizedDomainsGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AuthorizedDomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AuthorizedDomainsGrpcTransport, + ) + +def test_authorized_domains_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AuthorizedDomainsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_authorized_domains_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.appengine_admin_v1.services.authorized_domains.transports.AuthorizedDomainsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AuthorizedDomainsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_authorized_domains', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_authorized_domains_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.authorized_domains.transports.AuthorizedDomainsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AuthorizedDomainsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_authorized_domains_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.authorized_domains.transports.AuthorizedDomainsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AuthorizedDomainsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ), + quota_project_id="octopus", + ) + + +def test_authorized_domains_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.appengine_admin_v1.services.authorized_domains.transports.AuthorizedDomainsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AuthorizedDomainsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_authorized_domains_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AuthorizedDomainsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_authorized_domains_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AuthorizedDomainsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AuthorizedDomainsGrpcTransport, + transports.AuthorizedDomainsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_authorized_domains_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AuthorizedDomainsGrpcTransport, + transports.AuthorizedDomainsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_authorized_domains_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AuthorizedDomainsGrpcTransport, grpc_helpers), + (transports.AuthorizedDomainsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_authorized_domains_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + scopes=["1", "2"], + default_host="appengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AuthorizedDomainsGrpcTransport, transports.AuthorizedDomainsGrpcAsyncIOTransport]) +def test_authorized_domains_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_authorized_domains_host_no_port(): + client = AuthorizedDomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com'), + ) + assert client.transport._host == 'appengine.googleapis.com:443' + + +def test_authorized_domains_host_with_port(): + client = AuthorizedDomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com:8000'), + ) + assert client.transport._host == 'appengine.googleapis.com:8000' + +def test_authorized_domains_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AuthorizedDomainsGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_authorized_domains_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AuthorizedDomainsGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.AuthorizedDomainsGrpcTransport, transports.AuthorizedDomainsGrpcAsyncIOTransport]) +def test_authorized_domains_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.AuthorizedDomainsGrpcTransport, transports.AuthorizedDomainsGrpcAsyncIOTransport]) +def test_authorized_domains_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AuthorizedDomainsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = AuthorizedDomainsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AuthorizedDomainsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = AuthorizedDomainsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = AuthorizedDomainsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AuthorizedDomainsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AuthorizedDomainsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = AuthorizedDomainsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AuthorizedDomainsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = AuthorizedDomainsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = AuthorizedDomainsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AuthorizedDomainsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AuthorizedDomainsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = AuthorizedDomainsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AuthorizedDomainsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.AuthorizedDomainsTransport, '_prep_wrapped_messages') as prep: + client = AuthorizedDomainsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AuthorizedDomainsTransport, '_prep_wrapped_messages') as prep: + transport_class = AuthorizedDomainsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py new file mode 100644 index 0000000..8dad54e --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py @@ -0,0 +1,1908 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.appengine_admin_v1.services.domain_mappings import DomainMappingsAsyncClient +from google.cloud.appengine_admin_v1.services.domain_mappings import DomainMappingsClient +from google.cloud.appengine_admin_v1.services.domain_mappings import pagers +from google.cloud.appengine_admin_v1.services.domain_mappings import transports +from google.cloud.appengine_admin_v1.services.domain_mappings.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import domain_mapping +from google.cloud.appengine_admin_v1.types import operation as ga_operation +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert DomainMappingsClient._get_default_mtls_endpoint(None) is None + assert DomainMappingsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DomainMappingsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DomainMappingsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DomainMappingsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DomainMappingsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + DomainMappingsClient, + DomainMappingsAsyncClient, +]) +def test_domain_mappings_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'appengine.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DomainMappingsGrpcTransport, "grpc"), + (transports.DomainMappingsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_domain_mappings_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + DomainMappingsClient, + DomainMappingsAsyncClient, +]) +def test_domain_mappings_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'appengine.googleapis.com:443' + + +def test_domain_mappings_client_get_transport_class(): + transport = DomainMappingsClient.get_transport_class() + available_transports = [ + transports.DomainMappingsGrpcTransport, + ] + assert transport in available_transports + + transport = DomainMappingsClient.get_transport_class("grpc") + assert transport == transports.DomainMappingsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DomainMappingsClient, transports.DomainMappingsGrpcTransport, "grpc"), + (DomainMappingsAsyncClient, transports.DomainMappingsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(DomainMappingsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DomainMappingsClient)) +@mock.patch.object(DomainMappingsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DomainMappingsAsyncClient)) +def test_domain_mappings_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(DomainMappingsClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(DomainMappingsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (DomainMappingsClient, transports.DomainMappingsGrpcTransport, "grpc", "true"), + (DomainMappingsAsyncClient, transports.DomainMappingsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DomainMappingsClient, transports.DomainMappingsGrpcTransport, "grpc", "false"), + (DomainMappingsAsyncClient, transports.DomainMappingsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(DomainMappingsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DomainMappingsClient)) +@mock.patch.object(DomainMappingsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DomainMappingsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_domain_mappings_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DomainMappingsClient, transports.DomainMappingsGrpcTransport, "grpc"), + (DomainMappingsAsyncClient, transports.DomainMappingsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_domain_mappings_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DomainMappingsClient, transports.DomainMappingsGrpcTransport, "grpc"), + (DomainMappingsAsyncClient, transports.DomainMappingsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_domain_mappings_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_domain_mappings_client_client_options_from_dict(): + with mock.patch('google.cloud.appengine_admin_v1.services.domain_mappings.transports.DomainMappingsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DomainMappingsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_domain_mappings(transport: str = 'grpc', request_type=appengine.ListDomainMappingsRequest): + client = DomainMappingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_domain_mappings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = appengine.ListDomainMappingsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_domain_mappings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListDomainMappingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDomainMappingsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_domain_mappings_from_dict(): + test_list_domain_mappings(request_type=dict) + + +def test_list_domain_mappings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DomainMappingsClient( + credentials=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_domain_mappings), + '__call__') as call: + client.list_domain_mappings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListDomainMappingsRequest() + + +@pytest.mark.asyncio +async def test_list_domain_mappings_async(transport: str = 'grpc_asyncio', request_type=appengine.ListDomainMappingsRequest): + client = DomainMappingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_domain_mappings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListDomainMappingsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_domain_mappings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListDomainMappingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDomainMappingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_domain_mappings_async_from_dict(): + await test_list_domain_mappings_async(request_type=dict) + + +def test_list_domain_mappings_field_headers(): + client = DomainMappingsClient( + credentials=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. + request = appengine.ListDomainMappingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_domain_mappings), + '__call__') as call: + call.return_value = appengine.ListDomainMappingsResponse() + client.list_domain_mappings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_domain_mappings_field_headers_async(): + client = DomainMappingsAsyncClient( + credentials=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. + request = appengine.ListDomainMappingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_domain_mappings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListDomainMappingsResponse()) + await client.list_domain_mappings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_list_domain_mappings_pager(): + client = DomainMappingsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_domain_mappings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListDomainMappingsResponse( + domain_mappings=[ + domain_mapping.DomainMapping(), + domain_mapping.DomainMapping(), + domain_mapping.DomainMapping(), + ], + next_page_token='abc', + ), + appengine.ListDomainMappingsResponse( + domain_mappings=[], + next_page_token='def', + ), + appengine.ListDomainMappingsResponse( + domain_mappings=[ + domain_mapping.DomainMapping(), + ], + next_page_token='ghi', + ), + appengine.ListDomainMappingsResponse( + domain_mappings=[ + domain_mapping.DomainMapping(), + domain_mapping.DomainMapping(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_domain_mappings(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, domain_mapping.DomainMapping) + for i in results) + +def test_list_domain_mappings_pages(): + client = DomainMappingsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_domain_mappings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListDomainMappingsResponse( + domain_mappings=[ + domain_mapping.DomainMapping(), + domain_mapping.DomainMapping(), + domain_mapping.DomainMapping(), + ], + next_page_token='abc', + ), + appengine.ListDomainMappingsResponse( + domain_mappings=[], + next_page_token='def', + ), + appengine.ListDomainMappingsResponse( + domain_mappings=[ + domain_mapping.DomainMapping(), + ], + next_page_token='ghi', + ), + appengine.ListDomainMappingsResponse( + domain_mappings=[ + domain_mapping.DomainMapping(), + domain_mapping.DomainMapping(), + ], + ), + RuntimeError, + ) + pages = list(client.list_domain_mappings(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_domain_mappings_async_pager(): + client = DomainMappingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_domain_mappings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListDomainMappingsResponse( + domain_mappings=[ + domain_mapping.DomainMapping(), + domain_mapping.DomainMapping(), + domain_mapping.DomainMapping(), + ], + next_page_token='abc', + ), + appengine.ListDomainMappingsResponse( + domain_mappings=[], + next_page_token='def', + ), + appengine.ListDomainMappingsResponse( + domain_mappings=[ + domain_mapping.DomainMapping(), + ], + next_page_token='ghi', + ), + appengine.ListDomainMappingsResponse( + domain_mappings=[ + domain_mapping.DomainMapping(), + domain_mapping.DomainMapping(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_domain_mappings(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, domain_mapping.DomainMapping) + for i in responses) + +@pytest.mark.asyncio +async def test_list_domain_mappings_async_pages(): + client = DomainMappingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_domain_mappings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListDomainMappingsResponse( + domain_mappings=[ + domain_mapping.DomainMapping(), + domain_mapping.DomainMapping(), + domain_mapping.DomainMapping(), + ], + next_page_token='abc', + ), + appengine.ListDomainMappingsResponse( + domain_mappings=[], + next_page_token='def', + ), + appengine.ListDomainMappingsResponse( + domain_mappings=[ + domain_mapping.DomainMapping(), + ], + next_page_token='ghi', + ), + appengine.ListDomainMappingsResponse( + domain_mappings=[ + domain_mapping.DomainMapping(), + domain_mapping.DomainMapping(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_domain_mappings(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_domain_mapping(transport: str = 'grpc', request_type=appengine.GetDomainMappingRequest): + client = DomainMappingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_domain_mapping), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = domain_mapping.DomainMapping( + name='name_value', + id='id_value', + ) + response = client.get_domain_mapping(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetDomainMappingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, domain_mapping.DomainMapping) + assert response.name == 'name_value' + assert response.id == 'id_value' + + +def test_get_domain_mapping_from_dict(): + test_get_domain_mapping(request_type=dict) + + +def test_get_domain_mapping_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DomainMappingsClient( + credentials=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_domain_mapping), + '__call__') as call: + client.get_domain_mapping() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetDomainMappingRequest() + + +@pytest.mark.asyncio +async def test_get_domain_mapping_async(transport: str = 'grpc_asyncio', request_type=appengine.GetDomainMappingRequest): + client = DomainMappingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_domain_mapping), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(domain_mapping.DomainMapping( + name='name_value', + id='id_value', + )) + response = await client.get_domain_mapping(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetDomainMappingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, domain_mapping.DomainMapping) + assert response.name == 'name_value' + assert response.id == 'id_value' + + +@pytest.mark.asyncio +async def test_get_domain_mapping_async_from_dict(): + await test_get_domain_mapping_async(request_type=dict) + + +def test_get_domain_mapping_field_headers(): + client = DomainMappingsClient( + credentials=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. + request = appengine.GetDomainMappingRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_domain_mapping), + '__call__') as call: + call.return_value = domain_mapping.DomainMapping() + client.get_domain_mapping(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_domain_mapping_field_headers_async(): + client = DomainMappingsAsyncClient( + credentials=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. + request = appengine.GetDomainMappingRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_domain_mapping), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(domain_mapping.DomainMapping()) + await client.get_domain_mapping(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_create_domain_mapping(transport: str = 'grpc', request_type=appengine.CreateDomainMappingRequest): + client = DomainMappingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_domain_mapping), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_domain_mapping(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.CreateDomainMappingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_domain_mapping_from_dict(): + test_create_domain_mapping(request_type=dict) + + +def test_create_domain_mapping_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DomainMappingsClient( + credentials=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_domain_mapping), + '__call__') as call: + client.create_domain_mapping() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.CreateDomainMappingRequest() + + +@pytest.mark.asyncio +async def test_create_domain_mapping_async(transport: str = 'grpc_asyncio', request_type=appengine.CreateDomainMappingRequest): + client = DomainMappingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_domain_mapping), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_domain_mapping(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.CreateDomainMappingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_domain_mapping_async_from_dict(): + await test_create_domain_mapping_async(request_type=dict) + + +def test_create_domain_mapping_field_headers(): + client = DomainMappingsClient( + credentials=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. + request = appengine.CreateDomainMappingRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_domain_mapping), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_domain_mapping(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_domain_mapping_field_headers_async(): + client = DomainMappingsAsyncClient( + credentials=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. + request = appengine.CreateDomainMappingRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_domain_mapping), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_domain_mapping(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_update_domain_mapping(transport: str = 'grpc', request_type=appengine.UpdateDomainMappingRequest): + client = DomainMappingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_domain_mapping), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_domain_mapping(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.UpdateDomainMappingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_domain_mapping_from_dict(): + test_update_domain_mapping(request_type=dict) + + +def test_update_domain_mapping_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DomainMappingsClient( + credentials=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_domain_mapping), + '__call__') as call: + client.update_domain_mapping() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.UpdateDomainMappingRequest() + + +@pytest.mark.asyncio +async def test_update_domain_mapping_async(transport: str = 'grpc_asyncio', request_type=appengine.UpdateDomainMappingRequest): + client = DomainMappingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_domain_mapping), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_domain_mapping(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.UpdateDomainMappingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_domain_mapping_async_from_dict(): + await test_update_domain_mapping_async(request_type=dict) + + +def test_update_domain_mapping_field_headers(): + client = DomainMappingsClient( + credentials=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. + request = appengine.UpdateDomainMappingRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_domain_mapping), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_domain_mapping(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_domain_mapping_field_headers_async(): + client = DomainMappingsAsyncClient( + credentials=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. + request = appengine.UpdateDomainMappingRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_domain_mapping), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_domain_mapping(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_delete_domain_mapping(transport: str = 'grpc', request_type=appengine.DeleteDomainMappingRequest): + client = DomainMappingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_domain_mapping), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_domain_mapping(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DeleteDomainMappingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_domain_mapping_from_dict(): + test_delete_domain_mapping(request_type=dict) + + +def test_delete_domain_mapping_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DomainMappingsClient( + credentials=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_domain_mapping), + '__call__') as call: + client.delete_domain_mapping() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DeleteDomainMappingRequest() + + +@pytest.mark.asyncio +async def test_delete_domain_mapping_async(transport: str = 'grpc_asyncio', request_type=appengine.DeleteDomainMappingRequest): + client = DomainMappingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_domain_mapping), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_domain_mapping(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DeleteDomainMappingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_domain_mapping_async_from_dict(): + await test_delete_domain_mapping_async(request_type=dict) + + +def test_delete_domain_mapping_field_headers(): + client = DomainMappingsClient( + credentials=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. + request = appengine.DeleteDomainMappingRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_domain_mapping), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_domain_mapping(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_domain_mapping_field_headers_async(): + client = DomainMappingsAsyncClient( + credentials=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. + request = appengine.DeleteDomainMappingRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_domain_mapping), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_domain_mapping(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DomainMappingsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DomainMappingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DomainMappingsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DomainMappingsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DomainMappingsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DomainMappingsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DomainMappingsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DomainMappingsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DomainMappingsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DomainMappingsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DomainMappingsGrpcTransport, + transports.DomainMappingsGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DomainMappingsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DomainMappingsGrpcTransport, + ) + +def test_domain_mappings_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DomainMappingsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_domain_mappings_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.appengine_admin_v1.services.domain_mappings.transports.DomainMappingsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DomainMappingsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_domain_mappings', + 'get_domain_mapping', + 'create_domain_mapping', + 'update_domain_mapping', + 'delete_domain_mapping', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_domain_mappings_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.domain_mappings.transports.DomainMappingsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DomainMappingsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_domain_mappings_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.domain_mappings.transports.DomainMappingsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DomainMappingsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ), + quota_project_id="octopus", + ) + + +def test_domain_mappings_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.appengine_admin_v1.services.domain_mappings.transports.DomainMappingsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DomainMappingsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_domain_mappings_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DomainMappingsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_domain_mappings_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + DomainMappingsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DomainMappingsGrpcTransport, + transports.DomainMappingsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_domain_mappings_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DomainMappingsGrpcTransport, + transports.DomainMappingsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_domain_mappings_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DomainMappingsGrpcTransport, grpc_helpers), + (transports.DomainMappingsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_domain_mappings_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + scopes=["1", "2"], + default_host="appengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DomainMappingsGrpcTransport, transports.DomainMappingsGrpcAsyncIOTransport]) +def test_domain_mappings_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_domain_mappings_host_no_port(): + client = DomainMappingsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com'), + ) + assert client.transport._host == 'appengine.googleapis.com:443' + + +def test_domain_mappings_host_with_port(): + client = DomainMappingsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com:8000'), + ) + assert client.transport._host == 'appengine.googleapis.com:8000' + +def test_domain_mappings_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DomainMappingsGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_domain_mappings_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DomainMappingsGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.DomainMappingsGrpcTransport, transports.DomainMappingsGrpcAsyncIOTransport]) +def test_domain_mappings_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.DomainMappingsGrpcTransport, transports.DomainMappingsGrpcAsyncIOTransport]) +def test_domain_mappings_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_domain_mappings_grpc_lro_client(): + client = DomainMappingsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_domain_mappings_grpc_lro_async_client(): + client = DomainMappingsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DomainMappingsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = DomainMappingsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DomainMappingsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = DomainMappingsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = DomainMappingsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DomainMappingsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DomainMappingsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = DomainMappingsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DomainMappingsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = DomainMappingsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = DomainMappingsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DomainMappingsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = DomainMappingsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = DomainMappingsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DomainMappingsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.DomainMappingsTransport, '_prep_wrapped_messages') as prep: + client = DomainMappingsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DomainMappingsTransport, '_prep_wrapped_messages') as prep: + transport_class = DomainMappingsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_firewall.py b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_firewall.py new file mode 100644 index 0000000..a4088ab --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_firewall.py @@ -0,0 +1,2050 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.appengine_admin_v1.services.firewall import FirewallAsyncClient +from google.cloud.appengine_admin_v1.services.firewall import FirewallClient +from google.cloud.appengine_admin_v1.services.firewall import pagers +from google.cloud.appengine_admin_v1.services.firewall import transports +from google.cloud.appengine_admin_v1.services.firewall.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import firewall +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert FirewallClient._get_default_mtls_endpoint(None) is None + assert FirewallClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert FirewallClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert FirewallClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert FirewallClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert FirewallClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + FirewallClient, + FirewallAsyncClient, +]) +def test_firewall_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'appengine.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.FirewallGrpcTransport, "grpc"), + (transports.FirewallGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_firewall_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + FirewallClient, + FirewallAsyncClient, +]) +def test_firewall_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'appengine.googleapis.com:443' + + +def test_firewall_client_get_transport_class(): + transport = FirewallClient.get_transport_class() + available_transports = [ + transports.FirewallGrpcTransport, + ] + assert transport in available_transports + + transport = FirewallClient.get_transport_class("grpc") + assert transport == transports.FirewallGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FirewallClient, transports.FirewallGrpcTransport, "grpc"), + (FirewallAsyncClient, transports.FirewallGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(FirewallClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FirewallClient)) +@mock.patch.object(FirewallAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FirewallAsyncClient)) +def test_firewall_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(FirewallClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(FirewallClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (FirewallClient, transports.FirewallGrpcTransport, "grpc", "true"), + (FirewallAsyncClient, transports.FirewallGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (FirewallClient, transports.FirewallGrpcTransport, "grpc", "false"), + (FirewallAsyncClient, transports.FirewallGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(FirewallClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FirewallClient)) +@mock.patch.object(FirewallAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FirewallAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_firewall_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FirewallClient, transports.FirewallGrpcTransport, "grpc"), + (FirewallAsyncClient, transports.FirewallGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_firewall_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FirewallClient, transports.FirewallGrpcTransport, "grpc"), + (FirewallAsyncClient, transports.FirewallGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_firewall_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_firewall_client_client_options_from_dict(): + with mock.patch('google.cloud.appengine_admin_v1.services.firewall.transports.FirewallGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = FirewallClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_ingress_rules(transport: str = 'grpc', request_type=appengine.ListIngressRulesRequest): + client = FirewallClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ingress_rules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = appengine.ListIngressRulesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_ingress_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListIngressRulesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListIngressRulesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_ingress_rules_from_dict(): + test_list_ingress_rules(request_type=dict) + + +def test_list_ingress_rules_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FirewallClient( + credentials=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_ingress_rules), + '__call__') as call: + client.list_ingress_rules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListIngressRulesRequest() + + +@pytest.mark.asyncio +async def test_list_ingress_rules_async(transport: str = 'grpc_asyncio', request_type=appengine.ListIngressRulesRequest): + client = FirewallAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ingress_rules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListIngressRulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_ingress_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListIngressRulesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListIngressRulesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_ingress_rules_async_from_dict(): + await test_list_ingress_rules_async(request_type=dict) + + +def test_list_ingress_rules_field_headers(): + client = FirewallClient( + credentials=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. + request = appengine.ListIngressRulesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ingress_rules), + '__call__') as call: + call.return_value = appengine.ListIngressRulesResponse() + client.list_ingress_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_ingress_rules_field_headers_async(): + client = FirewallAsyncClient( + credentials=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. + request = appengine.ListIngressRulesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ingress_rules), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListIngressRulesResponse()) + await client.list_ingress_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_list_ingress_rules_pager(): + client = FirewallClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ingress_rules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListIngressRulesResponse( + ingress_rules=[ + firewall.FirewallRule(), + firewall.FirewallRule(), + firewall.FirewallRule(), + ], + next_page_token='abc', + ), + appengine.ListIngressRulesResponse( + ingress_rules=[], + next_page_token='def', + ), + appengine.ListIngressRulesResponse( + ingress_rules=[ + firewall.FirewallRule(), + ], + next_page_token='ghi', + ), + appengine.ListIngressRulesResponse( + ingress_rules=[ + firewall.FirewallRule(), + firewall.FirewallRule(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_ingress_rules(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, firewall.FirewallRule) + for i in results) + +def test_list_ingress_rules_pages(): + client = FirewallClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ingress_rules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListIngressRulesResponse( + ingress_rules=[ + firewall.FirewallRule(), + firewall.FirewallRule(), + firewall.FirewallRule(), + ], + next_page_token='abc', + ), + appengine.ListIngressRulesResponse( + ingress_rules=[], + next_page_token='def', + ), + appengine.ListIngressRulesResponse( + ingress_rules=[ + firewall.FirewallRule(), + ], + next_page_token='ghi', + ), + appengine.ListIngressRulesResponse( + ingress_rules=[ + firewall.FirewallRule(), + firewall.FirewallRule(), + ], + ), + RuntimeError, + ) + pages = list(client.list_ingress_rules(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_ingress_rules_async_pager(): + client = FirewallAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ingress_rules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListIngressRulesResponse( + ingress_rules=[ + firewall.FirewallRule(), + firewall.FirewallRule(), + firewall.FirewallRule(), + ], + next_page_token='abc', + ), + appengine.ListIngressRulesResponse( + ingress_rules=[], + next_page_token='def', + ), + appengine.ListIngressRulesResponse( + ingress_rules=[ + firewall.FirewallRule(), + ], + next_page_token='ghi', + ), + appengine.ListIngressRulesResponse( + ingress_rules=[ + firewall.FirewallRule(), + firewall.FirewallRule(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_ingress_rules(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, firewall.FirewallRule) + for i in responses) + +@pytest.mark.asyncio +async def test_list_ingress_rules_async_pages(): + client = FirewallAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ingress_rules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListIngressRulesResponse( + ingress_rules=[ + firewall.FirewallRule(), + firewall.FirewallRule(), + firewall.FirewallRule(), + ], + next_page_token='abc', + ), + appengine.ListIngressRulesResponse( + ingress_rules=[], + next_page_token='def', + ), + appengine.ListIngressRulesResponse( + ingress_rules=[ + firewall.FirewallRule(), + ], + next_page_token='ghi', + ), + appengine.ListIngressRulesResponse( + ingress_rules=[ + firewall.FirewallRule(), + firewall.FirewallRule(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_ingress_rules(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_batch_update_ingress_rules(transport: str = 'grpc', request_type=appengine.BatchUpdateIngressRulesRequest): + client = FirewallClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_ingress_rules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = appengine.BatchUpdateIngressRulesResponse( + ) + response = client.batch_update_ingress_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.BatchUpdateIngressRulesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, appengine.BatchUpdateIngressRulesResponse) + + +def test_batch_update_ingress_rules_from_dict(): + test_batch_update_ingress_rules(request_type=dict) + + +def test_batch_update_ingress_rules_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FirewallClient( + credentials=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_update_ingress_rules), + '__call__') as call: + client.batch_update_ingress_rules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.BatchUpdateIngressRulesRequest() + + +@pytest.mark.asyncio +async def test_batch_update_ingress_rules_async(transport: str = 'grpc_asyncio', request_type=appengine.BatchUpdateIngressRulesRequest): + client = FirewallAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_ingress_rules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(appengine.BatchUpdateIngressRulesResponse( + )) + response = await client.batch_update_ingress_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.BatchUpdateIngressRulesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, appengine.BatchUpdateIngressRulesResponse) + + +@pytest.mark.asyncio +async def test_batch_update_ingress_rules_async_from_dict(): + await test_batch_update_ingress_rules_async(request_type=dict) + + +def test_batch_update_ingress_rules_field_headers(): + client = FirewallClient( + credentials=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. + request = appengine.BatchUpdateIngressRulesRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_ingress_rules), + '__call__') as call: + call.return_value = appengine.BatchUpdateIngressRulesResponse() + client.batch_update_ingress_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_update_ingress_rules_field_headers_async(): + client = FirewallAsyncClient( + credentials=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. + request = appengine.BatchUpdateIngressRulesRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_ingress_rules), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(appengine.BatchUpdateIngressRulesResponse()) + await client.batch_update_ingress_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_create_ingress_rule(transport: str = 'grpc', request_type=appengine.CreateIngressRuleRequest): + client = FirewallClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ingress_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = firewall.FirewallRule( + priority=898, + action=firewall.FirewallRule.Action.ALLOW, + source_range='source_range_value', + description='description_value', + ) + response = client.create_ingress_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.CreateIngressRuleRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, firewall.FirewallRule) + assert response.priority == 898 + assert response.action == firewall.FirewallRule.Action.ALLOW + assert response.source_range == 'source_range_value' + assert response.description == 'description_value' + + +def test_create_ingress_rule_from_dict(): + test_create_ingress_rule(request_type=dict) + + +def test_create_ingress_rule_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FirewallClient( + credentials=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_ingress_rule), + '__call__') as call: + client.create_ingress_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.CreateIngressRuleRequest() + + +@pytest.mark.asyncio +async def test_create_ingress_rule_async(transport: str = 'grpc_asyncio', request_type=appengine.CreateIngressRuleRequest): + client = FirewallAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ingress_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(firewall.FirewallRule( + priority=898, + action=firewall.FirewallRule.Action.ALLOW, + source_range='source_range_value', + description='description_value', + )) + response = await client.create_ingress_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.CreateIngressRuleRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, firewall.FirewallRule) + assert response.priority == 898 + assert response.action == firewall.FirewallRule.Action.ALLOW + assert response.source_range == 'source_range_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_create_ingress_rule_async_from_dict(): + await test_create_ingress_rule_async(request_type=dict) + + +def test_create_ingress_rule_field_headers(): + client = FirewallClient( + credentials=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. + request = appengine.CreateIngressRuleRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ingress_rule), + '__call__') as call: + call.return_value = firewall.FirewallRule() + client.create_ingress_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_ingress_rule_field_headers_async(): + client = FirewallAsyncClient( + credentials=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. + request = appengine.CreateIngressRuleRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ingress_rule), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(firewall.FirewallRule()) + await client.create_ingress_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_get_ingress_rule(transport: str = 'grpc', request_type=appengine.GetIngressRuleRequest): + client = FirewallClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ingress_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = firewall.FirewallRule( + priority=898, + action=firewall.FirewallRule.Action.ALLOW, + source_range='source_range_value', + description='description_value', + ) + response = client.get_ingress_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetIngressRuleRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, firewall.FirewallRule) + assert response.priority == 898 + assert response.action == firewall.FirewallRule.Action.ALLOW + assert response.source_range == 'source_range_value' + assert response.description == 'description_value' + + +def test_get_ingress_rule_from_dict(): + test_get_ingress_rule(request_type=dict) + + +def test_get_ingress_rule_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FirewallClient( + credentials=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_ingress_rule), + '__call__') as call: + client.get_ingress_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetIngressRuleRequest() + + +@pytest.mark.asyncio +async def test_get_ingress_rule_async(transport: str = 'grpc_asyncio', request_type=appengine.GetIngressRuleRequest): + client = FirewallAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ingress_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(firewall.FirewallRule( + priority=898, + action=firewall.FirewallRule.Action.ALLOW, + source_range='source_range_value', + description='description_value', + )) + response = await client.get_ingress_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetIngressRuleRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, firewall.FirewallRule) + assert response.priority == 898 + assert response.action == firewall.FirewallRule.Action.ALLOW + assert response.source_range == 'source_range_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_get_ingress_rule_async_from_dict(): + await test_get_ingress_rule_async(request_type=dict) + + +def test_get_ingress_rule_field_headers(): + client = FirewallClient( + credentials=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. + request = appengine.GetIngressRuleRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ingress_rule), + '__call__') as call: + call.return_value = firewall.FirewallRule() + client.get_ingress_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_ingress_rule_field_headers_async(): + client = FirewallAsyncClient( + credentials=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. + request = appengine.GetIngressRuleRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ingress_rule), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(firewall.FirewallRule()) + await client.get_ingress_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_update_ingress_rule(transport: str = 'grpc', request_type=appengine.UpdateIngressRuleRequest): + client = FirewallClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ingress_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = firewall.FirewallRule( + priority=898, + action=firewall.FirewallRule.Action.ALLOW, + source_range='source_range_value', + description='description_value', + ) + response = client.update_ingress_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.UpdateIngressRuleRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, firewall.FirewallRule) + assert response.priority == 898 + assert response.action == firewall.FirewallRule.Action.ALLOW + assert response.source_range == 'source_range_value' + assert response.description == 'description_value' + + +def test_update_ingress_rule_from_dict(): + test_update_ingress_rule(request_type=dict) + + +def test_update_ingress_rule_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FirewallClient( + credentials=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_ingress_rule), + '__call__') as call: + client.update_ingress_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.UpdateIngressRuleRequest() + + +@pytest.mark.asyncio +async def test_update_ingress_rule_async(transport: str = 'grpc_asyncio', request_type=appengine.UpdateIngressRuleRequest): + client = FirewallAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ingress_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(firewall.FirewallRule( + priority=898, + action=firewall.FirewallRule.Action.ALLOW, + source_range='source_range_value', + description='description_value', + )) + response = await client.update_ingress_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.UpdateIngressRuleRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, firewall.FirewallRule) + assert response.priority == 898 + assert response.action == firewall.FirewallRule.Action.ALLOW + assert response.source_range == 'source_range_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_update_ingress_rule_async_from_dict(): + await test_update_ingress_rule_async(request_type=dict) + + +def test_update_ingress_rule_field_headers(): + client = FirewallClient( + credentials=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. + request = appengine.UpdateIngressRuleRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ingress_rule), + '__call__') as call: + call.return_value = firewall.FirewallRule() + client.update_ingress_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_ingress_rule_field_headers_async(): + client = FirewallAsyncClient( + credentials=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. + request = appengine.UpdateIngressRuleRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ingress_rule), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(firewall.FirewallRule()) + await client.update_ingress_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_delete_ingress_rule(transport: str = 'grpc', request_type=appengine.DeleteIngressRuleRequest): + client = FirewallClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_ingress_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_ingress_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DeleteIngressRuleRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_ingress_rule_from_dict(): + test_delete_ingress_rule(request_type=dict) + + +def test_delete_ingress_rule_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FirewallClient( + credentials=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_ingress_rule), + '__call__') as call: + client.delete_ingress_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DeleteIngressRuleRequest() + + +@pytest.mark.asyncio +async def test_delete_ingress_rule_async(transport: str = 'grpc_asyncio', request_type=appengine.DeleteIngressRuleRequest): + client = FirewallAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_ingress_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_ingress_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DeleteIngressRuleRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_ingress_rule_async_from_dict(): + await test_delete_ingress_rule_async(request_type=dict) + + +def test_delete_ingress_rule_field_headers(): + client = FirewallClient( + credentials=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. + request = appengine.DeleteIngressRuleRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_ingress_rule), + '__call__') as call: + call.return_value = None + client.delete_ingress_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_ingress_rule_field_headers_async(): + client = FirewallAsyncClient( + credentials=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. + request = appengine.DeleteIngressRuleRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_ingress_rule), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_ingress_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.FirewallGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FirewallClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.FirewallGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FirewallClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.FirewallGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FirewallClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.FirewallGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = FirewallClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.FirewallGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.FirewallGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.FirewallGrpcTransport, + transports.FirewallGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = FirewallClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.FirewallGrpcTransport, + ) + +def test_firewall_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.FirewallTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_firewall_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.appengine_admin_v1.services.firewall.transports.FirewallTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.FirewallTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_ingress_rules', + 'batch_update_ingress_rules', + 'create_ingress_rule', + 'get_ingress_rule', + 'update_ingress_rule', + 'delete_ingress_rule', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_firewall_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.firewall.transports.FirewallTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FirewallTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_firewall_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.firewall.transports.FirewallTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FirewallTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ), + quota_project_id="octopus", + ) + + +def test_firewall_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.appengine_admin_v1.services.firewall.transports.FirewallTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FirewallTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_firewall_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + FirewallClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_firewall_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + FirewallClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FirewallGrpcTransport, + transports.FirewallGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_firewall_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FirewallGrpcTransport, + transports.FirewallGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_firewall_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FirewallGrpcTransport, grpc_helpers), + (transports.FirewallGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_firewall_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + scopes=["1", "2"], + default_host="appengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.FirewallGrpcTransport, transports.FirewallGrpcAsyncIOTransport]) +def test_firewall_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_firewall_host_no_port(): + client = FirewallClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com'), + ) + assert client.transport._host == 'appengine.googleapis.com:443' + + +def test_firewall_host_with_port(): + client = FirewallClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com:8000'), + ) + assert client.transport._host == 'appengine.googleapis.com:8000' + +def test_firewall_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FirewallGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_firewall_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FirewallGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.FirewallGrpcTransport, transports.FirewallGrpcAsyncIOTransport]) +def test_firewall_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.FirewallGrpcTransport, transports.FirewallGrpcAsyncIOTransport]) +def test_firewall_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = FirewallClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = FirewallClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = FirewallClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = FirewallClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = FirewallClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = FirewallClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = FirewallClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = FirewallClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = FirewallClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = FirewallClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = FirewallClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = FirewallClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = FirewallClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = FirewallClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = FirewallClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.FirewallTransport, '_prep_wrapped_messages') as prep: + client = FirewallClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.FirewallTransport, '_prep_wrapped_messages') as prep: + transport_class = FirewallClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_instances.py b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_instances.py new file mode 100644 index 0000000..e53c21b --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_instances.py @@ -0,0 +1,1839 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.appengine_admin_v1.services.instances import InstancesAsyncClient +from google.cloud.appengine_admin_v1.services.instances import InstancesClient +from google.cloud.appengine_admin_v1.services.instances import pagers +from google.cloud.appengine_admin_v1.services.instances import transports +from google.cloud.appengine_admin_v1.services.instances.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import instance +from google.cloud.appengine_admin_v1.types import operation as ga_operation +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert InstancesClient._get_default_mtls_endpoint(None) is None + assert InstancesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert InstancesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert InstancesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert InstancesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert InstancesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + InstancesClient, + InstancesAsyncClient, +]) +def test_instances_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'appengine.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.InstancesGrpcTransport, "grpc"), + (transports.InstancesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_instances_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + InstancesClient, + InstancesAsyncClient, +]) +def test_instances_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'appengine.googleapis.com:443' + + +def test_instances_client_get_transport_class(): + transport = InstancesClient.get_transport_class() + available_transports = [ + transports.InstancesGrpcTransport, + ] + assert transport in available_transports + + transport = InstancesClient.get_transport_class("grpc") + assert transport == transports.InstancesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (InstancesClient, transports.InstancesGrpcTransport, "grpc"), + (InstancesAsyncClient, transports.InstancesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(InstancesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(InstancesClient)) +@mock.patch.object(InstancesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(InstancesAsyncClient)) +def test_instances_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(InstancesClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(InstancesClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (InstancesClient, transports.InstancesGrpcTransport, "grpc", "true"), + (InstancesAsyncClient, transports.InstancesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (InstancesClient, transports.InstancesGrpcTransport, "grpc", "false"), + (InstancesAsyncClient, transports.InstancesGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(InstancesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(InstancesClient)) +@mock.patch.object(InstancesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(InstancesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_instances_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (InstancesClient, transports.InstancesGrpcTransport, "grpc"), + (InstancesAsyncClient, transports.InstancesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_instances_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (InstancesClient, transports.InstancesGrpcTransport, "grpc"), + (InstancesAsyncClient, transports.InstancesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_instances_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_instances_client_client_options_from_dict(): + with mock.patch('google.cloud.appengine_admin_v1.services.instances.transports.InstancesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = InstancesClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_instances(transport: str = 'grpc', request_type=appengine.ListInstancesRequest): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = appengine.ListInstancesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListInstancesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_instances_from_dict(): + test_list_instances(request_type=dict) + + +def test_list_instances_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = InstancesClient( + credentials=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_instances), + '__call__') as call: + client.list_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListInstancesRequest() + + +@pytest.mark.asyncio +async def test_list_instances_async(transport: str = 'grpc_asyncio', request_type=appengine.ListInstancesRequest): + client = InstancesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListInstancesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListInstancesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_instances_async_from_dict(): + await test_list_instances_async(request_type=dict) + + +def test_list_instances_field_headers(): + client = InstancesClient( + credentials=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. + request = appengine.ListInstancesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + call.return_value = appengine.ListInstancesResponse() + client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_instances_field_headers_async(): + client = InstancesAsyncClient( + credentials=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. + request = appengine.ListInstancesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListInstancesResponse()) + await client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_list_instances_pager(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + instance.Instance(), + ], + next_page_token='abc', + ), + appengine.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + appengine.ListInstancesResponse( + instances=[ + instance.Instance(), + ], + next_page_token='ghi', + ), + appengine.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_instances(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, instance.Instance) + for i in results) + +def test_list_instances_pages(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + instance.Instance(), + ], + next_page_token='abc', + ), + appengine.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + appengine.ListInstancesResponse( + instances=[ + instance.Instance(), + ], + next_page_token='ghi', + ), + appengine.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + ], + ), + RuntimeError, + ) + pages = list(client.list_instances(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_instances_async_pager(): + client = InstancesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + instance.Instance(), + ], + next_page_token='abc', + ), + appengine.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + appengine.ListInstancesResponse( + instances=[ + instance.Instance(), + ], + next_page_token='ghi', + ), + appengine.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_instances(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, instance.Instance) + for i in responses) + +@pytest.mark.asyncio +async def test_list_instances_async_pages(): + client = InstancesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + instance.Instance(), + ], + next_page_token='abc', + ), + appengine.ListInstancesResponse( + instances=[], + next_page_token='def', + ), + appengine.ListInstancesResponse( + instances=[ + instance.Instance(), + ], + next_page_token='ghi', + ), + appengine.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_instances(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_instance(transport: str = 'grpc', request_type=appengine.GetInstanceRequest): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = instance.Instance( + name='name_value', + id='id_value', + app_engine_release='app_engine_release_value', + availability=instance.Instance.Availability.RESIDENT, + vm_name='vm_name_value', + vm_zone_name='vm_zone_name_value', + vm_id='vm_id_value', + requests=892, + errors=669, + qps=0.340, + average_latency=1578, + memory_usage=1293, + vm_status='vm_status_value', + vm_debug_enabled=True, + vm_ip='vm_ip_value', + vm_liveness=instance.Instance.Liveness.LivenessState.UNKNOWN, + ) + response = client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, instance.Instance) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.app_engine_release == 'app_engine_release_value' + assert response.availability == instance.Instance.Availability.RESIDENT + assert response.vm_name == 'vm_name_value' + assert response.vm_zone_name == 'vm_zone_name_value' + assert response.vm_id == 'vm_id_value' + assert response.requests == 892 + assert response.errors == 669 + assert math.isclose(response.qps, 0.340, rel_tol=1e-6) + assert response.average_latency == 1578 + assert response.memory_usage == 1293 + assert response.vm_status == 'vm_status_value' + assert response.vm_debug_enabled is True + assert response.vm_ip == 'vm_ip_value' + assert response.vm_liveness == instance.Instance.Liveness.LivenessState.UNKNOWN + + +def test_get_instance_from_dict(): + test_get_instance(request_type=dict) + + +def test_get_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = InstancesClient( + credentials=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_instance), + '__call__') as call: + client.get_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetInstanceRequest() + + +@pytest.mark.asyncio +async def test_get_instance_async(transport: str = 'grpc_asyncio', request_type=appengine.GetInstanceRequest): + client = InstancesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(instance.Instance( + name='name_value', + id='id_value', + app_engine_release='app_engine_release_value', + availability=instance.Instance.Availability.RESIDENT, + vm_name='vm_name_value', + vm_zone_name='vm_zone_name_value', + vm_id='vm_id_value', + requests=892, + errors=669, + qps=0.340, + average_latency=1578, + memory_usage=1293, + vm_status='vm_status_value', + vm_debug_enabled=True, + vm_ip='vm_ip_value', + vm_liveness=instance.Instance.Liveness.LivenessState.UNKNOWN, + )) + response = await client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, instance.Instance) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.app_engine_release == 'app_engine_release_value' + assert response.availability == instance.Instance.Availability.RESIDENT + assert response.vm_name == 'vm_name_value' + assert response.vm_zone_name == 'vm_zone_name_value' + assert response.vm_id == 'vm_id_value' + assert response.requests == 892 + assert response.errors == 669 + assert math.isclose(response.qps, 0.340, rel_tol=1e-6) + assert response.average_latency == 1578 + assert response.memory_usage == 1293 + assert response.vm_status == 'vm_status_value' + assert response.vm_debug_enabled is True + assert response.vm_ip == 'vm_ip_value' + assert response.vm_liveness == instance.Instance.Liveness.LivenessState.UNKNOWN + + +@pytest.mark.asyncio +async def test_get_instance_async_from_dict(): + await test_get_instance_async(request_type=dict) + + +def test_get_instance_field_headers(): + client = InstancesClient( + credentials=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. + request = appengine.GetInstanceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + call.return_value = instance.Instance() + client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_instance_field_headers_async(): + client = InstancesAsyncClient( + credentials=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. + request = appengine.GetInstanceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance.Instance()) + await client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_delete_instance(transport: str = 'grpc', request_type=appengine.DeleteInstanceRequest): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DeleteInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_instance_from_dict(): + test_delete_instance(request_type=dict) + + +def test_delete_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = InstancesClient( + credentials=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_instance), + '__call__') as call: + client.delete_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DeleteInstanceRequest() + + +@pytest.mark.asyncio +async def test_delete_instance_async(transport: str = 'grpc_asyncio', request_type=appengine.DeleteInstanceRequest): + client = InstancesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DeleteInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_instance_async_from_dict(): + await test_delete_instance_async(request_type=dict) + + +def test_delete_instance_field_headers(): + client = InstancesClient( + credentials=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. + request = appengine.DeleteInstanceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_instance_field_headers_async(): + client = InstancesAsyncClient( + credentials=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. + request = appengine.DeleteInstanceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_debug_instance(transport: str = 'grpc', request_type=appengine.DebugInstanceRequest): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.debug_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.debug_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DebugInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_debug_instance_from_dict(): + test_debug_instance(request_type=dict) + + +def test_debug_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.debug_instance), + '__call__') as call: + client.debug_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DebugInstanceRequest() + + +@pytest.mark.asyncio +async def test_debug_instance_async(transport: str = 'grpc_asyncio', request_type=appengine.DebugInstanceRequest): + client = InstancesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.debug_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.debug_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DebugInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_debug_instance_async_from_dict(): + await test_debug_instance_async(request_type=dict) + + +def test_debug_instance_field_headers(): + client = InstancesClient( + credentials=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. + request = appengine.DebugInstanceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.debug_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.debug_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_debug_instance_field_headers_async(): + client = InstancesAsyncClient( + credentials=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. + request = appengine.DebugInstanceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.debug_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.debug_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.InstancesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.InstancesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = InstancesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.InstancesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = InstancesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.InstancesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = InstancesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.InstancesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.InstancesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.InstancesGrpcTransport, + transports.InstancesGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.InstancesGrpcTransport, + ) + +def test_instances_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.InstancesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_instances_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.appengine_admin_v1.services.instances.transports.InstancesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.InstancesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_instances', + 'get_instance', + 'delete_instance', + 'debug_instance', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_instances_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.instances.transports.InstancesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.InstancesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_instances_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.instances.transports.InstancesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.InstancesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ), + quota_project_id="octopus", + ) + + +def test_instances_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.appengine_admin_v1.services.instances.transports.InstancesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.InstancesTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_instances_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + InstancesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_instances_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + InstancesClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.InstancesGrpcTransport, + transports.InstancesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_instances_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.InstancesGrpcTransport, + transports.InstancesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_instances_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.InstancesGrpcTransport, grpc_helpers), + (transports.InstancesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_instances_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + scopes=["1", "2"], + default_host="appengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.InstancesGrpcTransport, transports.InstancesGrpcAsyncIOTransport]) +def test_instances_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_instances_host_no_port(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com'), + ) + assert client.transport._host == 'appengine.googleapis.com:443' + + +def test_instances_host_with_port(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com:8000'), + ) + assert client.transport._host == 'appengine.googleapis.com:8000' + +def test_instances_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.InstancesGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_instances_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.InstancesGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.InstancesGrpcTransport, transports.InstancesGrpcAsyncIOTransport]) +def test_instances_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.InstancesGrpcTransport, transports.InstancesGrpcAsyncIOTransport]) +def test_instances_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_instances_grpc_lro_client(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_instances_grpc_lro_async_client(): + client = InstancesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_instance_path(): + app = "squid" + service = "clam" + version = "whelk" + instance = "octopus" + expected = "apps/{app}/services/{service}/versions/{version}/instances/{instance}".format(app=app, service=service, version=version, instance=instance, ) + actual = InstancesClient.instance_path(app, service, version, instance) + assert expected == actual + + +def test_parse_instance_path(): + expected = { + "app": "oyster", + "service": "nudibranch", + "version": "cuttlefish", + "instance": "mussel", + } + path = InstancesClient.instance_path(**expected) + + # Check that the path construction is reversible. + actual = InstancesClient.parse_instance_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = InstancesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = InstancesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = InstancesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = InstancesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = InstancesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = InstancesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = InstancesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = InstancesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = InstancesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = InstancesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = InstancesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = InstancesClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = InstancesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = InstancesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = InstancesClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.InstancesTransport, '_prep_wrapped_messages') as prep: + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.InstancesTransport, '_prep_wrapped_messages') as prep: + transport_class = InstancesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_services.py b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_services.py new file mode 100644 index 0000000..e63f79e --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_services.py @@ -0,0 +1,1761 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.appengine_admin_v1.services.services import ServicesAsyncClient +from google.cloud.appengine_admin_v1.services.services import ServicesClient +from google.cloud.appengine_admin_v1.services.services import pagers +from google.cloud.appengine_admin_v1.services.services import transports +from google.cloud.appengine_admin_v1.services.services.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import network_settings +from google.cloud.appengine_admin_v1.types import operation as ga_operation +from google.cloud.appengine_admin_v1.types import service +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ServicesClient._get_default_mtls_endpoint(None) is None + assert ServicesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ServicesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ServicesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ServicesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ServicesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + ServicesClient, + ServicesAsyncClient, +]) +def test_services_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'appengine.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ServicesGrpcTransport, "grpc"), + (transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_services_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + ServicesClient, + ServicesAsyncClient, +]) +def test_services_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'appengine.googleapis.com:443' + + +def test_services_client_get_transport_class(): + transport = ServicesClient.get_transport_class() + available_transports = [ + transports.ServicesGrpcTransport, + ] + assert transport in available_transports + + transport = ServicesClient.get_transport_class("grpc") + assert transport == transports.ServicesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServicesClient, transports.ServicesGrpcTransport, "grpc"), + (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ServicesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesClient)) +@mock.patch.object(ServicesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesAsyncClient)) +def test_services_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(ServicesClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(ServicesClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ServicesClient, transports.ServicesGrpcTransport, "grpc", "true"), + (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ServicesClient, transports.ServicesGrpcTransport, "grpc", "false"), + (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ServicesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesClient)) +@mock.patch.object(ServicesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_services_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServicesClient, transports.ServicesGrpcTransport, "grpc"), + (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_services_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ServicesClient, transports.ServicesGrpcTransport, "grpc"), + (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_services_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_services_client_client_options_from_dict(): + with mock.patch('google.cloud.appengine_admin_v1.services.services.transports.ServicesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ServicesClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_services(transport: str = 'grpc', request_type=appengine.ListServicesRequest): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = appengine.ListServicesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListServicesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_services_from_dict(): + test_list_services(request_type=dict) + + +def test_list_services_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServicesClient( + credentials=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_services), + '__call__') as call: + client.list_services() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListServicesRequest() + + +@pytest.mark.asyncio +async def test_list_services_async(transport: str = 'grpc_asyncio', request_type=appengine.ListServicesRequest): + client = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListServicesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListServicesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_services_async_from_dict(): + await test_list_services_async(request_type=dict) + + +def test_list_services_field_headers(): + client = ServicesClient( + credentials=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. + request = appengine.ListServicesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + call.return_value = appengine.ListServicesResponse() + client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_services_field_headers_async(): + client = ServicesAsyncClient( + credentials=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. + request = appengine.ListServicesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListServicesResponse()) + await client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_list_services_pager(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + service.Service(), + ], + next_page_token='abc', + ), + appengine.ListServicesResponse( + services=[], + next_page_token='def', + ), + appengine.ListServicesResponse( + services=[ + service.Service(), + ], + next_page_token='ghi', + ), + appengine.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_services(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, service.Service) + for i in results) + +def test_list_services_pages(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + service.Service(), + ], + next_page_token='abc', + ), + appengine.ListServicesResponse( + services=[], + next_page_token='def', + ), + appengine.ListServicesResponse( + services=[ + service.Service(), + ], + next_page_token='ghi', + ), + appengine.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + ], + ), + RuntimeError, + ) + pages = list(client.list_services(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_services_async_pager(): + client = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + service.Service(), + ], + next_page_token='abc', + ), + appengine.ListServicesResponse( + services=[], + next_page_token='def', + ), + appengine.ListServicesResponse( + services=[ + service.Service(), + ], + next_page_token='ghi', + ), + appengine.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_services(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, service.Service) + for i in responses) + +@pytest.mark.asyncio +async def test_list_services_async_pages(): + client = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + service.Service(), + ], + next_page_token='abc', + ), + appengine.ListServicesResponse( + services=[], + next_page_token='def', + ), + appengine.ListServicesResponse( + services=[ + service.Service(), + ], + next_page_token='ghi', + ), + appengine.ListServicesResponse( + services=[ + service.Service(), + service.Service(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_services(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_service(transport: str = 'grpc', request_type=appengine.GetServiceRequest): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.Service( + name='name_value', + id='id_value', + ) + response = client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.Service) + assert response.name == 'name_value' + assert response.id == 'id_value' + + +def test_get_service_from_dict(): + test_get_service(request_type=dict) + + +def test_get_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServicesClient( + credentials=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_service), + '__call__') as call: + client.get_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetServiceRequest() + + +@pytest.mark.asyncio +async def test_get_service_async(transport: str = 'grpc_asyncio', request_type=appengine.GetServiceRequest): + client = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.Service( + name='name_value', + id='id_value', + )) + response = await client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.Service) + assert response.name == 'name_value' + assert response.id == 'id_value' + + +@pytest.mark.asyncio +async def test_get_service_async_from_dict(): + await test_get_service_async(request_type=dict) + + +def test_get_service_field_headers(): + client = ServicesClient( + credentials=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. + request = appengine.GetServiceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + call.return_value = service.Service() + client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_service_field_headers_async(): + client = ServicesAsyncClient( + credentials=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. + request = appengine.GetServiceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Service()) + await client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_update_service(transport: str = 'grpc', request_type=appengine.UpdateServiceRequest): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.UpdateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_service_from_dict(): + test_update_service(request_type=dict) + + +def test_update_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServicesClient( + credentials=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_service), + '__call__') as call: + client.update_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.UpdateServiceRequest() + + +@pytest.mark.asyncio +async def test_update_service_async(transport: str = 'grpc_asyncio', request_type=appengine.UpdateServiceRequest): + client = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.UpdateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_service_async_from_dict(): + await test_update_service_async(request_type=dict) + + +def test_update_service_field_headers(): + client = ServicesClient( + credentials=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. + request = appengine.UpdateServiceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_service_field_headers_async(): + client = ServicesAsyncClient( + credentials=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. + request = appengine.UpdateServiceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_delete_service(transport: str = 'grpc', request_type=appengine.DeleteServiceRequest): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DeleteServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_service_from_dict(): + test_delete_service(request_type=dict) + + +def test_delete_service_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ServicesClient( + credentials=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_service), + '__call__') as call: + client.delete_service() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DeleteServiceRequest() + + +@pytest.mark.asyncio +async def test_delete_service_async(transport: str = 'grpc_asyncio', request_type=appengine.DeleteServiceRequest): + client = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DeleteServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_service_async_from_dict(): + await test_delete_service_async(request_type=dict) + + +def test_delete_service_field_headers(): + client = ServicesClient( + credentials=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. + request = appengine.DeleteServiceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_service_field_headers_async(): + client = ServicesAsyncClient( + credentials=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. + request = appengine.DeleteServiceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServicesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ServicesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ServicesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ServicesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ServicesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ServicesGrpcTransport, + transports.ServicesGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ServicesGrpcTransport, + ) + +def test_services_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ServicesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_services_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.appengine_admin_v1.services.services.transports.ServicesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ServicesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_services', + 'get_service', + 'update_service', + 'delete_service', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_services_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.services.transports.ServicesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServicesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_services_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.services.transports.ServicesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServicesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ), + quota_project_id="octopus", + ) + + +def test_services_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.appengine_admin_v1.services.services.transports.ServicesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ServicesTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_services_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ServicesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_services_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ServicesClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ServicesGrpcTransport, + transports.ServicesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_services_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ServicesGrpcTransport, + transports.ServicesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_services_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ServicesGrpcTransport, grpc_helpers), + (transports.ServicesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_services_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + scopes=["1", "2"], + default_host="appengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ServicesGrpcTransport, transports.ServicesGrpcAsyncIOTransport]) +def test_services_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_services_host_no_port(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com'), + ) + assert client.transport._host == 'appengine.googleapis.com:443' + + +def test_services_host_with_port(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com:8000'), + ) + assert client.transport._host == 'appengine.googleapis.com:8000' + +def test_services_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ServicesGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_services_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ServicesGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.ServicesGrpcTransport, transports.ServicesGrpcAsyncIOTransport]) +def test_services_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.ServicesGrpcTransport, transports.ServicesGrpcAsyncIOTransport]) +def test_services_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_services_grpc_lro_client(): + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_services_grpc_lro_async_client(): + client = ServicesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ServicesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = ServicesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ServicesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = ServicesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = ServicesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ServicesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ServicesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = ServicesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ServicesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = ServicesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = ServicesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ServicesClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ServicesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = ServicesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ServicesClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.ServicesTransport, '_prep_wrapped_messages') as prep: + client = ServicesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ServicesTransport, '_prep_wrapped_messages') as prep: + transport_class = ServicesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_versions.py b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_versions.py new file mode 100644 index 0000000..74dae92 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_versions.py @@ -0,0 +1,1977 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.appengine_admin_v1.services.versions import VersionsAsyncClient +from google.cloud.appengine_admin_v1.services.versions import VersionsClient +from google.cloud.appengine_admin_v1.services.versions import pagers +from google.cloud.appengine_admin_v1.services.versions import transports +from google.cloud.appengine_admin_v1.services.versions.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.appengine_admin_v1.types import app_yaml +from google.cloud.appengine_admin_v1.types import appengine +from google.cloud.appengine_admin_v1.types import deploy +from google.cloud.appengine_admin_v1.types import operation as ga_operation +from google.cloud.appengine_admin_v1.types import version +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert VersionsClient._get_default_mtls_endpoint(None) is None + assert VersionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert VersionsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert VersionsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert VersionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert VersionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + VersionsClient, + VersionsAsyncClient, +]) +def test_versions_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'appengine.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.VersionsGrpcTransport, "grpc"), + (transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_versions_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + VersionsClient, + VersionsAsyncClient, +]) +def test_versions_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'appengine.googleapis.com:443' + + +def test_versions_client_get_transport_class(): + transport = VersionsClient.get_transport_class() + available_transports = [ + transports.VersionsGrpcTransport, + ] + assert transport in available_transports + + transport = VersionsClient.get_transport_class("grpc") + assert transport == transports.VersionsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient)) +@mock.patch.object(VersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsAsyncClient)) +def test_versions_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(VersionsClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(VersionsClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc", "true"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (VersionsClient, transports.VersionsGrpcTransport, "grpc", "false"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient)) +@mock.patch.object(VersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_versions_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_versions_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_versions_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_versions_client_client_options_from_dict(): + with mock.patch('google.cloud.appengine_admin_v1.services.versions.transports.VersionsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = VersionsClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_list_versions(transport: str = 'grpc', request_type=appengine.ListVersionsRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = appengine.ListVersionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListVersionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_versions_from_dict(): + test_list_versions(request_type=dict) + + +def test_list_versions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=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: + client.list_versions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListVersionsRequest() + + +@pytest.mark.asyncio +async def test_list_versions_async(transport: str = 'grpc_asyncio', request_type=appengine.ListVersionsRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListVersionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.ListVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListVersionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_versions_async_from_dict(): + await test_list_versions_async(request_type=dict) + + +def test_list_versions_field_headers(): + client = VersionsClient( + credentials=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. + request = appengine.ListVersionsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + call.return_value = appengine.ListVersionsResponse() + client.list_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_versions_field_headers_async(): + client = VersionsAsyncClient( + credentials=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. + request = appengine.ListVersionsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListVersionsResponse()) + await client.list_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_list_versions_pager(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + version.Version(), + ], + next_page_token='abc', + ), + appengine.ListVersionsResponse( + versions=[], + next_page_token='def', + ), + appengine.ListVersionsResponse( + versions=[ + version.Version(), + ], + next_page_token='ghi', + ), + appengine.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_versions(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, version.Version) + for i in results) + +def test_list_versions_pages(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + version.Version(), + ], + next_page_token='abc', + ), + appengine.ListVersionsResponse( + versions=[], + next_page_token='def', + ), + appengine.ListVersionsResponse( + versions=[ + version.Version(), + ], + next_page_token='ghi', + ), + appengine.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + ], + ), + RuntimeError, + ) + pages = list(client.list_versions(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_versions_async_pager(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + version.Version(), + ], + next_page_token='abc', + ), + appengine.ListVersionsResponse( + versions=[], + next_page_token='def', + ), + appengine.ListVersionsResponse( + versions=[ + version.Version(), + ], + next_page_token='ghi', + ), + appengine.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_versions(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, version.Version) + for i in responses) + +@pytest.mark.asyncio +async def test_list_versions_async_pages(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + appengine.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + version.Version(), + ], + next_page_token='abc', + ), + appengine.ListVersionsResponse( + versions=[], + next_page_token='def', + ), + appengine.ListVersionsResponse( + versions=[ + version.Version(), + ], + next_page_token='ghi', + ), + appengine.ListVersionsResponse( + versions=[ + version.Version(), + version.Version(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_versions(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_get_version(transport: str = 'grpc', request_type=appengine.GetVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = version.Version( + name='name_value', + id='id_value', + inbound_services=[version.InboundServiceType.INBOUND_SERVICE_MAIL], + instance_class='instance_class_value', + zones=['zones_value'], + runtime='runtime_value', + runtime_channel='runtime_channel_value', + threadsafe=True, + vm=True, + env='env_value', + serving_status=version.ServingStatus.SERVING, + created_by='created_by_value', + disk_usage_bytes=1701, + runtime_api_version='runtime_api_version_value', + runtime_main_executable_path='runtime_main_executable_path_value', + service_account='service_account_value', + nobuild_files_regex='nobuild_files_regex_value', + version_url='version_url_value', + automatic_scaling=version.AutomaticScaling(cool_down_period=duration_pb2.Duration(seconds=751)), + ) + response = client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, version.Version) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.inbound_services == [version.InboundServiceType.INBOUND_SERVICE_MAIL] + assert response.instance_class == 'instance_class_value' + assert response.zones == ['zones_value'] + assert response.runtime == 'runtime_value' + assert response.runtime_channel == 'runtime_channel_value' + assert response.threadsafe is True + assert response.vm is True + assert response.env == 'env_value' + assert response.serving_status == version.ServingStatus.SERVING + assert response.created_by == 'created_by_value' + assert response.disk_usage_bytes == 1701 + assert response.runtime_api_version == 'runtime_api_version_value' + assert response.runtime_main_executable_path == 'runtime_main_executable_path_value' + assert response.service_account == 'service_account_value' + assert response.nobuild_files_regex == 'nobuild_files_regex_value' + assert response.version_url == 'version_url_value' + + +def test_get_version_from_dict(): + test_get_version(request_type=dict) + + +def test_get_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=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: + client.get_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetVersionRequest() + + +@pytest.mark.asyncio +async def test_get_version_async(transport: str = 'grpc_asyncio', request_type=appengine.GetVersionRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(version.Version( + name='name_value', + id='id_value', + inbound_services=[version.InboundServiceType.INBOUND_SERVICE_MAIL], + instance_class='instance_class_value', + zones=['zones_value'], + runtime='runtime_value', + runtime_channel='runtime_channel_value', + threadsafe=True, + vm=True, + env='env_value', + serving_status=version.ServingStatus.SERVING, + created_by='created_by_value', + disk_usage_bytes=1701, + runtime_api_version='runtime_api_version_value', + runtime_main_executable_path='runtime_main_executable_path_value', + service_account='service_account_value', + nobuild_files_regex='nobuild_files_regex_value', + version_url='version_url_value', + )) + response = await client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.GetVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, version.Version) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.inbound_services == [version.InboundServiceType.INBOUND_SERVICE_MAIL] + assert response.instance_class == 'instance_class_value' + assert response.zones == ['zones_value'] + assert response.runtime == 'runtime_value' + assert response.runtime_channel == 'runtime_channel_value' + assert response.threadsafe is True + assert response.vm is True + assert response.env == 'env_value' + assert response.serving_status == version.ServingStatus.SERVING + assert response.created_by == 'created_by_value' + assert response.disk_usage_bytes == 1701 + assert response.runtime_api_version == 'runtime_api_version_value' + assert response.runtime_main_executable_path == 'runtime_main_executable_path_value' + assert response.service_account == 'service_account_value' + assert response.nobuild_files_regex == 'nobuild_files_regex_value' + assert response.version_url == 'version_url_value' + + +@pytest.mark.asyncio +async def test_get_version_async_from_dict(): + await test_get_version_async(request_type=dict) + + +def test_get_version_field_headers(): + client = VersionsClient( + credentials=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. + request = appengine.GetVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + call.return_value = version.Version() + client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_version_field_headers_async(): + client = VersionsAsyncClient( + credentials=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. + request = appengine.GetVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.Version()) + await client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_create_version(transport: str = 'grpc', request_type=appengine.CreateVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.CreateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_version_from_dict(): + test_create_version(request_type=dict) + + +def test_create_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=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: + client.create_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.CreateVersionRequest() + + +@pytest.mark.asyncio +async def test_create_version_async(transport: str = 'grpc_asyncio', request_type=appengine.CreateVersionRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.CreateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_version_async_from_dict(): + await test_create_version_async(request_type=dict) + + +def test_create_version_field_headers(): + client = VersionsClient( + credentials=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. + request = appengine.CreateVersionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_version_field_headers_async(): + client = VersionsAsyncClient( + credentials=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. + request = appengine.CreateVersionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_update_version(transport: str = 'grpc', request_type=appengine.UpdateVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.UpdateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_version_from_dict(): + test_update_version(request_type=dict) + + +def test_update_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=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: + client.update_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.UpdateVersionRequest() + + +@pytest.mark.asyncio +async def test_update_version_async(transport: str = 'grpc_asyncio', request_type=appengine.UpdateVersionRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.UpdateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_version_async_from_dict(): + await test_update_version_async(request_type=dict) + + +def test_update_version_field_headers(): + client = VersionsClient( + credentials=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. + request = appengine.UpdateVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_version_field_headers_async(): + client = VersionsAsyncClient( + credentials=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. + request = appengine.UpdateVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_delete_version(transport: str = 'grpc', request_type=appengine.DeleteVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DeleteVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_version_from_dict(): + test_delete_version(request_type=dict) + + +def test_delete_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=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: + client.delete_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DeleteVersionRequest() + + +@pytest.mark.asyncio +async def test_delete_version_async(transport: str = 'grpc_asyncio', request_type=appengine.DeleteVersionRequest): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == appengine.DeleteVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_version_async_from_dict(): + await test_delete_version_async(request_type=dict) + + +def test_delete_version_field_headers(): + client = VersionsClient( + credentials=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. + request = appengine.DeleteVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_version_field_headers_async(): + client = VersionsAsyncClient( + credentials=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. + request = appengine.DeleteVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.VersionsGrpcTransport( + credentials=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 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( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = VersionsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.VersionsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.VersionsGrpcTransport, + transports.VersionsGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.VersionsGrpcTransport, + ) + +def test_versions_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.VersionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_versions_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.appengine_admin_v1.services.versions.transports.VersionsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.VersionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_versions', + 'get_version', + 'create_version', + 'update_version', + 'delete_version', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_versions_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_versions_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + ), + quota_project_id="octopus", + ) + + +def test_versions_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.appengine_admin_v1.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_versions_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + VersionsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_versions_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + VersionsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VersionsGrpcTransport, + transports.VersionsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_versions_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VersionsGrpcTransport, + transports.VersionsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_versions_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VersionsGrpcTransport, grpc_helpers), + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_versions_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "appengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/appengine.admin', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', +), + scopes=["1", "2"], + default_host="appengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport]) +def test_versions_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_versions_host_no_port(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com'), + ) + assert client.transport._host == 'appengine.googleapis.com:443' + + +def test_versions_host_with_port(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com:8000'), + ) + assert client.transport._host == 'appengine.googleapis.com:8000' + +def test_versions_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VersionsGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_versions_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VersionsGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport]) +def test_versions_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport]) +def test_versions_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_versions_grpc_lro_client(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_versions_grpc_lro_async_client(): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = VersionsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = VersionsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = VersionsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = VersionsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = VersionsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = VersionsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = VersionsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = VersionsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = VersionsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = VersionsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.VersionsTransport, '_prep_wrapped_messages') as prep: + client = VersionsClient( + credentials=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) From 06714acda205536ef3f1cd6a0fb154ccea217cc5 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 23 Jul 2021 21:30:46 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/master/packages/owl-bot/README.md --- .../services/applications/client.py | 4 + .../authorized_certificates/client.py | 4 + .../services/authorized_domains/client.py | 4 + .../services/domain_mappings/client.py | 4 + .../services/firewall/client.py | 4 + .../services/instances/client.py | 4 + .../services/services/client.py | 4 + .../services/versions/client.py | 4 + owl-bot-staging/v1/.coveragerc | 17 - owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - .../docs/appengine_admin_v1/applications.rst | 6 - .../authorized_certificates.rst | 10 - .../appengine_admin_v1/authorized_domains.rst | 10 - .../appengine_admin_v1/domain_mappings.rst | 10 - .../v1/docs/appengine_admin_v1/firewall.rst | 10 - .../v1/docs/appengine_admin_v1/instances.rst | 10 - .../v1/docs/appengine_admin_v1/services.rst | 13 - .../v1/docs/appengine_admin_v1/types.rst | 7 - .../v1/docs/appengine_admin_v1/versions.rst | 10 - owl-bot-staging/v1/docs/conf.py | 376 --- owl-bot-staging/v1/docs/index.rst | 7 - .../google/cloud/appengine_admin/__init__.py | 253 -- .../v1/google/cloud/appengine_admin/py.typed | 2 - .../cloud/appengine_admin_v1/__init__.py | 254 -- .../appengine_admin_v1/gapic_metadata.json | 461 ---- .../google/cloud/appengine_admin_v1/py.typed | 2 - .../appengine_admin_v1/services/__init__.py | 15 - .../services/applications/__init__.py | 22 - .../services/applications/async_client.py | 434 ---- .../services/applications/client.py | 620 ----- .../applications/transports/__init__.py | 33 - .../services/applications/transports/base.py | 220 -- .../services/applications/transports/grpc.py | 376 --- .../applications/transports/grpc_asyncio.py | 380 --- .../authorized_certificates/__init__.py | 22 - .../authorized_certificates/async_client.py | 459 ---- .../authorized_certificates/client.py | 646 ------ .../authorized_certificates/pagers.py | 141 -- .../transports/__init__.py | 33 - .../transports/base.py | 228 -- .../transports/grpc.py | 366 --- .../transports/grpc_asyncio.py | 370 --- .../services/authorized_domains/__init__.py | 22 - .../authorized_domains/async_client.py | 233 -- .../services/authorized_domains/client.py | 416 ---- .../services/authorized_domains/pagers.py | 141 -- .../authorized_domains/transports/__init__.py | 33 - .../authorized_domains/transports/base.py | 170 -- .../authorized_domains/transports/grpc.py | 255 -- .../transports/grpc_asyncio.py | 259 --- .../services/domain_mappings/__init__.py | 22 - .../services/domain_mappings/async_client.py | 504 ---- .../services/domain_mappings/client.py | 691 ------ .../services/domain_mappings/pagers.py | 141 -- .../domain_mappings/transports/__init__.py | 33 - .../domain_mappings/transports/base.py | 234 -- .../domain_mappings/transports/grpc.py | 385 ---- .../transports/grpc_asyncio.py | 389 ---- .../services/firewall/__init__.py | 22 - .../services/firewall/async_client.py | 515 ----- .../services/firewall/client.py | 703 ------ .../services/firewall/pagers.py | 141 -- .../services/firewall/transports/__init__.py | 33 - .../services/firewall/transports/base.py | 242 -- .../services/firewall/transports/grpc.py | 400 ---- .../firewall/transports/grpc_asyncio.py | 404 ---- .../services/instances/__init__.py | 22 - .../services/instances/async_client.py | 459 ---- .../services/instances/client.py | 654 ------ .../services/instances/pagers.py | 141 -- .../services/instances/transports/__init__.py | 33 - .../services/instances/transports/base.py | 220 -- .../services/instances/transports/grpc.py | 377 --- .../instances/transports/grpc_asyncio.py | 381 --- .../services/services/__init__.py | 22 - .../services/services/async_client.py | 448 ---- .../services/services/client.py | 634 ----- .../services/services/pagers.py | 141 -- .../services/services/transports/__init__.py | 33 - .../services/services/transports/base.py | 220 -- .../services/services/transports/grpc.py | 352 --- .../services/transports/grpc_asyncio.py | 356 --- .../services/versions/__init__.py | 22 - .../services/versions/async_client.py | 535 ----- .../services/versions/client.py | 722 ------ .../services/versions/pagers.py | 141 -- .../services/versions/transports/__init__.py | 33 - .../services/versions/transports/base.py | 234 -- .../services/versions/transports/grpc.py | 413 ---- .../versions/transports/grpc_asyncio.py | 417 ---- .../appengine_admin_v1/types/__init__.py | 250 -- .../appengine_admin_v1/types/app_yaml.py | 539 ----- .../appengine_admin_v1/types/appengine.py | 1103 --------- .../appengine_admin_v1/types/application.py | 284 --- .../appengine_admin_v1/types/audit_data.py | 84 - .../appengine_admin_v1/types/certificate.py | 229 -- .../cloud/appengine_admin_v1/types/deploy.py | 191 -- .../types/deployed_files.py | 25 - .../cloud/appengine_admin_v1/types/domain.py | 53 - .../types/domain_mapping.py | 161 -- .../appengine_admin_v1/types/firewall.py | 86 - .../appengine_admin_v1/types/instance.py | 183 -- .../appengine_admin_v1/types/location.py | 60 - .../types/network_settings.py | 49 - .../appengine_admin_v1/types/operation.py | 120 - .../cloud/appengine_admin_v1/types/service.py | 121 - .../cloud/appengine_admin_v1/types/version.py | 973 -------- owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 132 -- .../fixup_appengine_admin_v1_keywords.py | 209 -- owl-bot-staging/v1/setup.py | 54 - owl-bot-staging/v1/tests/__init__.py | 16 - owl-bot-staging/v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/appengine_admin_v1/__init__.py | 16 - .../appengine_admin_v1/test_applications.py | 1539 ------------- .../test_authorized_certificates.py | 1927 ---------------- .../test_authorized_domains.py | 1264 ---------- .../test_domain_mappings.py | 1908 --------------- .../gapic/appengine_admin_v1/test_firewall.py | 2050 ----------------- .../appengine_admin_v1/test_instances.py | 1839 --------------- .../gapic/appengine_admin_v1/test_services.py | 1761 -------------- .../gapic/appengine_admin_v1/test_versions.py | 1977 ---------------- .../appengine_admin_v1/test_applications.py | 29 +- .../test_authorized_certificates.py | 31 +- .../test_authorized_domains.py | 31 +- .../test_domain_mappings.py | 31 +- .../gapic/appengine_admin_v1/test_firewall.py | 29 +- .../appengine_admin_v1/test_instances.py | 29 +- .../gapic/appengine_admin_v1/test_services.py | 29 +- .../gapic/appengine_admin_v1/test_versions.py | 29 +- 132 files changed, 176 insertions(+), 38604 deletions(-) delete mode 100644 owl-bot-staging/v1/.coveragerc delete mode 100644 owl-bot-staging/v1/MANIFEST.in delete mode 100644 owl-bot-staging/v1/README.rst delete mode 100644 owl-bot-staging/v1/docs/appengine_admin_v1/applications.rst delete mode 100644 owl-bot-staging/v1/docs/appengine_admin_v1/authorized_certificates.rst delete mode 100644 owl-bot-staging/v1/docs/appengine_admin_v1/authorized_domains.rst delete mode 100644 owl-bot-staging/v1/docs/appengine_admin_v1/domain_mappings.rst delete mode 100644 owl-bot-staging/v1/docs/appengine_admin_v1/firewall.rst delete mode 100644 owl-bot-staging/v1/docs/appengine_admin_v1/instances.rst delete mode 100644 owl-bot-staging/v1/docs/appengine_admin_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/appengine_admin_v1/types.rst delete mode 100644 owl-bot-staging/v1/docs/appengine_admin_v1/versions.rst delete mode 100644 owl-bot-staging/v1/docs/conf.py delete mode 100644 owl-bot-staging/v1/docs/index.rst delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/app_yaml.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/appengine.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/application.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/audit_data.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/certificate.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/deploy.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/deployed_files.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/domain.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/domain_mapping.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/firewall.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/instance.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/location.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/network_settings.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/operation.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/service.py delete mode 100644 owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/version.py delete mode 100644 owl-bot-staging/v1/mypy.ini delete mode 100644 owl-bot-staging/v1/noxfile.py delete mode 100644 owl-bot-staging/v1/scripts/fixup_appengine_admin_v1_keywords.py delete mode 100644 owl-bot-staging/v1/setup.py delete mode 100644 owl-bot-staging/v1/tests/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_applications.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_firewall.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_instances.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_services.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_versions.py diff --git a/google/cloud/appengine_admin_v1/services/applications/client.py b/google/cloud/appengine_admin_v1/services/applications/client.py index 58a29ed..6c8e925 100644 --- a/google/cloud/appengine_admin_v1/services/applications/client.py +++ b/google/cloud/appengine_admin_v1/services/applications/client.py @@ -330,6 +330,10 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), ) def get_application( diff --git a/google/cloud/appengine_admin_v1/services/authorized_certificates/client.py b/google/cloud/appengine_admin_v1/services/authorized_certificates/client.py index 79bdf59..8f67075 100644 --- a/google/cloud/appengine_admin_v1/services/authorized_certificates/client.py +++ b/google/cloud/appengine_admin_v1/services/authorized_certificates/client.py @@ -335,6 +335,10 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), ) def list_authorized_certificates( diff --git a/google/cloud/appengine_admin_v1/services/authorized_domains/client.py b/google/cloud/appengine_admin_v1/services/authorized_domains/client.py index c427da1..545b69d 100644 --- a/google/cloud/appengine_admin_v1/services/authorized_domains/client.py +++ b/google/cloud/appengine_admin_v1/services/authorized_domains/client.py @@ -334,6 +334,10 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), ) def list_authorized_domains( diff --git a/google/cloud/appengine_admin_v1/services/domain_mappings/client.py b/google/cloud/appengine_admin_v1/services/domain_mappings/client.py index 01ca9eb..8032b46 100644 --- a/google/cloud/appengine_admin_v1/services/domain_mappings/client.py +++ b/google/cloud/appengine_admin_v1/services/domain_mappings/client.py @@ -333,6 +333,10 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), ) def list_domain_mappings( diff --git a/google/cloud/appengine_admin_v1/services/firewall/client.py b/google/cloud/appengine_admin_v1/services/firewall/client.py index ba7b180..eaa3159 100644 --- a/google/cloud/appengine_admin_v1/services/firewall/client.py +++ b/google/cloud/appengine_admin_v1/services/firewall/client.py @@ -338,6 +338,10 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), ) def list_ingress_rules( diff --git a/google/cloud/appengine_admin_v1/services/instances/client.py b/google/cloud/appengine_admin_v1/services/instances/client.py index d834836..0991030 100644 --- a/google/cloud/appengine_admin_v1/services/instances/client.py +++ b/google/cloud/appengine_admin_v1/services/instances/client.py @@ -348,6 +348,10 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), ) def list_instances( diff --git a/google/cloud/appengine_admin_v1/services/services/client.py b/google/cloud/appengine_admin_v1/services/services/client.py index 7f20d31..2d630ee 100644 --- a/google/cloud/appengine_admin_v1/services/services/client.py +++ b/google/cloud/appengine_admin_v1/services/services/client.py @@ -332,6 +332,10 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), ) def list_services( diff --git a/google/cloud/appengine_admin_v1/services/versions/client.py b/google/cloud/appengine_admin_v1/services/versions/client.py index ed1e086..4d05135 100644 --- a/google/cloud/appengine_admin_v1/services/versions/client.py +++ b/google/cloud/appengine_admin_v1/services/versions/client.py @@ -335,6 +335,10 @@ def __init__( client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), ) def list_versions( diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index 44c6382..0000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/appengine_admin/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in deleted file mode 100644 index 6103ec7..0000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/appengine_admin *.py -recursive-include google/cloud/appengine_admin_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index f6231b8..0000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Appengine Admin API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Appengine Admin API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/appengine_admin_v1/applications.rst b/owl-bot-staging/v1/docs/appengine_admin_v1/applications.rst deleted file mode 100644 index 8afb1c7..0000000 --- a/owl-bot-staging/v1/docs/appengine_admin_v1/applications.rst +++ /dev/null @@ -1,6 +0,0 @@ -Applications ------------------------------- - -.. automodule:: google.cloud.appengine_admin_v1.services.applications - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/appengine_admin_v1/authorized_certificates.rst b/owl-bot-staging/v1/docs/appengine_admin_v1/authorized_certificates.rst deleted file mode 100644 index 03ac310..0000000 --- a/owl-bot-staging/v1/docs/appengine_admin_v1/authorized_certificates.rst +++ /dev/null @@ -1,10 +0,0 @@ -AuthorizedCertificates ----------------------------------------- - -.. automodule:: google.cloud.appengine_admin_v1.services.authorized_certificates - :members: - :inherited-members: - -.. automodule:: google.cloud.appengine_admin_v1.services.authorized_certificates.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/appengine_admin_v1/authorized_domains.rst b/owl-bot-staging/v1/docs/appengine_admin_v1/authorized_domains.rst deleted file mode 100644 index d02102a..0000000 --- a/owl-bot-staging/v1/docs/appengine_admin_v1/authorized_domains.rst +++ /dev/null @@ -1,10 +0,0 @@ -AuthorizedDomains ------------------------------------ - -.. automodule:: google.cloud.appengine_admin_v1.services.authorized_domains - :members: - :inherited-members: - -.. automodule:: google.cloud.appengine_admin_v1.services.authorized_domains.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/appengine_admin_v1/domain_mappings.rst b/owl-bot-staging/v1/docs/appengine_admin_v1/domain_mappings.rst deleted file mode 100644 index 89af15b..0000000 --- a/owl-bot-staging/v1/docs/appengine_admin_v1/domain_mappings.rst +++ /dev/null @@ -1,10 +0,0 @@ -DomainMappings --------------------------------- - -.. automodule:: google.cloud.appengine_admin_v1.services.domain_mappings - :members: - :inherited-members: - -.. automodule:: google.cloud.appengine_admin_v1.services.domain_mappings.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/appengine_admin_v1/firewall.rst b/owl-bot-staging/v1/docs/appengine_admin_v1/firewall.rst deleted file mode 100644 index ce343d1..0000000 --- a/owl-bot-staging/v1/docs/appengine_admin_v1/firewall.rst +++ /dev/null @@ -1,10 +0,0 @@ -Firewall --------------------------- - -.. automodule:: google.cloud.appengine_admin_v1.services.firewall - :members: - :inherited-members: - -.. automodule:: google.cloud.appengine_admin_v1.services.firewall.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/appengine_admin_v1/instances.rst b/owl-bot-staging/v1/docs/appengine_admin_v1/instances.rst deleted file mode 100644 index 57f5079..0000000 --- a/owl-bot-staging/v1/docs/appengine_admin_v1/instances.rst +++ /dev/null @@ -1,10 +0,0 @@ -Instances ---------------------------- - -.. automodule:: google.cloud.appengine_admin_v1.services.instances - :members: - :inherited-members: - -.. automodule:: google.cloud.appengine_admin_v1.services.instances.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/appengine_admin_v1/services.rst b/owl-bot-staging/v1/docs/appengine_admin_v1/services.rst deleted file mode 100644 index ebe1b56..0000000 --- a/owl-bot-staging/v1/docs/appengine_admin_v1/services.rst +++ /dev/null @@ -1,13 +0,0 @@ -Services for Google Cloud Appengine Admin v1 API -================================================ -.. toctree:: - :maxdepth: 2 - - applications - authorized_certificates - authorized_domains - domain_mappings - firewall - instances - services - versions diff --git a/owl-bot-staging/v1/docs/appengine_admin_v1/types.rst b/owl-bot-staging/v1/docs/appengine_admin_v1/types.rst deleted file mode 100644 index cc6979e..0000000 --- a/owl-bot-staging/v1/docs/appengine_admin_v1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Appengine Admin v1 API -============================================= - -.. automodule:: google.cloud.appengine_admin_v1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1/docs/appengine_admin_v1/versions.rst b/owl-bot-staging/v1/docs/appengine_admin_v1/versions.rst deleted file mode 100644 index 58a0f63..0000000 --- a/owl-bot-staging/v1/docs/appengine_admin_v1/versions.rst +++ /dev/null @@ -1,10 +0,0 @@ -Versions --------------------------- - -.. automodule:: google.cloud.appengine_admin_v1.services.versions - :members: - :inherited-members: - -.. automodule:: google.cloud.appengine_admin_v1.services.versions.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py deleted file mode 100644 index 2aafff4..0000000 --- a/owl-bot-staging/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-appengine-admin documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-appengine-admin" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-appengine-admin-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - master_doc, - "google-cloud-appengine-admin.tex", - u"google-cloud-appengine-admin Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - master_doc, - "google-cloud-appengine-admin", - u"Google Cloud Appengine Admin Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "google-cloud-appengine-admin", - u"google-cloud-appengine-admin Documentation", - author, - "google-cloud-appengine-admin", - "GAPIC library for Google Cloud Appengine Admin API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst deleted file mode 100644 index 75f0698..0000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - appengine_admin_v1/services - appengine_admin_v1/types diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin/__init__.py deleted file mode 100644 index e0b30cc..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin/__init__.py +++ /dev/null @@ -1,253 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.cloud.appengine_admin_v1.services.applications.client import ApplicationsClient -from google.cloud.appengine_admin_v1.services.applications.async_client import ApplicationsAsyncClient -from google.cloud.appengine_admin_v1.services.authorized_certificates.client import AuthorizedCertificatesClient -from google.cloud.appengine_admin_v1.services.authorized_certificates.async_client import AuthorizedCertificatesAsyncClient -from google.cloud.appengine_admin_v1.services.authorized_domains.client import AuthorizedDomainsClient -from google.cloud.appengine_admin_v1.services.authorized_domains.async_client import AuthorizedDomainsAsyncClient -from google.cloud.appengine_admin_v1.services.domain_mappings.client import DomainMappingsClient -from google.cloud.appengine_admin_v1.services.domain_mappings.async_client import DomainMappingsAsyncClient -from google.cloud.appengine_admin_v1.services.firewall.client import FirewallClient -from google.cloud.appengine_admin_v1.services.firewall.async_client import FirewallAsyncClient -from google.cloud.appengine_admin_v1.services.instances.client import InstancesClient -from google.cloud.appengine_admin_v1.services.instances.async_client import InstancesAsyncClient -from google.cloud.appengine_admin_v1.services.services.client import ServicesClient -from google.cloud.appengine_admin_v1.services.services.async_client import ServicesAsyncClient -from google.cloud.appengine_admin_v1.services.versions.client import VersionsClient -from google.cloud.appengine_admin_v1.services.versions.async_client import VersionsAsyncClient - -from google.cloud.appengine_admin_v1.types.app_yaml import ApiConfigHandler -from google.cloud.appengine_admin_v1.types.app_yaml import ApiEndpointHandler -from google.cloud.appengine_admin_v1.types.app_yaml import ErrorHandler -from google.cloud.appengine_admin_v1.types.app_yaml import HealthCheck -from google.cloud.appengine_admin_v1.types.app_yaml import Library -from google.cloud.appengine_admin_v1.types.app_yaml import LivenessCheck -from google.cloud.appengine_admin_v1.types.app_yaml import ReadinessCheck -from google.cloud.appengine_admin_v1.types.app_yaml import ScriptHandler -from google.cloud.appengine_admin_v1.types.app_yaml import StaticFilesHandler -from google.cloud.appengine_admin_v1.types.app_yaml import UrlMap -from google.cloud.appengine_admin_v1.types.app_yaml import AuthFailAction -from google.cloud.appengine_admin_v1.types.app_yaml import LoginRequirement -from google.cloud.appengine_admin_v1.types.app_yaml import SecurityLevel -from google.cloud.appengine_admin_v1.types.appengine import BatchUpdateIngressRulesRequest -from google.cloud.appengine_admin_v1.types.appengine import BatchUpdateIngressRulesResponse -from google.cloud.appengine_admin_v1.types.appengine import CreateApplicationRequest -from google.cloud.appengine_admin_v1.types.appengine import CreateAuthorizedCertificateRequest -from google.cloud.appengine_admin_v1.types.appengine import CreateDomainMappingRequest -from google.cloud.appengine_admin_v1.types.appengine import CreateIngressRuleRequest -from google.cloud.appengine_admin_v1.types.appengine import CreateVersionRequest -from google.cloud.appengine_admin_v1.types.appengine import DebugInstanceRequest -from google.cloud.appengine_admin_v1.types.appengine import DeleteAuthorizedCertificateRequest -from google.cloud.appengine_admin_v1.types.appengine import DeleteDomainMappingRequest -from google.cloud.appengine_admin_v1.types.appengine import DeleteIngressRuleRequest -from google.cloud.appengine_admin_v1.types.appengine import DeleteInstanceRequest -from google.cloud.appengine_admin_v1.types.appengine import DeleteServiceRequest -from google.cloud.appengine_admin_v1.types.appengine import DeleteVersionRequest -from google.cloud.appengine_admin_v1.types.appengine import GetApplicationRequest -from google.cloud.appengine_admin_v1.types.appengine import GetAuthorizedCertificateRequest -from google.cloud.appengine_admin_v1.types.appengine import GetDomainMappingRequest -from google.cloud.appengine_admin_v1.types.appengine import GetIngressRuleRequest -from google.cloud.appengine_admin_v1.types.appengine import GetInstanceRequest -from google.cloud.appengine_admin_v1.types.appengine import GetServiceRequest -from google.cloud.appengine_admin_v1.types.appengine import GetVersionRequest -from google.cloud.appengine_admin_v1.types.appengine import ListAuthorizedCertificatesRequest -from google.cloud.appengine_admin_v1.types.appengine import ListAuthorizedCertificatesResponse -from google.cloud.appengine_admin_v1.types.appengine import ListAuthorizedDomainsRequest -from google.cloud.appengine_admin_v1.types.appengine import ListAuthorizedDomainsResponse -from google.cloud.appengine_admin_v1.types.appengine import ListDomainMappingsRequest -from google.cloud.appengine_admin_v1.types.appengine import ListDomainMappingsResponse -from google.cloud.appengine_admin_v1.types.appengine import ListIngressRulesRequest -from google.cloud.appengine_admin_v1.types.appengine import ListIngressRulesResponse -from google.cloud.appengine_admin_v1.types.appengine import ListInstancesRequest -from google.cloud.appengine_admin_v1.types.appengine import ListInstancesResponse -from google.cloud.appengine_admin_v1.types.appengine import ListServicesRequest -from google.cloud.appengine_admin_v1.types.appengine import ListServicesResponse -from google.cloud.appengine_admin_v1.types.appengine import ListVersionsRequest -from google.cloud.appengine_admin_v1.types.appengine import ListVersionsResponse -from google.cloud.appengine_admin_v1.types.appengine import RepairApplicationRequest -from google.cloud.appengine_admin_v1.types.appengine import UpdateApplicationRequest -from google.cloud.appengine_admin_v1.types.appengine import UpdateAuthorizedCertificateRequest -from google.cloud.appengine_admin_v1.types.appengine import UpdateDomainMappingRequest -from google.cloud.appengine_admin_v1.types.appengine import UpdateIngressRuleRequest -from google.cloud.appengine_admin_v1.types.appengine import UpdateServiceRequest -from google.cloud.appengine_admin_v1.types.appengine import UpdateVersionRequest -from google.cloud.appengine_admin_v1.types.appengine import AuthorizedCertificateView -from google.cloud.appengine_admin_v1.types.appengine import DomainOverrideStrategy -from google.cloud.appengine_admin_v1.types.appengine import VersionView -from google.cloud.appengine_admin_v1.types.application import Application -from google.cloud.appengine_admin_v1.types.application import UrlDispatchRule -from google.cloud.appengine_admin_v1.types.audit_data import AuditData -from google.cloud.appengine_admin_v1.types.audit_data import CreateVersionMethod -from google.cloud.appengine_admin_v1.types.audit_data import UpdateServiceMethod -from google.cloud.appengine_admin_v1.types.certificate import AuthorizedCertificate -from google.cloud.appengine_admin_v1.types.certificate import CertificateRawData -from google.cloud.appengine_admin_v1.types.certificate import ManagedCertificate -from google.cloud.appengine_admin_v1.types.certificate import ManagementStatus -from google.cloud.appengine_admin_v1.types.deploy import CloudBuildOptions -from google.cloud.appengine_admin_v1.types.deploy import ContainerInfo -from google.cloud.appengine_admin_v1.types.deploy import Deployment -from google.cloud.appengine_admin_v1.types.deploy import FileInfo -from google.cloud.appengine_admin_v1.types.deploy import ZipInfo -from google.cloud.appengine_admin_v1.types.domain import AuthorizedDomain -from google.cloud.appengine_admin_v1.types.domain_mapping import DomainMapping -from google.cloud.appengine_admin_v1.types.domain_mapping import ResourceRecord -from google.cloud.appengine_admin_v1.types.domain_mapping import SslSettings -from google.cloud.appengine_admin_v1.types.firewall import FirewallRule -from google.cloud.appengine_admin_v1.types.instance import Instance -from google.cloud.appengine_admin_v1.types.location import LocationMetadata -from google.cloud.appengine_admin_v1.types.network_settings import NetworkSettings -from google.cloud.appengine_admin_v1.types.operation import CreateVersionMetadataV1 -from google.cloud.appengine_admin_v1.types.operation import OperationMetadataV1 -from google.cloud.appengine_admin_v1.types.service import Service -from google.cloud.appengine_admin_v1.types.service import TrafficSplit -from google.cloud.appengine_admin_v1.types.version import AutomaticScaling -from google.cloud.appengine_admin_v1.types.version import BasicScaling -from google.cloud.appengine_admin_v1.types.version import CpuUtilization -from google.cloud.appengine_admin_v1.types.version import DiskUtilization -from google.cloud.appengine_admin_v1.types.version import EndpointsApiService -from google.cloud.appengine_admin_v1.types.version import Entrypoint -from google.cloud.appengine_admin_v1.types.version import ManualScaling -from google.cloud.appengine_admin_v1.types.version import Network -from google.cloud.appengine_admin_v1.types.version import NetworkUtilization -from google.cloud.appengine_admin_v1.types.version import RequestUtilization -from google.cloud.appengine_admin_v1.types.version import Resources -from google.cloud.appengine_admin_v1.types.version import StandardSchedulerSettings -from google.cloud.appengine_admin_v1.types.version import Version -from google.cloud.appengine_admin_v1.types.version import Volume -from google.cloud.appengine_admin_v1.types.version import VpcAccessConnector -from google.cloud.appengine_admin_v1.types.version import InboundServiceType -from google.cloud.appengine_admin_v1.types.version import ServingStatus - -__all__ = ('ApplicationsClient', - 'ApplicationsAsyncClient', - 'AuthorizedCertificatesClient', - 'AuthorizedCertificatesAsyncClient', - 'AuthorizedDomainsClient', - 'AuthorizedDomainsAsyncClient', - 'DomainMappingsClient', - 'DomainMappingsAsyncClient', - 'FirewallClient', - 'FirewallAsyncClient', - 'InstancesClient', - 'InstancesAsyncClient', - 'ServicesClient', - 'ServicesAsyncClient', - 'VersionsClient', - 'VersionsAsyncClient', - 'ApiConfigHandler', - 'ApiEndpointHandler', - 'ErrorHandler', - 'HealthCheck', - 'Library', - 'LivenessCheck', - 'ReadinessCheck', - 'ScriptHandler', - 'StaticFilesHandler', - 'UrlMap', - 'AuthFailAction', - 'LoginRequirement', - 'SecurityLevel', - 'BatchUpdateIngressRulesRequest', - 'BatchUpdateIngressRulesResponse', - 'CreateApplicationRequest', - 'CreateAuthorizedCertificateRequest', - 'CreateDomainMappingRequest', - 'CreateIngressRuleRequest', - 'CreateVersionRequest', - 'DebugInstanceRequest', - 'DeleteAuthorizedCertificateRequest', - 'DeleteDomainMappingRequest', - 'DeleteIngressRuleRequest', - 'DeleteInstanceRequest', - 'DeleteServiceRequest', - 'DeleteVersionRequest', - 'GetApplicationRequest', - 'GetAuthorizedCertificateRequest', - 'GetDomainMappingRequest', - 'GetIngressRuleRequest', - 'GetInstanceRequest', - 'GetServiceRequest', - 'GetVersionRequest', - 'ListAuthorizedCertificatesRequest', - 'ListAuthorizedCertificatesResponse', - 'ListAuthorizedDomainsRequest', - 'ListAuthorizedDomainsResponse', - 'ListDomainMappingsRequest', - 'ListDomainMappingsResponse', - 'ListIngressRulesRequest', - 'ListIngressRulesResponse', - 'ListInstancesRequest', - 'ListInstancesResponse', - 'ListServicesRequest', - 'ListServicesResponse', - 'ListVersionsRequest', - 'ListVersionsResponse', - 'RepairApplicationRequest', - 'UpdateApplicationRequest', - 'UpdateAuthorizedCertificateRequest', - 'UpdateDomainMappingRequest', - 'UpdateIngressRuleRequest', - 'UpdateServiceRequest', - 'UpdateVersionRequest', - 'AuthorizedCertificateView', - 'DomainOverrideStrategy', - 'VersionView', - 'Application', - 'UrlDispatchRule', - 'AuditData', - 'CreateVersionMethod', - 'UpdateServiceMethod', - 'AuthorizedCertificate', - 'CertificateRawData', - 'ManagedCertificate', - 'ManagementStatus', - 'CloudBuildOptions', - 'ContainerInfo', - 'Deployment', - 'FileInfo', - 'ZipInfo', - 'AuthorizedDomain', - 'DomainMapping', - 'ResourceRecord', - 'SslSettings', - 'FirewallRule', - 'Instance', - 'LocationMetadata', - 'NetworkSettings', - 'CreateVersionMetadataV1', - 'OperationMetadataV1', - 'Service', - 'TrafficSplit', - 'AutomaticScaling', - 'BasicScaling', - 'CpuUtilization', - 'DiskUtilization', - 'EndpointsApiService', - 'Entrypoint', - 'ManualScaling', - 'Network', - 'NetworkUtilization', - 'RequestUtilization', - 'Resources', - 'StandardSchedulerSettings', - 'Version', - 'Volume', - 'VpcAccessConnector', - 'InboundServiceType', - 'ServingStatus', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin/py.typed b/owl-bot-staging/v1/google/cloud/appengine_admin/py.typed deleted file mode 100644 index f846732..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-appengine-admin package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/__init__.py deleted file mode 100644 index d72b66e..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/__init__.py +++ /dev/null @@ -1,254 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from .services.applications import ApplicationsClient -from .services.applications import ApplicationsAsyncClient -from .services.authorized_certificates import AuthorizedCertificatesClient -from .services.authorized_certificates import AuthorizedCertificatesAsyncClient -from .services.authorized_domains import AuthorizedDomainsClient -from .services.authorized_domains import AuthorizedDomainsAsyncClient -from .services.domain_mappings import DomainMappingsClient -from .services.domain_mappings import DomainMappingsAsyncClient -from .services.firewall import FirewallClient -from .services.firewall import FirewallAsyncClient -from .services.instances import InstancesClient -from .services.instances import InstancesAsyncClient -from .services.services import ServicesClient -from .services.services import ServicesAsyncClient -from .services.versions import VersionsClient -from .services.versions import VersionsAsyncClient - -from .types.app_yaml import ApiConfigHandler -from .types.app_yaml import ApiEndpointHandler -from .types.app_yaml import ErrorHandler -from .types.app_yaml import HealthCheck -from .types.app_yaml import Library -from .types.app_yaml import LivenessCheck -from .types.app_yaml import ReadinessCheck -from .types.app_yaml import ScriptHandler -from .types.app_yaml import StaticFilesHandler -from .types.app_yaml import UrlMap -from .types.app_yaml import AuthFailAction -from .types.app_yaml import LoginRequirement -from .types.app_yaml import SecurityLevel -from .types.appengine import BatchUpdateIngressRulesRequest -from .types.appengine import BatchUpdateIngressRulesResponse -from .types.appengine import CreateApplicationRequest -from .types.appengine import CreateAuthorizedCertificateRequest -from .types.appengine import CreateDomainMappingRequest -from .types.appengine import CreateIngressRuleRequest -from .types.appengine import CreateVersionRequest -from .types.appengine import DebugInstanceRequest -from .types.appengine import DeleteAuthorizedCertificateRequest -from .types.appengine import DeleteDomainMappingRequest -from .types.appengine import DeleteIngressRuleRequest -from .types.appengine import DeleteInstanceRequest -from .types.appengine import DeleteServiceRequest -from .types.appengine import DeleteVersionRequest -from .types.appengine import GetApplicationRequest -from .types.appengine import GetAuthorizedCertificateRequest -from .types.appengine import GetDomainMappingRequest -from .types.appengine import GetIngressRuleRequest -from .types.appengine import GetInstanceRequest -from .types.appengine import GetServiceRequest -from .types.appengine import GetVersionRequest -from .types.appengine import ListAuthorizedCertificatesRequest -from .types.appengine import ListAuthorizedCertificatesResponse -from .types.appengine import ListAuthorizedDomainsRequest -from .types.appengine import ListAuthorizedDomainsResponse -from .types.appengine import ListDomainMappingsRequest -from .types.appengine import ListDomainMappingsResponse -from .types.appengine import ListIngressRulesRequest -from .types.appengine import ListIngressRulesResponse -from .types.appengine import ListInstancesRequest -from .types.appengine import ListInstancesResponse -from .types.appengine import ListServicesRequest -from .types.appengine import ListServicesResponse -from .types.appengine import ListVersionsRequest -from .types.appengine import ListVersionsResponse -from .types.appengine import RepairApplicationRequest -from .types.appengine import UpdateApplicationRequest -from .types.appengine import UpdateAuthorizedCertificateRequest -from .types.appengine import UpdateDomainMappingRequest -from .types.appengine import UpdateIngressRuleRequest -from .types.appengine import UpdateServiceRequest -from .types.appengine import UpdateVersionRequest -from .types.appengine import AuthorizedCertificateView -from .types.appengine import DomainOverrideStrategy -from .types.appengine import VersionView -from .types.application import Application -from .types.application import UrlDispatchRule -from .types.audit_data import AuditData -from .types.audit_data import CreateVersionMethod -from .types.audit_data import UpdateServiceMethod -from .types.certificate import AuthorizedCertificate -from .types.certificate import CertificateRawData -from .types.certificate import ManagedCertificate -from .types.certificate import ManagementStatus -from .types.deploy import CloudBuildOptions -from .types.deploy import ContainerInfo -from .types.deploy import Deployment -from .types.deploy import FileInfo -from .types.deploy import ZipInfo -from .types.domain import AuthorizedDomain -from .types.domain_mapping import DomainMapping -from .types.domain_mapping import ResourceRecord -from .types.domain_mapping import SslSettings -from .types.firewall import FirewallRule -from .types.instance import Instance -from .types.location import LocationMetadata -from .types.network_settings import NetworkSettings -from .types.operation import CreateVersionMetadataV1 -from .types.operation import OperationMetadataV1 -from .types.service import Service -from .types.service import TrafficSplit -from .types.version import AutomaticScaling -from .types.version import BasicScaling -from .types.version import CpuUtilization -from .types.version import DiskUtilization -from .types.version import EndpointsApiService -from .types.version import Entrypoint -from .types.version import ManualScaling -from .types.version import Network -from .types.version import NetworkUtilization -from .types.version import RequestUtilization -from .types.version import Resources -from .types.version import StandardSchedulerSettings -from .types.version import Version -from .types.version import Volume -from .types.version import VpcAccessConnector -from .types.version import InboundServiceType -from .types.version import ServingStatus - -__all__ = ( - 'ApplicationsAsyncClient', - 'AuthorizedCertificatesAsyncClient', - 'AuthorizedDomainsAsyncClient', - 'DomainMappingsAsyncClient', - 'FirewallAsyncClient', - 'InstancesAsyncClient', - 'ServicesAsyncClient', - 'VersionsAsyncClient', -'ApiConfigHandler', -'ApiEndpointHandler', -'Application', -'ApplicationsClient', -'AuditData', -'AuthFailAction', -'AuthorizedCertificate', -'AuthorizedCertificateView', -'AuthorizedCertificatesClient', -'AuthorizedDomain', -'AuthorizedDomainsClient', -'AutomaticScaling', -'BasicScaling', -'BatchUpdateIngressRulesRequest', -'BatchUpdateIngressRulesResponse', -'CertificateRawData', -'CloudBuildOptions', -'ContainerInfo', -'CpuUtilization', -'CreateApplicationRequest', -'CreateAuthorizedCertificateRequest', -'CreateDomainMappingRequest', -'CreateIngressRuleRequest', -'CreateVersionMetadataV1', -'CreateVersionMethod', -'CreateVersionRequest', -'DebugInstanceRequest', -'DeleteAuthorizedCertificateRequest', -'DeleteDomainMappingRequest', -'DeleteIngressRuleRequest', -'DeleteInstanceRequest', -'DeleteServiceRequest', -'DeleteVersionRequest', -'Deployment', -'DiskUtilization', -'DomainMapping', -'DomainMappingsClient', -'DomainOverrideStrategy', -'EndpointsApiService', -'Entrypoint', -'ErrorHandler', -'FileInfo', -'FirewallClient', -'FirewallRule', -'GetApplicationRequest', -'GetAuthorizedCertificateRequest', -'GetDomainMappingRequest', -'GetIngressRuleRequest', -'GetInstanceRequest', -'GetServiceRequest', -'GetVersionRequest', -'HealthCheck', -'InboundServiceType', -'Instance', -'InstancesClient', -'Library', -'ListAuthorizedCertificatesRequest', -'ListAuthorizedCertificatesResponse', -'ListAuthorizedDomainsRequest', -'ListAuthorizedDomainsResponse', -'ListDomainMappingsRequest', -'ListDomainMappingsResponse', -'ListIngressRulesRequest', -'ListIngressRulesResponse', -'ListInstancesRequest', -'ListInstancesResponse', -'ListServicesRequest', -'ListServicesResponse', -'ListVersionsRequest', -'ListVersionsResponse', -'LivenessCheck', -'LocationMetadata', -'LoginRequirement', -'ManagedCertificate', -'ManagementStatus', -'ManualScaling', -'Network', -'NetworkSettings', -'NetworkUtilization', -'OperationMetadataV1', -'ReadinessCheck', -'RepairApplicationRequest', -'RequestUtilization', -'ResourceRecord', -'Resources', -'ScriptHandler', -'SecurityLevel', -'Service', -'ServicesClient', -'ServingStatus', -'SslSettings', -'StandardSchedulerSettings', -'StaticFilesHandler', -'TrafficSplit', -'UpdateApplicationRequest', -'UpdateAuthorizedCertificateRequest', -'UpdateDomainMappingRequest', -'UpdateIngressRuleRequest', -'UpdateServiceMethod', -'UpdateServiceRequest', -'UpdateVersionRequest', -'UrlDispatchRule', -'UrlMap', -'Version', -'VersionView', -'VersionsClient', -'Volume', -'VpcAccessConnector', -'ZipInfo', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/gapic_metadata.json deleted file mode 100644 index 0bb6583..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/gapic_metadata.json +++ /dev/null @@ -1,461 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.appengine_admin_v1", - "protoPackage": "google.appengine.v1", - "schema": "1.0", - "services": { - "Applications": { - "clients": { - "grpc": { - "libraryClient": "ApplicationsClient", - "rpcs": { - "CreateApplication": { - "methods": [ - "create_application" - ] - }, - "GetApplication": { - "methods": [ - "get_application" - ] - }, - "RepairApplication": { - "methods": [ - "repair_application" - ] - }, - "UpdateApplication": { - "methods": [ - "update_application" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ApplicationsAsyncClient", - "rpcs": { - "CreateApplication": { - "methods": [ - "create_application" - ] - }, - "GetApplication": { - "methods": [ - "get_application" - ] - }, - "RepairApplication": { - "methods": [ - "repair_application" - ] - }, - "UpdateApplication": { - "methods": [ - "update_application" - ] - } - } - } - } - }, - "AuthorizedCertificates": { - "clients": { - "grpc": { - "libraryClient": "AuthorizedCertificatesClient", - "rpcs": { - "CreateAuthorizedCertificate": { - "methods": [ - "create_authorized_certificate" - ] - }, - "DeleteAuthorizedCertificate": { - "methods": [ - "delete_authorized_certificate" - ] - }, - "GetAuthorizedCertificate": { - "methods": [ - "get_authorized_certificate" - ] - }, - "ListAuthorizedCertificates": { - "methods": [ - "list_authorized_certificates" - ] - }, - "UpdateAuthorizedCertificate": { - "methods": [ - "update_authorized_certificate" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AuthorizedCertificatesAsyncClient", - "rpcs": { - "CreateAuthorizedCertificate": { - "methods": [ - "create_authorized_certificate" - ] - }, - "DeleteAuthorizedCertificate": { - "methods": [ - "delete_authorized_certificate" - ] - }, - "GetAuthorizedCertificate": { - "methods": [ - "get_authorized_certificate" - ] - }, - "ListAuthorizedCertificates": { - "methods": [ - "list_authorized_certificates" - ] - }, - "UpdateAuthorizedCertificate": { - "methods": [ - "update_authorized_certificate" - ] - } - } - } - } - }, - "AuthorizedDomains": { - "clients": { - "grpc": { - "libraryClient": "AuthorizedDomainsClient", - "rpcs": { - "ListAuthorizedDomains": { - "methods": [ - "list_authorized_domains" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AuthorizedDomainsAsyncClient", - "rpcs": { - "ListAuthorizedDomains": { - "methods": [ - "list_authorized_domains" - ] - } - } - } - } - }, - "DomainMappings": { - "clients": { - "grpc": { - "libraryClient": "DomainMappingsClient", - "rpcs": { - "CreateDomainMapping": { - "methods": [ - "create_domain_mapping" - ] - }, - "DeleteDomainMapping": { - "methods": [ - "delete_domain_mapping" - ] - }, - "GetDomainMapping": { - "methods": [ - "get_domain_mapping" - ] - }, - "ListDomainMappings": { - "methods": [ - "list_domain_mappings" - ] - }, - "UpdateDomainMapping": { - "methods": [ - "update_domain_mapping" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DomainMappingsAsyncClient", - "rpcs": { - "CreateDomainMapping": { - "methods": [ - "create_domain_mapping" - ] - }, - "DeleteDomainMapping": { - "methods": [ - "delete_domain_mapping" - ] - }, - "GetDomainMapping": { - "methods": [ - "get_domain_mapping" - ] - }, - "ListDomainMappings": { - "methods": [ - "list_domain_mappings" - ] - }, - "UpdateDomainMapping": { - "methods": [ - "update_domain_mapping" - ] - } - } - } - } - }, - "Firewall": { - "clients": { - "grpc": { - "libraryClient": "FirewallClient", - "rpcs": { - "BatchUpdateIngressRules": { - "methods": [ - "batch_update_ingress_rules" - ] - }, - "CreateIngressRule": { - "methods": [ - "create_ingress_rule" - ] - }, - "DeleteIngressRule": { - "methods": [ - "delete_ingress_rule" - ] - }, - "GetIngressRule": { - "methods": [ - "get_ingress_rule" - ] - }, - "ListIngressRules": { - "methods": [ - "list_ingress_rules" - ] - }, - "UpdateIngressRule": { - "methods": [ - "update_ingress_rule" - ] - } - } - }, - "grpc-async": { - "libraryClient": "FirewallAsyncClient", - "rpcs": { - "BatchUpdateIngressRules": { - "methods": [ - "batch_update_ingress_rules" - ] - }, - "CreateIngressRule": { - "methods": [ - "create_ingress_rule" - ] - }, - "DeleteIngressRule": { - "methods": [ - "delete_ingress_rule" - ] - }, - "GetIngressRule": { - "methods": [ - "get_ingress_rule" - ] - }, - "ListIngressRules": { - "methods": [ - "list_ingress_rules" - ] - }, - "UpdateIngressRule": { - "methods": [ - "update_ingress_rule" - ] - } - } - } - } - }, - "Instances": { - "clients": { - "grpc": { - "libraryClient": "InstancesClient", - "rpcs": { - "DebugInstance": { - "methods": [ - "debug_instance" - ] - }, - "DeleteInstance": { - "methods": [ - "delete_instance" - ] - }, - "GetInstance": { - "methods": [ - "get_instance" - ] - }, - "ListInstances": { - "methods": [ - "list_instances" - ] - } - } - }, - "grpc-async": { - "libraryClient": "InstancesAsyncClient", - "rpcs": { - "DebugInstance": { - "methods": [ - "debug_instance" - ] - }, - "DeleteInstance": { - "methods": [ - "delete_instance" - ] - }, - "GetInstance": { - "methods": [ - "get_instance" - ] - }, - "ListInstances": { - "methods": [ - "list_instances" - ] - } - } - } - } - }, - "Services": { - "clients": { - "grpc": { - "libraryClient": "ServicesClient", - "rpcs": { - "DeleteService": { - "methods": [ - "delete_service" - ] - }, - "GetService": { - "methods": [ - "get_service" - ] - }, - "ListServices": { - "methods": [ - "list_services" - ] - }, - "UpdateService": { - "methods": [ - "update_service" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ServicesAsyncClient", - "rpcs": { - "DeleteService": { - "methods": [ - "delete_service" - ] - }, - "GetService": { - "methods": [ - "get_service" - ] - }, - "ListServices": { - "methods": [ - "list_services" - ] - }, - "UpdateService": { - "methods": [ - "update_service" - ] - } - } - } - } - }, - "Versions": { - "clients": { - "grpc": { - "libraryClient": "VersionsClient", - "rpcs": { - "CreateVersion": { - "methods": [ - "create_version" - ] - }, - "DeleteVersion": { - "methods": [ - "delete_version" - ] - }, - "GetVersion": { - "methods": [ - "get_version" - ] - }, - "ListVersions": { - "methods": [ - "list_versions" - ] - }, - "UpdateVersion": { - "methods": [ - "update_version" - ] - } - } - }, - "grpc-async": { - "libraryClient": "VersionsAsyncClient", - "rpcs": { - "CreateVersion": { - "methods": [ - "create_version" - ] - }, - "DeleteVersion": { - "methods": [ - "delete_version" - ] - }, - "GetVersion": { - "methods": [ - "get_version" - ] - }, - "ListVersions": { - "methods": [ - "list_versions" - ] - }, - "UpdateVersion": { - "methods": [ - "update_version" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/py.typed b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/py.typed deleted file mode 100644 index f846732..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-appengine-admin package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/__init__.py deleted file mode 100644 index 4de6597..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/__init__.py deleted file mode 100644 index 4da2040..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ApplicationsClient -from .async_client import ApplicationsAsyncClient - -__all__ = ( - 'ApplicationsClient', - 'ApplicationsAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/async_client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/async_client.py deleted file mode 100644 index 9e0a567..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/async_client.py +++ /dev/null @@ -1,434 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation as gac_operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import application -from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.protobuf import duration_pb2 # type: ignore -from .transports.base import ApplicationsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ApplicationsGrpcAsyncIOTransport -from .client import ApplicationsClient - - -class ApplicationsAsyncClient: - """Manages App Engine applications.""" - - _client: ApplicationsClient - - DEFAULT_ENDPOINT = ApplicationsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ApplicationsClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(ApplicationsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ApplicationsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ApplicationsClient.common_folder_path) - parse_common_folder_path = staticmethod(ApplicationsClient.parse_common_folder_path) - common_organization_path = staticmethod(ApplicationsClient.common_organization_path) - parse_common_organization_path = staticmethod(ApplicationsClient.parse_common_organization_path) - common_project_path = staticmethod(ApplicationsClient.common_project_path) - parse_common_project_path = staticmethod(ApplicationsClient.parse_common_project_path) - common_location_path = staticmethod(ApplicationsClient.common_location_path) - parse_common_location_path = staticmethod(ApplicationsClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ApplicationsAsyncClient: The constructed client. - """ - return ApplicationsClient.from_service_account_info.__func__(ApplicationsAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ApplicationsAsyncClient: The constructed client. - """ - return ApplicationsClient.from_service_account_file.__func__(ApplicationsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> ApplicationsTransport: - """Returns the transport used by the client instance. - - Returns: - ApplicationsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ApplicationsClient).get_transport_class, type(ApplicationsClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ApplicationsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the applications client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ApplicationsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ApplicationsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_application(self, - request: appengine.GetApplicationRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> application.Application: - r"""Gets information about an application. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.GetApplicationRequest`): - The request object. Request message for - `Applications.GetApplication`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.Application: - An Application resource contains the - top-level configuration of an App Engine - application. - - """ - # Create or coerce a protobuf request object. - request = appengine.GetApplicationRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_application, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_application(self, - request: appengine.CreateApplicationRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates an App Engine application for a Google Cloud Platform - project. Required fields: - - - ``id`` - The ID of the target Cloud Platform project. - - *location* - The - `region `__ - where you want the App Engine application located. - - For more information about App Engine applications, see - `Managing Projects, Applications, and - Billing `__. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.CreateApplicationRequest`): - The request object. Request message for - `Applications.CreateApplication`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Application` An Application resource contains the top-level configuration of an App - Engine application. - - """ - # Create or coerce a protobuf request object. - request = appengine.CreateApplicationRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_application, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - application.Application, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - async def update_application(self, - request: appengine.UpdateApplicationRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the specified Application resource. You can update the - following fields: - - - ``auth_domain`` - Google authentication domain for - controlling user access to the application. - - ``default_cookie_expiration`` - Cookie expiration policy for - the application. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.UpdateApplicationRequest`): - The request object. Request message for - `Applications.UpdateApplication`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Application` An Application resource contains the top-level configuration of an App - Engine application. - - """ - # Create or coerce a protobuf request object. - request = appengine.UpdateApplicationRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_application, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - application.Application, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - async def repair_application(self, - request: appengine.RepairApplicationRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Recreates the required App Engine features for the specified App - Engine application, for example a Cloud Storage bucket or App - Engine service account. Use this method if you receive an error - message about a missing feature, for example, *Error retrieving - the App Engine service account*. If you have deleted your App - Engine service account, this will not be able to recreate it. - Instead, you should attempt to use the IAM undelete API if - possible at - https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params=%7B"name"%3A"projects%2F-%2FserviceAccounts%2Funique_id"%2C"resource"%3A%7B%7D%7D - . If the deletion was recent, the numeric ID can be found in the - Cloud Console Activity Log. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.RepairApplicationRequest`): - The request object. Request message for - 'Applications.RepairApplication'. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Application` An Application resource contains the top-level configuration of an App - Engine application. - - """ - # Create or coerce a protobuf request object. - request = appengine.RepairApplicationRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.repair_application, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - application.Application, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-appengine-admin", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ApplicationsAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/client.py deleted file mode 100644 index 909612f..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/client.py +++ /dev/null @@ -1,620 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation as gac_operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import application -from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.protobuf import duration_pb2 # type: ignore -from .transports.base import ApplicationsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ApplicationsGrpcTransport -from .transports.grpc_asyncio import ApplicationsGrpcAsyncIOTransport - - -class ApplicationsClientMeta(type): - """Metaclass for the Applications client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[ApplicationsTransport]] - _transport_registry["grpc"] = ApplicationsGrpcTransport - _transport_registry["grpc_asyncio"] = ApplicationsGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ApplicationsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class ApplicationsClient(metaclass=ApplicationsClientMeta): - """Manages App Engine applications.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "appengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ApplicationsClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ApplicationsClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> ApplicationsTransport: - """Returns the transport used by the client instance. - - Returns: - ApplicationsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ApplicationsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the applications client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ApplicationsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ApplicationsTransport): - # transport is a ApplicationsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def get_application(self, - request: appengine.GetApplicationRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> application.Application: - r"""Gets information about an application. - - Args: - request (google.cloud.appengine_admin_v1.types.GetApplicationRequest): - The request object. Request message for - `Applications.GetApplication`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.Application: - An Application resource contains the - top-level configuration of an App Engine - application. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.GetApplicationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.GetApplicationRequest): - request = appengine.GetApplicationRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_application] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_application(self, - request: appengine.CreateApplicationRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gac_operation.Operation: - r"""Creates an App Engine application for a Google Cloud Platform - project. Required fields: - - - ``id`` - The ID of the target Cloud Platform project. - - *location* - The - `region `__ - where you want the App Engine application located. - - For more information about App Engine applications, see - `Managing Projects, Applications, and - Billing `__. - - Args: - request (google.cloud.appengine_admin_v1.types.CreateApplicationRequest): - The request object. Request message for - `Applications.CreateApplication`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Application` An Application resource contains the top-level configuration of an App - Engine application. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.CreateApplicationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.CreateApplicationRequest): - request = appengine.CreateApplicationRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_application] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = gac_operation.from_gapic( - response, - self._transport.operations_client, - application.Application, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - def update_application(self, - request: appengine.UpdateApplicationRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gac_operation.Operation: - r"""Updates the specified Application resource. You can update the - following fields: - - - ``auth_domain`` - Google authentication domain for - controlling user access to the application. - - ``default_cookie_expiration`` - Cookie expiration policy for - the application. - - Args: - request (google.cloud.appengine_admin_v1.types.UpdateApplicationRequest): - The request object. Request message for - `Applications.UpdateApplication`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Application` An Application resource contains the top-level configuration of an App - Engine application. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.UpdateApplicationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.UpdateApplicationRequest): - request = appengine.UpdateApplicationRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_application] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = gac_operation.from_gapic( - response, - self._transport.operations_client, - application.Application, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - def repair_application(self, - request: appengine.RepairApplicationRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gac_operation.Operation: - r"""Recreates the required App Engine features for the specified App - Engine application, for example a Cloud Storage bucket or App - Engine service account. Use this method if you receive an error - message about a missing feature, for example, *Error retrieving - the App Engine service account*. If you have deleted your App - Engine service account, this will not be able to recreate it. - Instead, you should attempt to use the IAM undelete API if - possible at - https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params=%7B"name"%3A"projects%2F-%2FserviceAccounts%2Funique_id"%2C"resource"%3A%7B%7D%7D - . If the deletion was recent, the numeric ID can be found in the - Cloud Console Activity Log. - - Args: - request (google.cloud.appengine_admin_v1.types.RepairApplicationRequest): - The request object. Request message for - 'Applications.RepairApplication'. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Application` An Application resource contains the top-level configuration of an App - Engine application. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.RepairApplicationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.RepairApplicationRequest): - request = appengine.RepairApplicationRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.repair_application] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = gac_operation.from_gapic( - response, - self._transport.operations_client, - application.Application, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-appengine-admin", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ApplicationsClient", -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/__init__.py deleted file mode 100644 index ec29c43..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ApplicationsTransport -from .grpc import ApplicationsGrpcTransport -from .grpc_asyncio import ApplicationsGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ApplicationsTransport]] -_transport_registry['grpc'] = ApplicationsGrpcTransport -_transport_registry['grpc_asyncio'] = ApplicationsGrpcAsyncIOTransport - -__all__ = ( - 'ApplicationsTransport', - 'ApplicationsGrpcTransport', - 'ApplicationsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/base.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/base.py deleted file mode 100644 index 7254922..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/base.py +++ /dev/null @@ -1,220 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import application -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-appengine-admin', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class ApplicationsTransport(abc.ABC): - """Abstract transport class for Applications.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ) - - DEFAULT_HOST: str = 'appengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials is service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.get_application: gapic_v1.method.wrap_method( - self.get_application, - default_timeout=None, - client_info=client_info, - ), - self.create_application: gapic_v1.method.wrap_method( - self.create_application, - default_timeout=None, - client_info=client_info, - ), - self.update_application: gapic_v1.method.wrap_method( - self.update_application, - default_timeout=None, - client_info=client_info, - ), - self.repair_application: gapic_v1.method.wrap_method( - self.repair_application, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def get_application(self) -> Callable[ - [appengine.GetApplicationRequest], - Union[ - application.Application, - Awaitable[application.Application] - ]]: - raise NotImplementedError() - - @property - def create_application(self) -> Callable[ - [appengine.CreateApplicationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_application(self) -> Callable[ - [appengine.UpdateApplicationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def repair_application(self) -> Callable[ - [appengine.RepairApplicationRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'ApplicationsTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/grpc.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/grpc.py deleted file mode 100644 index b79e293..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/grpc.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import application -from google.longrunning import operations_pb2 # type: ignore -from .base import ApplicationsTransport, DEFAULT_CLIENT_INFO - - -class ApplicationsGrpcTransport(ApplicationsTransport): - """gRPC backend transport for Applications. - - Manages App Engine applications. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_application(self) -> Callable[ - [appengine.GetApplicationRequest], - application.Application]: - r"""Return a callable for the get application method over gRPC. - - Gets information about an application. - - Returns: - Callable[[~.GetApplicationRequest], - ~.Application]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_application' not in self._stubs: - self._stubs['get_application'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Applications/GetApplication', - request_serializer=appengine.GetApplicationRequest.serialize, - response_deserializer=application.Application.deserialize, - ) - return self._stubs['get_application'] - - @property - def create_application(self) -> Callable[ - [appengine.CreateApplicationRequest], - operations_pb2.Operation]: - r"""Return a callable for the create application method over gRPC. - - Creates an App Engine application for a Google Cloud Platform - project. Required fields: - - - ``id`` - The ID of the target Cloud Platform project. - - *location* - The - `region `__ - where you want the App Engine application located. - - For more information about App Engine applications, see - `Managing Projects, Applications, and - Billing `__. - - Returns: - Callable[[~.CreateApplicationRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_application' not in self._stubs: - self._stubs['create_application'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Applications/CreateApplication', - request_serializer=appengine.CreateApplicationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_application'] - - @property - def update_application(self) -> Callable[ - [appengine.UpdateApplicationRequest], - operations_pb2.Operation]: - r"""Return a callable for the update application method over gRPC. - - Updates the specified Application resource. You can update the - following fields: - - - ``auth_domain`` - Google authentication domain for - controlling user access to the application. - - ``default_cookie_expiration`` - Cookie expiration policy for - the application. - - Returns: - Callable[[~.UpdateApplicationRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_application' not in self._stubs: - self._stubs['update_application'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Applications/UpdateApplication', - request_serializer=appengine.UpdateApplicationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_application'] - - @property - def repair_application(self) -> Callable[ - [appengine.RepairApplicationRequest], - operations_pb2.Operation]: - r"""Return a callable for the repair application method over gRPC. - - Recreates the required App Engine features for the specified App - Engine application, for example a Cloud Storage bucket or App - Engine service account. Use this method if you receive an error - message about a missing feature, for example, *Error retrieving - the App Engine service account*. If you have deleted your App - Engine service account, this will not be able to recreate it. - Instead, you should attempt to use the IAM undelete API if - possible at - https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params=%7B"name"%3A"projects%2F-%2FserviceAccounts%2Funique_id"%2C"resource"%3A%7B%7D%7D - . If the deletion was recent, the numeric ID can be found in the - Cloud Console Activity Log. - - Returns: - Callable[[~.RepairApplicationRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'repair_application' not in self._stubs: - self._stubs['repair_application'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Applications/RepairApplication', - request_serializer=appengine.RepairApplicationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['repair_application'] - - -__all__ = ( - 'ApplicationsGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/grpc_asyncio.py deleted file mode 100644 index fb68688..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/applications/transports/grpc_asyncio.py +++ /dev/null @@ -1,380 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import application -from google.longrunning import operations_pb2 # type: ignore -from .base import ApplicationsTransport, DEFAULT_CLIENT_INFO -from .grpc import ApplicationsGrpcTransport - - -class ApplicationsGrpcAsyncIOTransport(ApplicationsTransport): - """gRPC AsyncIO backend transport for Applications. - - Manages App Engine applications. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_application(self) -> Callable[ - [appengine.GetApplicationRequest], - Awaitable[application.Application]]: - r"""Return a callable for the get application method over gRPC. - - Gets information about an application. - - Returns: - Callable[[~.GetApplicationRequest], - Awaitable[~.Application]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_application' not in self._stubs: - self._stubs['get_application'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Applications/GetApplication', - request_serializer=appengine.GetApplicationRequest.serialize, - response_deserializer=application.Application.deserialize, - ) - return self._stubs['get_application'] - - @property - def create_application(self) -> Callable[ - [appengine.CreateApplicationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create application method over gRPC. - - Creates an App Engine application for a Google Cloud Platform - project. Required fields: - - - ``id`` - The ID of the target Cloud Platform project. - - *location* - The - `region `__ - where you want the App Engine application located. - - For more information about App Engine applications, see - `Managing Projects, Applications, and - Billing `__. - - Returns: - Callable[[~.CreateApplicationRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_application' not in self._stubs: - self._stubs['create_application'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Applications/CreateApplication', - request_serializer=appengine.CreateApplicationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_application'] - - @property - def update_application(self) -> Callable[ - [appengine.UpdateApplicationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update application method over gRPC. - - Updates the specified Application resource. You can update the - following fields: - - - ``auth_domain`` - Google authentication domain for - controlling user access to the application. - - ``default_cookie_expiration`` - Cookie expiration policy for - the application. - - Returns: - Callable[[~.UpdateApplicationRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_application' not in self._stubs: - self._stubs['update_application'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Applications/UpdateApplication', - request_serializer=appengine.UpdateApplicationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_application'] - - @property - def repair_application(self) -> Callable[ - [appengine.RepairApplicationRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the repair application method over gRPC. - - Recreates the required App Engine features for the specified App - Engine application, for example a Cloud Storage bucket or App - Engine service account. Use this method if you receive an error - message about a missing feature, for example, *Error retrieving - the App Engine service account*. If you have deleted your App - Engine service account, this will not be able to recreate it. - Instead, you should attempt to use the IAM undelete API if - possible at - https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params=%7B"name"%3A"projects%2F-%2FserviceAccounts%2Funique_id"%2C"resource"%3A%7B%7D%7D - . If the deletion was recent, the numeric ID can be found in the - Cloud Console Activity Log. - - Returns: - Callable[[~.RepairApplicationRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'repair_application' not in self._stubs: - self._stubs['repair_application'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Applications/RepairApplication', - request_serializer=appengine.RepairApplicationRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['repair_application'] - - -__all__ = ( - 'ApplicationsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/__init__.py deleted file mode 100644 index 5a113af..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import AuthorizedCertificatesClient -from .async_client import AuthorizedCertificatesAsyncClient - -__all__ = ( - 'AuthorizedCertificatesClient', - 'AuthorizedCertificatesAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/async_client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/async_client.py deleted file mode 100644 index 85b96ce..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/async_client.py +++ /dev/null @@ -1,459 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.appengine_admin_v1.services.authorized_certificates import pagers -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import certificate -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import AuthorizedCertificatesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AuthorizedCertificatesGrpcAsyncIOTransport -from .client import AuthorizedCertificatesClient - - -class AuthorizedCertificatesAsyncClient: - """Manages SSL certificates a user is authorized to administer. - A user can administer any SSL certificates applicable to their - authorized domains. - """ - - _client: AuthorizedCertificatesClient - - DEFAULT_ENDPOINT = AuthorizedCertificatesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AuthorizedCertificatesClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(AuthorizedCertificatesClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AuthorizedCertificatesClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AuthorizedCertificatesClient.common_folder_path) - parse_common_folder_path = staticmethod(AuthorizedCertificatesClient.parse_common_folder_path) - common_organization_path = staticmethod(AuthorizedCertificatesClient.common_organization_path) - parse_common_organization_path = staticmethod(AuthorizedCertificatesClient.parse_common_organization_path) - common_project_path = staticmethod(AuthorizedCertificatesClient.common_project_path) - parse_common_project_path = staticmethod(AuthorizedCertificatesClient.parse_common_project_path) - common_location_path = staticmethod(AuthorizedCertificatesClient.common_location_path) - parse_common_location_path = staticmethod(AuthorizedCertificatesClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - AuthorizedCertificatesAsyncClient: The constructed client. - """ - return AuthorizedCertificatesClient.from_service_account_info.__func__(AuthorizedCertificatesAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - AuthorizedCertificatesAsyncClient: The constructed client. - """ - return AuthorizedCertificatesClient.from_service_account_file.__func__(AuthorizedCertificatesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> AuthorizedCertificatesTransport: - """Returns the transport used by the client instance. - - Returns: - AuthorizedCertificatesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(AuthorizedCertificatesClient).get_transport_class, type(AuthorizedCertificatesClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, AuthorizedCertificatesTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the authorized certificates client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.AuthorizedCertificatesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = AuthorizedCertificatesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_authorized_certificates(self, - request: appengine.ListAuthorizedCertificatesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAuthorizedCertificatesAsyncPager: - r"""Lists all SSL certificates the user is authorized to - administer. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesRequest`): - The request object. Request message for - `AuthorizedCertificates.ListAuthorizedCertificates`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.services.authorized_certificates.pagers.ListAuthorizedCertificatesAsyncPager: - Response message for - AuthorizedCertificates.ListAuthorizedCertificates. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = appengine.ListAuthorizedCertificatesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_authorized_certificates, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListAuthorizedCertificatesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_authorized_certificate(self, - request: appengine.GetAuthorizedCertificateRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> certificate.AuthorizedCertificate: - r"""Gets the specified SSL certificate. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.GetAuthorizedCertificateRequest`): - The request object. Request message for - `AuthorizedCertificates.GetAuthorizedCertificate`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.AuthorizedCertificate: - An SSL certificate that a user has - been authorized to administer. A user is - authorized to administer any certificate - that applies to one of their authorized - domains. - - """ - # Create or coerce a protobuf request object. - request = appengine.GetAuthorizedCertificateRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_authorized_certificate, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_authorized_certificate(self, - request: appengine.CreateAuthorizedCertificateRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> certificate.AuthorizedCertificate: - r"""Uploads the specified SSL certificate. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.CreateAuthorizedCertificateRequest`): - The request object. Request message for - `AuthorizedCertificates.CreateAuthorizedCertificate`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.AuthorizedCertificate: - An SSL certificate that a user has - been authorized to administer. A user is - authorized to administer any certificate - that applies to one of their authorized - domains. - - """ - # Create or coerce a protobuf request object. - request = appengine.CreateAuthorizedCertificateRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_authorized_certificate, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_authorized_certificate(self, - request: appengine.UpdateAuthorizedCertificateRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> certificate.AuthorizedCertificate: - r"""Updates the specified SSL certificate. To renew a certificate - and maintain its existing domain mappings, update - ``certificate_data`` with a new certificate. The new certificate - must be applicable to the same domains as the original - certificate. The certificate ``display_name`` may also be - updated. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.UpdateAuthorizedCertificateRequest`): - The request object. Request message for - `AuthorizedCertificates.UpdateAuthorizedCertificate`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.AuthorizedCertificate: - An SSL certificate that a user has - been authorized to administer. A user is - authorized to administer any certificate - that applies to one of their authorized - domains. - - """ - # Create or coerce a protobuf request object. - request = appengine.UpdateAuthorizedCertificateRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_authorized_certificate, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_authorized_certificate(self, - request: appengine.DeleteAuthorizedCertificateRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified SSL certificate. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.DeleteAuthorizedCertificateRequest`): - The request object. Request message for - `AuthorizedCertificates.DeleteAuthorizedCertificate`. - 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. - """ - # Create or coerce a protobuf request object. - request = appengine.DeleteAuthorizedCertificateRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_authorized_certificate, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-appengine-admin", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "AuthorizedCertificatesAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/client.py deleted file mode 100644 index c313304..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/client.py +++ /dev/null @@ -1,646 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.appengine_admin_v1.services.authorized_certificates import pagers -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import certificate -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import AuthorizedCertificatesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AuthorizedCertificatesGrpcTransport -from .transports.grpc_asyncio import AuthorizedCertificatesGrpcAsyncIOTransport - - -class AuthorizedCertificatesClientMeta(type): - """Metaclass for the AuthorizedCertificates client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[AuthorizedCertificatesTransport]] - _transport_registry["grpc"] = AuthorizedCertificatesGrpcTransport - _transport_registry["grpc_asyncio"] = AuthorizedCertificatesGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[AuthorizedCertificatesTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class AuthorizedCertificatesClient(metaclass=AuthorizedCertificatesClientMeta): - """Manages SSL certificates a user is authorized to administer. - A user can administer any SSL certificates applicable to their - authorized domains. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "appengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - AuthorizedCertificatesClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - AuthorizedCertificatesClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> AuthorizedCertificatesTransport: - """Returns the transport used by the client instance. - - Returns: - AuthorizedCertificatesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AuthorizedCertificatesTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the authorized certificates client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, AuthorizedCertificatesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, AuthorizedCertificatesTransport): - # transport is a AuthorizedCertificatesTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def list_authorized_certificates(self, - request: appengine.ListAuthorizedCertificatesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAuthorizedCertificatesPager: - r"""Lists all SSL certificates the user is authorized to - administer. - - Args: - request (google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesRequest): - The request object. Request message for - `AuthorizedCertificates.ListAuthorizedCertificates`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.services.authorized_certificates.pagers.ListAuthorizedCertificatesPager: - Response message for - AuthorizedCertificates.ListAuthorizedCertificates. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.ListAuthorizedCertificatesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.ListAuthorizedCertificatesRequest): - request = appengine.ListAuthorizedCertificatesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_authorized_certificates] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListAuthorizedCertificatesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_authorized_certificate(self, - request: appengine.GetAuthorizedCertificateRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> certificate.AuthorizedCertificate: - r"""Gets the specified SSL certificate. - - Args: - request (google.cloud.appengine_admin_v1.types.GetAuthorizedCertificateRequest): - The request object. Request message for - `AuthorizedCertificates.GetAuthorizedCertificate`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.AuthorizedCertificate: - An SSL certificate that a user has - been authorized to administer. A user is - authorized to administer any certificate - that applies to one of their authorized - domains. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.GetAuthorizedCertificateRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.GetAuthorizedCertificateRequest): - request = appengine.GetAuthorizedCertificateRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_authorized_certificate] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_authorized_certificate(self, - request: appengine.CreateAuthorizedCertificateRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> certificate.AuthorizedCertificate: - r"""Uploads the specified SSL certificate. - - Args: - request (google.cloud.appengine_admin_v1.types.CreateAuthorizedCertificateRequest): - The request object. Request message for - `AuthorizedCertificates.CreateAuthorizedCertificate`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.AuthorizedCertificate: - An SSL certificate that a user has - been authorized to administer. A user is - authorized to administer any certificate - that applies to one of their authorized - domains. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.CreateAuthorizedCertificateRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.CreateAuthorizedCertificateRequest): - request = appengine.CreateAuthorizedCertificateRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_authorized_certificate] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_authorized_certificate(self, - request: appengine.UpdateAuthorizedCertificateRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> certificate.AuthorizedCertificate: - r"""Updates the specified SSL certificate. To renew a certificate - and maintain its existing domain mappings, update - ``certificate_data`` with a new certificate. The new certificate - must be applicable to the same domains as the original - certificate. The certificate ``display_name`` may also be - updated. - - Args: - request (google.cloud.appengine_admin_v1.types.UpdateAuthorizedCertificateRequest): - The request object. Request message for - `AuthorizedCertificates.UpdateAuthorizedCertificate`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.AuthorizedCertificate: - An SSL certificate that a user has - been authorized to administer. A user is - authorized to administer any certificate - that applies to one of their authorized - domains. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.UpdateAuthorizedCertificateRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.UpdateAuthorizedCertificateRequest): - request = appengine.UpdateAuthorizedCertificateRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_authorized_certificate] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_authorized_certificate(self, - request: appengine.DeleteAuthorizedCertificateRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified SSL certificate. - - Args: - request (google.cloud.appengine_admin_v1.types.DeleteAuthorizedCertificateRequest): - The request object. Request message for - `AuthorizedCertificates.DeleteAuthorizedCertificate`. - 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. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.DeleteAuthorizedCertificateRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.DeleteAuthorizedCertificateRequest): - request = appengine.DeleteAuthorizedCertificateRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_authorized_certificate] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-appengine-admin", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "AuthorizedCertificatesClient", -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/pagers.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/pagers.py deleted file mode 100644 index 2da15e4..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/pagers.py +++ /dev/null @@ -1,141 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import certificate - - -class ListAuthorizedCertificatesPager: - """A pager for iterating through ``list_authorized_certificates`` requests. - - This class thinly wraps an initial - :class:`google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``certificates`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAuthorizedCertificates`` requests and continue to iterate - through the ``certificates`` field on the - corresponding responses. - - All the usual :class:`google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., appengine.ListAuthorizedCertificatesResponse], - request: appengine.ListAuthorizedCertificatesRequest, - response: appengine.ListAuthorizedCertificatesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesRequest): - The initial request object. - response (google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = appengine.ListAuthorizedCertificatesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[appengine.ListAuthorizedCertificatesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[certificate.AuthorizedCertificate]: - for page in self.pages: - yield from page.certificates - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAuthorizedCertificatesAsyncPager: - """A pager for iterating through ``list_authorized_certificates`` requests. - - This class thinly wraps an initial - :class:`google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``certificates`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAuthorizedCertificates`` requests and continue to iterate - through the ``certificates`` field on the - corresponding responses. - - All the usual :class:`google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[appengine.ListAuthorizedCertificatesResponse]], - request: appengine.ListAuthorizedCertificatesRequest, - response: appengine.ListAuthorizedCertificatesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesRequest): - The initial request object. - response (google.cloud.appengine_admin_v1.types.ListAuthorizedCertificatesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = appengine.ListAuthorizedCertificatesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[appengine.ListAuthorizedCertificatesResponse]: - 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, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[certificate.AuthorizedCertificate]: - async def async_generator(): - async for page in self.pages: - for response in page.certificates: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/__init__.py deleted file mode 100644 index 03a834e..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import AuthorizedCertificatesTransport -from .grpc import AuthorizedCertificatesGrpcTransport -from .grpc_asyncio import AuthorizedCertificatesGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AuthorizedCertificatesTransport]] -_transport_registry['grpc'] = AuthorizedCertificatesGrpcTransport -_transport_registry['grpc_asyncio'] = AuthorizedCertificatesGrpcAsyncIOTransport - -__all__ = ( - 'AuthorizedCertificatesTransport', - 'AuthorizedCertificatesGrpcTransport', - 'AuthorizedCertificatesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/base.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/base.py deleted file mode 100644 index 4935474..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/base.py +++ /dev/null @@ -1,228 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import certificate -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-appengine-admin', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class AuthorizedCertificatesTransport(abc.ABC): - """Abstract transport class for AuthorizedCertificates.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ) - - DEFAULT_HOST: str = 'appengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials is service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_authorized_certificates: gapic_v1.method.wrap_method( - self.list_authorized_certificates, - default_timeout=None, - client_info=client_info, - ), - self.get_authorized_certificate: gapic_v1.method.wrap_method( - self.get_authorized_certificate, - default_timeout=None, - client_info=client_info, - ), - self.create_authorized_certificate: gapic_v1.method.wrap_method( - self.create_authorized_certificate, - default_timeout=None, - client_info=client_info, - ), - self.update_authorized_certificate: gapic_v1.method.wrap_method( - self.update_authorized_certificate, - default_timeout=None, - client_info=client_info, - ), - self.delete_authorized_certificate: gapic_v1.method.wrap_method( - self.delete_authorized_certificate, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def list_authorized_certificates(self) -> Callable[ - [appengine.ListAuthorizedCertificatesRequest], - Union[ - appengine.ListAuthorizedCertificatesResponse, - Awaitable[appengine.ListAuthorizedCertificatesResponse] - ]]: - raise NotImplementedError() - - @property - def get_authorized_certificate(self) -> Callable[ - [appengine.GetAuthorizedCertificateRequest], - Union[ - certificate.AuthorizedCertificate, - Awaitable[certificate.AuthorizedCertificate] - ]]: - raise NotImplementedError() - - @property - def create_authorized_certificate(self) -> Callable[ - [appengine.CreateAuthorizedCertificateRequest], - Union[ - certificate.AuthorizedCertificate, - Awaitable[certificate.AuthorizedCertificate] - ]]: - raise NotImplementedError() - - @property - def update_authorized_certificate(self) -> Callable[ - [appengine.UpdateAuthorizedCertificateRequest], - Union[ - certificate.AuthorizedCertificate, - Awaitable[certificate.AuthorizedCertificate] - ]]: - raise NotImplementedError() - - @property - def delete_authorized_certificate(self) -> Callable[ - [appengine.DeleteAuthorizedCertificateRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'AuthorizedCertificatesTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc.py deleted file mode 100644 index f747f56..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc.py +++ /dev/null @@ -1,366 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import certificate -from google.protobuf import empty_pb2 # type: ignore -from .base import AuthorizedCertificatesTransport, DEFAULT_CLIENT_INFO - - -class AuthorizedCertificatesGrpcTransport(AuthorizedCertificatesTransport): - """gRPC backend transport for AuthorizedCertificates. - - Manages SSL certificates a user is authorized to administer. - A user can administer any SSL certificates applicable to their - authorized domains. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_authorized_certificates(self) -> Callable[ - [appengine.ListAuthorizedCertificatesRequest], - appengine.ListAuthorizedCertificatesResponse]: - r"""Return a callable for the list authorized certificates method over gRPC. - - Lists all SSL certificates the user is authorized to - administer. - - Returns: - Callable[[~.ListAuthorizedCertificatesRequest], - ~.ListAuthorizedCertificatesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_authorized_certificates' not in self._stubs: - self._stubs['list_authorized_certificates'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.AuthorizedCertificates/ListAuthorizedCertificates', - request_serializer=appengine.ListAuthorizedCertificatesRequest.serialize, - response_deserializer=appengine.ListAuthorizedCertificatesResponse.deserialize, - ) - return self._stubs['list_authorized_certificates'] - - @property - def get_authorized_certificate(self) -> Callable[ - [appengine.GetAuthorizedCertificateRequest], - certificate.AuthorizedCertificate]: - r"""Return a callable for the get authorized certificate method over gRPC. - - Gets the specified SSL certificate. - - Returns: - Callable[[~.GetAuthorizedCertificateRequest], - ~.AuthorizedCertificate]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_authorized_certificate' not in self._stubs: - self._stubs['get_authorized_certificate'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.AuthorizedCertificates/GetAuthorizedCertificate', - request_serializer=appengine.GetAuthorizedCertificateRequest.serialize, - response_deserializer=certificate.AuthorizedCertificate.deserialize, - ) - return self._stubs['get_authorized_certificate'] - - @property - def create_authorized_certificate(self) -> Callable[ - [appengine.CreateAuthorizedCertificateRequest], - certificate.AuthorizedCertificate]: - r"""Return a callable for the create authorized certificate method over gRPC. - - Uploads the specified SSL certificate. - - Returns: - Callable[[~.CreateAuthorizedCertificateRequest], - ~.AuthorizedCertificate]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_authorized_certificate' not in self._stubs: - self._stubs['create_authorized_certificate'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.AuthorizedCertificates/CreateAuthorizedCertificate', - request_serializer=appengine.CreateAuthorizedCertificateRequest.serialize, - response_deserializer=certificate.AuthorizedCertificate.deserialize, - ) - return self._stubs['create_authorized_certificate'] - - @property - def update_authorized_certificate(self) -> Callable[ - [appengine.UpdateAuthorizedCertificateRequest], - certificate.AuthorizedCertificate]: - r"""Return a callable for the update authorized certificate method over gRPC. - - Updates the specified SSL certificate. To renew a certificate - and maintain its existing domain mappings, update - ``certificate_data`` with a new certificate. The new certificate - must be applicable to the same domains as the original - certificate. The certificate ``display_name`` may also be - updated. - - Returns: - Callable[[~.UpdateAuthorizedCertificateRequest], - ~.AuthorizedCertificate]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_authorized_certificate' not in self._stubs: - self._stubs['update_authorized_certificate'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.AuthorizedCertificates/UpdateAuthorizedCertificate', - request_serializer=appengine.UpdateAuthorizedCertificateRequest.serialize, - response_deserializer=certificate.AuthorizedCertificate.deserialize, - ) - return self._stubs['update_authorized_certificate'] - - @property - def delete_authorized_certificate(self) -> Callable[ - [appengine.DeleteAuthorizedCertificateRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete authorized certificate method over gRPC. - - Deletes the specified SSL certificate. - - Returns: - Callable[[~.DeleteAuthorizedCertificateRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_authorized_certificate' not in self._stubs: - self._stubs['delete_authorized_certificate'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.AuthorizedCertificates/DeleteAuthorizedCertificate', - request_serializer=appengine.DeleteAuthorizedCertificateRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_authorized_certificate'] - - -__all__ = ( - 'AuthorizedCertificatesGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc_asyncio.py deleted file mode 100644 index 7b34f97..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_certificates/transports/grpc_asyncio.py +++ /dev/null @@ -1,370 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import certificate -from google.protobuf import empty_pb2 # type: ignore -from .base import AuthorizedCertificatesTransport, DEFAULT_CLIENT_INFO -from .grpc import AuthorizedCertificatesGrpcTransport - - -class AuthorizedCertificatesGrpcAsyncIOTransport(AuthorizedCertificatesTransport): - """gRPC AsyncIO backend transport for AuthorizedCertificates. - - Manages SSL certificates a user is authorized to administer. - A user can administer any SSL certificates applicable to their - authorized domains. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_authorized_certificates(self) -> Callable[ - [appengine.ListAuthorizedCertificatesRequest], - Awaitable[appengine.ListAuthorizedCertificatesResponse]]: - r"""Return a callable for the list authorized certificates method over gRPC. - - Lists all SSL certificates the user is authorized to - administer. - - Returns: - Callable[[~.ListAuthorizedCertificatesRequest], - Awaitable[~.ListAuthorizedCertificatesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_authorized_certificates' not in self._stubs: - self._stubs['list_authorized_certificates'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.AuthorizedCertificates/ListAuthorizedCertificates', - request_serializer=appengine.ListAuthorizedCertificatesRequest.serialize, - response_deserializer=appengine.ListAuthorizedCertificatesResponse.deserialize, - ) - return self._stubs['list_authorized_certificates'] - - @property - def get_authorized_certificate(self) -> Callable[ - [appengine.GetAuthorizedCertificateRequest], - Awaitable[certificate.AuthorizedCertificate]]: - r"""Return a callable for the get authorized certificate method over gRPC. - - Gets the specified SSL certificate. - - Returns: - Callable[[~.GetAuthorizedCertificateRequest], - Awaitable[~.AuthorizedCertificate]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_authorized_certificate' not in self._stubs: - self._stubs['get_authorized_certificate'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.AuthorizedCertificates/GetAuthorizedCertificate', - request_serializer=appengine.GetAuthorizedCertificateRequest.serialize, - response_deserializer=certificate.AuthorizedCertificate.deserialize, - ) - return self._stubs['get_authorized_certificate'] - - @property - def create_authorized_certificate(self) -> Callable[ - [appengine.CreateAuthorizedCertificateRequest], - Awaitable[certificate.AuthorizedCertificate]]: - r"""Return a callable for the create authorized certificate method over gRPC. - - Uploads the specified SSL certificate. - - Returns: - Callable[[~.CreateAuthorizedCertificateRequest], - Awaitable[~.AuthorizedCertificate]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_authorized_certificate' not in self._stubs: - self._stubs['create_authorized_certificate'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.AuthorizedCertificates/CreateAuthorizedCertificate', - request_serializer=appengine.CreateAuthorizedCertificateRequest.serialize, - response_deserializer=certificate.AuthorizedCertificate.deserialize, - ) - return self._stubs['create_authorized_certificate'] - - @property - def update_authorized_certificate(self) -> Callable[ - [appengine.UpdateAuthorizedCertificateRequest], - Awaitable[certificate.AuthorizedCertificate]]: - r"""Return a callable for the update authorized certificate method over gRPC. - - Updates the specified SSL certificate. To renew a certificate - and maintain its existing domain mappings, update - ``certificate_data`` with a new certificate. The new certificate - must be applicable to the same domains as the original - certificate. The certificate ``display_name`` may also be - updated. - - Returns: - Callable[[~.UpdateAuthorizedCertificateRequest], - Awaitable[~.AuthorizedCertificate]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_authorized_certificate' not in self._stubs: - self._stubs['update_authorized_certificate'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.AuthorizedCertificates/UpdateAuthorizedCertificate', - request_serializer=appengine.UpdateAuthorizedCertificateRequest.serialize, - response_deserializer=certificate.AuthorizedCertificate.deserialize, - ) - return self._stubs['update_authorized_certificate'] - - @property - def delete_authorized_certificate(self) -> Callable[ - [appengine.DeleteAuthorizedCertificateRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete authorized certificate method over gRPC. - - Deletes the specified SSL certificate. - - Returns: - Callable[[~.DeleteAuthorizedCertificateRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_authorized_certificate' not in self._stubs: - self._stubs['delete_authorized_certificate'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.AuthorizedCertificates/DeleteAuthorizedCertificate', - request_serializer=appengine.DeleteAuthorizedCertificateRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_authorized_certificate'] - - -__all__ = ( - 'AuthorizedCertificatesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/__init__.py deleted file mode 100644 index 2cc1a32..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import AuthorizedDomainsClient -from .async_client import AuthorizedDomainsAsyncClient - -__all__ = ( - 'AuthorizedDomainsClient', - 'AuthorizedDomainsAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/async_client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/async_client.py deleted file mode 100644 index 186d938..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/async_client.py +++ /dev/null @@ -1,233 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.appengine_admin_v1.services.authorized_domains import pagers -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import domain -from .transports.base import AuthorizedDomainsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AuthorizedDomainsGrpcAsyncIOTransport -from .client import AuthorizedDomainsClient - - -class AuthorizedDomainsAsyncClient: - """Manages domains a user is authorized to administer. To authorize use - of a domain, verify ownership via `Webmaster - Central `__. - """ - - _client: AuthorizedDomainsClient - - DEFAULT_ENDPOINT = AuthorizedDomainsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AuthorizedDomainsClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(AuthorizedDomainsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AuthorizedDomainsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AuthorizedDomainsClient.common_folder_path) - parse_common_folder_path = staticmethod(AuthorizedDomainsClient.parse_common_folder_path) - common_organization_path = staticmethod(AuthorizedDomainsClient.common_organization_path) - parse_common_organization_path = staticmethod(AuthorizedDomainsClient.parse_common_organization_path) - common_project_path = staticmethod(AuthorizedDomainsClient.common_project_path) - parse_common_project_path = staticmethod(AuthorizedDomainsClient.parse_common_project_path) - common_location_path = staticmethod(AuthorizedDomainsClient.common_location_path) - parse_common_location_path = staticmethod(AuthorizedDomainsClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - AuthorizedDomainsAsyncClient: The constructed client. - """ - return AuthorizedDomainsClient.from_service_account_info.__func__(AuthorizedDomainsAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - AuthorizedDomainsAsyncClient: The constructed client. - """ - return AuthorizedDomainsClient.from_service_account_file.__func__(AuthorizedDomainsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> AuthorizedDomainsTransport: - """Returns the transport used by the client instance. - - Returns: - AuthorizedDomainsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(AuthorizedDomainsClient).get_transport_class, type(AuthorizedDomainsClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, AuthorizedDomainsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the authorized domains client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.AuthorizedDomainsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = AuthorizedDomainsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_authorized_domains(self, - request: appengine.ListAuthorizedDomainsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAuthorizedDomainsAsyncPager: - r"""Lists all domains the user is authorized to - administer. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsRequest`): - The request object. Request message for - `AuthorizedDomains.ListAuthorizedDomains`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.services.authorized_domains.pagers.ListAuthorizedDomainsAsyncPager: - Response message for - AuthorizedDomains.ListAuthorizedDomains. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = appengine.ListAuthorizedDomainsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_authorized_domains, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListAuthorizedDomainsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-appengine-admin", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "AuthorizedDomainsAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/client.py deleted file mode 100644 index b5fd82b..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/client.py +++ /dev/null @@ -1,416 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.appengine_admin_v1.services.authorized_domains import pagers -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import domain -from .transports.base import AuthorizedDomainsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AuthorizedDomainsGrpcTransport -from .transports.grpc_asyncio import AuthorizedDomainsGrpcAsyncIOTransport - - -class AuthorizedDomainsClientMeta(type): - """Metaclass for the AuthorizedDomains client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[AuthorizedDomainsTransport]] - _transport_registry["grpc"] = AuthorizedDomainsGrpcTransport - _transport_registry["grpc_asyncio"] = AuthorizedDomainsGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[AuthorizedDomainsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class AuthorizedDomainsClient(metaclass=AuthorizedDomainsClientMeta): - """Manages domains a user is authorized to administer. To authorize use - of a domain, verify ownership via `Webmaster - Central `__. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "appengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - AuthorizedDomainsClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - AuthorizedDomainsClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> AuthorizedDomainsTransport: - """Returns the transport used by the client instance. - - Returns: - AuthorizedDomainsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AuthorizedDomainsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the authorized domains client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, AuthorizedDomainsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, AuthorizedDomainsTransport): - # transport is a AuthorizedDomainsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def list_authorized_domains(self, - request: appengine.ListAuthorizedDomainsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAuthorizedDomainsPager: - r"""Lists all domains the user is authorized to - administer. - - Args: - request (google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsRequest): - The request object. Request message for - `AuthorizedDomains.ListAuthorizedDomains`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.services.authorized_domains.pagers.ListAuthorizedDomainsPager: - Response message for - AuthorizedDomains.ListAuthorizedDomains. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.ListAuthorizedDomainsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.ListAuthorizedDomainsRequest): - request = appengine.ListAuthorizedDomainsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_authorized_domains] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListAuthorizedDomainsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-appengine-admin", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "AuthorizedDomainsClient", -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/pagers.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/pagers.py deleted file mode 100644 index 1a037ec..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/pagers.py +++ /dev/null @@ -1,141 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import domain - - -class ListAuthorizedDomainsPager: - """A pager for iterating through ``list_authorized_domains`` requests. - - This class thinly wraps an initial - :class:`google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``domains`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAuthorizedDomains`` requests and continue to iterate - through the ``domains`` field on the - corresponding responses. - - All the usual :class:`google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., appengine.ListAuthorizedDomainsResponse], - request: appengine.ListAuthorizedDomainsRequest, - response: appengine.ListAuthorizedDomainsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsRequest): - The initial request object. - response (google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = appengine.ListAuthorizedDomainsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[appengine.ListAuthorizedDomainsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[domain.AuthorizedDomain]: - for page in self.pages: - yield from page.domains - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAuthorizedDomainsAsyncPager: - """A pager for iterating through ``list_authorized_domains`` requests. - - This class thinly wraps an initial - :class:`google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``domains`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAuthorizedDomains`` requests and continue to iterate - through the ``domains`` field on the - corresponding responses. - - All the usual :class:`google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[appengine.ListAuthorizedDomainsResponse]], - request: appengine.ListAuthorizedDomainsRequest, - response: appengine.ListAuthorizedDomainsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsRequest): - The initial request object. - response (google.cloud.appengine_admin_v1.types.ListAuthorizedDomainsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = appengine.ListAuthorizedDomainsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[appengine.ListAuthorizedDomainsResponse]: - 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, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[domain.AuthorizedDomain]: - async def async_generator(): - async for page in self.pages: - for response in page.domains: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/__init__.py deleted file mode 100644 index 6334caa..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import AuthorizedDomainsTransport -from .grpc import AuthorizedDomainsGrpcTransport -from .grpc_asyncio import AuthorizedDomainsGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AuthorizedDomainsTransport]] -_transport_registry['grpc'] = AuthorizedDomainsGrpcTransport -_transport_registry['grpc_asyncio'] = AuthorizedDomainsGrpcAsyncIOTransport - -__all__ = ( - 'AuthorizedDomainsTransport', - 'AuthorizedDomainsGrpcTransport', - 'AuthorizedDomainsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/base.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/base.py deleted file mode 100644 index d59d717..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/base.py +++ /dev/null @@ -1,170 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-appengine-admin', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class AuthorizedDomainsTransport(abc.ABC): - """Abstract transport class for AuthorizedDomains.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ) - - DEFAULT_HOST: str = 'appengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials is service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_authorized_domains: gapic_v1.method.wrap_method( - self.list_authorized_domains, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def list_authorized_domains(self) -> Callable[ - [appengine.ListAuthorizedDomainsRequest], - Union[ - appengine.ListAuthorizedDomainsResponse, - Awaitable[appengine.ListAuthorizedDomainsResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'AuthorizedDomainsTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc.py deleted file mode 100644 index f868356..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc.py +++ /dev/null @@ -1,255 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from .base import AuthorizedDomainsTransport, DEFAULT_CLIENT_INFO - - -class AuthorizedDomainsGrpcTransport(AuthorizedDomainsTransport): - """gRPC backend transport for AuthorizedDomains. - - Manages domains a user is authorized to administer. To authorize use - of a domain, verify ownership via `Webmaster - Central `__. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_authorized_domains(self) -> Callable[ - [appengine.ListAuthorizedDomainsRequest], - appengine.ListAuthorizedDomainsResponse]: - r"""Return a callable for the list authorized domains method over gRPC. - - Lists all domains the user is authorized to - administer. - - Returns: - Callable[[~.ListAuthorizedDomainsRequest], - ~.ListAuthorizedDomainsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_authorized_domains' not in self._stubs: - self._stubs['list_authorized_domains'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.AuthorizedDomains/ListAuthorizedDomains', - request_serializer=appengine.ListAuthorizedDomainsRequest.serialize, - response_deserializer=appengine.ListAuthorizedDomainsResponse.deserialize, - ) - return self._stubs['list_authorized_domains'] - - -__all__ = ( - 'AuthorizedDomainsGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc_asyncio.py deleted file mode 100644 index 21976cd..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/authorized_domains/transports/grpc_asyncio.py +++ /dev/null @@ -1,259 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from .base import AuthorizedDomainsTransport, DEFAULT_CLIENT_INFO -from .grpc import AuthorizedDomainsGrpcTransport - - -class AuthorizedDomainsGrpcAsyncIOTransport(AuthorizedDomainsTransport): - """gRPC AsyncIO backend transport for AuthorizedDomains. - - Manages domains a user is authorized to administer. To authorize use - of a domain, verify ownership via `Webmaster - Central `__. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_authorized_domains(self) -> Callable[ - [appengine.ListAuthorizedDomainsRequest], - Awaitable[appengine.ListAuthorizedDomainsResponse]]: - r"""Return a callable for the list authorized domains method over gRPC. - - Lists all domains the user is authorized to - administer. - - Returns: - Callable[[~.ListAuthorizedDomainsRequest], - Awaitable[~.ListAuthorizedDomainsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_authorized_domains' not in self._stubs: - self._stubs['list_authorized_domains'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.AuthorizedDomains/ListAuthorizedDomains', - request_serializer=appengine.ListAuthorizedDomainsRequest.serialize, - response_deserializer=appengine.ListAuthorizedDomainsResponse.deserialize, - ) - return self._stubs['list_authorized_domains'] - - -__all__ = ( - 'AuthorizedDomainsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/__init__.py deleted file mode 100644 index ddd8876..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import DomainMappingsClient -from .async_client import DomainMappingsAsyncClient - -__all__ = ( - 'DomainMappingsClient', - 'DomainMappingsAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/async_client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/async_client.py deleted file mode 100644 index 4dfb7bd..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/async_client.py +++ /dev/null @@ -1,504 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation as gac_operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.appengine_admin_v1.services.domain_mappings import pagers -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import domain_mapping -from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.protobuf import empty_pb2 # type: ignore -from .transports.base import DomainMappingsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import DomainMappingsGrpcAsyncIOTransport -from .client import DomainMappingsClient - - -class DomainMappingsAsyncClient: - """Manages domains serving an application.""" - - _client: DomainMappingsClient - - DEFAULT_ENDPOINT = DomainMappingsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DomainMappingsClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(DomainMappingsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DomainMappingsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DomainMappingsClient.common_folder_path) - parse_common_folder_path = staticmethod(DomainMappingsClient.parse_common_folder_path) - common_organization_path = staticmethod(DomainMappingsClient.common_organization_path) - parse_common_organization_path = staticmethod(DomainMappingsClient.parse_common_organization_path) - common_project_path = staticmethod(DomainMappingsClient.common_project_path) - parse_common_project_path = staticmethod(DomainMappingsClient.parse_common_project_path) - common_location_path = staticmethod(DomainMappingsClient.common_location_path) - parse_common_location_path = staticmethod(DomainMappingsClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DomainMappingsAsyncClient: The constructed client. - """ - return DomainMappingsClient.from_service_account_info.__func__(DomainMappingsAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DomainMappingsAsyncClient: The constructed client. - """ - return DomainMappingsClient.from_service_account_file.__func__(DomainMappingsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> DomainMappingsTransport: - """Returns the transport used by the client instance. - - Returns: - DomainMappingsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(DomainMappingsClient).get_transport_class, type(DomainMappingsClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, DomainMappingsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the domain mappings client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.DomainMappingsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = DomainMappingsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_domain_mappings(self, - request: appengine.ListDomainMappingsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDomainMappingsAsyncPager: - r"""Lists the domain mappings on an application. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.ListDomainMappingsRequest`): - The request object. Request message for - `DomainMappings.ListDomainMappings`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.services.domain_mappings.pagers.ListDomainMappingsAsyncPager: - Response message for DomainMappings.ListDomainMappings. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = appengine.ListDomainMappingsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_domain_mappings, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListDomainMappingsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_domain_mapping(self, - request: appengine.GetDomainMappingRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> domain_mapping.DomainMapping: - r"""Gets the specified domain mapping. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.GetDomainMappingRequest`): - The request object. Request message for - `DomainMappings.GetDomainMapping`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.DomainMapping: - A domain serving an App Engine - application. - - """ - # Create or coerce a protobuf request object. - request = appengine.GetDomainMappingRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_domain_mapping, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_domain_mapping(self, - request: appengine.CreateDomainMappingRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Maps a domain to an application. A user must be authorized to - administer a domain in order to map it to an application. For a - list of available authorized domains, see - ```AuthorizedDomains.ListAuthorizedDomains`` <>`__. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.CreateDomainMappingRequest`): - The request object. Request message for - `DomainMappings.CreateDomainMapping`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.appengine_admin_v1.types.DomainMapping` - A domain serving an App Engine application. - - """ - # Create or coerce a protobuf request object. - request = appengine.CreateDomainMappingRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_domain_mapping, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - domain_mapping.DomainMapping, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - async def update_domain_mapping(self, - request: appengine.UpdateDomainMappingRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the specified domain mapping. To map an SSL certificate - to a domain mapping, update ``certificate_id`` to point to an - ``AuthorizedCertificate`` resource. A user must be authorized to - administer the associated domain in order to update a - ``DomainMapping`` resource. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.UpdateDomainMappingRequest`): - The request object. Request message for - `DomainMappings.UpdateDomainMapping`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.appengine_admin_v1.types.DomainMapping` - A domain serving an App Engine application. - - """ - # Create or coerce a protobuf request object. - request = appengine.UpdateDomainMappingRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_domain_mapping, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - domain_mapping.DomainMapping, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - async def delete_domain_mapping(self, - request: appengine.DeleteDomainMappingRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the specified domain mapping. A user must be authorized - to administer the associated domain in order to delete a - ``DomainMapping`` resource. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.DeleteDomainMappingRequest`): - The request object. Request message for - `DomainMappings.DeleteDomainMapping`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - request = appengine.DeleteDomainMappingRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_domain_mapping, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-appengine-admin", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "DomainMappingsAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/client.py deleted file mode 100644 index 45a1b8a..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/client.py +++ /dev/null @@ -1,691 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation as gac_operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.appengine_admin_v1.services.domain_mappings import pagers -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import domain_mapping -from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.protobuf import empty_pb2 # type: ignore -from .transports.base import DomainMappingsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DomainMappingsGrpcTransport -from .transports.grpc_asyncio import DomainMappingsGrpcAsyncIOTransport - - -class DomainMappingsClientMeta(type): - """Metaclass for the DomainMappings client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[DomainMappingsTransport]] - _transport_registry["grpc"] = DomainMappingsGrpcTransport - _transport_registry["grpc_asyncio"] = DomainMappingsGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[DomainMappingsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class DomainMappingsClient(metaclass=DomainMappingsClientMeta): - """Manages domains serving an application.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "appengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DomainMappingsClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DomainMappingsClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> DomainMappingsTransport: - """Returns the transport used by the client instance. - - Returns: - DomainMappingsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DomainMappingsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the domain mappings client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, DomainMappingsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, DomainMappingsTransport): - # transport is a DomainMappingsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def list_domain_mappings(self, - request: appengine.ListDomainMappingsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDomainMappingsPager: - r"""Lists the domain mappings on an application. - - Args: - request (google.cloud.appengine_admin_v1.types.ListDomainMappingsRequest): - The request object. Request message for - `DomainMappings.ListDomainMappings`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.services.domain_mappings.pagers.ListDomainMappingsPager: - Response message for DomainMappings.ListDomainMappings. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.ListDomainMappingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.ListDomainMappingsRequest): - request = appengine.ListDomainMappingsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_domain_mappings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListDomainMappingsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_domain_mapping(self, - request: appengine.GetDomainMappingRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> domain_mapping.DomainMapping: - r"""Gets the specified domain mapping. - - Args: - request (google.cloud.appengine_admin_v1.types.GetDomainMappingRequest): - The request object. Request message for - `DomainMappings.GetDomainMapping`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.DomainMapping: - A domain serving an App Engine - application. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.GetDomainMappingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.GetDomainMappingRequest): - request = appengine.GetDomainMappingRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_domain_mapping] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_domain_mapping(self, - request: appengine.CreateDomainMappingRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gac_operation.Operation: - r"""Maps a domain to an application. A user must be authorized to - administer a domain in order to map it to an application. For a - list of available authorized domains, see - ```AuthorizedDomains.ListAuthorizedDomains`` <>`__. - - Args: - request (google.cloud.appengine_admin_v1.types.CreateDomainMappingRequest): - The request object. Request message for - `DomainMappings.CreateDomainMapping`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.appengine_admin_v1.types.DomainMapping` - A domain serving an App Engine application. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.CreateDomainMappingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.CreateDomainMappingRequest): - request = appengine.CreateDomainMappingRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_domain_mapping] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = gac_operation.from_gapic( - response, - self._transport.operations_client, - domain_mapping.DomainMapping, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - def update_domain_mapping(self, - request: appengine.UpdateDomainMappingRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gac_operation.Operation: - r"""Updates the specified domain mapping. To map an SSL certificate - to a domain mapping, update ``certificate_id`` to point to an - ``AuthorizedCertificate`` resource. A user must be authorized to - administer the associated domain in order to update a - ``DomainMapping`` resource. - - Args: - request (google.cloud.appengine_admin_v1.types.UpdateDomainMappingRequest): - The request object. Request message for - `DomainMappings.UpdateDomainMapping`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.appengine_admin_v1.types.DomainMapping` - A domain serving an App Engine application. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.UpdateDomainMappingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.UpdateDomainMappingRequest): - request = appengine.UpdateDomainMappingRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_domain_mapping] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = gac_operation.from_gapic( - response, - self._transport.operations_client, - domain_mapping.DomainMapping, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - def delete_domain_mapping(self, - request: appengine.DeleteDomainMappingRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gac_operation.Operation: - r"""Deletes the specified domain mapping. A user must be authorized - to administer the associated domain in order to delete a - ``DomainMapping`` resource. - - Args: - request (google.cloud.appengine_admin_v1.types.DeleteDomainMappingRequest): - The request object. Request message for - `DomainMappings.DeleteDomainMapping`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.DeleteDomainMappingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.DeleteDomainMappingRequest): - request = appengine.DeleteDomainMappingRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_domain_mapping] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = gac_operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-appengine-admin", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "DomainMappingsClient", -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/pagers.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/pagers.py deleted file mode 100644 index ab3b9e0..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/pagers.py +++ /dev/null @@ -1,141 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import domain_mapping - - -class ListDomainMappingsPager: - """A pager for iterating through ``list_domain_mappings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.appengine_admin_v1.types.ListDomainMappingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``domain_mappings`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDomainMappings`` requests and continue to iterate - through the ``domain_mappings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.appengine_admin_v1.types.ListDomainMappingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., appengine.ListDomainMappingsResponse], - request: appengine.ListDomainMappingsRequest, - response: appengine.ListDomainMappingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.appengine_admin_v1.types.ListDomainMappingsRequest): - The initial request object. - response (google.cloud.appengine_admin_v1.types.ListDomainMappingsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = appengine.ListDomainMappingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[appengine.ListDomainMappingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[domain_mapping.DomainMapping]: - for page in self.pages: - yield from page.domain_mappings - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDomainMappingsAsyncPager: - """A pager for iterating through ``list_domain_mappings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.appengine_admin_v1.types.ListDomainMappingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``domain_mappings`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDomainMappings`` requests and continue to iterate - through the ``domain_mappings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.appengine_admin_v1.types.ListDomainMappingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[appengine.ListDomainMappingsResponse]], - request: appengine.ListDomainMappingsRequest, - response: appengine.ListDomainMappingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.appengine_admin_v1.types.ListDomainMappingsRequest): - The initial request object. - response (google.cloud.appengine_admin_v1.types.ListDomainMappingsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = appengine.ListDomainMappingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[appengine.ListDomainMappingsResponse]: - 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, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[domain_mapping.DomainMapping]: - async def async_generator(): - async for page in self.pages: - for response in page.domain_mappings: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/__init__.py deleted file mode 100644 index 486f6a7..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import DomainMappingsTransport -from .grpc import DomainMappingsGrpcTransport -from .grpc_asyncio import DomainMappingsGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DomainMappingsTransport]] -_transport_registry['grpc'] = DomainMappingsGrpcTransport -_transport_registry['grpc_asyncio'] = DomainMappingsGrpcAsyncIOTransport - -__all__ = ( - 'DomainMappingsTransport', - 'DomainMappingsGrpcTransport', - 'DomainMappingsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/base.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/base.py deleted file mode 100644 index 0f72811..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/base.py +++ /dev/null @@ -1,234 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import domain_mapping -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-appengine-admin', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class DomainMappingsTransport(abc.ABC): - """Abstract transport class for DomainMappings.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ) - - DEFAULT_HOST: str = 'appengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials is service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_domain_mappings: gapic_v1.method.wrap_method( - self.list_domain_mappings, - default_timeout=None, - client_info=client_info, - ), - self.get_domain_mapping: gapic_v1.method.wrap_method( - self.get_domain_mapping, - default_timeout=None, - client_info=client_info, - ), - self.create_domain_mapping: gapic_v1.method.wrap_method( - self.create_domain_mapping, - default_timeout=None, - client_info=client_info, - ), - self.update_domain_mapping: gapic_v1.method.wrap_method( - self.update_domain_mapping, - default_timeout=None, - client_info=client_info, - ), - self.delete_domain_mapping: gapic_v1.method.wrap_method( - self.delete_domain_mapping, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_domain_mappings(self) -> Callable[ - [appengine.ListDomainMappingsRequest], - Union[ - appengine.ListDomainMappingsResponse, - Awaitable[appengine.ListDomainMappingsResponse] - ]]: - raise NotImplementedError() - - @property - def get_domain_mapping(self) -> Callable[ - [appengine.GetDomainMappingRequest], - Union[ - domain_mapping.DomainMapping, - Awaitable[domain_mapping.DomainMapping] - ]]: - raise NotImplementedError() - - @property - def create_domain_mapping(self) -> Callable[ - [appengine.CreateDomainMappingRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_domain_mapping(self) -> Callable[ - [appengine.UpdateDomainMappingRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_domain_mapping(self) -> Callable[ - [appengine.DeleteDomainMappingRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'DomainMappingsTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc.py deleted file mode 100644 index 4ae1052..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc.py +++ /dev/null @@ -1,385 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import domain_mapping -from google.longrunning import operations_pb2 # type: ignore -from .base import DomainMappingsTransport, DEFAULT_CLIENT_INFO - - -class DomainMappingsGrpcTransport(DomainMappingsTransport): - """gRPC backend transport for DomainMappings. - - Manages domains serving an application. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_domain_mappings(self) -> Callable[ - [appengine.ListDomainMappingsRequest], - appengine.ListDomainMappingsResponse]: - r"""Return a callable for the list domain mappings method over gRPC. - - Lists the domain mappings on an application. - - Returns: - Callable[[~.ListDomainMappingsRequest], - ~.ListDomainMappingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_domain_mappings' not in self._stubs: - self._stubs['list_domain_mappings'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.DomainMappings/ListDomainMappings', - request_serializer=appengine.ListDomainMappingsRequest.serialize, - response_deserializer=appengine.ListDomainMappingsResponse.deserialize, - ) - return self._stubs['list_domain_mappings'] - - @property - def get_domain_mapping(self) -> Callable[ - [appengine.GetDomainMappingRequest], - domain_mapping.DomainMapping]: - r"""Return a callable for the get domain mapping method over gRPC. - - Gets the specified domain mapping. - - Returns: - Callable[[~.GetDomainMappingRequest], - ~.DomainMapping]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_domain_mapping' not in self._stubs: - self._stubs['get_domain_mapping'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.DomainMappings/GetDomainMapping', - request_serializer=appengine.GetDomainMappingRequest.serialize, - response_deserializer=domain_mapping.DomainMapping.deserialize, - ) - return self._stubs['get_domain_mapping'] - - @property - def create_domain_mapping(self) -> Callable[ - [appengine.CreateDomainMappingRequest], - operations_pb2.Operation]: - r"""Return a callable for the create domain mapping method over gRPC. - - Maps a domain to an application. A user must be authorized to - administer a domain in order to map it to an application. For a - list of available authorized domains, see - ```AuthorizedDomains.ListAuthorizedDomains`` <>`__. - - Returns: - Callable[[~.CreateDomainMappingRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_domain_mapping' not in self._stubs: - self._stubs['create_domain_mapping'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.DomainMappings/CreateDomainMapping', - request_serializer=appengine.CreateDomainMappingRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_domain_mapping'] - - @property - def update_domain_mapping(self) -> Callable[ - [appengine.UpdateDomainMappingRequest], - operations_pb2.Operation]: - r"""Return a callable for the update domain mapping method over gRPC. - - Updates the specified domain mapping. To map an SSL certificate - to a domain mapping, update ``certificate_id`` to point to an - ``AuthorizedCertificate`` resource. A user must be authorized to - administer the associated domain in order to update a - ``DomainMapping`` resource. - - Returns: - Callable[[~.UpdateDomainMappingRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_domain_mapping' not in self._stubs: - self._stubs['update_domain_mapping'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.DomainMappings/UpdateDomainMapping', - request_serializer=appengine.UpdateDomainMappingRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_domain_mapping'] - - @property - def delete_domain_mapping(self) -> Callable[ - [appengine.DeleteDomainMappingRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete domain mapping method over gRPC. - - Deletes the specified domain mapping. A user must be authorized - to administer the associated domain in order to delete a - ``DomainMapping`` resource. - - Returns: - Callable[[~.DeleteDomainMappingRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_domain_mapping' not in self._stubs: - self._stubs['delete_domain_mapping'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.DomainMappings/DeleteDomainMapping', - request_serializer=appengine.DeleteDomainMappingRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_domain_mapping'] - - -__all__ = ( - 'DomainMappingsGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc_asyncio.py deleted file mode 100644 index b68101f..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/domain_mappings/transports/grpc_asyncio.py +++ /dev/null @@ -1,389 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import domain_mapping -from google.longrunning import operations_pb2 # type: ignore -from .base import DomainMappingsTransport, DEFAULT_CLIENT_INFO -from .grpc import DomainMappingsGrpcTransport - - -class DomainMappingsGrpcAsyncIOTransport(DomainMappingsTransport): - """gRPC AsyncIO backend transport for DomainMappings. - - Manages domains serving an application. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_domain_mappings(self) -> Callable[ - [appengine.ListDomainMappingsRequest], - Awaitable[appengine.ListDomainMappingsResponse]]: - r"""Return a callable for the list domain mappings method over gRPC. - - Lists the domain mappings on an application. - - Returns: - Callable[[~.ListDomainMappingsRequest], - Awaitable[~.ListDomainMappingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_domain_mappings' not in self._stubs: - self._stubs['list_domain_mappings'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.DomainMappings/ListDomainMappings', - request_serializer=appengine.ListDomainMappingsRequest.serialize, - response_deserializer=appengine.ListDomainMappingsResponse.deserialize, - ) - return self._stubs['list_domain_mappings'] - - @property - def get_domain_mapping(self) -> Callable[ - [appengine.GetDomainMappingRequest], - Awaitable[domain_mapping.DomainMapping]]: - r"""Return a callable for the get domain mapping method over gRPC. - - Gets the specified domain mapping. - - Returns: - Callable[[~.GetDomainMappingRequest], - Awaitable[~.DomainMapping]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_domain_mapping' not in self._stubs: - self._stubs['get_domain_mapping'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.DomainMappings/GetDomainMapping', - request_serializer=appengine.GetDomainMappingRequest.serialize, - response_deserializer=domain_mapping.DomainMapping.deserialize, - ) - return self._stubs['get_domain_mapping'] - - @property - def create_domain_mapping(self) -> Callable[ - [appengine.CreateDomainMappingRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create domain mapping method over gRPC. - - Maps a domain to an application. A user must be authorized to - administer a domain in order to map it to an application. For a - list of available authorized domains, see - ```AuthorizedDomains.ListAuthorizedDomains`` <>`__. - - Returns: - Callable[[~.CreateDomainMappingRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_domain_mapping' not in self._stubs: - self._stubs['create_domain_mapping'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.DomainMappings/CreateDomainMapping', - request_serializer=appengine.CreateDomainMappingRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_domain_mapping'] - - @property - def update_domain_mapping(self) -> Callable[ - [appengine.UpdateDomainMappingRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update domain mapping method over gRPC. - - Updates the specified domain mapping. To map an SSL certificate - to a domain mapping, update ``certificate_id`` to point to an - ``AuthorizedCertificate`` resource. A user must be authorized to - administer the associated domain in order to update a - ``DomainMapping`` resource. - - Returns: - Callable[[~.UpdateDomainMappingRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_domain_mapping' not in self._stubs: - self._stubs['update_domain_mapping'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.DomainMappings/UpdateDomainMapping', - request_serializer=appengine.UpdateDomainMappingRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_domain_mapping'] - - @property - def delete_domain_mapping(self) -> Callable[ - [appengine.DeleteDomainMappingRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete domain mapping method over gRPC. - - Deletes the specified domain mapping. A user must be authorized - to administer the associated domain in order to delete a - ``DomainMapping`` resource. - - Returns: - Callable[[~.DeleteDomainMappingRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_domain_mapping' not in self._stubs: - self._stubs['delete_domain_mapping'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.DomainMappings/DeleteDomainMapping', - request_serializer=appengine.DeleteDomainMappingRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_domain_mapping'] - - -__all__ = ( - 'DomainMappingsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/__init__.py deleted file mode 100644 index 56728f7..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import FirewallClient -from .async_client import FirewallAsyncClient - -__all__ = ( - 'FirewallClient', - 'FirewallAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/async_client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/async_client.py deleted file mode 100644 index 3784ac7..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/async_client.py +++ /dev/null @@ -1,515 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.appengine_admin_v1.services.firewall import pagers -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import firewall -from .transports.base import FirewallTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import FirewallGrpcAsyncIOTransport -from .client import FirewallClient - - -class FirewallAsyncClient: - """Firewall resources are used to define a collection of access - control rules for an Application. Each rule is defined with a - position which specifies the rule's order in the sequence of - rules, an IP range to be matched against requests, and an action - to take upon matching requests. - Every request is evaluated against the Firewall rules in - priority order. Processesing stops at the first rule which - matches the request's IP address. A final rule always specifies - an action that applies to all remaining IP addresses. The - default final rule for a newly-created application will be set - to "allow" if not otherwise specified by the user. - """ - - _client: FirewallClient - - DEFAULT_ENDPOINT = FirewallClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = FirewallClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(FirewallClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(FirewallClient.parse_common_billing_account_path) - common_folder_path = staticmethod(FirewallClient.common_folder_path) - parse_common_folder_path = staticmethod(FirewallClient.parse_common_folder_path) - common_organization_path = staticmethod(FirewallClient.common_organization_path) - parse_common_organization_path = staticmethod(FirewallClient.parse_common_organization_path) - common_project_path = staticmethod(FirewallClient.common_project_path) - parse_common_project_path = staticmethod(FirewallClient.parse_common_project_path) - common_location_path = staticmethod(FirewallClient.common_location_path) - parse_common_location_path = staticmethod(FirewallClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - FirewallAsyncClient: The constructed client. - """ - return FirewallClient.from_service_account_info.__func__(FirewallAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - FirewallAsyncClient: The constructed client. - """ - return FirewallClient.from_service_account_file.__func__(FirewallAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> FirewallTransport: - """Returns the transport used by the client instance. - - Returns: - FirewallTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(FirewallClient).get_transport_class, type(FirewallClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, FirewallTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the firewall client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.FirewallTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = FirewallClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_ingress_rules(self, - request: appengine.ListIngressRulesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListIngressRulesAsyncPager: - r"""Lists the firewall rules of an application. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.ListIngressRulesRequest`): - The request object. Request message for - `Firewall.ListIngressRules`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.services.firewall.pagers.ListIngressRulesAsyncPager: - Response message for Firewall.ListIngressRules. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = appengine.ListIngressRulesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_ingress_rules, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListIngressRulesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def batch_update_ingress_rules(self, - request: appengine.BatchUpdateIngressRulesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> appengine.BatchUpdateIngressRulesResponse: - r"""Replaces the entire firewall ruleset in one bulk operation. This - overrides and replaces the rules of an existing firewall with - the new rules. - - If the final rule does not match traffic with the '*' wildcard - IP range, then an "allow all" rule is explicitly added to the - end of the list. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.BatchUpdateIngressRulesRequest`): - The request object. Request message for - `Firewall.BatchUpdateIngressRules`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.BatchUpdateIngressRulesResponse: - Response message for Firewall.UpdateAllIngressRules. - """ - # Create or coerce a protobuf request object. - request = appengine.BatchUpdateIngressRulesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.batch_update_ingress_rules, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_ingress_rule(self, - request: appengine.CreateIngressRuleRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> firewall.FirewallRule: - r"""Creates a firewall rule for the application. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.CreateIngressRuleRequest`): - The request object. Request message for - `Firewall.CreateIngressRule`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.FirewallRule: - A single firewall rule that is - evaluated against incoming traffic and - provides an action to take on matched - requests. - - """ - # Create or coerce a protobuf request object. - request = appengine.CreateIngressRuleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_ingress_rule, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_ingress_rule(self, - request: appengine.GetIngressRuleRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> firewall.FirewallRule: - r"""Gets the specified firewall rule. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.GetIngressRuleRequest`): - The request object. Request message for - `Firewall.GetIngressRule`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.FirewallRule: - A single firewall rule that is - evaluated against incoming traffic and - provides an action to take on matched - requests. - - """ - # Create or coerce a protobuf request object. - request = appengine.GetIngressRuleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_ingress_rule, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_ingress_rule(self, - request: appengine.UpdateIngressRuleRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> firewall.FirewallRule: - r"""Updates the specified firewall rule. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.UpdateIngressRuleRequest`): - The request object. Request message for - `Firewall.UpdateIngressRule`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.FirewallRule: - A single firewall rule that is - evaluated against incoming traffic and - provides an action to take on matched - requests. - - """ - # Create or coerce a protobuf request object. - request = appengine.UpdateIngressRuleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_ingress_rule, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_ingress_rule(self, - request: appengine.DeleteIngressRuleRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified firewall rule. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.DeleteIngressRuleRequest`): - The request object. Request message for - `Firewall.DeleteIngressRule`. - 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. - """ - # Create or coerce a protobuf request object. - request = appengine.DeleteIngressRuleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_ingress_rule, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-appengine-admin", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "FirewallAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/client.py deleted file mode 100644 index 9ff6406..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/client.py +++ /dev/null @@ -1,703 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.appengine_admin_v1.services.firewall import pagers -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import firewall -from .transports.base import FirewallTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import FirewallGrpcTransport -from .transports.grpc_asyncio import FirewallGrpcAsyncIOTransport - - -class FirewallClientMeta(type): - """Metaclass for the Firewall client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[FirewallTransport]] - _transport_registry["grpc"] = FirewallGrpcTransport - _transport_registry["grpc_asyncio"] = FirewallGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[FirewallTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class FirewallClient(metaclass=FirewallClientMeta): - """Firewall resources are used to define a collection of access - control rules for an Application. Each rule is defined with a - position which specifies the rule's order in the sequence of - rules, an IP range to be matched against requests, and an action - to take upon matching requests. - Every request is evaluated against the Firewall rules in - priority order. Processesing stops at the first rule which - matches the request's IP address. A final rule always specifies - an action that applies to all remaining IP addresses. The - default final rule for a newly-created application will be set - to "allow" if not otherwise specified by the user. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "appengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - FirewallClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - FirewallClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> FirewallTransport: - """Returns the transport used by the client instance. - - Returns: - FirewallTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, FirewallTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the firewall client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, FirewallTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, FirewallTransport): - # transport is a FirewallTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def list_ingress_rules(self, - request: appengine.ListIngressRulesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListIngressRulesPager: - r"""Lists the firewall rules of an application. - - Args: - request (google.cloud.appengine_admin_v1.types.ListIngressRulesRequest): - The request object. Request message for - `Firewall.ListIngressRules`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.services.firewall.pagers.ListIngressRulesPager: - Response message for Firewall.ListIngressRules. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.ListIngressRulesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.ListIngressRulesRequest): - request = appengine.ListIngressRulesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_ingress_rules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListIngressRulesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def batch_update_ingress_rules(self, - request: appengine.BatchUpdateIngressRulesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> appengine.BatchUpdateIngressRulesResponse: - r"""Replaces the entire firewall ruleset in one bulk operation. This - overrides and replaces the rules of an existing firewall with - the new rules. - - If the final rule does not match traffic with the '*' wildcard - IP range, then an "allow all" rule is explicitly added to the - end of the list. - - Args: - request (google.cloud.appengine_admin_v1.types.BatchUpdateIngressRulesRequest): - The request object. Request message for - `Firewall.BatchUpdateIngressRules`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.BatchUpdateIngressRulesResponse: - Response message for Firewall.UpdateAllIngressRules. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.BatchUpdateIngressRulesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.BatchUpdateIngressRulesRequest): - request = appengine.BatchUpdateIngressRulesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_update_ingress_rules] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_ingress_rule(self, - request: appengine.CreateIngressRuleRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> firewall.FirewallRule: - r"""Creates a firewall rule for the application. - - Args: - request (google.cloud.appengine_admin_v1.types.CreateIngressRuleRequest): - The request object. Request message for - `Firewall.CreateIngressRule`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.FirewallRule: - A single firewall rule that is - evaluated against incoming traffic and - provides an action to take on matched - requests. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.CreateIngressRuleRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.CreateIngressRuleRequest): - request = appengine.CreateIngressRuleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_ingress_rule] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_ingress_rule(self, - request: appengine.GetIngressRuleRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> firewall.FirewallRule: - r"""Gets the specified firewall rule. - - Args: - request (google.cloud.appengine_admin_v1.types.GetIngressRuleRequest): - The request object. Request message for - `Firewall.GetIngressRule`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.FirewallRule: - A single firewall rule that is - evaluated against incoming traffic and - provides an action to take on matched - requests. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.GetIngressRuleRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.GetIngressRuleRequest): - request = appengine.GetIngressRuleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_ingress_rule] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_ingress_rule(self, - request: appengine.UpdateIngressRuleRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> firewall.FirewallRule: - r"""Updates the specified firewall rule. - - Args: - request (google.cloud.appengine_admin_v1.types.UpdateIngressRuleRequest): - The request object. Request message for - `Firewall.UpdateIngressRule`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.FirewallRule: - A single firewall rule that is - evaluated against incoming traffic and - provides an action to take on matched - requests. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.UpdateIngressRuleRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.UpdateIngressRuleRequest): - request = appengine.UpdateIngressRuleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_ingress_rule] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_ingress_rule(self, - request: appengine.DeleteIngressRuleRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified firewall rule. - - Args: - request (google.cloud.appengine_admin_v1.types.DeleteIngressRuleRequest): - The request object. Request message for - `Firewall.DeleteIngressRule`. - 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. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.DeleteIngressRuleRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.DeleteIngressRuleRequest): - request = appengine.DeleteIngressRuleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_ingress_rule] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-appengine-admin", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "FirewallClient", -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/pagers.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/pagers.py deleted file mode 100644 index eb8440d..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/pagers.py +++ /dev/null @@ -1,141 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import firewall - - -class ListIngressRulesPager: - """A pager for iterating through ``list_ingress_rules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.appengine_admin_v1.types.ListIngressRulesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``ingress_rules`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListIngressRules`` requests and continue to iterate - through the ``ingress_rules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.appengine_admin_v1.types.ListIngressRulesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., appengine.ListIngressRulesResponse], - request: appengine.ListIngressRulesRequest, - response: appengine.ListIngressRulesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.appengine_admin_v1.types.ListIngressRulesRequest): - The initial request object. - response (google.cloud.appengine_admin_v1.types.ListIngressRulesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = appengine.ListIngressRulesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[appengine.ListIngressRulesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[firewall.FirewallRule]: - for page in self.pages: - yield from page.ingress_rules - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListIngressRulesAsyncPager: - """A pager for iterating through ``list_ingress_rules`` requests. - - This class thinly wraps an initial - :class:`google.cloud.appengine_admin_v1.types.ListIngressRulesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``ingress_rules`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListIngressRules`` requests and continue to iterate - through the ``ingress_rules`` field on the - corresponding responses. - - All the usual :class:`google.cloud.appengine_admin_v1.types.ListIngressRulesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[appengine.ListIngressRulesResponse]], - request: appengine.ListIngressRulesRequest, - response: appengine.ListIngressRulesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.appengine_admin_v1.types.ListIngressRulesRequest): - The initial request object. - response (google.cloud.appengine_admin_v1.types.ListIngressRulesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = appengine.ListIngressRulesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[appengine.ListIngressRulesResponse]: - 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, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[firewall.FirewallRule]: - async def async_generator(): - async for page in self.pages: - for response in page.ingress_rules: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/__init__.py deleted file mode 100644 index cdbfc05..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import FirewallTransport -from .grpc import FirewallGrpcTransport -from .grpc_asyncio import FirewallGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[FirewallTransport]] -_transport_registry['grpc'] = FirewallGrpcTransport -_transport_registry['grpc_asyncio'] = FirewallGrpcAsyncIOTransport - -__all__ = ( - 'FirewallTransport', - 'FirewallGrpcTransport', - 'FirewallGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/base.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/base.py deleted file mode 100644 index f3ea7b6..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/base.py +++ /dev/null @@ -1,242 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import firewall -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-appengine-admin', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class FirewallTransport(abc.ABC): - """Abstract transport class for Firewall.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ) - - DEFAULT_HOST: str = 'appengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials is service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_ingress_rules: gapic_v1.method.wrap_method( - self.list_ingress_rules, - default_timeout=None, - client_info=client_info, - ), - self.batch_update_ingress_rules: gapic_v1.method.wrap_method( - self.batch_update_ingress_rules, - default_timeout=None, - client_info=client_info, - ), - self.create_ingress_rule: gapic_v1.method.wrap_method( - self.create_ingress_rule, - default_timeout=None, - client_info=client_info, - ), - self.get_ingress_rule: gapic_v1.method.wrap_method( - self.get_ingress_rule, - default_timeout=None, - client_info=client_info, - ), - self.update_ingress_rule: gapic_v1.method.wrap_method( - self.update_ingress_rule, - default_timeout=None, - client_info=client_info, - ), - self.delete_ingress_rule: gapic_v1.method.wrap_method( - self.delete_ingress_rule, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def list_ingress_rules(self) -> Callable[ - [appengine.ListIngressRulesRequest], - Union[ - appengine.ListIngressRulesResponse, - Awaitable[appengine.ListIngressRulesResponse] - ]]: - raise NotImplementedError() - - @property - def batch_update_ingress_rules(self) -> Callable[ - [appengine.BatchUpdateIngressRulesRequest], - Union[ - appengine.BatchUpdateIngressRulesResponse, - Awaitable[appengine.BatchUpdateIngressRulesResponse] - ]]: - raise NotImplementedError() - - @property - def create_ingress_rule(self) -> Callable[ - [appengine.CreateIngressRuleRequest], - Union[ - firewall.FirewallRule, - Awaitable[firewall.FirewallRule] - ]]: - raise NotImplementedError() - - @property - def get_ingress_rule(self) -> Callable[ - [appengine.GetIngressRuleRequest], - Union[ - firewall.FirewallRule, - Awaitable[firewall.FirewallRule] - ]]: - raise NotImplementedError() - - @property - def update_ingress_rule(self) -> Callable[ - [appengine.UpdateIngressRuleRequest], - Union[ - firewall.FirewallRule, - Awaitable[firewall.FirewallRule] - ]]: - raise NotImplementedError() - - @property - def delete_ingress_rule(self) -> Callable[ - [appengine.DeleteIngressRuleRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'FirewallTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/grpc.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/grpc.py deleted file mode 100644 index 2b0ca92..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/grpc.py +++ /dev/null @@ -1,400 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import firewall -from google.protobuf import empty_pb2 # type: ignore -from .base import FirewallTransport, DEFAULT_CLIENT_INFO - - -class FirewallGrpcTransport(FirewallTransport): - """gRPC backend transport for Firewall. - - Firewall resources are used to define a collection of access - control rules for an Application. Each rule is defined with a - position which specifies the rule's order in the sequence of - rules, an IP range to be matched against requests, and an action - to take upon matching requests. - Every request is evaluated against the Firewall rules in - priority order. Processesing stops at the first rule which - matches the request's IP address. A final rule always specifies - an action that applies to all remaining IP addresses. The - default final rule for a newly-created application will be set - to "allow" if not otherwise specified by the user. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_ingress_rules(self) -> Callable[ - [appengine.ListIngressRulesRequest], - appengine.ListIngressRulesResponse]: - r"""Return a callable for the list ingress rules method over gRPC. - - Lists the firewall rules of an application. - - Returns: - Callable[[~.ListIngressRulesRequest], - ~.ListIngressRulesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_ingress_rules' not in self._stubs: - self._stubs['list_ingress_rules'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Firewall/ListIngressRules', - request_serializer=appengine.ListIngressRulesRequest.serialize, - response_deserializer=appengine.ListIngressRulesResponse.deserialize, - ) - return self._stubs['list_ingress_rules'] - - @property - def batch_update_ingress_rules(self) -> Callable[ - [appengine.BatchUpdateIngressRulesRequest], - appengine.BatchUpdateIngressRulesResponse]: - r"""Return a callable for the batch update ingress rules method over gRPC. - - Replaces the entire firewall ruleset in one bulk operation. This - overrides and replaces the rules of an existing firewall with - the new rules. - - If the final rule does not match traffic with the '*' wildcard - IP range, then an "allow all" rule is explicitly added to the - end of the list. - - Returns: - Callable[[~.BatchUpdateIngressRulesRequest], - ~.BatchUpdateIngressRulesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_update_ingress_rules' not in self._stubs: - self._stubs['batch_update_ingress_rules'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Firewall/BatchUpdateIngressRules', - request_serializer=appengine.BatchUpdateIngressRulesRequest.serialize, - response_deserializer=appengine.BatchUpdateIngressRulesResponse.deserialize, - ) - return self._stubs['batch_update_ingress_rules'] - - @property - def create_ingress_rule(self) -> Callable[ - [appengine.CreateIngressRuleRequest], - firewall.FirewallRule]: - r"""Return a callable for the create ingress rule method over gRPC. - - Creates a firewall rule for the application. - - Returns: - Callable[[~.CreateIngressRuleRequest], - ~.FirewallRule]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_ingress_rule' not in self._stubs: - self._stubs['create_ingress_rule'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Firewall/CreateIngressRule', - request_serializer=appengine.CreateIngressRuleRequest.serialize, - response_deserializer=firewall.FirewallRule.deserialize, - ) - return self._stubs['create_ingress_rule'] - - @property - def get_ingress_rule(self) -> Callable[ - [appengine.GetIngressRuleRequest], - firewall.FirewallRule]: - r"""Return a callable for the get ingress rule method over gRPC. - - Gets the specified firewall rule. - - Returns: - Callable[[~.GetIngressRuleRequest], - ~.FirewallRule]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_ingress_rule' not in self._stubs: - self._stubs['get_ingress_rule'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Firewall/GetIngressRule', - request_serializer=appengine.GetIngressRuleRequest.serialize, - response_deserializer=firewall.FirewallRule.deserialize, - ) - return self._stubs['get_ingress_rule'] - - @property - def update_ingress_rule(self) -> Callable[ - [appengine.UpdateIngressRuleRequest], - firewall.FirewallRule]: - r"""Return a callable for the update ingress rule method over gRPC. - - Updates the specified firewall rule. - - Returns: - Callable[[~.UpdateIngressRuleRequest], - ~.FirewallRule]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_ingress_rule' not in self._stubs: - self._stubs['update_ingress_rule'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Firewall/UpdateIngressRule', - request_serializer=appengine.UpdateIngressRuleRequest.serialize, - response_deserializer=firewall.FirewallRule.deserialize, - ) - return self._stubs['update_ingress_rule'] - - @property - def delete_ingress_rule(self) -> Callable[ - [appengine.DeleteIngressRuleRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete ingress rule method over gRPC. - - Deletes the specified firewall rule. - - Returns: - Callable[[~.DeleteIngressRuleRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_ingress_rule' not in self._stubs: - self._stubs['delete_ingress_rule'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Firewall/DeleteIngressRule', - request_serializer=appengine.DeleteIngressRuleRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_ingress_rule'] - - -__all__ = ( - 'FirewallGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/grpc_asyncio.py deleted file mode 100644 index 1ce6dda..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/firewall/transports/grpc_asyncio.py +++ /dev/null @@ -1,404 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import firewall -from google.protobuf import empty_pb2 # type: ignore -from .base import FirewallTransport, DEFAULT_CLIENT_INFO -from .grpc import FirewallGrpcTransport - - -class FirewallGrpcAsyncIOTransport(FirewallTransport): - """gRPC AsyncIO backend transport for Firewall. - - Firewall resources are used to define a collection of access - control rules for an Application. Each rule is defined with a - position which specifies the rule's order in the sequence of - rules, an IP range to be matched against requests, and an action - to take upon matching requests. - Every request is evaluated against the Firewall rules in - priority order. Processesing stops at the first rule which - matches the request's IP address. A final rule always specifies - an action that applies to all remaining IP addresses. The - default final rule for a newly-created application will be set - to "allow" if not otherwise specified by the user. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_ingress_rules(self) -> Callable[ - [appengine.ListIngressRulesRequest], - Awaitable[appengine.ListIngressRulesResponse]]: - r"""Return a callable for the list ingress rules method over gRPC. - - Lists the firewall rules of an application. - - Returns: - Callable[[~.ListIngressRulesRequest], - Awaitable[~.ListIngressRulesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_ingress_rules' not in self._stubs: - self._stubs['list_ingress_rules'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Firewall/ListIngressRules', - request_serializer=appengine.ListIngressRulesRequest.serialize, - response_deserializer=appengine.ListIngressRulesResponse.deserialize, - ) - return self._stubs['list_ingress_rules'] - - @property - def batch_update_ingress_rules(self) -> Callable[ - [appengine.BatchUpdateIngressRulesRequest], - Awaitable[appengine.BatchUpdateIngressRulesResponse]]: - r"""Return a callable for the batch update ingress rules method over gRPC. - - Replaces the entire firewall ruleset in one bulk operation. This - overrides and replaces the rules of an existing firewall with - the new rules. - - If the final rule does not match traffic with the '*' wildcard - IP range, then an "allow all" rule is explicitly added to the - end of the list. - - Returns: - Callable[[~.BatchUpdateIngressRulesRequest], - Awaitable[~.BatchUpdateIngressRulesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'batch_update_ingress_rules' not in self._stubs: - self._stubs['batch_update_ingress_rules'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Firewall/BatchUpdateIngressRules', - request_serializer=appengine.BatchUpdateIngressRulesRequest.serialize, - response_deserializer=appengine.BatchUpdateIngressRulesResponse.deserialize, - ) - return self._stubs['batch_update_ingress_rules'] - - @property - def create_ingress_rule(self) -> Callable[ - [appengine.CreateIngressRuleRequest], - Awaitable[firewall.FirewallRule]]: - r"""Return a callable for the create ingress rule method over gRPC. - - Creates a firewall rule for the application. - - Returns: - Callable[[~.CreateIngressRuleRequest], - Awaitable[~.FirewallRule]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_ingress_rule' not in self._stubs: - self._stubs['create_ingress_rule'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Firewall/CreateIngressRule', - request_serializer=appengine.CreateIngressRuleRequest.serialize, - response_deserializer=firewall.FirewallRule.deserialize, - ) - return self._stubs['create_ingress_rule'] - - @property - def get_ingress_rule(self) -> Callable[ - [appengine.GetIngressRuleRequest], - Awaitable[firewall.FirewallRule]]: - r"""Return a callable for the get ingress rule method over gRPC. - - Gets the specified firewall rule. - - Returns: - Callable[[~.GetIngressRuleRequest], - Awaitable[~.FirewallRule]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_ingress_rule' not in self._stubs: - self._stubs['get_ingress_rule'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Firewall/GetIngressRule', - request_serializer=appengine.GetIngressRuleRequest.serialize, - response_deserializer=firewall.FirewallRule.deserialize, - ) - return self._stubs['get_ingress_rule'] - - @property - def update_ingress_rule(self) -> Callable[ - [appengine.UpdateIngressRuleRequest], - Awaitable[firewall.FirewallRule]]: - r"""Return a callable for the update ingress rule method over gRPC. - - Updates the specified firewall rule. - - Returns: - Callable[[~.UpdateIngressRuleRequest], - Awaitable[~.FirewallRule]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_ingress_rule' not in self._stubs: - self._stubs['update_ingress_rule'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Firewall/UpdateIngressRule', - request_serializer=appengine.UpdateIngressRuleRequest.serialize, - response_deserializer=firewall.FirewallRule.deserialize, - ) - return self._stubs['update_ingress_rule'] - - @property - def delete_ingress_rule(self) -> Callable[ - [appengine.DeleteIngressRuleRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete ingress rule method over gRPC. - - Deletes the specified firewall rule. - - Returns: - Callable[[~.DeleteIngressRuleRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_ingress_rule' not in self._stubs: - self._stubs['delete_ingress_rule'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Firewall/DeleteIngressRule', - request_serializer=appengine.DeleteIngressRuleRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_ingress_rule'] - - -__all__ = ( - 'FirewallGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/__init__.py deleted file mode 100644 index 0567e49..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import InstancesClient -from .async_client import InstancesAsyncClient - -__all__ = ( - 'InstancesClient', - 'InstancesAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/async_client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/async_client.py deleted file mode 100644 index b48b6d1..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/async_client.py +++ /dev/null @@ -1,459 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation as gac_operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.appengine_admin_v1.services.instances import pagers -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import instance -from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import InstancesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import InstancesGrpcAsyncIOTransport -from .client import InstancesClient - - -class InstancesAsyncClient: - """Manages instances of a version.""" - - _client: InstancesClient - - DEFAULT_ENDPOINT = InstancesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = InstancesClient.DEFAULT_MTLS_ENDPOINT - - instance_path = staticmethod(InstancesClient.instance_path) - parse_instance_path = staticmethod(InstancesClient.parse_instance_path) - common_billing_account_path = staticmethod(InstancesClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(InstancesClient.parse_common_billing_account_path) - common_folder_path = staticmethod(InstancesClient.common_folder_path) - parse_common_folder_path = staticmethod(InstancesClient.parse_common_folder_path) - common_organization_path = staticmethod(InstancesClient.common_organization_path) - parse_common_organization_path = staticmethod(InstancesClient.parse_common_organization_path) - common_project_path = staticmethod(InstancesClient.common_project_path) - parse_common_project_path = staticmethod(InstancesClient.parse_common_project_path) - common_location_path = staticmethod(InstancesClient.common_location_path) - parse_common_location_path = staticmethod(InstancesClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - InstancesAsyncClient: The constructed client. - """ - return InstancesClient.from_service_account_info.__func__(InstancesAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - InstancesAsyncClient: The constructed client. - """ - return InstancesClient.from_service_account_file.__func__(InstancesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> InstancesTransport: - """Returns the transport used by the client instance. - - Returns: - InstancesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(InstancesClient).get_transport_class, type(InstancesClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, InstancesTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the instances client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.InstancesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = InstancesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_instances(self, - request: appengine.ListInstancesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListInstancesAsyncPager: - r"""Lists the instances of a version. - - Tip: To aggregate details about instances over time, see the - `Stackdriver Monitoring - API `__. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.ListInstancesRequest`): - The request object. Request message for - `Instances.ListInstances`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.services.instances.pagers.ListInstancesAsyncPager: - Response message for Instances.ListInstances. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = appengine.ListInstancesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_instances, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListInstancesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_instance(self, - request: appengine.GetInstanceRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> instance.Instance: - r"""Gets instance information. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.GetInstanceRequest`): - The request object. Request message for - `Instances.GetInstance`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.Instance: - An Instance resource is the computing - unit that App Engine uses to - automatically scale an application. - - """ - # Create or coerce a protobuf request object. - request = appengine.GetInstanceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_instance, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_instance(self, - request: appengine.DeleteInstanceRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Stops a running instance. - - The instance might be automatically recreated based on the - scaling settings of the version. For more information, see "How - Instances are Managed" (`standard - environment `__ - \| `flexible - environment `__). - - To ensure that instances are not re-created and avoid getting - billed, you can stop all instances within the target version by - changing the serving status of the version to ``STOPPED`` with - the - ```apps.services.versions.patch`` `__ - method. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.DeleteInstanceRequest`): - The request object. Request message for - `Instances.DeleteInstance`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - request = appengine.DeleteInstanceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_instance, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - async def debug_instance(self, - request: appengine.DebugInstanceRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Enables debugging on a VM instance. This allows you - to use the SSH command to connect to the virtual machine - where the instance lives. While in "debug mode", the - instance continues to serve live traffic. You should - delete the instance when you are done debugging and then - allow the system to take over and determine if another - instance should be started. - - Only applicable for instances in App Engine flexible - environment. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.DebugInstanceRequest`): - The request object. Request message for - `Instances.DebugInstance`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Instance` An Instance resource is the computing unit that App Engine uses to - automatically scale an application. - - """ - # Create or coerce a protobuf request object. - request = appengine.DebugInstanceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.debug_instance, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - instance.Instance, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-appengine-admin", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "InstancesAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/client.py deleted file mode 100644 index f510d7e..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/client.py +++ /dev/null @@ -1,654 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation as gac_operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.appengine_admin_v1.services.instances import pagers -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import instance -from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import InstancesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import InstancesGrpcTransport -from .transports.grpc_asyncio import InstancesGrpcAsyncIOTransport - - -class InstancesClientMeta(type): - """Metaclass for the Instances client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[InstancesTransport]] - _transport_registry["grpc"] = InstancesGrpcTransport - _transport_registry["grpc_asyncio"] = InstancesGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[InstancesTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class InstancesClient(metaclass=InstancesClientMeta): - """Manages instances of a version.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "appengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - InstancesClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - InstancesClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> InstancesTransport: - """Returns the transport used by the client instance. - - Returns: - InstancesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def instance_path(app: str,service: str,version: str,instance: str,) -> str: - """Returns a fully-qualified instance string.""" - return "apps/{app}/services/{service}/versions/{version}/instances/{instance}".format(app=app, service=service, version=version, instance=instance, ) - - @staticmethod - def parse_instance_path(path: str) -> Dict[str,str]: - """Parses a instance path into its component segments.""" - m = re.match(r"^apps/(?P.+?)/services/(?P.+?)/versions/(?P.+?)/instances/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, InstancesTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the instances client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, InstancesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, InstancesTransport): - # transport is a InstancesTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def list_instances(self, - request: appengine.ListInstancesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListInstancesPager: - r"""Lists the instances of a version. - - Tip: To aggregate details about instances over time, see the - `Stackdriver Monitoring - API `__. - - Args: - request (google.cloud.appengine_admin_v1.types.ListInstancesRequest): - The request object. Request message for - `Instances.ListInstances`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.services.instances.pagers.ListInstancesPager: - Response message for Instances.ListInstances. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.ListInstancesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.ListInstancesRequest): - request = appengine.ListInstancesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_instances] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListInstancesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_instance(self, - request: appengine.GetInstanceRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> instance.Instance: - r"""Gets instance information. - - Args: - request (google.cloud.appengine_admin_v1.types.GetInstanceRequest): - The request object. Request message for - `Instances.GetInstance`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.Instance: - An Instance resource is the computing - unit that App Engine uses to - automatically scale an application. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.GetInstanceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.GetInstanceRequest): - request = appengine.GetInstanceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_instance] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_instance(self, - request: appengine.DeleteInstanceRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gac_operation.Operation: - r"""Stops a running instance. - - The instance might be automatically recreated based on the - scaling settings of the version. For more information, see "How - Instances are Managed" (`standard - environment `__ - \| `flexible - environment `__). - - To ensure that instances are not re-created and avoid getting - billed, you can stop all instances within the target version by - changing the serving status of the version to ``STOPPED`` with - the - ```apps.services.versions.patch`` `__ - method. - - Args: - request (google.cloud.appengine_admin_v1.types.DeleteInstanceRequest): - The request object. Request message for - `Instances.DeleteInstance`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.DeleteInstanceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.DeleteInstanceRequest): - request = appengine.DeleteInstanceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_instance] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = gac_operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - def debug_instance(self, - request: appengine.DebugInstanceRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gac_operation.Operation: - r"""Enables debugging on a VM instance. This allows you - to use the SSH command to connect to the virtual machine - where the instance lives. While in "debug mode", the - instance continues to serve live traffic. You should - delete the instance when you are done debugging and then - allow the system to take over and determine if another - instance should be started. - - Only applicable for instances in App Engine flexible - environment. - - Args: - request (google.cloud.appengine_admin_v1.types.DebugInstanceRequest): - The request object. Request message for - `Instances.DebugInstance`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Instance` An Instance resource is the computing unit that App Engine uses to - automatically scale an application. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.DebugInstanceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.DebugInstanceRequest): - request = appengine.DebugInstanceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.debug_instance] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = gac_operation.from_gapic( - response, - self._transport.operations_client, - instance.Instance, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-appengine-admin", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "InstancesClient", -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/pagers.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/pagers.py deleted file mode 100644 index 08a248d..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/pagers.py +++ /dev/null @@ -1,141 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import instance - - -class ListInstancesPager: - """A pager for iterating through ``list_instances`` requests. - - This class thinly wraps an initial - :class:`google.cloud.appengine_admin_v1.types.ListInstancesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``instances`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListInstances`` requests and continue to iterate - through the ``instances`` field on the - corresponding responses. - - All the usual :class:`google.cloud.appengine_admin_v1.types.ListInstancesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., appengine.ListInstancesResponse], - request: appengine.ListInstancesRequest, - response: appengine.ListInstancesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.appengine_admin_v1.types.ListInstancesRequest): - The initial request object. - response (google.cloud.appengine_admin_v1.types.ListInstancesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = appengine.ListInstancesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[appengine.ListInstancesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[instance.Instance]: - for page in self.pages: - yield from page.instances - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListInstancesAsyncPager: - """A pager for iterating through ``list_instances`` requests. - - This class thinly wraps an initial - :class:`google.cloud.appengine_admin_v1.types.ListInstancesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``instances`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListInstances`` requests and continue to iterate - through the ``instances`` field on the - corresponding responses. - - All the usual :class:`google.cloud.appengine_admin_v1.types.ListInstancesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[appengine.ListInstancesResponse]], - request: appengine.ListInstancesRequest, - response: appengine.ListInstancesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.appengine_admin_v1.types.ListInstancesRequest): - The initial request object. - response (google.cloud.appengine_admin_v1.types.ListInstancesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = appengine.ListInstancesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[appengine.ListInstancesResponse]: - 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, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[instance.Instance]: - async def async_generator(): - async for page in self.pages: - for response in page.instances: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/__init__.py deleted file mode 100644 index f8f9921..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import InstancesTransport -from .grpc import InstancesGrpcTransport -from .grpc_asyncio import InstancesGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[InstancesTransport]] -_transport_registry['grpc'] = InstancesGrpcTransport -_transport_registry['grpc_asyncio'] = InstancesGrpcAsyncIOTransport - -__all__ = ( - 'InstancesTransport', - 'InstancesGrpcTransport', - 'InstancesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/base.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/base.py deleted file mode 100644 index 94e4717..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/base.py +++ /dev/null @@ -1,220 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import instance -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-appengine-admin', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class InstancesTransport(abc.ABC): - """Abstract transport class for Instances.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ) - - DEFAULT_HOST: str = 'appengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials is service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_instances: gapic_v1.method.wrap_method( - self.list_instances, - default_timeout=None, - client_info=client_info, - ), - self.get_instance: gapic_v1.method.wrap_method( - self.get_instance, - default_timeout=None, - client_info=client_info, - ), - self.delete_instance: gapic_v1.method.wrap_method( - self.delete_instance, - default_timeout=None, - client_info=client_info, - ), - self.debug_instance: gapic_v1.method.wrap_method( - self.debug_instance, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_instances(self) -> Callable[ - [appengine.ListInstancesRequest], - Union[ - appengine.ListInstancesResponse, - Awaitable[appengine.ListInstancesResponse] - ]]: - raise NotImplementedError() - - @property - def get_instance(self) -> Callable[ - [appengine.GetInstanceRequest], - Union[ - instance.Instance, - Awaitable[instance.Instance] - ]]: - raise NotImplementedError() - - @property - def delete_instance(self) -> Callable[ - [appengine.DeleteInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def debug_instance(self) -> Callable[ - [appengine.DebugInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'InstancesTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/grpc.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/grpc.py deleted file mode 100644 index d46b857..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/grpc.py +++ /dev/null @@ -1,377 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import instance -from google.longrunning import operations_pb2 # type: ignore -from .base import InstancesTransport, DEFAULT_CLIENT_INFO - - -class InstancesGrpcTransport(InstancesTransport): - """gRPC backend transport for Instances. - - Manages instances of a version. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_instances(self) -> Callable[ - [appengine.ListInstancesRequest], - appengine.ListInstancesResponse]: - r"""Return a callable for the list instances method over gRPC. - - Lists the instances of a version. - - Tip: To aggregate details about instances over time, see the - `Stackdriver Monitoring - API `__. - - Returns: - Callable[[~.ListInstancesRequest], - ~.ListInstancesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_instances' not in self._stubs: - self._stubs['list_instances'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Instances/ListInstances', - request_serializer=appengine.ListInstancesRequest.serialize, - response_deserializer=appengine.ListInstancesResponse.deserialize, - ) - return self._stubs['list_instances'] - - @property - def get_instance(self) -> Callable[ - [appengine.GetInstanceRequest], - instance.Instance]: - r"""Return a callable for the get instance method over gRPC. - - Gets instance information. - - Returns: - Callable[[~.GetInstanceRequest], - ~.Instance]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_instance' not in self._stubs: - self._stubs['get_instance'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Instances/GetInstance', - request_serializer=appengine.GetInstanceRequest.serialize, - response_deserializer=instance.Instance.deserialize, - ) - return self._stubs['get_instance'] - - @property - def delete_instance(self) -> Callable[ - [appengine.DeleteInstanceRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete instance method over gRPC. - - Stops a running instance. - - The instance might be automatically recreated based on the - scaling settings of the version. For more information, see "How - Instances are Managed" (`standard - environment `__ - \| `flexible - environment `__). - - To ensure that instances are not re-created and avoid getting - billed, you can stop all instances within the target version by - changing the serving status of the version to ``STOPPED`` with - the - ```apps.services.versions.patch`` `__ - method. - - Returns: - Callable[[~.DeleteInstanceRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_instance' not in self._stubs: - self._stubs['delete_instance'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Instances/DeleteInstance', - request_serializer=appengine.DeleteInstanceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_instance'] - - @property - def debug_instance(self) -> Callable[ - [appengine.DebugInstanceRequest], - operations_pb2.Operation]: - r"""Return a callable for the debug instance method over gRPC. - - Enables debugging on a VM instance. This allows you - to use the SSH command to connect to the virtual machine - where the instance lives. While in "debug mode", the - instance continues to serve live traffic. You should - delete the instance when you are done debugging and then - allow the system to take over and determine if another - instance should be started. - - Only applicable for instances in App Engine flexible - environment. - - Returns: - Callable[[~.DebugInstanceRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'debug_instance' not in self._stubs: - self._stubs['debug_instance'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Instances/DebugInstance', - request_serializer=appengine.DebugInstanceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['debug_instance'] - - -__all__ = ( - 'InstancesGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/grpc_asyncio.py deleted file mode 100644 index b695723..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/instances/transports/grpc_asyncio.py +++ /dev/null @@ -1,381 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import instance -from google.longrunning import operations_pb2 # type: ignore -from .base import InstancesTransport, DEFAULT_CLIENT_INFO -from .grpc import InstancesGrpcTransport - - -class InstancesGrpcAsyncIOTransport(InstancesTransport): - """gRPC AsyncIO backend transport for Instances. - - Manages instances of a version. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_instances(self) -> Callable[ - [appengine.ListInstancesRequest], - Awaitable[appengine.ListInstancesResponse]]: - r"""Return a callable for the list instances method over gRPC. - - Lists the instances of a version. - - Tip: To aggregate details about instances over time, see the - `Stackdriver Monitoring - API `__. - - Returns: - Callable[[~.ListInstancesRequest], - Awaitable[~.ListInstancesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_instances' not in self._stubs: - self._stubs['list_instances'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Instances/ListInstances', - request_serializer=appengine.ListInstancesRequest.serialize, - response_deserializer=appengine.ListInstancesResponse.deserialize, - ) - return self._stubs['list_instances'] - - @property - def get_instance(self) -> Callable[ - [appengine.GetInstanceRequest], - Awaitable[instance.Instance]]: - r"""Return a callable for the get instance method over gRPC. - - Gets instance information. - - Returns: - Callable[[~.GetInstanceRequest], - Awaitable[~.Instance]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_instance' not in self._stubs: - self._stubs['get_instance'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Instances/GetInstance', - request_serializer=appengine.GetInstanceRequest.serialize, - response_deserializer=instance.Instance.deserialize, - ) - return self._stubs['get_instance'] - - @property - def delete_instance(self) -> Callable[ - [appengine.DeleteInstanceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete instance method over gRPC. - - Stops a running instance. - - The instance might be automatically recreated based on the - scaling settings of the version. For more information, see "How - Instances are Managed" (`standard - environment `__ - \| `flexible - environment `__). - - To ensure that instances are not re-created and avoid getting - billed, you can stop all instances within the target version by - changing the serving status of the version to ``STOPPED`` with - the - ```apps.services.versions.patch`` `__ - method. - - Returns: - Callable[[~.DeleteInstanceRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_instance' not in self._stubs: - self._stubs['delete_instance'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Instances/DeleteInstance', - request_serializer=appengine.DeleteInstanceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_instance'] - - @property - def debug_instance(self) -> Callable[ - [appengine.DebugInstanceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the debug instance method over gRPC. - - Enables debugging on a VM instance. This allows you - to use the SSH command to connect to the virtual machine - where the instance lives. While in "debug mode", the - instance continues to serve live traffic. You should - delete the instance when you are done debugging and then - allow the system to take over and determine if another - instance should be started. - - Only applicable for instances in App Engine flexible - environment. - - Returns: - Callable[[~.DebugInstanceRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'debug_instance' not in self._stubs: - self._stubs['debug_instance'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Instances/DebugInstance', - request_serializer=appengine.DebugInstanceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['debug_instance'] - - -__all__ = ( - 'InstancesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/__init__.py deleted file mode 100644 index f4257d7..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ServicesClient -from .async_client import ServicesAsyncClient - -__all__ = ( - 'ServicesClient', - 'ServicesAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/async_client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/async_client.py deleted file mode 100644 index 95c9965..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/async_client.py +++ /dev/null @@ -1,448 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation as gac_operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.appengine_admin_v1.services.services import pagers -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import network_settings -from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.cloud.appengine_admin_v1.types import service -from google.protobuf import empty_pb2 # type: ignore -from .transports.base import ServicesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ServicesGrpcAsyncIOTransport -from .client import ServicesClient - - -class ServicesAsyncClient: - """Manages services of an application.""" - - _client: ServicesClient - - DEFAULT_ENDPOINT = ServicesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ServicesClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(ServicesClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ServicesClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ServicesClient.common_folder_path) - parse_common_folder_path = staticmethod(ServicesClient.parse_common_folder_path) - common_organization_path = staticmethod(ServicesClient.common_organization_path) - parse_common_organization_path = staticmethod(ServicesClient.parse_common_organization_path) - common_project_path = staticmethod(ServicesClient.common_project_path) - parse_common_project_path = staticmethod(ServicesClient.parse_common_project_path) - common_location_path = staticmethod(ServicesClient.common_location_path) - parse_common_location_path = staticmethod(ServicesClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ServicesAsyncClient: The constructed client. - """ - return ServicesClient.from_service_account_info.__func__(ServicesAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ServicesAsyncClient: The constructed client. - """ - return ServicesClient.from_service_account_file.__func__(ServicesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> ServicesTransport: - """Returns the transport used by the client instance. - - Returns: - ServicesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ServicesClient).get_transport_class, type(ServicesClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ServicesTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the services client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ServicesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ServicesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_services(self, - request: appengine.ListServicesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServicesAsyncPager: - r"""Lists all the services in the application. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.ListServicesRequest`): - The request object. Request message for - `Services.ListServices`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.services.services.pagers.ListServicesAsyncPager: - Response message for Services.ListServices. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = appengine.ListServicesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_services, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListServicesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_service(self, - request: appengine.GetServiceRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.Service: - r"""Gets the current configuration of the specified - service. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.GetServiceRequest`): - The request object. Request message for - `Services.GetService`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.Service: - A Service resource is a logical - component of an application that can - share state and communicate in a secure - fashion with other services. For - example, an application that handles - customer requests might include separate - services to handle tasks such as backend - data analysis or API requests from - mobile devices. Each service has a - collection of versions that define a - specific set of code used to implement - the functionality of that service. - - """ - # Create or coerce a protobuf request object. - request = appengine.GetServiceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_service, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_service(self, - request: appengine.UpdateServiceRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the configuration of the specified service. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.UpdateServiceRequest`): - The request object. Request message for - `Services.UpdateService`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Service` A Service resource is a logical component of an application that can share - state and communicate in a secure fashion with other - services. For example, an application that handles - customer requests might include separate services to - handle tasks such as backend data analysis or API - requests from mobile devices. Each service has a - collection of versions that define a specific set of - code used to implement the functionality of that - service. - - """ - # Create or coerce a protobuf request object. - request = appengine.UpdateServiceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_service, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - service.Service, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - async def delete_service(self, - request: appengine.DeleteServiceRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the specified service and all enclosed - versions. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.DeleteServiceRequest`): - The request object. Request message for - `Services.DeleteService`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - request = appengine.DeleteServiceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_service, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-appengine-admin", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ServicesAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/client.py deleted file mode 100644 index 6778b93..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/client.py +++ /dev/null @@ -1,634 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation as gac_operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.appengine_admin_v1.services.services import pagers -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import network_settings -from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.cloud.appengine_admin_v1.types import service -from google.protobuf import empty_pb2 # type: ignore -from .transports.base import ServicesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ServicesGrpcTransport -from .transports.grpc_asyncio import ServicesGrpcAsyncIOTransport - - -class ServicesClientMeta(type): - """Metaclass for the Services client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[ServicesTransport]] - _transport_registry["grpc"] = ServicesGrpcTransport - _transport_registry["grpc_asyncio"] = ServicesGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ServicesTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class ServicesClient(metaclass=ServicesClientMeta): - """Manages services of an application.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "appengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ServicesClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ServicesClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> ServicesTransport: - """Returns the transport used by the client instance. - - Returns: - ServicesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ServicesTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the services client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ServicesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ServicesTransport): - # transport is a ServicesTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def list_services(self, - request: appengine.ListServicesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListServicesPager: - r"""Lists all the services in the application. - - Args: - request (google.cloud.appengine_admin_v1.types.ListServicesRequest): - The request object. Request message for - `Services.ListServices`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.services.services.pagers.ListServicesPager: - Response message for Services.ListServices. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.ListServicesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.ListServicesRequest): - request = appengine.ListServicesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_services] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListServicesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_service(self, - request: appengine.GetServiceRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.Service: - r"""Gets the current configuration of the specified - service. - - Args: - request (google.cloud.appengine_admin_v1.types.GetServiceRequest): - The request object. Request message for - `Services.GetService`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.Service: - A Service resource is a logical - component of an application that can - share state and communicate in a secure - fashion with other services. For - example, an application that handles - customer requests might include separate - services to handle tasks such as backend - data analysis or API requests from - mobile devices. Each service has a - collection of versions that define a - specific set of code used to implement - the functionality of that service. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.GetServiceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.GetServiceRequest): - request = appengine.GetServiceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_service] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_service(self, - request: appengine.UpdateServiceRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gac_operation.Operation: - r"""Updates the configuration of the specified service. - - Args: - request (google.cloud.appengine_admin_v1.types.UpdateServiceRequest): - The request object. Request message for - `Services.UpdateService`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Service` A Service resource is a logical component of an application that can share - state and communicate in a secure fashion with other - services. For example, an application that handles - customer requests might include separate services to - handle tasks such as backend data analysis or API - requests from mobile devices. Each service has a - collection of versions that define a specific set of - code used to implement the functionality of that - service. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.UpdateServiceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.UpdateServiceRequest): - request = appengine.UpdateServiceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_service] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = gac_operation.from_gapic( - response, - self._transport.operations_client, - service.Service, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - def delete_service(self, - request: appengine.DeleteServiceRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gac_operation.Operation: - r"""Deletes the specified service and all enclosed - versions. - - Args: - request (google.cloud.appengine_admin_v1.types.DeleteServiceRequest): - The request object. Request message for - `Services.DeleteService`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.DeleteServiceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.DeleteServiceRequest): - request = appengine.DeleteServiceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_service] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = gac_operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-appengine-admin", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ServicesClient", -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/pagers.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/pagers.py deleted file mode 100644 index ce295d1..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/pagers.py +++ /dev/null @@ -1,141 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import service - - -class ListServicesPager: - """A pager for iterating through ``list_services`` requests. - - This class thinly wraps an initial - :class:`google.cloud.appengine_admin_v1.types.ListServicesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``services`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListServices`` requests and continue to iterate - through the ``services`` field on the - corresponding responses. - - All the usual :class:`google.cloud.appengine_admin_v1.types.ListServicesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., appengine.ListServicesResponse], - request: appengine.ListServicesRequest, - response: appengine.ListServicesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.appengine_admin_v1.types.ListServicesRequest): - The initial request object. - response (google.cloud.appengine_admin_v1.types.ListServicesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = appengine.ListServicesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[appengine.ListServicesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[service.Service]: - for page in self.pages: - yield from page.services - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServicesAsyncPager: - """A pager for iterating through ``list_services`` requests. - - This class thinly wraps an initial - :class:`google.cloud.appengine_admin_v1.types.ListServicesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``services`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListServices`` requests and continue to iterate - through the ``services`` field on the - corresponding responses. - - All the usual :class:`google.cloud.appengine_admin_v1.types.ListServicesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[appengine.ListServicesResponse]], - request: appengine.ListServicesRequest, - response: appengine.ListServicesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.appengine_admin_v1.types.ListServicesRequest): - The initial request object. - response (google.cloud.appengine_admin_v1.types.ListServicesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = appengine.ListServicesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[appengine.ListServicesResponse]: - 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, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[service.Service]: - async def async_generator(): - async for page in self.pages: - for response in page.services: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/__init__.py deleted file mode 100644 index 919f871..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ServicesTransport -from .grpc import ServicesGrpcTransport -from .grpc_asyncio import ServicesGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ServicesTransport]] -_transport_registry['grpc'] = ServicesGrpcTransport -_transport_registry['grpc_asyncio'] = ServicesGrpcAsyncIOTransport - -__all__ = ( - 'ServicesTransport', - 'ServicesGrpcTransport', - 'ServicesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/base.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/base.py deleted file mode 100644 index b5523fc..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/base.py +++ /dev/null @@ -1,220 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import service -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-appengine-admin', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class ServicesTransport(abc.ABC): - """Abstract transport class for Services.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ) - - DEFAULT_HOST: str = 'appengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials is service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_services: gapic_v1.method.wrap_method( - self.list_services, - default_timeout=None, - client_info=client_info, - ), - self.get_service: gapic_v1.method.wrap_method( - self.get_service, - default_timeout=None, - client_info=client_info, - ), - self.update_service: gapic_v1.method.wrap_method( - self.update_service, - default_timeout=None, - client_info=client_info, - ), - self.delete_service: gapic_v1.method.wrap_method( - self.delete_service, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_services(self) -> Callable[ - [appengine.ListServicesRequest], - Union[ - appengine.ListServicesResponse, - Awaitable[appengine.ListServicesResponse] - ]]: - raise NotImplementedError() - - @property - def get_service(self) -> Callable[ - [appengine.GetServiceRequest], - Union[ - service.Service, - Awaitable[service.Service] - ]]: - raise NotImplementedError() - - @property - def update_service(self) -> Callable[ - [appengine.UpdateServiceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_service(self) -> Callable[ - [appengine.DeleteServiceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'ServicesTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/grpc.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/grpc.py deleted file mode 100644 index eac4202..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/grpc.py +++ /dev/null @@ -1,352 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import service -from google.longrunning import operations_pb2 # type: ignore -from .base import ServicesTransport, DEFAULT_CLIENT_INFO - - -class ServicesGrpcTransport(ServicesTransport): - """gRPC backend transport for Services. - - Manages services of an application. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_services(self) -> Callable[ - [appengine.ListServicesRequest], - appengine.ListServicesResponse]: - r"""Return a callable for the list services method over gRPC. - - Lists all the services in the application. - - Returns: - Callable[[~.ListServicesRequest], - ~.ListServicesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_services' not in self._stubs: - self._stubs['list_services'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Services/ListServices', - request_serializer=appengine.ListServicesRequest.serialize, - response_deserializer=appengine.ListServicesResponse.deserialize, - ) - return self._stubs['list_services'] - - @property - def get_service(self) -> Callable[ - [appengine.GetServiceRequest], - service.Service]: - r"""Return a callable for the get service method over gRPC. - - Gets the current configuration of the specified - service. - - Returns: - Callable[[~.GetServiceRequest], - ~.Service]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_service' not in self._stubs: - self._stubs['get_service'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Services/GetService', - request_serializer=appengine.GetServiceRequest.serialize, - response_deserializer=service.Service.deserialize, - ) - return self._stubs['get_service'] - - @property - def update_service(self) -> Callable[ - [appengine.UpdateServiceRequest], - operations_pb2.Operation]: - r"""Return a callable for the update service method over gRPC. - - Updates the configuration of the specified service. - - Returns: - Callable[[~.UpdateServiceRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_service' not in self._stubs: - self._stubs['update_service'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Services/UpdateService', - request_serializer=appengine.UpdateServiceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_service'] - - @property - def delete_service(self) -> Callable[ - [appengine.DeleteServiceRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete service method over gRPC. - - Deletes the specified service and all enclosed - versions. - - Returns: - Callable[[~.DeleteServiceRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_service' not in self._stubs: - self._stubs['delete_service'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Services/DeleteService', - request_serializer=appengine.DeleteServiceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_service'] - - -__all__ = ( - 'ServicesGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/grpc_asyncio.py deleted file mode 100644 index b54bff0..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/services/transports/grpc_asyncio.py +++ /dev/null @@ -1,356 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import service -from google.longrunning import operations_pb2 # type: ignore -from .base import ServicesTransport, DEFAULT_CLIENT_INFO -from .grpc import ServicesGrpcTransport - - -class ServicesGrpcAsyncIOTransport(ServicesTransport): - """gRPC AsyncIO backend transport for Services. - - Manages services of an application. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_services(self) -> Callable[ - [appengine.ListServicesRequest], - Awaitable[appengine.ListServicesResponse]]: - r"""Return a callable for the list services method over gRPC. - - Lists all the services in the application. - - Returns: - Callable[[~.ListServicesRequest], - Awaitable[~.ListServicesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_services' not in self._stubs: - self._stubs['list_services'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Services/ListServices', - request_serializer=appengine.ListServicesRequest.serialize, - response_deserializer=appengine.ListServicesResponse.deserialize, - ) - return self._stubs['list_services'] - - @property - def get_service(self) -> Callable[ - [appengine.GetServiceRequest], - Awaitable[service.Service]]: - r"""Return a callable for the get service method over gRPC. - - Gets the current configuration of the specified - service. - - Returns: - Callable[[~.GetServiceRequest], - Awaitable[~.Service]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_service' not in self._stubs: - self._stubs['get_service'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Services/GetService', - request_serializer=appengine.GetServiceRequest.serialize, - response_deserializer=service.Service.deserialize, - ) - return self._stubs['get_service'] - - @property - def update_service(self) -> Callable[ - [appengine.UpdateServiceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update service method over gRPC. - - Updates the configuration of the specified service. - - Returns: - Callable[[~.UpdateServiceRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_service' not in self._stubs: - self._stubs['update_service'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Services/UpdateService', - request_serializer=appengine.UpdateServiceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_service'] - - @property - def delete_service(self) -> Callable[ - [appengine.DeleteServiceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete service method over gRPC. - - Deletes the specified service and all enclosed - versions. - - Returns: - Callable[[~.DeleteServiceRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_service' not in self._stubs: - self._stubs['delete_service'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Services/DeleteService', - request_serializer=appengine.DeleteServiceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_service'] - - -__all__ = ( - 'ServicesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/__init__.py deleted file mode 100644 index 630246b..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import VersionsClient -from .async_client import VersionsAsyncClient - -__all__ = ( - 'VersionsClient', - 'VersionsAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/async_client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/async_client.py deleted file mode 100644 index 07674aa..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/async_client.py +++ /dev/null @@ -1,535 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation as gac_operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.appengine_admin_v1.services.versions import pagers -from google.cloud.appengine_admin_v1.types import app_yaml -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import deploy -from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.cloud.appengine_admin_v1.types import version -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport -from .client import VersionsClient - - -class VersionsAsyncClient: - """Manages versions of a service.""" - - _client: VersionsClient - - DEFAULT_ENDPOINT = VersionsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = VersionsClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(VersionsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(VersionsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(VersionsClient.common_folder_path) - parse_common_folder_path = staticmethod(VersionsClient.parse_common_folder_path) - common_organization_path = staticmethod(VersionsClient.common_organization_path) - parse_common_organization_path = staticmethod(VersionsClient.parse_common_organization_path) - common_project_path = staticmethod(VersionsClient.common_project_path) - parse_common_project_path = staticmethod(VersionsClient.parse_common_project_path) - common_location_path = staticmethod(VersionsClient.common_location_path) - parse_common_location_path = staticmethod(VersionsClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VersionsAsyncClient: The constructed client. - """ - return VersionsClient.from_service_account_info.__func__(VersionsAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VersionsAsyncClient: The constructed client. - """ - return VersionsClient.from_service_account_file.__func__(VersionsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> VersionsTransport: - """Returns the transport used by the client instance. - - Returns: - VersionsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(VersionsClient).get_transport_class, type(VersionsClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, VersionsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the versions client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.VersionsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = VersionsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_versions(self, - request: appengine.ListVersionsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListVersionsAsyncPager: - r"""Lists the versions of a service. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.ListVersionsRequest`): - The request object. Request message for - `Versions.ListVersions`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.services.versions.pagers.ListVersionsAsyncPager: - Response message for Versions.ListVersions. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = appengine.ListVersionsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_versions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListVersionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_version(self, - request: appengine.GetVersionRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> version.Version: - r"""Gets the specified Version resource. By default, only a - ``BASIC_VIEW`` will be returned. Specify the ``FULL_VIEW`` - parameter to get the full resource. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.GetVersionRequest`): - The request object. Request message for - `Versions.GetVersion`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.Version: - A Version resource is a specific set - of source code and configuration files - that are deployed into a service. - - """ - # Create or coerce a protobuf request object. - request = appengine.GetVersionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_version, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_version(self, - request: appengine.CreateVersionRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deploys code and resource files to a new version. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.CreateVersionRequest`): - The request object. Request message for - `Versions.CreateVersion`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Version` A Version resource is a specific set of source code and configuration files - that are deployed into a service. - - """ - # Create or coerce a protobuf request object. - request = appengine.CreateVersionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_version, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - version.Version, - metadata_type=ga_operation.CreateVersionMetadataV1, - ) - - # Done; return the response. - return response - - async def update_version(self, - request: appengine.UpdateVersionRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the specified Version resource. You can specify the - following fields depending on the App Engine environment and - type of scaling that the version resource uses: - - **Standard environment** - - - ```instance_class`` `__ - - *automatic scaling* in the standard environment: - - - ```automatic_scaling.min_idle_instances`` `__ - - ```automatic_scaling.max_idle_instances`` `__ - - ```automaticScaling.standard_scheduler_settings.max_instances`` `__ - - ```automaticScaling.standard_scheduler_settings.min_instances`` `__ - - ```automaticScaling.standard_scheduler_settings.target_cpu_utilization`` `__ - - ```automaticScaling.standard_scheduler_settings.target_throughput_utilization`` `__ - - *basic scaling* or *manual scaling* in the standard environment: - - - ```serving_status`` `__ - - ```manual_scaling.instances`` `__ - - **Flexible environment** - - - ```serving_status`` `__ - - *automatic scaling* in the flexible environment: - - - ```automatic_scaling.min_total_instances`` `__ - - ```automatic_scaling.max_total_instances`` `__ - - ```automatic_scaling.cool_down_period_sec`` `__ - - ```automatic_scaling.cpu_utilization.target_utilization`` `__ - - *manual scaling* in the flexible environment: - - - ```manual_scaling.instances`` `__ - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.UpdateVersionRequest`): - The request object. Request message for - `Versions.UpdateVersion`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Version` A Version resource is a specific set of source code and configuration files - that are deployed into a service. - - """ - # Create or coerce a protobuf request object. - request = appengine.UpdateVersionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_version, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - version.Version, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - async def delete_version(self, - request: appengine.DeleteVersionRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes an existing Version resource. - - Args: - request (:class:`google.cloud.appengine_admin_v1.types.DeleteVersionRequest`): - The request object. Request message for - `Versions.DeleteVersion`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - request = appengine.DeleteVersionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_version, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-appengine-admin", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "VersionsAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/client.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/client.py deleted file mode 100644 index b5c1817..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/client.py +++ /dev/null @@ -1,722 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation as gac_operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.appengine_admin_v1.services.versions import pagers -from google.cloud.appengine_admin_v1.types import app_yaml -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import deploy -from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.cloud.appengine_admin_v1.types import version -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import VersionsGrpcTransport -from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport - - -class VersionsClientMeta(type): - """Metaclass for the Versions client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] - _transport_registry["grpc"] = VersionsGrpcTransport - _transport_registry["grpc_asyncio"] = VersionsGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[VersionsTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class VersionsClient(metaclass=VersionsClientMeta): - """Manages versions of a service.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "appengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VersionsClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - VersionsClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> VersionsTransport: - """Returns the transport used by the client instance. - - Returns: - VersionsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, VersionsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the versions client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, VersionsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, VersionsTransport): - # transport is a VersionsTransport instance. - if credentials or client_options.credentials_file: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def list_versions(self, - request: appengine.ListVersionsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListVersionsPager: - r"""Lists the versions of a service. - - Args: - request (google.cloud.appengine_admin_v1.types.ListVersionsRequest): - The request object. Request message for - `Versions.ListVersions`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.services.versions.pagers.ListVersionsPager: - Response message for Versions.ListVersions. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.ListVersionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.ListVersionsRequest): - request = appengine.ListVersionsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_versions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListVersionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_version(self, - request: appengine.GetVersionRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> version.Version: - r"""Gets the specified Version resource. By default, only a - ``BASIC_VIEW`` will be returned. Specify the ``FULL_VIEW`` - parameter to get the full resource. - - Args: - request (google.cloud.appengine_admin_v1.types.GetVersionRequest): - The request object. Request message for - `Versions.GetVersion`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.appengine_admin_v1.types.Version: - A Version resource is a specific set - of source code and configuration files - that are deployed into a service. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.GetVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.GetVersionRequest): - request = appengine.GetVersionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_version(self, - request: appengine.CreateVersionRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gac_operation.Operation: - r"""Deploys code and resource files to a new version. - - Args: - request (google.cloud.appengine_admin_v1.types.CreateVersionRequest): - The request object. Request message for - `Versions.CreateVersion`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Version` A Version resource is a specific set of source code and configuration files - that are deployed into a service. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.CreateVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.CreateVersionRequest): - request = appengine.CreateVersionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = gac_operation.from_gapic( - response, - self._transport.operations_client, - version.Version, - metadata_type=ga_operation.CreateVersionMetadataV1, - ) - - # Done; return the response. - return response - - def update_version(self, - request: appengine.UpdateVersionRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gac_operation.Operation: - r"""Updates the specified Version resource. You can specify the - following fields depending on the App Engine environment and - type of scaling that the version resource uses: - - **Standard environment** - - - ```instance_class`` `__ - - *automatic scaling* in the standard environment: - - - ```automatic_scaling.min_idle_instances`` `__ - - ```automatic_scaling.max_idle_instances`` `__ - - ```automaticScaling.standard_scheduler_settings.max_instances`` `__ - - ```automaticScaling.standard_scheduler_settings.min_instances`` `__ - - ```automaticScaling.standard_scheduler_settings.target_cpu_utilization`` `__ - - ```automaticScaling.standard_scheduler_settings.target_throughput_utilization`` `__ - - *basic scaling* or *manual scaling* in the standard environment: - - - ```serving_status`` `__ - - ```manual_scaling.instances`` `__ - - **Flexible environment** - - - ```serving_status`` `__ - - *automatic scaling* in the flexible environment: - - - ```automatic_scaling.min_total_instances`` `__ - - ```automatic_scaling.max_total_instances`` `__ - - ```automatic_scaling.cool_down_period_sec`` `__ - - ```automatic_scaling.cpu_utilization.target_utilization`` `__ - - *manual scaling* in the flexible environment: - - - ```manual_scaling.instances`` `__ - - Args: - request (google.cloud.appengine_admin_v1.types.UpdateVersionRequest): - The request object. Request message for - `Versions.UpdateVersion`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.appengine_admin_v1.types.Version` A Version resource is a specific set of source code and configuration files - that are deployed into a service. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.UpdateVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.UpdateVersionRequest): - request = appengine.UpdateVersionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = gac_operation.from_gapic( - response, - self._transport.operations_client, - version.Version, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - def delete_version(self, - request: appengine.DeleteVersionRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gac_operation.Operation: - r"""Deletes an existing Version resource. - - Args: - request (google.cloud.appengine_admin_v1.types.DeleteVersionRequest): - The request object. Request message for - `Versions.DeleteVersion`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a appengine.DeleteVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, appengine.DeleteVersionRequest): - request = appengine.DeleteVersionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = gac_operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=ga_operation.OperationMetadataV1, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-appengine-admin", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "VersionsClient", -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/pagers.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/pagers.py deleted file mode 100644 index b32c743..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/pagers.py +++ /dev/null @@ -1,141 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import version - - -class ListVersionsPager: - """A pager for iterating through ``list_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.appengine_admin_v1.types.ListVersionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``versions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListVersions`` requests and continue to iterate - through the ``versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.appengine_admin_v1.types.ListVersionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., appengine.ListVersionsResponse], - request: appengine.ListVersionsRequest, - response: appengine.ListVersionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.appengine_admin_v1.types.ListVersionsRequest): - The initial request object. - response (google.cloud.appengine_admin_v1.types.ListVersionsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = appengine.ListVersionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[appengine.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, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[version.Version]: - for page in self.pages: - yield from page.versions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListVersionsAsyncPager: - """A pager for iterating through ``list_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.appengine_admin_v1.types.ListVersionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``versions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListVersions`` requests and continue to iterate - through the ``versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.appengine_admin_v1.types.ListVersionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[appengine.ListVersionsResponse]], - request: appengine.ListVersionsRequest, - response: appengine.ListVersionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.appengine_admin_v1.types.ListVersionsRequest): - The initial request object. - response (google.cloud.appengine_admin_v1.types.ListVersionsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = appengine.ListVersionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[appengine.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, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[version.Version]: - async def async_generator(): - async for page in self.pages: - for response in page.versions: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/__init__.py deleted file mode 100644 index dfb70ce..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import VersionsTransport -from .grpc import VersionsGrpcTransport -from .grpc_asyncio import VersionsGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] -_transport_registry['grpc'] = VersionsGrpcTransport -_transport_registry['grpc_asyncio'] = VersionsGrpcAsyncIOTransport - -__all__ = ( - 'VersionsTransport', - 'VersionsGrpcTransport', - 'VersionsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/base.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/base.py deleted file mode 100644 index e907f17..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/base.py +++ /dev/null @@ -1,234 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import version -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-appengine-admin', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class VersionsTransport(abc.ABC): - """Abstract transport class for Versions.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ) - - DEFAULT_HOST: str = 'appengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - - # If the credentials is service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_versions: gapic_v1.method.wrap_method( - self.list_versions, - default_timeout=None, - client_info=client_info, - ), - self.get_version: gapic_v1.method.wrap_method( - self.get_version, - default_timeout=None, - client_info=client_info, - ), - self.create_version: gapic_v1.method.wrap_method( - self.create_version, - default_timeout=None, - client_info=client_info, - ), - self.update_version: gapic_v1.method.wrap_method( - self.update_version, - default_timeout=None, - client_info=client_info, - ), - self.delete_version: gapic_v1.method.wrap_method( - self.delete_version, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_versions(self) -> Callable[ - [appengine.ListVersionsRequest], - Union[ - appengine.ListVersionsResponse, - Awaitable[appengine.ListVersionsResponse] - ]]: - raise NotImplementedError() - - @property - def get_version(self) -> Callable[ - [appengine.GetVersionRequest], - Union[ - version.Version, - Awaitable[version.Version] - ]]: - raise NotImplementedError() - - @property - def create_version(self) -> Callable[ - [appengine.CreateVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_version(self) -> Callable[ - [appengine.UpdateVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_version(self) -> Callable[ - [appengine.DeleteVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'VersionsTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/grpc.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/grpc.py deleted file mode 100644 index 15e5f11..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/grpc.py +++ /dev/null @@ -1,413 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import version -from google.longrunning import operations_pb2 # type: ignore -from .base import VersionsTransport, DEFAULT_CLIENT_INFO - - -class VersionsGrpcTransport(VersionsTransport): - """gRPC backend transport for Versions. - - Manages versions of a service. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_versions(self) -> Callable[ - [appengine.ListVersionsRequest], - appengine.ListVersionsResponse]: - r"""Return a callable for the list versions method over gRPC. - - Lists the versions of a service. - - Returns: - Callable[[~.ListVersionsRequest], - ~.ListVersionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_versions' not in self._stubs: - self._stubs['list_versions'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Versions/ListVersions', - request_serializer=appengine.ListVersionsRequest.serialize, - response_deserializer=appengine.ListVersionsResponse.deserialize, - ) - return self._stubs['list_versions'] - - @property - def get_version(self) -> Callable[ - [appengine.GetVersionRequest], - version.Version]: - r"""Return a callable for the get version method over gRPC. - - Gets the specified Version resource. By default, only a - ``BASIC_VIEW`` will be returned. Specify the ``FULL_VIEW`` - parameter to get the full resource. - - Returns: - Callable[[~.GetVersionRequest], - ~.Version]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_version' not in self._stubs: - self._stubs['get_version'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Versions/GetVersion', - request_serializer=appengine.GetVersionRequest.serialize, - response_deserializer=version.Version.deserialize, - ) - return self._stubs['get_version'] - - @property - def create_version(self) -> Callable[ - [appengine.CreateVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the create version method over gRPC. - - Deploys code and resource files to a new version. - - Returns: - Callable[[~.CreateVersionRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_version' not in self._stubs: - self._stubs['create_version'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Versions/CreateVersion', - request_serializer=appengine.CreateVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_version'] - - @property - def update_version(self) -> Callable[ - [appengine.UpdateVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the update version method over gRPC. - - Updates the specified Version resource. You can specify the - following fields depending on the App Engine environment and - type of scaling that the version resource uses: - - **Standard environment** - - - ```instance_class`` `__ - - *automatic scaling* in the standard environment: - - - ```automatic_scaling.min_idle_instances`` `__ - - ```automatic_scaling.max_idle_instances`` `__ - - ```automaticScaling.standard_scheduler_settings.max_instances`` `__ - - ```automaticScaling.standard_scheduler_settings.min_instances`` `__ - - ```automaticScaling.standard_scheduler_settings.target_cpu_utilization`` `__ - - ```automaticScaling.standard_scheduler_settings.target_throughput_utilization`` `__ - - *basic scaling* or *manual scaling* in the standard environment: - - - ```serving_status`` `__ - - ```manual_scaling.instances`` `__ - - **Flexible environment** - - - ```serving_status`` `__ - - *automatic scaling* in the flexible environment: - - - ```automatic_scaling.min_total_instances`` `__ - - ```automatic_scaling.max_total_instances`` `__ - - ```automatic_scaling.cool_down_period_sec`` `__ - - ```automatic_scaling.cpu_utilization.target_utilization`` `__ - - *manual scaling* in the flexible environment: - - - ```manual_scaling.instances`` `__ - - Returns: - Callable[[~.UpdateVersionRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_version' not in self._stubs: - self._stubs['update_version'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Versions/UpdateVersion', - request_serializer=appengine.UpdateVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_version'] - - @property - def delete_version(self) -> Callable[ - [appengine.DeleteVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete version method over gRPC. - - Deletes an existing Version resource. - - Returns: - Callable[[~.DeleteVersionRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_version' not in self._stubs: - self._stubs['delete_version'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Versions/DeleteVersion', - request_serializer=appengine.DeleteVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_version'] - - -__all__ = ( - 'VersionsGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/grpc_asyncio.py deleted file mode 100644 index 011f072..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/services/versions/transports/grpc_asyncio.py +++ /dev/null @@ -1,417 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import version -from google.longrunning import operations_pb2 # type: ignore -from .base import VersionsTransport, DEFAULT_CLIENT_INFO -from .grpc import VersionsGrpcTransport - - -class VersionsGrpcAsyncIOTransport(VersionsTransport): - """gRPC AsyncIO backend transport for Versions. - - Manages versions of a service. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'appengine.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_versions(self) -> Callable[ - [appengine.ListVersionsRequest], - Awaitable[appengine.ListVersionsResponse]]: - r"""Return a callable for the list versions method over gRPC. - - Lists the versions of a service. - - Returns: - Callable[[~.ListVersionsRequest], - Awaitable[~.ListVersionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_versions' not in self._stubs: - self._stubs['list_versions'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Versions/ListVersions', - request_serializer=appengine.ListVersionsRequest.serialize, - response_deserializer=appengine.ListVersionsResponse.deserialize, - ) - return self._stubs['list_versions'] - - @property - def get_version(self) -> Callable[ - [appengine.GetVersionRequest], - Awaitable[version.Version]]: - r"""Return a callable for the get version method over gRPC. - - Gets the specified Version resource. By default, only a - ``BASIC_VIEW`` will be returned. Specify the ``FULL_VIEW`` - parameter to get the full resource. - - Returns: - Callable[[~.GetVersionRequest], - Awaitable[~.Version]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_version' not in self._stubs: - self._stubs['get_version'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Versions/GetVersion', - request_serializer=appengine.GetVersionRequest.serialize, - response_deserializer=version.Version.deserialize, - ) - return self._stubs['get_version'] - - @property - def create_version(self) -> Callable[ - [appengine.CreateVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create version method over gRPC. - - Deploys code and resource files to a new version. - - Returns: - Callable[[~.CreateVersionRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_version' not in self._stubs: - self._stubs['create_version'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Versions/CreateVersion', - request_serializer=appengine.CreateVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_version'] - - @property - def update_version(self) -> Callable[ - [appengine.UpdateVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update version method over gRPC. - - Updates the specified Version resource. You can specify the - following fields depending on the App Engine environment and - type of scaling that the version resource uses: - - **Standard environment** - - - ```instance_class`` `__ - - *automatic scaling* in the standard environment: - - - ```automatic_scaling.min_idle_instances`` `__ - - ```automatic_scaling.max_idle_instances`` `__ - - ```automaticScaling.standard_scheduler_settings.max_instances`` `__ - - ```automaticScaling.standard_scheduler_settings.min_instances`` `__ - - ```automaticScaling.standard_scheduler_settings.target_cpu_utilization`` `__ - - ```automaticScaling.standard_scheduler_settings.target_throughput_utilization`` `__ - - *basic scaling* or *manual scaling* in the standard environment: - - - ```serving_status`` `__ - - ```manual_scaling.instances`` `__ - - **Flexible environment** - - - ```serving_status`` `__ - - *automatic scaling* in the flexible environment: - - - ```automatic_scaling.min_total_instances`` `__ - - ```automatic_scaling.max_total_instances`` `__ - - ```automatic_scaling.cool_down_period_sec`` `__ - - ```automatic_scaling.cpu_utilization.target_utilization`` `__ - - *manual scaling* in the flexible environment: - - - ```manual_scaling.instances`` `__ - - Returns: - Callable[[~.UpdateVersionRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_version' not in self._stubs: - self._stubs['update_version'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Versions/UpdateVersion', - request_serializer=appengine.UpdateVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_version'] - - @property - def delete_version(self) -> Callable[ - [appengine.DeleteVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete version method over gRPC. - - Deletes an existing Version resource. - - Returns: - Callable[[~.DeleteVersionRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_version' not in self._stubs: - self._stubs['delete_version'] = self.grpc_channel.unary_unary( - '/google.appengine.v1.Versions/DeleteVersion', - request_serializer=appengine.DeleteVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_version'] - - -__all__ = ( - 'VersionsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/__init__.py deleted file mode 100644 index 2152b04..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/__init__.py +++ /dev/null @@ -1,250 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .app_yaml import ( - ApiConfigHandler, - ApiEndpointHandler, - ErrorHandler, - HealthCheck, - Library, - LivenessCheck, - ReadinessCheck, - ScriptHandler, - StaticFilesHandler, - UrlMap, - AuthFailAction, - LoginRequirement, - SecurityLevel, -) -from .appengine import ( - BatchUpdateIngressRulesRequest, - BatchUpdateIngressRulesResponse, - CreateApplicationRequest, - CreateAuthorizedCertificateRequest, - CreateDomainMappingRequest, - CreateIngressRuleRequest, - CreateVersionRequest, - DebugInstanceRequest, - DeleteAuthorizedCertificateRequest, - DeleteDomainMappingRequest, - DeleteIngressRuleRequest, - DeleteInstanceRequest, - DeleteServiceRequest, - DeleteVersionRequest, - GetApplicationRequest, - GetAuthorizedCertificateRequest, - GetDomainMappingRequest, - GetIngressRuleRequest, - GetInstanceRequest, - GetServiceRequest, - GetVersionRequest, - ListAuthorizedCertificatesRequest, - ListAuthorizedCertificatesResponse, - ListAuthorizedDomainsRequest, - ListAuthorizedDomainsResponse, - ListDomainMappingsRequest, - ListDomainMappingsResponse, - ListIngressRulesRequest, - ListIngressRulesResponse, - ListInstancesRequest, - ListInstancesResponse, - ListServicesRequest, - ListServicesResponse, - ListVersionsRequest, - ListVersionsResponse, - RepairApplicationRequest, - UpdateApplicationRequest, - UpdateAuthorizedCertificateRequest, - UpdateDomainMappingRequest, - UpdateIngressRuleRequest, - UpdateServiceRequest, - UpdateVersionRequest, - AuthorizedCertificateView, - DomainOverrideStrategy, - VersionView, -) -from .application import ( - Application, - UrlDispatchRule, -) -from .audit_data import ( - AuditData, - CreateVersionMethod, - UpdateServiceMethod, -) -from .certificate import ( - AuthorizedCertificate, - CertificateRawData, - ManagedCertificate, - ManagementStatus, -) -from .deploy import ( - CloudBuildOptions, - ContainerInfo, - Deployment, - FileInfo, - ZipInfo, -) -from .domain import ( - AuthorizedDomain, -) -from .domain_mapping import ( - DomainMapping, - ResourceRecord, - SslSettings, -) -from .firewall import ( - FirewallRule, -) -from .instance import ( - Instance, -) -from .location import ( - LocationMetadata, -) -from .network_settings import ( - NetworkSettings, -) -from .operation import ( - CreateVersionMetadataV1, - OperationMetadataV1, -) -from .service import ( - Service, - TrafficSplit, -) -from .version import ( - AutomaticScaling, - BasicScaling, - CpuUtilization, - DiskUtilization, - EndpointsApiService, - Entrypoint, - ManualScaling, - Network, - NetworkUtilization, - RequestUtilization, - Resources, - StandardSchedulerSettings, - Version, - Volume, - VpcAccessConnector, - InboundServiceType, - ServingStatus, -) - -__all__ = ( - 'ApiConfigHandler', - 'ApiEndpointHandler', - 'ErrorHandler', - 'HealthCheck', - 'Library', - 'LivenessCheck', - 'ReadinessCheck', - 'ScriptHandler', - 'StaticFilesHandler', - 'UrlMap', - 'AuthFailAction', - 'LoginRequirement', - 'SecurityLevel', - 'BatchUpdateIngressRulesRequest', - 'BatchUpdateIngressRulesResponse', - 'CreateApplicationRequest', - 'CreateAuthorizedCertificateRequest', - 'CreateDomainMappingRequest', - 'CreateIngressRuleRequest', - 'CreateVersionRequest', - 'DebugInstanceRequest', - 'DeleteAuthorizedCertificateRequest', - 'DeleteDomainMappingRequest', - 'DeleteIngressRuleRequest', - 'DeleteInstanceRequest', - 'DeleteServiceRequest', - 'DeleteVersionRequest', - 'GetApplicationRequest', - 'GetAuthorizedCertificateRequest', - 'GetDomainMappingRequest', - 'GetIngressRuleRequest', - 'GetInstanceRequest', - 'GetServiceRequest', - 'GetVersionRequest', - 'ListAuthorizedCertificatesRequest', - 'ListAuthorizedCertificatesResponse', - 'ListAuthorizedDomainsRequest', - 'ListAuthorizedDomainsResponse', - 'ListDomainMappingsRequest', - 'ListDomainMappingsResponse', - 'ListIngressRulesRequest', - 'ListIngressRulesResponse', - 'ListInstancesRequest', - 'ListInstancesResponse', - 'ListServicesRequest', - 'ListServicesResponse', - 'ListVersionsRequest', - 'ListVersionsResponse', - 'RepairApplicationRequest', - 'UpdateApplicationRequest', - 'UpdateAuthorizedCertificateRequest', - 'UpdateDomainMappingRequest', - 'UpdateIngressRuleRequest', - 'UpdateServiceRequest', - 'UpdateVersionRequest', - 'AuthorizedCertificateView', - 'DomainOverrideStrategy', - 'VersionView', - 'Application', - 'UrlDispatchRule', - 'AuditData', - 'CreateVersionMethod', - 'UpdateServiceMethod', - 'AuthorizedCertificate', - 'CertificateRawData', - 'ManagedCertificate', - 'ManagementStatus', - 'CloudBuildOptions', - 'ContainerInfo', - 'Deployment', - 'FileInfo', - 'ZipInfo', - 'AuthorizedDomain', - 'DomainMapping', - 'ResourceRecord', - 'SslSettings', - 'FirewallRule', - 'Instance', - 'LocationMetadata', - 'NetworkSettings', - 'CreateVersionMetadataV1', - 'OperationMetadataV1', - 'Service', - 'TrafficSplit', - 'AutomaticScaling', - 'BasicScaling', - 'CpuUtilization', - 'DiskUtilization', - 'EndpointsApiService', - 'Entrypoint', - 'ManualScaling', - 'Network', - 'NetworkUtilization', - 'RequestUtilization', - 'Resources', - 'StandardSchedulerSettings', - 'Version', - 'Volume', - 'VpcAccessConnector', - 'InboundServiceType', - 'ServingStatus', -) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/app_yaml.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/app_yaml.py deleted file mode 100644 index a5b49e2..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/app_yaml.py +++ /dev/null @@ -1,539 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.appengine.v1', - manifest={ - 'AuthFailAction', - 'LoginRequirement', - 'SecurityLevel', - 'ApiConfigHandler', - 'ErrorHandler', - 'UrlMap', - 'StaticFilesHandler', - 'ScriptHandler', - 'ApiEndpointHandler', - 'HealthCheck', - 'ReadinessCheck', - 'LivenessCheck', - 'Library', - }, -) - - -class AuthFailAction(proto.Enum): - r"""Actions to take when the user is not logged in.""" - AUTH_FAIL_ACTION_UNSPECIFIED = 0 - AUTH_FAIL_ACTION_REDIRECT = 1 - AUTH_FAIL_ACTION_UNAUTHORIZED = 2 - - -class LoginRequirement(proto.Enum): - r"""Methods to restrict access to a URL based on login status.""" - LOGIN_UNSPECIFIED = 0 - LOGIN_OPTIONAL = 1 - LOGIN_ADMIN = 2 - LOGIN_REQUIRED = 3 - - -class SecurityLevel(proto.Enum): - r"""Methods to enforce security (HTTPS) on a URL.""" - _pb_options = {'allow_alias': True} - SECURE_UNSPECIFIED = 0 - SECURE_DEFAULT = 0 - SECURE_NEVER = 1 - SECURE_OPTIONAL = 2 - SECURE_ALWAYS = 3 - - -class ApiConfigHandler(proto.Message): - r"""`Google Cloud - Endpoints `__ - configuration for API handlers. - - Attributes: - auth_fail_action (google.cloud.appengine_admin_v1.types.AuthFailAction): - Action to take when users access resources that require - authentication. Defaults to ``redirect``. - login (google.cloud.appengine_admin_v1.types.LoginRequirement): - Level of login required to access this resource. Defaults to - ``optional``. - script (str): - Path to the script from the application root - directory. - security_level (google.cloud.appengine_admin_v1.types.SecurityLevel): - Security (HTTPS) enforcement for this URL. - url (str): - URL to serve the endpoint at. - """ - - auth_fail_action = proto.Field( - proto.ENUM, - number=1, - enum='AuthFailAction', - ) - login = proto.Field( - proto.ENUM, - number=2, - enum='LoginRequirement', - ) - script = proto.Field( - proto.STRING, - number=3, - ) - security_level = proto.Field( - proto.ENUM, - number=4, - enum='SecurityLevel', - ) - url = proto.Field( - proto.STRING, - number=5, - ) - - -class ErrorHandler(proto.Message): - r"""Custom static error page to be served when an error occurs. - Attributes: - error_code (google.cloud.appengine_admin_v1.types.ErrorHandler.ErrorCode): - Error condition this handler applies to. - static_file (str): - Static file content to be served for this - error. - mime_type (str): - MIME type of file. Defaults to ``text/html``. - """ - class ErrorCode(proto.Enum): - r"""Error codes.""" - _pb_options = {'allow_alias': True} - ERROR_CODE_UNSPECIFIED = 0 - ERROR_CODE_DEFAULT = 0 - ERROR_CODE_OVER_QUOTA = 1 - ERROR_CODE_DOS_API_DENIAL = 2 - ERROR_CODE_TIMEOUT = 3 - - error_code = proto.Field( - proto.ENUM, - number=1, - enum=ErrorCode, - ) - static_file = proto.Field( - proto.STRING, - number=2, - ) - mime_type = proto.Field( - proto.STRING, - number=3, - ) - - -class UrlMap(proto.Message): - r"""URL pattern and description of how the URL should be handled. - App Engine can handle URLs by executing application code or by - serving static files uploaded with the version, such as images, - CSS, or JavaScript. - - Attributes: - url_regex (str): - URL prefix. Uses regular expression syntax, - which means regexp special characters must be - escaped, but should not contain groupings. All - URLs that begin with this prefix are handled by - this handler, using the portion of the URL after - the prefix as part of the file path. - static_files (google.cloud.appengine_admin_v1.types.StaticFilesHandler): - Returns the contents of a file, such as an - image, as the response. - script (google.cloud.appengine_admin_v1.types.ScriptHandler): - Executes a script to handle the requests that match this URL - pattern. Only the ``auto`` value is supported for Node.js in - the App Engine standard environment, for example - ``"script": "auto"``. - api_endpoint (google.cloud.appengine_admin_v1.types.ApiEndpointHandler): - Uses API Endpoints to handle requests. - security_level (google.cloud.appengine_admin_v1.types.SecurityLevel): - Security (HTTPS) enforcement for this URL. - login (google.cloud.appengine_admin_v1.types.LoginRequirement): - Level of login required to access this - resource. Not supported for Node.js in the App - Engine standard environment. - auth_fail_action (google.cloud.appengine_admin_v1.types.AuthFailAction): - Action to take when users access resources that require - authentication. Defaults to ``redirect``. - redirect_http_response_code (google.cloud.appengine_admin_v1.types.UrlMap.RedirectHttpResponseCode): - ``30x`` code to use when performing redirects for the - ``secure`` field. Defaults to ``302``. - """ - class RedirectHttpResponseCode(proto.Enum): - r"""Redirect codes.""" - REDIRECT_HTTP_RESPONSE_CODE_UNSPECIFIED = 0 - REDIRECT_HTTP_RESPONSE_CODE_301 = 1 - REDIRECT_HTTP_RESPONSE_CODE_302 = 2 - REDIRECT_HTTP_RESPONSE_CODE_303 = 3 - REDIRECT_HTTP_RESPONSE_CODE_307 = 4 - - url_regex = proto.Field( - proto.STRING, - number=1, - ) - static_files = proto.Field( - proto.MESSAGE, - number=2, - oneof='handler_type', - message='StaticFilesHandler', - ) - script = proto.Field( - proto.MESSAGE, - number=3, - oneof='handler_type', - message='ScriptHandler', - ) - api_endpoint = proto.Field( - proto.MESSAGE, - number=4, - oneof='handler_type', - message='ApiEndpointHandler', - ) - security_level = proto.Field( - proto.ENUM, - number=5, - enum='SecurityLevel', - ) - login = proto.Field( - proto.ENUM, - number=6, - enum='LoginRequirement', - ) - auth_fail_action = proto.Field( - proto.ENUM, - number=7, - enum='AuthFailAction', - ) - redirect_http_response_code = proto.Field( - proto.ENUM, - number=8, - enum=RedirectHttpResponseCode, - ) - - -class StaticFilesHandler(proto.Message): - r"""Files served directly to the user for a given URL, such as - images, CSS stylesheets, or JavaScript source files. Static file - handlers describe which files in the application directory are - static files, and which URLs serve them. - - Attributes: - path (str): - Path to the static files matched by the URL - pattern, from the application root directory. - The path can refer to text matched in groupings - in the URL pattern. - upload_path_regex (str): - Regular expression that matches the file - paths for all files that should be referenced by - this handler. - http_headers (Sequence[google.cloud.appengine_admin_v1.types.StaticFilesHandler.HttpHeadersEntry]): - HTTP headers to use for all responses from - these URLs. - mime_type (str): - MIME type used to serve all files served by - this handler. - Defaults to file-specific MIME types, which are - derived from each file's filename extension. - expiration (google.protobuf.duration_pb2.Duration): - Time a static file served by this handler - should be cached by web proxies and browsers. - require_matching_file (bool): - Whether this handler should match the request - if the file referenced by the handler does not - exist. - application_readable (bool): - Whether files should also be uploaded as code - data. By default, files declared in static file - handlers are uploaded as static data and are - only served to end users; they cannot be read by - the application. If enabled, uploads are charged - against both your code and static data storage - resource quotas. - """ - - path = proto.Field( - proto.STRING, - number=1, - ) - upload_path_regex = proto.Field( - proto.STRING, - number=2, - ) - http_headers = proto.MapField( - proto.STRING, - proto.STRING, - number=3, - ) - mime_type = proto.Field( - proto.STRING, - number=4, - ) - expiration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - require_matching_file = proto.Field( - proto.BOOL, - number=6, - ) - application_readable = proto.Field( - proto.BOOL, - number=7, - ) - - -class ScriptHandler(proto.Message): - r"""Executes a script to handle the request that matches the URL - pattern. - - Attributes: - script_path (str): - Path to the script from the application root - directory. - """ - - script_path = proto.Field( - proto.STRING, - number=1, - ) - - -class ApiEndpointHandler(proto.Message): - r"""Uses Google Cloud Endpoints to handle requests. - Attributes: - script_path (str): - Path to the script from the application root - directory. - """ - - script_path = proto.Field( - proto.STRING, - number=1, - ) - - -class HealthCheck(proto.Message): - r"""Health checking configuration for VM instances. Unhealthy - instances are killed and replaced with new instances. Only - applicable for instances in App Engine flexible environment. - - Attributes: - disable_health_check (bool): - Whether to explicitly disable health checks - for this instance. - host (str): - Host header to send when performing an HTTP - health check. Example: "myapp.appspot.com". - healthy_threshold (int): - Number of consecutive successful health - checks required before receiving traffic. - unhealthy_threshold (int): - Number of consecutive failed health checks - required before removing traffic. - restart_threshold (int): - Number of consecutive failed health checks - required before an instance is restarted. - check_interval (google.protobuf.duration_pb2.Duration): - Interval between health checks. - timeout (google.protobuf.duration_pb2.Duration): - Time before the health check is considered - failed. - """ - - disable_health_check = proto.Field( - proto.BOOL, - number=1, - ) - host = proto.Field( - proto.STRING, - number=2, - ) - healthy_threshold = proto.Field( - proto.UINT32, - number=3, - ) - unhealthy_threshold = proto.Field( - proto.UINT32, - number=4, - ) - restart_threshold = proto.Field( - proto.UINT32, - number=5, - ) - check_interval = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - timeout = proto.Field( - proto.MESSAGE, - number=7, - message=duration_pb2.Duration, - ) - - -class ReadinessCheck(proto.Message): - r"""Readiness checking configuration for VM instances. Unhealthy - instances are removed from traffic rotation. - - Attributes: - path (str): - The request path. - host (str): - Host header to send when performing a HTTP - Readiness check. Example: "myapp.appspot.com". - failure_threshold (int): - Number of consecutive failed checks required - before removing traffic. - success_threshold (int): - Number of consecutive successful checks - required before receiving traffic. - check_interval (google.protobuf.duration_pb2.Duration): - Interval between health checks. - timeout (google.protobuf.duration_pb2.Duration): - Time before the check is considered failed. - app_start_timeout (google.protobuf.duration_pb2.Duration): - A maximum time limit on application - initialization, measured from moment the - application successfully replies to a - healthcheck until it is ready to serve traffic. - """ - - path = proto.Field( - proto.STRING, - number=1, - ) - host = proto.Field( - proto.STRING, - number=2, - ) - failure_threshold = proto.Field( - proto.UINT32, - number=3, - ) - success_threshold = proto.Field( - proto.UINT32, - number=4, - ) - check_interval = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - timeout = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - app_start_timeout = proto.Field( - proto.MESSAGE, - number=7, - message=duration_pb2.Duration, - ) - - -class LivenessCheck(proto.Message): - r"""Health checking configuration for VM instances. Unhealthy - instances are killed and replaced with new instances. - - Attributes: - path (str): - The request path. - host (str): - Host header to send when performing a HTTP - Liveness check. Example: "myapp.appspot.com". - failure_threshold (int): - Number of consecutive failed checks required - before considering the VM unhealthy. - success_threshold (int): - Number of consecutive successful checks - required before considering the VM healthy. - check_interval (google.protobuf.duration_pb2.Duration): - Interval between health checks. - timeout (google.protobuf.duration_pb2.Duration): - Time before the check is considered failed. - initial_delay (google.protobuf.duration_pb2.Duration): - The initial delay before starting to execute - the checks. - """ - - path = proto.Field( - proto.STRING, - number=1, - ) - host = proto.Field( - proto.STRING, - number=2, - ) - failure_threshold = proto.Field( - proto.UINT32, - number=3, - ) - success_threshold = proto.Field( - proto.UINT32, - number=4, - ) - check_interval = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - timeout = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - initial_delay = proto.Field( - proto.MESSAGE, - number=7, - message=duration_pb2.Duration, - ) - - -class Library(proto.Message): - r"""Third-party Python runtime library that is required by the - application. - - Attributes: - name (str): - Name of the library. Example: "django". - version (str): - Version of the library to select, or - "latest". - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - version = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/appengine.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/appengine.py deleted file mode 100644 index 815b78d..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/appengine.py +++ /dev/null @@ -1,1103 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.appengine_admin_v1.types import application as ga_application -from google.cloud.appengine_admin_v1.types import certificate as ga_certificate -from google.cloud.appengine_admin_v1.types import domain -from google.cloud.appengine_admin_v1.types import domain_mapping as ga_domain_mapping -from google.cloud.appengine_admin_v1.types import firewall -from google.cloud.appengine_admin_v1.types import instance -from google.cloud.appengine_admin_v1.types import service as ga_service -from google.cloud.appengine_admin_v1.types import version as ga_version -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.appengine.v1', - manifest={ - 'VersionView', - 'AuthorizedCertificateView', - 'DomainOverrideStrategy', - 'GetApplicationRequest', - 'CreateApplicationRequest', - 'UpdateApplicationRequest', - 'RepairApplicationRequest', - 'ListServicesRequest', - 'ListServicesResponse', - 'GetServiceRequest', - 'UpdateServiceRequest', - 'DeleteServiceRequest', - 'ListVersionsRequest', - 'ListVersionsResponse', - 'GetVersionRequest', - 'CreateVersionRequest', - 'UpdateVersionRequest', - 'DeleteVersionRequest', - 'ListInstancesRequest', - 'ListInstancesResponse', - 'GetInstanceRequest', - 'DeleteInstanceRequest', - 'DebugInstanceRequest', - 'ListIngressRulesRequest', - 'ListIngressRulesResponse', - 'BatchUpdateIngressRulesRequest', - 'BatchUpdateIngressRulesResponse', - 'CreateIngressRuleRequest', - 'GetIngressRuleRequest', - 'UpdateIngressRuleRequest', - 'DeleteIngressRuleRequest', - 'ListAuthorizedDomainsRequest', - 'ListAuthorizedDomainsResponse', - 'ListAuthorizedCertificatesRequest', - 'ListAuthorizedCertificatesResponse', - 'GetAuthorizedCertificateRequest', - 'CreateAuthorizedCertificateRequest', - 'UpdateAuthorizedCertificateRequest', - 'DeleteAuthorizedCertificateRequest', - 'ListDomainMappingsRequest', - 'ListDomainMappingsResponse', - 'GetDomainMappingRequest', - 'CreateDomainMappingRequest', - 'UpdateDomainMappingRequest', - 'DeleteDomainMappingRequest', - }, -) - - -class VersionView(proto.Enum): - r"""Fields that should be returned when - [Version][google.appengine.v1.Version] resources are retrieved. - """ - BASIC = 0 - FULL = 1 - - -class AuthorizedCertificateView(proto.Enum): - r"""Fields that should be returned when an AuthorizedCertificate - resource is retrieved. - """ - BASIC_CERTIFICATE = 0 - FULL_CERTIFICATE = 1 - - -class DomainOverrideStrategy(proto.Enum): - r"""Override strategy for mutating an existing mapping.""" - UNSPECIFIED_DOMAIN_OVERRIDE_STRATEGY = 0 - STRICT = 1 - OVERRIDE = 2 - - -class GetApplicationRequest(proto.Message): - r"""Request message for ``Applications.GetApplication``. - Attributes: - name (str): - Name of the Application resource to get. Example: - ``apps/myapp``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateApplicationRequest(proto.Message): - r"""Request message for ``Applications.CreateApplication``. - Attributes: - application (google.cloud.appengine_admin_v1.types.Application): - Application configuration. - """ - - application = proto.Field( - proto.MESSAGE, - number=2, - message=ga_application.Application, - ) - - -class UpdateApplicationRequest(proto.Message): - r"""Request message for ``Applications.UpdateApplication``. - Attributes: - name (str): - Name of the Application resource to update. Example: - ``apps/myapp``. - application (google.cloud.appengine_admin_v1.types.Application): - An Application containing the updated - resource. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Standard field mask for the set of fields to - be updated. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - application = proto.Field( - proto.MESSAGE, - number=2, - message=ga_application.Application, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class RepairApplicationRequest(proto.Message): - r"""Request message for 'Applications.RepairApplication'. - Attributes: - name (str): - Name of the application to repair. Example: ``apps/myapp`` - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListServicesRequest(proto.Message): - r"""Request message for ``Services.ListServices``. - Attributes: - parent (str): - Name of the parent Application resource. Example: - ``apps/myapp``. - page_size (int): - Maximum results to return per page. - page_token (str): - Continuation token for fetching the next page - of results. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListServicesResponse(proto.Message): - r"""Response message for ``Services.ListServices``. - Attributes: - services (Sequence[google.cloud.appengine_admin_v1.types.Service]): - The services belonging to the requested - application. - next_page_token (str): - Continuation token for fetching the next page - of results. - """ - - @property - def raw_page(self): - return self - - services = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ga_service.Service, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetServiceRequest(proto.Message): - r"""Request message for ``Services.GetService``. - Attributes: - name (str): - Name of the resource requested. Example: - ``apps/myapp/services/default``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateServiceRequest(proto.Message): - r"""Request message for ``Services.UpdateService``. - Attributes: - name (str): - Name of the resource to update. Example: - ``apps/myapp/services/default``. - service (google.cloud.appengine_admin_v1.types.Service): - A Service resource containing the updated - service. Only fields set in the field mask will - be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Standard field mask for the set of fields to - be updated. - migrate_traffic (bool): - Set to ``true`` to gradually shift traffic to one or more - versions that you specify. By default, traffic is shifted - immediately. For gradual traffic migration, the target - versions must be located within instances that are - configured for both `warmup - requests `__ - and `automatic - scaling `__. - You must specify the - ```shardBy`` `__ - field in the Service resource. Gradual traffic migration is - not supported in the App Engine flexible environment. For - examples, see `Migrating and Splitting - Traffic `__. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - service = proto.Field( - proto.MESSAGE, - number=2, - message=ga_service.Service, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - migrate_traffic = proto.Field( - proto.BOOL, - number=4, - ) - - -class DeleteServiceRequest(proto.Message): - r"""Request message for ``Services.DeleteService``. - Attributes: - name (str): - Name of the resource requested. Example: - ``apps/myapp/services/default``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListVersionsRequest(proto.Message): - r"""Request message for ``Versions.ListVersions``. - Attributes: - parent (str): - Name of the parent Service resource. Example: - ``apps/myapp/services/default``. - view (google.cloud.appengine_admin_v1.types.VersionView): - Controls the set of fields returned in the ``List`` - response. - page_size (int): - Maximum results to return per page. - page_token (str): - Continuation token for fetching the next page - of results. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - view = proto.Field( - proto.ENUM, - number=2, - enum='VersionView', - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class ListVersionsResponse(proto.Message): - r"""Response message for ``Versions.ListVersions``. - Attributes: - versions (Sequence[google.cloud.appengine_admin_v1.types.Version]): - The versions belonging to the requested - service. - next_page_token (str): - Continuation token for fetching the next page - of results. - """ - - @property - def raw_page(self): - return self - - versions = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ga_version.Version, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetVersionRequest(proto.Message): - r"""Request message for ``Versions.GetVersion``. - Attributes: - name (str): - Name of the resource requested. Example: - ``apps/myapp/services/default/versions/v1``. - view (google.cloud.appengine_admin_v1.types.VersionView): - Controls the set of fields returned in the ``Get`` response. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - view = proto.Field( - proto.ENUM, - number=2, - enum='VersionView', - ) - - -class CreateVersionRequest(proto.Message): - r"""Request message for ``Versions.CreateVersion``. - Attributes: - parent (str): - Name of the parent resource to create this version under. - Example: ``apps/myapp/services/default``. - version (google.cloud.appengine_admin_v1.types.Version): - Application deployment configuration. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - version = proto.Field( - proto.MESSAGE, - number=2, - message=ga_version.Version, - ) - - -class UpdateVersionRequest(proto.Message): - r"""Request message for ``Versions.UpdateVersion``. - Attributes: - name (str): - Name of the resource to update. Example: - ``apps/myapp/services/default/versions/1``. - version (google.cloud.appengine_admin_v1.types.Version): - A Version containing the updated resource. - Only fields set in the field mask will be - updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Standard field mask for the set of fields to - be updated. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - version = proto.Field( - proto.MESSAGE, - number=2, - message=ga_version.Version, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteVersionRequest(proto.Message): - r"""Request message for ``Versions.DeleteVersion``. - Attributes: - name (str): - Name of the resource requested. Example: - ``apps/myapp/services/default/versions/v1``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListInstancesRequest(proto.Message): - r"""Request message for ``Instances.ListInstances``. - Attributes: - parent (str): - Name of the parent Version resource. Example: - ``apps/myapp/services/default/versions/v1``. - page_size (int): - Maximum results to return per page. - page_token (str): - Continuation token for fetching the next page - of results. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListInstancesResponse(proto.Message): - r"""Response message for ``Instances.ListInstances``. - Attributes: - instances (Sequence[google.cloud.appengine_admin_v1.types.Instance]): - The instances belonging to the requested - version. - next_page_token (str): - Continuation token for fetching the next page - of results. - """ - - @property - def raw_page(self): - return self - - instances = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=instance.Instance, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetInstanceRequest(proto.Message): - r"""Request message for ``Instances.GetInstance``. - Attributes: - name (str): - Name of the resource requested. Example: - ``apps/myapp/services/default/versions/v1/instances/instance-1``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteInstanceRequest(proto.Message): - r"""Request message for ``Instances.DeleteInstance``. - Attributes: - name (str): - Name of the resource requested. Example: - ``apps/myapp/services/default/versions/v1/instances/instance-1``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class DebugInstanceRequest(proto.Message): - r"""Request message for ``Instances.DebugInstance``. - Attributes: - name (str): - Name of the resource requested. Example: - ``apps/myapp/services/default/versions/v1/instances/instance-1``. - ssh_key (str): - Public SSH key to add to the instance. Examples: - - - ``[USERNAME]:ssh-rsa [KEY_VALUE] [USERNAME]`` - - ``[USERNAME]:ssh-rsa [KEY_VALUE] google-ssh {"userName":"[USERNAME]","expireOn":"[EXPIRE_TIME]"}`` - - For more information, see `Adding and Removing SSH - Keys `__. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - ssh_key = proto.Field( - proto.STRING, - number=2, - ) - - -class ListIngressRulesRequest(proto.Message): - r"""Request message for ``Firewall.ListIngressRules``. - Attributes: - parent (str): - Name of the Firewall collection to retrieve. Example: - ``apps/myapp/firewall/ingressRules``. - page_size (int): - Maximum results to return per page. - page_token (str): - Continuation token for fetching the next page - of results. - matching_address (str): - A valid IP Address. If set, only rules - matching this address will be returned. The - first returned rule will be the rule that fires - on requests from this IP. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - matching_address = proto.Field( - proto.STRING, - number=4, - ) - - -class ListIngressRulesResponse(proto.Message): - r"""Response message for ``Firewall.ListIngressRules``. - Attributes: - ingress_rules (Sequence[google.cloud.appengine_admin_v1.types.FirewallRule]): - The ingress FirewallRules for this - application. - next_page_token (str): - Continuation token for fetching the next page - of results. - """ - - @property - def raw_page(self): - return self - - ingress_rules = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=firewall.FirewallRule, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class BatchUpdateIngressRulesRequest(proto.Message): - r"""Request message for ``Firewall.BatchUpdateIngressRules``. - Attributes: - name (str): - Name of the Firewall collection to set. Example: - ``apps/myapp/firewall/ingressRules``. - ingress_rules (Sequence[google.cloud.appengine_admin_v1.types.FirewallRule]): - A list of FirewallRules to replace the - existing set. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - ingress_rules = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=firewall.FirewallRule, - ) - - -class BatchUpdateIngressRulesResponse(proto.Message): - r"""Response message for ``Firewall.UpdateAllIngressRules``. - Attributes: - ingress_rules (Sequence[google.cloud.appengine_admin_v1.types.FirewallRule]): - The full list of ingress FirewallRules for - this application. - """ - - ingress_rules = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=firewall.FirewallRule, - ) - - -class CreateIngressRuleRequest(proto.Message): - r"""Request message for ``Firewall.CreateIngressRule``. - Attributes: - parent (str): - Name of the parent Firewall collection in which to create a - new rule. Example: ``apps/myapp/firewall/ingressRules``. - rule (google.cloud.appengine_admin_v1.types.FirewallRule): - A FirewallRule containing the new resource. - The user may optionally provide a position at - which the new rule will be placed. The positions - define a sequential list starting at 1. If a - rule already exists at the given position, rules - greater than the provided position will be moved - forward by one. - - If no position is provided, the server will - place the rule as the second to last rule in the - sequence before the required default allow-all - or deny-all rule. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - rule = proto.Field( - proto.MESSAGE, - number=2, - message=firewall.FirewallRule, - ) - - -class GetIngressRuleRequest(proto.Message): - r"""Request message for ``Firewall.GetIngressRule``. - Attributes: - name (str): - Name of the Firewall resource to retrieve. Example: - ``apps/myapp/firewall/ingressRules/100``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateIngressRuleRequest(proto.Message): - r"""Request message for ``Firewall.UpdateIngressRule``. - Attributes: - name (str): - Name of the Firewall resource to update. Example: - ``apps/myapp/firewall/ingressRules/100``. - rule (google.cloud.appengine_admin_v1.types.FirewallRule): - A FirewallRule containing the updated - resource - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Standard field mask for the set of fields to - be updated. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - rule = proto.Field( - proto.MESSAGE, - number=2, - message=firewall.FirewallRule, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteIngressRuleRequest(proto.Message): - r"""Request message for ``Firewall.DeleteIngressRule``. - Attributes: - name (str): - Name of the Firewall resource to delete. Example: - ``apps/myapp/firewall/ingressRules/100``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListAuthorizedDomainsRequest(proto.Message): - r"""Request message for ``AuthorizedDomains.ListAuthorizedDomains``. - Attributes: - parent (str): - Name of the parent Application resource. Example: - ``apps/myapp``. - page_size (int): - Maximum results to return per page. - page_token (str): - Continuation token for fetching the next page - of results. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListAuthorizedDomainsResponse(proto.Message): - r"""Response message for ``AuthorizedDomains.ListAuthorizedDomains``. - Attributes: - domains (Sequence[google.cloud.appengine_admin_v1.types.AuthorizedDomain]): - The authorized domains belonging to the user. - next_page_token (str): - Continuation token for fetching the next page - of results. - """ - - @property - def raw_page(self): - return self - - domains = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=domain.AuthorizedDomain, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class ListAuthorizedCertificatesRequest(proto.Message): - r"""Request message for - ``AuthorizedCertificates.ListAuthorizedCertificates``. - - Attributes: - parent (str): - Name of the parent ``Application`` resource. Example: - ``apps/myapp``. - view (google.cloud.appengine_admin_v1.types.AuthorizedCertificateView): - Controls the set of fields returned in the ``LIST`` - response. - page_size (int): - Maximum results to return per page. - page_token (str): - Continuation token for fetching the next page - of results. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - view = proto.Field( - proto.ENUM, - number=4, - enum='AuthorizedCertificateView', - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListAuthorizedCertificatesResponse(proto.Message): - r"""Response message for - ``AuthorizedCertificates.ListAuthorizedCertificates``. - - Attributes: - certificates (Sequence[google.cloud.appengine_admin_v1.types.AuthorizedCertificate]): - The SSL certificates the user is authorized - to administer. - next_page_token (str): - Continuation token for fetching the next page - of results. - """ - - @property - def raw_page(self): - return self - - certificates = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ga_certificate.AuthorizedCertificate, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetAuthorizedCertificateRequest(proto.Message): - r"""Request message for - ``AuthorizedCertificates.GetAuthorizedCertificate``. - - Attributes: - name (str): - Name of the resource requested. Example: - ``apps/myapp/authorizedCertificates/12345``. - view (google.cloud.appengine_admin_v1.types.AuthorizedCertificateView): - Controls the set of fields returned in the ``GET`` response. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - view = proto.Field( - proto.ENUM, - number=2, - enum='AuthorizedCertificateView', - ) - - -class CreateAuthorizedCertificateRequest(proto.Message): - r"""Request message for - ``AuthorizedCertificates.CreateAuthorizedCertificate``. - - Attributes: - parent (str): - Name of the parent ``Application`` resource. Example: - ``apps/myapp``. - certificate (google.cloud.appengine_admin_v1.types.AuthorizedCertificate): - SSL certificate data. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - certificate = proto.Field( - proto.MESSAGE, - number=2, - message=ga_certificate.AuthorizedCertificate, - ) - - -class UpdateAuthorizedCertificateRequest(proto.Message): - r"""Request message for - ``AuthorizedCertificates.UpdateAuthorizedCertificate``. - - Attributes: - name (str): - Name of the resource to update. Example: - ``apps/myapp/authorizedCertificates/12345``. - certificate (google.cloud.appengine_admin_v1.types.AuthorizedCertificate): - An ``AuthorizedCertificate`` containing the updated - resource. Only fields set in the field mask will be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Standard field mask for the set of fields to be updated. - Updates are only supported on the ``certificate_raw_data`` - and ``display_name`` fields. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - certificate = proto.Field( - proto.MESSAGE, - number=2, - message=ga_certificate.AuthorizedCertificate, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteAuthorizedCertificateRequest(proto.Message): - r"""Request message for - ``AuthorizedCertificates.DeleteAuthorizedCertificate``. - - Attributes: - name (str): - Name of the resource to delete. Example: - ``apps/myapp/authorizedCertificates/12345``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ListDomainMappingsRequest(proto.Message): - r"""Request message for ``DomainMappings.ListDomainMappings``. - Attributes: - parent (str): - Name of the parent Application resource. Example: - ``apps/myapp``. - page_size (int): - Maximum results to return per page. - page_token (str): - Continuation token for fetching the next page - of results. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class ListDomainMappingsResponse(proto.Message): - r"""Response message for ``DomainMappings.ListDomainMappings``. - Attributes: - domain_mappings (Sequence[google.cloud.appengine_admin_v1.types.DomainMapping]): - The domain mappings for the application. - next_page_token (str): - Continuation token for fetching the next page - of results. - """ - - @property - def raw_page(self): - return self - - domain_mappings = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ga_domain_mapping.DomainMapping, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetDomainMappingRequest(proto.Message): - r"""Request message for ``DomainMappings.GetDomainMapping``. - Attributes: - name (str): - Name of the resource requested. Example: - ``apps/myapp/domainMappings/example.com``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateDomainMappingRequest(proto.Message): - r"""Request message for ``DomainMappings.CreateDomainMapping``. - Attributes: - parent (str): - Name of the parent Application resource. Example: - ``apps/myapp``. - domain_mapping (google.cloud.appengine_admin_v1.types.DomainMapping): - Domain mapping configuration. - override_strategy (google.cloud.appengine_admin_v1.types.DomainOverrideStrategy): - Whether the domain creation should override - any existing mappings for this domain. By - default, overrides are rejected. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - domain_mapping = proto.Field( - proto.MESSAGE, - number=2, - message=ga_domain_mapping.DomainMapping, - ) - override_strategy = proto.Field( - proto.ENUM, - number=4, - enum='DomainOverrideStrategy', - ) - - -class UpdateDomainMappingRequest(proto.Message): - r"""Request message for ``DomainMappings.UpdateDomainMapping``. - Attributes: - name (str): - Name of the resource to update. Example: - ``apps/myapp/domainMappings/example.com``. - domain_mapping (google.cloud.appengine_admin_v1.types.DomainMapping): - A domain mapping containing the updated - resource. Only fields set in the field mask will - be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Standard field mask for the set of fields to - be updated. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - domain_mapping = proto.Field( - proto.MESSAGE, - number=2, - message=ga_domain_mapping.DomainMapping, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteDomainMappingRequest(proto.Message): - r"""Request message for ``DomainMappings.DeleteDomainMapping``. - Attributes: - name (str): - Name of the resource to delete. Example: - ``apps/myapp/domainMappings/example.com``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/application.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/application.py deleted file mode 100644 index dbcf39d..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/application.py +++ /dev/null @@ -1,284 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.appengine.v1', - manifest={ - 'Application', - 'UrlDispatchRule', - }, -) - - -class Application(proto.Message): - r"""An Application resource contains the top-level configuration - of an App Engine application. - - Attributes: - name (str): - Full path to the Application resource in the API. Example: - ``apps/myapp``. - - @OutputOnly - id (str): - Identifier of the Application resource. This identifier is - equivalent to the project ID of the Google Cloud Platform - project where you want to deploy your application. Example: - ``myapp``. - dispatch_rules (Sequence[google.cloud.appengine_admin_v1.types.UrlDispatchRule]): - HTTP path dispatch rules for requests to the - application that do not explicitly target a - service or version. Rules are order-dependent. - Up to 20 dispatch rules can be supported. - auth_domain (str): - Google Apps authentication domain that - controls which users can access this - application. - Defaults to open access for any Google Account. - location_id (str): - Location from which this application runs. Application - instances run out of the data centers in the specified - location, which is also where all of the application's end - user content is stored. - - Defaults to ``us-central``. - - View the list of `supported - locations `__. - code_bucket (str): - Google Cloud Storage bucket that can be used - for storing files associated with this - application. This bucket is associated with the - application and can be used by the gcloud - deployment commands. - @OutputOnly - default_cookie_expiration (google.protobuf.duration_pb2.Duration): - Cookie expiration policy for this - application. - serving_status (google.cloud.appengine_admin_v1.types.Application.ServingStatus): - Serving status of this application. - default_hostname (str): - Hostname used to reach this application, as - resolved by App Engine. - @OutputOnly - default_bucket (str): - Google Cloud Storage bucket that can be used - by this application to store content. - - @OutputOnly - iap (google.cloud.appengine_admin_v1.types.Application.IdentityAwareProxy): - - gcr_domain (str): - The Google Container Registry domain used for - storing managed build docker images for this - application. - database_type (google.cloud.appengine_admin_v1.types.Application.DatabaseType): - The type of the Cloud Firestore or Cloud - Datastore database associated with this - application. - feature_settings (google.cloud.appengine_admin_v1.types.Application.FeatureSettings): - The feature specific settings to be used in - the application. - """ - class ServingStatus(proto.Enum): - r"""""" - UNSPECIFIED = 0 - SERVING = 1 - USER_DISABLED = 2 - SYSTEM_DISABLED = 3 - - class DatabaseType(proto.Enum): - r"""""" - DATABASE_TYPE_UNSPECIFIED = 0 - CLOUD_DATASTORE = 1 - CLOUD_FIRESTORE = 2 - CLOUD_DATASTORE_COMPATIBILITY = 3 - - class IdentityAwareProxy(proto.Message): - r"""Identity-Aware Proxy - Attributes: - enabled (bool): - Whether the serving infrastructure will authenticate and - authorize all incoming requests. - - If true, the ``oauth2_client_id`` and - ``oauth2_client_secret`` fields must be non-empty. - oauth2_client_id (str): - OAuth2 client ID to use for the - authentication flow. - oauth2_client_secret (str): - OAuth2 client secret to use for the authentication flow. - - For security reasons, this value cannot be retrieved via the - API. Instead, the SHA-256 hash of the value is returned in - the ``oauth2_client_secret_sha256`` field. - - @InputOnly - oauth2_client_secret_sha256 (str): - Hex-encoded SHA-256 hash of the client - secret. - @OutputOnly - """ - - enabled = proto.Field( - proto.BOOL, - number=1, - ) - oauth2_client_id = proto.Field( - proto.STRING, - number=2, - ) - oauth2_client_secret = proto.Field( - proto.STRING, - number=3, - ) - oauth2_client_secret_sha256 = proto.Field( - proto.STRING, - number=4, - ) - - class FeatureSettings(proto.Message): - r"""The feature specific settings to be used in the application. - These define behaviors that are user configurable. - - Attributes: - split_health_checks (bool): - Boolean value indicating if split health checks should be - used instead of the legacy health checks. At an app.yaml - level, this means defaulting to 'readiness_check' and - 'liveness_check' values instead of 'health_check' ones. Once - the legacy 'health_check' behavior is deprecated, and this - value is always true, this setting can be removed. - use_container_optimized_os (bool): - If true, use `Container-Optimized - OS `__ - base image for VMs, rather than a base Debian image. - """ - - split_health_checks = proto.Field( - proto.BOOL, - number=1, - ) - use_container_optimized_os = proto.Field( - proto.BOOL, - number=2, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - id = proto.Field( - proto.STRING, - number=2, - ) - dispatch_rules = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='UrlDispatchRule', - ) - auth_domain = proto.Field( - proto.STRING, - number=6, - ) - location_id = proto.Field( - proto.STRING, - number=7, - ) - code_bucket = proto.Field( - proto.STRING, - number=8, - ) - default_cookie_expiration = proto.Field( - proto.MESSAGE, - number=9, - message=duration_pb2.Duration, - ) - serving_status = proto.Field( - proto.ENUM, - number=10, - enum=ServingStatus, - ) - default_hostname = proto.Field( - proto.STRING, - number=11, - ) - default_bucket = proto.Field( - proto.STRING, - number=12, - ) - iap = proto.Field( - proto.MESSAGE, - number=14, - message=IdentityAwareProxy, - ) - gcr_domain = proto.Field( - proto.STRING, - number=16, - ) - database_type = proto.Field( - proto.ENUM, - number=17, - enum=DatabaseType, - ) - feature_settings = proto.Field( - proto.MESSAGE, - number=18, - message=FeatureSettings, - ) - - -class UrlDispatchRule(proto.Message): - r"""Rules to match an HTTP request and dispatch that request to a - service. - - Attributes: - domain (str): - Domain name to match against. The wildcard "``*``" is - supported if specified before a period: "``*.``". - - Defaults to matching all domains: "``*``". - path (str): - Pathname within the host. Must start with a "``/``". A - single "``*``" can be included at the end of the path. - - The sum of the lengths of the domain and path may not exceed - 100 characters. - service (str): - Resource ID of a service in this application that should - serve the matched request. The service must already exist. - Example: ``default``. - """ - - domain = proto.Field( - proto.STRING, - number=1, - ) - path = proto.Field( - proto.STRING, - number=2, - ) - service = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/audit_data.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/audit_data.py deleted file mode 100644 index 9dbb7e8..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/audit_data.py +++ /dev/null @@ -1,84 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.appengine_admin_v1.types import appengine - - -__protobuf__ = proto.module( - package='google.appengine.v1', - manifest={ - 'AuditData', - 'UpdateServiceMethod', - 'CreateVersionMethod', - }, -) - - -class AuditData(proto.Message): - r"""App Engine admin service audit log. - Attributes: - update_service (google.cloud.appengine_admin_v1.types.UpdateServiceMethod): - Detailed information about UpdateService - call. - create_version (google.cloud.appengine_admin_v1.types.CreateVersionMethod): - Detailed information about CreateVersion - call. - """ - - update_service = proto.Field( - proto.MESSAGE, - number=1, - oneof='method', - message='UpdateServiceMethod', - ) - create_version = proto.Field( - proto.MESSAGE, - number=2, - oneof='method', - message='CreateVersionMethod', - ) - - -class UpdateServiceMethod(proto.Message): - r"""Detailed information about UpdateService call. - Attributes: - request (google.cloud.appengine_admin_v1.types.UpdateServiceRequest): - Update service request. - """ - - request = proto.Field( - proto.MESSAGE, - number=1, - message=appengine.UpdateServiceRequest, - ) - - -class CreateVersionMethod(proto.Message): - r"""Detailed information about CreateVersion call. - Attributes: - request (google.cloud.appengine_admin_v1.types.CreateVersionRequest): - Create version request. - """ - - request = proto.Field( - proto.MESSAGE, - number=1, - message=appengine.CreateVersionRequest, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/certificate.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/certificate.py deleted file mode 100644 index 72c6776..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/certificate.py +++ /dev/null @@ -1,229 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.appengine.v1', - manifest={ - 'ManagementStatus', - 'AuthorizedCertificate', - 'CertificateRawData', - 'ManagedCertificate', - }, -) - - -class ManagementStatus(proto.Enum): - r"""State of certificate management. Refers to the most recent - certificate acquisition or renewal attempt. - """ - MANAGEMENT_STATUS_UNSPECIFIED = 0 - OK = 1 - PENDING = 2 - FAILED_RETRYING_NOT_VISIBLE = 4 - FAILED_PERMANENT = 6 - FAILED_RETRYING_CAA_FORBIDDEN = 7 - FAILED_RETRYING_CAA_CHECKING = 8 - - -class AuthorizedCertificate(proto.Message): - r"""An SSL certificate that a user has been authorized to - administer. A user is authorized to administer any certificate - that applies to one of their authorized domains. - - Attributes: - name (str): - Full path to the ``AuthorizedCertificate`` resource in the - API. Example: ``apps/myapp/authorizedCertificates/12345``. - - @OutputOnly - id (str): - Relative name of the certificate. This is a unique value - autogenerated on ``AuthorizedCertificate`` resource - creation. Example: ``12345``. - - @OutputOnly - display_name (str): - The user-specified display name of the certificate. This is - not guaranteed to be unique. Example: ``My Certificate``. - domain_names (Sequence[str]): - Topmost applicable domains of this certificate. This - certificate applies to these domains and their subdomains. - Example: ``example.com``. - - @OutputOnly - expire_time (google.protobuf.timestamp_pb2.Timestamp): - The time when this certificate expires. To update the - renewal time on this certificate, upload an SSL certificate - with a different expiration time using - ```AuthorizedCertificates.UpdateAuthorizedCertificate`` <>`__. - - @OutputOnly - certificate_raw_data (google.cloud.appengine_admin_v1.types.CertificateRawData): - The SSL certificate serving the ``AuthorizedCertificate`` - resource. This must be obtained independently from a - certificate authority. - managed_certificate (google.cloud.appengine_admin_v1.types.ManagedCertificate): - Only applicable if this certificate is managed by App - Engine. Managed certificates are tied to the lifecycle of a - ``DomainMapping`` and cannot be updated or deleted via the - ``AuthorizedCertificates`` API. If this certificate is - manually administered by the user, this field will be empty. - - @OutputOnly - visible_domain_mappings (Sequence[str]): - The full paths to user visible Domain Mapping resources that - have this certificate mapped. Example: - ``apps/myapp/domainMappings/example.com``. - - This may not represent the full list of mapped domain - mappings if the user does not have ``VIEWER`` permissions on - all of the applications that have this certificate mapped. - See ``domain_mappings_count`` for a complete count. - - Only returned by ``GET`` or ``LIST`` requests when - specifically requested by the ``view=FULL_CERTIFICATE`` - option. - - @OutputOnly - domain_mappings_count (int): - Aggregate count of the domain mappings with this certificate - mapped. This count includes domain mappings on applications - for which the user does not have ``VIEWER`` permissions. - - Only returned by ``GET`` or ``LIST`` requests when - specifically requested by the ``view=FULL_CERTIFICATE`` - option. - - @OutputOnly - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - id = proto.Field( - proto.STRING, - number=2, - ) - display_name = proto.Field( - proto.STRING, - number=3, - ) - domain_names = proto.RepeatedField( - proto.STRING, - number=4, - ) - expire_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - certificate_raw_data = proto.Field( - proto.MESSAGE, - number=6, - message='CertificateRawData', - ) - managed_certificate = proto.Field( - proto.MESSAGE, - number=7, - message='ManagedCertificate', - ) - visible_domain_mappings = proto.RepeatedField( - proto.STRING, - number=8, - ) - domain_mappings_count = proto.Field( - proto.INT32, - number=9, - ) - - -class CertificateRawData(proto.Message): - r"""An SSL certificate obtained from a certificate authority. - Attributes: - public_certificate (str): - PEM encoded x.509 public key certificate. This field is set - once on certificate creation. Must include the header and - footer. Example: - - .. raw:: html - -

-                -----BEGIN CERTIFICATE-----
-                
-                -----END CERTIFICATE-----
-                
- private_key (str): - Unencrypted PEM encoded RSA private key. This field is set - once on certificate creation and then encrypted. The key - size must be 2048 bits or fewer. Must include the header and - footer. Example: - - .. raw:: html - -
-                -----BEGIN RSA PRIVATE KEY-----
-                
-                -----END RSA PRIVATE KEY-----
-                
- - @InputOnly - """ - - public_certificate = proto.Field( - proto.STRING, - number=1, - ) - private_key = proto.Field( - proto.STRING, - number=2, - ) - - -class ManagedCertificate(proto.Message): - r"""A certificate managed by App Engine. - Attributes: - last_renewal_time (google.protobuf.timestamp_pb2.Timestamp): - Time at which the certificate was last renewed. The renewal - process is fully managed. Certificate renewal will - automatically occur before the certificate expires. Renewal - errors can be tracked via ``ManagementStatus``. - - @OutputOnly - status (google.cloud.appengine_admin_v1.types.ManagementStatus): - Status of certificate management. Refers to - the most recent certificate acquisition or - renewal attempt. - @OutputOnly - """ - - last_renewal_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - status = proto.Field( - proto.ENUM, - number=2, - enum='ManagementStatus', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/deploy.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/deploy.py deleted file mode 100644 index 175cc77..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/deploy.py +++ /dev/null @@ -1,191 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.appengine.v1', - manifest={ - 'Deployment', - 'FileInfo', - 'ContainerInfo', - 'CloudBuildOptions', - 'ZipInfo', - }, -) - - -class Deployment(proto.Message): - r"""Code and application artifacts used to deploy a version to - App Engine. - - Attributes: - files (Sequence[google.cloud.appengine_admin_v1.types.Deployment.FilesEntry]): - Manifest of the files stored in Google Cloud - Storage that are included as part of this - version. All files must be readable using the - credentials supplied with this call. - container (google.cloud.appengine_admin_v1.types.ContainerInfo): - The Docker image for the container that runs - the version. Only applicable for instances - running in the App Engine flexible environment. - zip_ (google.cloud.appengine_admin_v1.types.ZipInfo): - The zip file for this deployment, if this is - a zip deployment. - cloud_build_options (google.cloud.appengine_admin_v1.types.CloudBuildOptions): - Options for any Google Cloud Build builds - created as a part of this deployment. - - These options will only be used if a new build - is created, such as when deploying to the App - Engine flexible environment using files or zip. - """ - - files = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message='FileInfo', - ) - container = proto.Field( - proto.MESSAGE, - number=2, - message='ContainerInfo', - ) - zip_ = proto.Field( - proto.MESSAGE, - number=3, - message='ZipInfo', - ) - cloud_build_options = proto.Field( - proto.MESSAGE, - number=6, - message='CloudBuildOptions', - ) - - -class FileInfo(proto.Message): - r"""Single source file that is part of the version to be - deployed. Each source file that is deployed must be specified - separately. - - Attributes: - source_url (str): - URL source to use to fetch this file. Must be - a URL to a resource in Google Cloud Storage in - the form - 'http(s)://storage.googleapis.com/\/\'. - sha1_sum (str): - The SHA1 hash of the file, in hex. - mime_type (str): - The MIME type of the file. - Defaults to the value from Google Cloud Storage. - """ - - source_url = proto.Field( - proto.STRING, - number=1, - ) - sha1_sum = proto.Field( - proto.STRING, - number=2, - ) - mime_type = proto.Field( - proto.STRING, - number=3, - ) - - -class ContainerInfo(proto.Message): - r"""Docker image that is used to create a container and start a - VM instance for the version that you deploy. Only applicable for - instances running in the App Engine flexible environment. - - Attributes: - image (str): - URI to the hosted container image in Google - Container Registry. The URI must be fully - qualified and include a tag or digest. Examples: - "gcr.io/my-project/image:tag" or "gcr.io/my- - project/image@digest". - """ - - image = proto.Field( - proto.STRING, - number=1, - ) - - -class CloudBuildOptions(proto.Message): - r"""Options for the build operations performed as a part of the - version deployment. Only applicable for App Engine flexible - environment when creating a version using source code directly. - - Attributes: - app_yaml_path (str): - Path to the yaml file used in deployment, - used to determine runtime configuration details. - Required for flexible environment builds. - - See - https://cloud.google.com/appengine/docs/standard/python/config/appref - for more details. - cloud_build_timeout (google.protobuf.duration_pb2.Duration): - The Cloud Build timeout used as part of any - dependent builds performed by version creation. - Defaults to 10 minutes. - """ - - app_yaml_path = proto.Field( - proto.STRING, - number=1, - ) - cloud_build_timeout = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -class ZipInfo(proto.Message): - r"""The zip file information for a zip deployment. - Attributes: - source_url (str): - URL of the zip file to deploy from. Must be a - URL to a resource in Google Cloud Storage in the - form - 'http(s)://storage.googleapis.com/\/\'. - files_count (int): - An estimate of the number of files in a zip - for a zip deployment. If set, must be greater - than or equal to the actual number of files. - Used for optimizing performance; if not - provided, deployment may be slow. - """ - - source_url = proto.Field( - proto.STRING, - number=3, - ) - files_count = proto.Field( - proto.INT32, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/deployed_files.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/deployed_files.py deleted file mode 100644 index e9fa874..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/deployed_files.py +++ /dev/null @@ -1,25 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - - -__protobuf__ = proto.module( - package='google.appengine.v1', - manifest={ - }, -) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/domain.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/domain.py deleted file mode 100644 index d237853..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/domain.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.appengine.v1', - manifest={ - 'AuthorizedDomain', - }, -) - - -class AuthorizedDomain(proto.Message): - r"""A domain that a user has been authorized to administer. To authorize - use of a domain, verify ownership via `Webmaster - Central `__. - - Attributes: - name (str): - Full path to the ``AuthorizedDomain`` resource in the API. - Example: ``apps/myapp/authorizedDomains/example.com``. - - @OutputOnly - id (str): - Fully qualified domain name of the domain authorized for - use. Example: ``example.com``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - id = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/domain_mapping.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/domain_mapping.py deleted file mode 100644 index 1f0e515..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/domain_mapping.py +++ /dev/null @@ -1,161 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.appengine.v1', - manifest={ - 'DomainMapping', - 'SslSettings', - 'ResourceRecord', - }, -) - - -class DomainMapping(proto.Message): - r"""A domain serving an App Engine application. - Attributes: - name (str): - Full path to the ``DomainMapping`` resource in the API. - Example: ``apps/myapp/domainMapping/example.com``. - - @OutputOnly - id (str): - Relative name of the domain serving the application. - Example: ``example.com``. - ssl_settings (google.cloud.appengine_admin_v1.types.SslSettings): - SSL configuration for this domain. If - unconfigured, this domain will not serve with - SSL. - resource_records (Sequence[google.cloud.appengine_admin_v1.types.ResourceRecord]): - The resource records required to configure - this domain mapping. These records must be added - to the domain's DNS configuration in order to - serve the application via this domain mapping. - @OutputOnly - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - id = proto.Field( - proto.STRING, - number=2, - ) - ssl_settings = proto.Field( - proto.MESSAGE, - number=3, - message='SslSettings', - ) - resource_records = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='ResourceRecord', - ) - - -class SslSettings(proto.Message): - r"""SSL configuration for a ``DomainMapping`` resource. - Attributes: - certificate_id (str): - ID of the ``AuthorizedCertificate`` resource configuring SSL - for the application. Clearing this field will remove SSL - support. - - By default, a managed certificate is automatically created - for every domain mapping. To omit SSL support or to - configure SSL manually, specify ``SslManagementType.MANUAL`` - on a ``CREATE`` or ``UPDATE`` request. You must be - authorized to administer the ``AuthorizedCertificate`` - resource to manually map it to a ``DomainMapping`` resource. - Example: ``12345``. - ssl_management_type (google.cloud.appengine_admin_v1.types.SslSettings.SslManagementType): - SSL management type for this domain. If ``AUTOMATIC``, a - managed certificate is automatically provisioned. If - ``MANUAL``, ``certificate_id`` must be manually specified in - order to configure SSL for this domain. - pending_managed_certificate_id (str): - ID of the managed ``AuthorizedCertificate`` resource - currently being provisioned, if applicable. Until the new - managed certificate has been successfully provisioned, the - previous SSL state will be preserved. Once the provisioning - process completes, the ``certificate_id`` field will reflect - the new managed certificate and this field will be left - empty. To remove SSL support while there is still a pending - managed certificate, clear the ``certificate_id`` field with - an ``UpdateDomainMappingRequest``. - - @OutputOnly - """ - class SslManagementType(proto.Enum): - r"""The SSL management type for this domain.""" - SSL_MANAGEMENT_TYPE_UNSPECIFIED = 0 - AUTOMATIC = 1 - MANUAL = 2 - - certificate_id = proto.Field( - proto.STRING, - number=1, - ) - ssl_management_type = proto.Field( - proto.ENUM, - number=3, - enum=SslManagementType, - ) - pending_managed_certificate_id = proto.Field( - proto.STRING, - number=4, - ) - - -class ResourceRecord(proto.Message): - r"""A DNS resource record. - Attributes: - name (str): - Relative name of the object affected by this record. Only - applicable for ``CNAME`` records. Example: 'www'. - rrdata (str): - Data for this record. Values vary by record - type, as defined in RFC 1035 (section 5) and RFC - 1034 (section 3.6.1). - type_ (google.cloud.appengine_admin_v1.types.ResourceRecord.RecordType): - Resource record type. Example: ``AAAA``. - """ - class RecordType(proto.Enum): - r"""A resource record type.""" - RECORD_TYPE_UNSPECIFIED = 0 - A = 1 - AAAA = 2 - CNAME = 3 - - name = proto.Field( - proto.STRING, - number=1, - ) - rrdata = proto.Field( - proto.STRING, - number=2, - ) - type_ = proto.Field( - proto.ENUM, - number=3, - enum=RecordType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/firewall.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/firewall.py deleted file mode 100644 index f426b35..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/firewall.py +++ /dev/null @@ -1,86 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.appengine.v1', - manifest={ - 'FirewallRule', - }, -) - - -class FirewallRule(proto.Message): - r"""A single firewall rule that is evaluated against incoming - traffic and provides an action to take on matched requests. - - Attributes: - priority (int): - A positive integer between [1, Int32.MaxValue-1] that - defines the order of rule evaluation. Rules with the lowest - priority are evaluated first. - - A default rule at priority Int32.MaxValue matches all IPv4 - and IPv6 traffic when no previous rule matches. Only the - action of this rule can be modified by the user. - action (google.cloud.appengine_admin_v1.types.FirewallRule.Action): - The action to take on matched requests. - source_range (str): - IP address or range, defined using CIDR notation, of - requests that this rule applies to. You can use the wildcard - character "*" to match all IPs equivalent to "0/0" and - "::/0" together. Examples: ``192.168.1.1`` or - ``192.168.0.0/16`` or ``2001:db8::/32`` or - ``2001:0db8:0000:0042:0000:8a2e:0370:7334``. - - .. raw:: html - -

Truncation will be silently performed on addresses which are not - properly truncated. For example, `1.2.3.4/24` is accepted as the same - address as `1.2.3.0/24`. Similarly, for IPv6, `2001:db8::1/32` is accepted - as the same address as `2001:db8::/32`. - description (str): - An optional string description of this rule. - This field has a maximum length of 100 - characters. - """ - class Action(proto.Enum): - r"""Available actions to take on matching requests.""" - UNSPECIFIED_ACTION = 0 - ALLOW = 1 - DENY = 2 - - priority = proto.Field( - proto.INT32, - number=1, - ) - action = proto.Field( - proto.ENUM, - number=2, - enum=Action, - ) - source_range = proto.Field( - proto.STRING, - number=3, - ) - description = proto.Field( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/instance.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/instance.py deleted file mode 100644 index 8a02aa3..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/instance.py +++ /dev/null @@ -1,183 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.appengine.v1', - manifest={ - 'Instance', - }, -) - - -class Instance(proto.Message): - r"""An Instance resource is the computing unit that App Engine - uses to automatically scale an application. - - Attributes: - name (str): - Output only. Full path to the Instance resource in the API. - Example: - ``apps/myapp/services/default/versions/v1/instances/instance-1``. - id (str): - Output only. Relative name of the instance within the - version. Example: ``instance-1``. - app_engine_release (str): - Output only. App Engine release this instance - is running on. - availability (google.cloud.appengine_admin_v1.types.Instance.Availability): - Output only. Availability of the instance. - vm_name (str): - Output only. Name of the virtual machine - where this instance lives. Only applicable for - instances in App Engine flexible environment. - vm_zone_name (str): - Output only. Zone where the virtual machine - is located. Only applicable for instances in App - Engine flexible environment. - vm_id (str): - Output only. Virtual machine ID of this - instance. Only applicable for instances in App - Engine flexible environment. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time that this instance was - started. - @OutputOnly - requests (int): - Output only. Number of requests since this - instance was started. - errors (int): - Output only. Number of errors since this - instance was started. - qps (float): - Output only. Average queries per second (QPS) - over the last minute. - average_latency (int): - Output only. Average latency (ms) over the - last minute. - memory_usage (int): - Output only. Total memory in use (bytes). - vm_status (str): - Output only. Status of the virtual machine - where this instance lives. Only applicable for - instances in App Engine flexible environment. - vm_debug_enabled (bool): - Output only. Whether this instance is in - debug mode. Only applicable for instances in App - Engine flexible environment. - vm_ip (str): - Output only. The IP address of this instance. - Only applicable for instances in App Engine - flexible environment. - vm_liveness (google.cloud.appengine_admin_v1.types.Instance.Liveness.LivenessState): - Output only. The liveness health check of - this instance. Only applicable for instances in - App Engine flexible environment. - """ - class Availability(proto.Enum): - r"""Availability of the instance.""" - UNSPECIFIED = 0 - RESIDENT = 1 - DYNAMIC = 2 - - class Liveness(proto.Message): - r"""Wrapper for LivenessState enum. """ - class LivenessState(proto.Enum): - r"""Liveness health check status for Flex instances.""" - LIVENESS_STATE_UNSPECIFIED = 0 - UNKNOWN = 1 - HEALTHY = 2 - UNHEALTHY = 3 - DRAINING = 4 - TIMEOUT = 5 - - name = proto.Field( - proto.STRING, - number=1, - ) - id = proto.Field( - proto.STRING, - number=2, - ) - app_engine_release = proto.Field( - proto.STRING, - number=3, - ) - availability = proto.Field( - proto.ENUM, - number=4, - enum=Availability, - ) - vm_name = proto.Field( - proto.STRING, - number=5, - ) - vm_zone_name = proto.Field( - proto.STRING, - number=6, - ) - vm_id = proto.Field( - proto.STRING, - number=7, - ) - start_time = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - requests = proto.Field( - proto.INT32, - number=9, - ) - errors = proto.Field( - proto.INT32, - number=10, - ) - qps = proto.Field( - proto.FLOAT, - number=11, - ) - average_latency = proto.Field( - proto.INT32, - number=12, - ) - memory_usage = proto.Field( - proto.INT64, - number=13, - ) - vm_status = proto.Field( - proto.STRING, - number=14, - ) - vm_debug_enabled = proto.Field( - proto.BOOL, - number=15, - ) - vm_ip = proto.Field( - proto.STRING, - number=16, - ) - vm_liveness = proto.Field( - proto.ENUM, - number=17, - enum=Liveness.LivenessState, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/location.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/location.py deleted file mode 100644 index 73a0dd3..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/location.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.appengine.v1', - manifest={ - 'LocationMetadata', - }, -) - - -class LocationMetadata(proto.Message): - r"""Metadata for the given - [google.cloud.location.Location][google.cloud.location.Location]. - - Attributes: - standard_environment_available (bool): - App Engine standard environment is available - in the given location. - @OutputOnly - flexible_environment_available (bool): - App Engine flexible environment is available - in the given location. - @OutputOnly - search_api_available (bool): - Output only. `Search - API `__ - is available in the given location. - """ - - standard_environment_available = proto.Field( - proto.BOOL, - number=2, - ) - flexible_environment_available = proto.Field( - proto.BOOL, - number=4, - ) - search_api_available = proto.Field( - proto.BOOL, - number=6, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/network_settings.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/network_settings.py deleted file mode 100644 index dd6950e..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/network_settings.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.appengine.v1', - manifest={ - 'NetworkSettings', - }, -) - - -class NetworkSettings(proto.Message): - r"""A NetworkSettings resource is a container for ingress - settings for a version or service. - - Attributes: - ingress_traffic_allowed (google.cloud.appengine_admin_v1.types.NetworkSettings.IngressTrafficAllowed): - The ingress settings for version or service. - """ - class IngressTrafficAllowed(proto.Enum): - r"""If unspecified, INGRESS_TRAFFIC_ALLOWED_ALL will be used.""" - INGRESS_TRAFFIC_ALLOWED_UNSPECIFIED = 0 - INGRESS_TRAFFIC_ALLOWED_ALL = 1 - INGRESS_TRAFFIC_ALLOWED_INTERNAL_ONLY = 2 - INGRESS_TRAFFIC_ALLOWED_INTERNAL_AND_LB = 3 - - ingress_traffic_allowed = proto.Field( - proto.ENUM, - number=1, - enum=IngressTrafficAllowed, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/operation.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/operation.py deleted file mode 100644 index 1cedf75..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/operation.py +++ /dev/null @@ -1,120 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.appengine.v1', - manifest={ - 'OperationMetadataV1', - 'CreateVersionMetadataV1', - }, -) - - -class OperationMetadataV1(proto.Message): - r"""Metadata for the given - [google.longrunning.Operation][google.longrunning.Operation]. - - Attributes: - method (str): - API method that initiated this operation. Example: - ``google.appengine.v1.Versions.CreateVersion``. - - @OutputOnly - insert_time (google.protobuf.timestamp_pb2.Timestamp): - Time that this operation was created. - @OutputOnly - end_time (google.protobuf.timestamp_pb2.Timestamp): - Time that this operation completed. - @OutputOnly - user (str): - User who requested this operation. - @OutputOnly - target (str): - Name of the resource that this operation is acting on. - Example: ``apps/myapp/services/default``. - - @OutputOnly - ephemeral_message (str): - Ephemeral message that may change every time - the operation is polled. @OutputOnly - warning (Sequence[str]): - Durable messages that persist on every - operation poll. @OutputOnly - create_version_metadata (google.cloud.appengine_admin_v1.types.CreateVersionMetadataV1): - - """ - - method = proto.Field( - proto.STRING, - number=1, - ) - insert_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - end_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - user = proto.Field( - proto.STRING, - number=4, - ) - target = proto.Field( - proto.STRING, - number=5, - ) - ephemeral_message = proto.Field( - proto.STRING, - number=6, - ) - warning = proto.RepeatedField( - proto.STRING, - number=7, - ) - create_version_metadata = proto.Field( - proto.MESSAGE, - number=8, - oneof='method_metadata', - message='CreateVersionMetadataV1', - ) - - -class CreateVersionMetadataV1(proto.Message): - r"""Metadata for the given - [google.longrunning.Operation][google.longrunning.Operation] during - a - [google.appengine.v1.CreateVersionRequest][google.appengine.v1.CreateVersionRequest]. - - Attributes: - cloud_build_id (str): - The Cloud Build ID if one was created as part - of the version create. @OutputOnly - """ - - cloud_build_id = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/service.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/service.py deleted file mode 100644 index 2fe2fdd..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/service.py +++ /dev/null @@ -1,121 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.appengine_admin_v1.types import network_settings as ga_network_settings - - -__protobuf__ = proto.module( - package='google.appengine.v1', - manifest={ - 'Service', - 'TrafficSplit', - }, -) - - -class Service(proto.Message): - r"""A Service resource is a logical component of an application - that can share state and communicate in a secure fashion with - other services. For example, an application that handles - customer requests might include separate services to handle - tasks such as backend data analysis or API requests from mobile - devices. Each service has a collection of versions that define a - specific set of code used to implement the functionality of that - service. - - Attributes: - name (str): - Full path to the Service resource in the API. Example: - ``apps/myapp/services/default``. - - @OutputOnly - id (str): - Relative name of the service within the application. - Example: ``default``. - - @OutputOnly - split (google.cloud.appengine_admin_v1.types.TrafficSplit): - Mapping that defines fractional HTTP traffic - diversion to different versions within the - service. - network_settings (google.cloud.appengine_admin_v1.types.NetworkSettings): - Ingress settings for this service. Will apply - to all versions. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - id = proto.Field( - proto.STRING, - number=2, - ) - split = proto.Field( - proto.MESSAGE, - number=3, - message='TrafficSplit', - ) - network_settings = proto.Field( - proto.MESSAGE, - number=6, - message=ga_network_settings.NetworkSettings, - ) - - -class TrafficSplit(proto.Message): - r"""Traffic routing configuration for versions within a single - service. Traffic splits define how traffic directed to the - service is assigned to versions. - - Attributes: - shard_by (google.cloud.appengine_admin_v1.types.TrafficSplit.ShardBy): - Mechanism used to determine which version a - request is sent to. The traffic selection - algorithm will be stable for either type until - allocations are changed. - allocations (Sequence[google.cloud.appengine_admin_v1.types.TrafficSplit.AllocationsEntry]): - Mapping from version IDs within the service to fractional - (0.000, 1] allocations of traffic for that version. Each - version can be specified only once, but some versions in the - service may not have any traffic allocation. Services that - have traffic allocated cannot be deleted until either the - service is deleted or their traffic allocation is removed. - Allocations must sum to 1. Up to two decimal place precision - is supported for IP-based splits and up to three decimal - places is supported for cookie-based splits. - """ - class ShardBy(proto.Enum): - r"""Available sharding mechanisms.""" - UNSPECIFIED = 0 - COOKIE = 1 - IP = 2 - RANDOM = 3 - - shard_by = proto.Field( - proto.ENUM, - number=1, - enum=ShardBy, - ) - allocations = proto.MapField( - proto.STRING, - proto.DOUBLE, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/version.py b/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/version.py deleted file mode 100644 index 03a31ef..0000000 --- a/owl-bot-staging/v1/google/cloud/appengine_admin_v1/types/version.py +++ /dev/null @@ -1,973 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import proto # type: ignore - -from google.cloud.appengine_admin_v1.types import app_yaml -from google.cloud.appengine_admin_v1.types import deploy -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.appengine.v1', - manifest={ - 'InboundServiceType', - 'ServingStatus', - 'Version', - 'EndpointsApiService', - 'AutomaticScaling', - 'BasicScaling', - 'ManualScaling', - 'CpuUtilization', - 'RequestUtilization', - 'DiskUtilization', - 'NetworkUtilization', - 'StandardSchedulerSettings', - 'Network', - 'Volume', - 'Resources', - 'VpcAccessConnector', - 'Entrypoint', - }, -) - - -class InboundServiceType(proto.Enum): - r"""Available inbound services.""" - INBOUND_SERVICE_UNSPECIFIED = 0 - INBOUND_SERVICE_MAIL = 1 - INBOUND_SERVICE_MAIL_BOUNCE = 2 - INBOUND_SERVICE_XMPP_ERROR = 3 - INBOUND_SERVICE_XMPP_MESSAGE = 4 - INBOUND_SERVICE_XMPP_SUBSCRIBE = 5 - INBOUND_SERVICE_XMPP_PRESENCE = 6 - INBOUND_SERVICE_CHANNEL_PRESENCE = 7 - INBOUND_SERVICE_WARMUP = 9 - - -class ServingStatus(proto.Enum): - r"""Run states of a version.""" - SERVING_STATUS_UNSPECIFIED = 0 - SERVING = 1 - STOPPED = 2 - - -class Version(proto.Message): - r"""A Version resource is a specific set of source code and - configuration files that are deployed into a service. - - Attributes: - name (str): - Full path to the Version resource in the API. Example: - ``apps/myapp/services/default/versions/v1``. - - @OutputOnly - id (str): - Relative name of the version within the service. Example: - ``v1``. Version names can contain only lowercase letters, - numbers, or hyphens. Reserved names: "default", "latest", - and any name with the prefix "ah-". - automatic_scaling (google.cloud.appengine_admin_v1.types.AutomaticScaling): - Automatic scaling is based on request rate, - response latencies, and other application - metrics. Instances are dynamically created and - destroyed as needed in order to handle traffic. - basic_scaling (google.cloud.appengine_admin_v1.types.BasicScaling): - A service with basic scaling will create an - instance when the application receives a - request. The instance will be turned down when - the app becomes idle. Basic scaling is ideal for - work that is intermittent or driven by user - activity. - manual_scaling (google.cloud.appengine_admin_v1.types.ManualScaling): - A service with manual scaling runs - continuously, allowing you to perform complex - initialization and rely on the state of its - memory over time. Manually scaled versions are - sometimes referred to as "backends". - inbound_services (Sequence[google.cloud.appengine_admin_v1.types.InboundServiceType]): - Before an application can receive email or - XMPP messages, the application must be - configured to enable the service. - instance_class (str): - Instance class that is used to run this version. Valid - values are: - - - AutomaticScaling: ``F1``, ``F2``, ``F4``, ``F4_1G`` - - ManualScaling or BasicScaling: ``B1``, ``B2``, ``B4``, - ``B8``, ``B4_1G`` - - Defaults to ``F1`` for AutomaticScaling and ``B1`` for - ManualScaling or BasicScaling. - network (google.cloud.appengine_admin_v1.types.Network): - Extra network settings. - Only applicable in the App Engine flexible - environment. - zones (Sequence[str]): - The Google Compute Engine zones that are - supported by this version in the App Engine - flexible environment. Deprecated. - resources (google.cloud.appengine_admin_v1.types.Resources): - Machine resources for this version. - Only applicable in the App Engine flexible - environment. - runtime (str): - Desired runtime. Example: ``python27``. - runtime_channel (str): - The channel of the runtime to use. Only available for some - runtimes. Defaults to the ``default`` channel. - threadsafe (bool): - Whether multiple requests can be dispatched - to this version at once. - vm (bool): - Whether to deploy this version in a container - on a virtual machine. - beta_settings (Sequence[google.cloud.appengine_admin_v1.types.Version.BetaSettingsEntry]): - Metadata settings that are supplied to this - version to enable beta runtime features. - env (str): - App Engine execution environment for this version. - - Defaults to ``standard``. - serving_status (google.cloud.appengine_admin_v1.types.ServingStatus): - Current serving status of this version. Only the versions - with a ``SERVING`` status create instances and can be - billed. - - ``SERVING_STATUS_UNSPECIFIED`` is an invalid value. Defaults - to ``SERVING``. - created_by (str): - Email address of the user who created this - version. - @OutputOnly - create_time (google.protobuf.timestamp_pb2.Timestamp): - Time that this version was created. - @OutputOnly - disk_usage_bytes (int): - Total size in bytes of all the files that are - included in this version and currently hosted on - the App Engine disk. - @OutputOnly - runtime_api_version (str): - The version of the API in the given runtime - environment. Please see the app.yaml reference - for valid values at - https://cloud.google.com/appengine/docs/standard//config/appref - runtime_main_executable_path (str): - The path or name of the app's main - executable. - service_account (str): - The identity that the deployed version will - run as. Admin API will use the App Engine - Appspot service account as default if this field - is neither provided in app.yaml file nor through - CLI flag. - handlers (Sequence[google.cloud.appengine_admin_v1.types.UrlMap]): - An ordered list of URL-matching patterns that should be - applied to incoming requests. The first matching URL handles - the request and other request handlers are not attempted. - - Only returned in ``GET`` requests if ``view=FULL`` is set. - error_handlers (Sequence[google.cloud.appengine_admin_v1.types.ErrorHandler]): - Custom static error pages. Limited to 10KB per page. - - Only returned in ``GET`` requests if ``view=FULL`` is set. - libraries (Sequence[google.cloud.appengine_admin_v1.types.Library]): - Configuration for third-party Python runtime libraries that - are required by the application. - - Only returned in ``GET`` requests if ``view=FULL`` is set. - api_config (google.cloud.appengine_admin_v1.types.ApiConfigHandler): - Serving configuration for `Google Cloud - Endpoints `__. - - Only returned in ``GET`` requests if ``view=FULL`` is set. - env_variables (Sequence[google.cloud.appengine_admin_v1.types.Version.EnvVariablesEntry]): - Environment variables available to the application. - - Only returned in ``GET`` requests if ``view=FULL`` is set. - build_env_variables (Sequence[google.cloud.appengine_admin_v1.types.Version.BuildEnvVariablesEntry]): - Environment variables available to the build environment. - - Only returned in ``GET`` requests if ``view=FULL`` is set. - default_expiration (google.protobuf.duration_pb2.Duration): - Duration that static files should be cached by web proxies - and browsers. Only applicable if the corresponding - `StaticFilesHandler `__ - does not specify its own expiration time. - - Only returned in ``GET`` requests if ``view=FULL`` is set. - health_check (google.cloud.appengine_admin_v1.types.HealthCheck): - Configures health checking for instances. Unhealthy - instances are stopped and replaced with new instances. Only - applicable in the App Engine flexible environment. - - Only returned in ``GET`` requests if ``view=FULL`` is set. - readiness_check (google.cloud.appengine_admin_v1.types.ReadinessCheck): - Configures readiness health checking for instances. - Unhealthy instances are not put into the backend traffic - rotation. - - Only returned in ``GET`` requests if ``view=FULL`` is set. - liveness_check (google.cloud.appengine_admin_v1.types.LivenessCheck): - Configures liveness health checking for instances. Unhealthy - instances are stopped and replaced with new instances - - Only returned in ``GET`` requests if ``view=FULL`` is set. - nobuild_files_regex (str): - Files that match this pattern will not be built into this - version. Only applicable for Go runtimes. - - Only returned in ``GET`` requests if ``view=FULL`` is set. - deployment (google.cloud.appengine_admin_v1.types.Deployment): - Code and application artifacts that make up this version. - - Only returned in ``GET`` requests if ``view=FULL`` is set. - version_url (str): - Serving URL for this version. Example: - "https://myversion-dot-myservice-dot- - myapp.appspot.com" - @OutputOnly - endpoints_api_service (google.cloud.appengine_admin_v1.types.EndpointsApiService): - Cloud Endpoints configuration. - - If endpoints_api_service is set, the Cloud Endpoints - Extensible Service Proxy will be provided to serve the API - implemented by the app. - entrypoint (google.cloud.appengine_admin_v1.types.Entrypoint): - The entrypoint for the application. - vpc_access_connector (google.cloud.appengine_admin_v1.types.VpcAccessConnector): - Enables VPC connectivity for standard apps. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - id = proto.Field( - proto.STRING, - number=2, - ) - automatic_scaling = proto.Field( - proto.MESSAGE, - number=3, - oneof='scaling', - message='AutomaticScaling', - ) - basic_scaling = proto.Field( - proto.MESSAGE, - number=4, - oneof='scaling', - message='BasicScaling', - ) - manual_scaling = proto.Field( - proto.MESSAGE, - number=5, - oneof='scaling', - message='ManualScaling', - ) - inbound_services = proto.RepeatedField( - proto.ENUM, - number=6, - enum='InboundServiceType', - ) - instance_class = proto.Field( - proto.STRING, - number=7, - ) - network = proto.Field( - proto.MESSAGE, - number=8, - message='Network', - ) - zones = proto.RepeatedField( - proto.STRING, - number=118, - ) - resources = proto.Field( - proto.MESSAGE, - number=9, - message='Resources', - ) - runtime = proto.Field( - proto.STRING, - number=10, - ) - runtime_channel = proto.Field( - proto.STRING, - number=117, - ) - threadsafe = proto.Field( - proto.BOOL, - number=11, - ) - vm = proto.Field( - proto.BOOL, - number=12, - ) - beta_settings = proto.MapField( - proto.STRING, - proto.STRING, - number=13, - ) - env = proto.Field( - proto.STRING, - number=14, - ) - serving_status = proto.Field( - proto.ENUM, - number=15, - enum='ServingStatus', - ) - created_by = proto.Field( - proto.STRING, - number=16, - ) - create_time = proto.Field( - proto.MESSAGE, - number=17, - message=timestamp_pb2.Timestamp, - ) - disk_usage_bytes = proto.Field( - proto.INT64, - number=18, - ) - runtime_api_version = proto.Field( - proto.STRING, - number=21, - ) - runtime_main_executable_path = proto.Field( - proto.STRING, - number=22, - ) - service_account = proto.Field( - proto.STRING, - number=127, - ) - handlers = proto.RepeatedField( - proto.MESSAGE, - number=100, - message=app_yaml.UrlMap, - ) - error_handlers = proto.RepeatedField( - proto.MESSAGE, - number=101, - message=app_yaml.ErrorHandler, - ) - libraries = proto.RepeatedField( - proto.MESSAGE, - number=102, - message=app_yaml.Library, - ) - api_config = proto.Field( - proto.MESSAGE, - number=103, - message=app_yaml.ApiConfigHandler, - ) - env_variables = proto.MapField( - proto.STRING, - proto.STRING, - number=104, - ) - build_env_variables = proto.MapField( - proto.STRING, - proto.STRING, - number=125, - ) - default_expiration = proto.Field( - proto.MESSAGE, - number=105, - message=duration_pb2.Duration, - ) - health_check = proto.Field( - proto.MESSAGE, - number=106, - message=app_yaml.HealthCheck, - ) - readiness_check = proto.Field( - proto.MESSAGE, - number=112, - message=app_yaml.ReadinessCheck, - ) - liveness_check = proto.Field( - proto.MESSAGE, - number=113, - message=app_yaml.LivenessCheck, - ) - nobuild_files_regex = proto.Field( - proto.STRING, - number=107, - ) - deployment = proto.Field( - proto.MESSAGE, - number=108, - message=deploy.Deployment, - ) - version_url = proto.Field( - proto.STRING, - number=109, - ) - endpoints_api_service = proto.Field( - proto.MESSAGE, - number=110, - message='EndpointsApiService', - ) - entrypoint = proto.Field( - proto.MESSAGE, - number=122, - message='Entrypoint', - ) - vpc_access_connector = proto.Field( - proto.MESSAGE, - number=121, - message='VpcAccessConnector', - ) - - -class EndpointsApiService(proto.Message): - r"""`Cloud Endpoints `__ - configuration. The Endpoints API Service provides tooling for - serving Open API and gRPC endpoints via an NGINX proxy. Only valid - for App Engine Flexible environment deployments. - - The fields here refer to the name and configuration ID of a - "service" resource in the `Service Management - API `__. - - Attributes: - name (str): - Endpoints service name which is the name of - the "service" resource in the Service Management - API. For example - "myapi.endpoints.myproject.cloud.goog". - config_id (str): - Endpoints service configuration ID as specified by the - Service Management API. For example "2016-09-19r1". - - By default, the rollout strategy for Endpoints is - ``RolloutStrategy.FIXED``. This means that Endpoints starts - up with a particular configuration ID. When a new - configuration is rolled out, Endpoints must be given the new - configuration ID. The ``config_id`` field is used to give - the configuration ID and is required in this case. - - Endpoints also has a rollout strategy called - ``RolloutStrategy.MANAGED``. When using this, Endpoints - fetches the latest configuration and does not need the - configuration ID. In this case, ``config_id`` must be - omitted. - rollout_strategy (google.cloud.appengine_admin_v1.types.EndpointsApiService.RolloutStrategy): - Endpoints rollout strategy. If ``FIXED``, ``config_id`` must - be specified. If ``MANAGED``, ``config_id`` must be omitted. - disable_trace_sampling (bool): - Enable or disable trace sampling. By default, - this is set to false for enabled. - """ - class RolloutStrategy(proto.Enum): - r"""Available rollout strategies.""" - UNSPECIFIED_ROLLOUT_STRATEGY = 0 - FIXED = 1 - MANAGED = 2 - - name = proto.Field( - proto.STRING, - number=1, - ) - config_id = proto.Field( - proto.STRING, - number=2, - ) - rollout_strategy = proto.Field( - proto.ENUM, - number=3, - enum=RolloutStrategy, - ) - disable_trace_sampling = proto.Field( - proto.BOOL, - number=4, - ) - - -class AutomaticScaling(proto.Message): - r"""Automatic scaling is based on request rate, response - latencies, and other application metrics. - - Attributes: - cool_down_period (google.protobuf.duration_pb2.Duration): - The time period that the - `Autoscaler `__ - should wait before it starts collecting information from a - new instance. This prevents the autoscaler from collecting - information when the instance is initializing, during which - the collected usage would not be reliable. Only applicable - in the App Engine flexible environment. - cpu_utilization (google.cloud.appengine_admin_v1.types.CpuUtilization): - Target scaling by CPU usage. - max_concurrent_requests (int): - Number of concurrent requests an automatic - scaling instance can accept before the scheduler - spawns a new instance. - Defaults to a runtime-specific value. - max_idle_instances (int): - Maximum number of idle instances that should - be maintained for this version. - max_total_instances (int): - Maximum number of instances that should be - started to handle requests for this version. - max_pending_latency (google.protobuf.duration_pb2.Duration): - Maximum amount of time that a request should - wait in the pending queue before starting a new - instance to handle it. - min_idle_instances (int): - Minimum number of idle instances that should - be maintained for this version. Only applicable - for the default version of a service. - min_total_instances (int): - Minimum number of running instances that - should be maintained for this version. - min_pending_latency (google.protobuf.duration_pb2.Duration): - Minimum amount of time a request should wait - in the pending queue before starting a new - instance to handle it. - request_utilization (google.cloud.appengine_admin_v1.types.RequestUtilization): - Target scaling by request utilization. - disk_utilization (google.cloud.appengine_admin_v1.types.DiskUtilization): - Target scaling by disk usage. - network_utilization (google.cloud.appengine_admin_v1.types.NetworkUtilization): - Target scaling by network usage. - standard_scheduler_settings (google.cloud.appengine_admin_v1.types.StandardSchedulerSettings): - Scheduler settings for standard environment. - """ - - cool_down_period = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - cpu_utilization = proto.Field( - proto.MESSAGE, - number=2, - message='CpuUtilization', - ) - max_concurrent_requests = proto.Field( - proto.INT32, - number=3, - ) - max_idle_instances = proto.Field( - proto.INT32, - number=4, - ) - max_total_instances = proto.Field( - proto.INT32, - number=5, - ) - max_pending_latency = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - min_idle_instances = proto.Field( - proto.INT32, - number=7, - ) - min_total_instances = proto.Field( - proto.INT32, - number=8, - ) - min_pending_latency = proto.Field( - proto.MESSAGE, - number=9, - message=duration_pb2.Duration, - ) - request_utilization = proto.Field( - proto.MESSAGE, - number=10, - message='RequestUtilization', - ) - disk_utilization = proto.Field( - proto.MESSAGE, - number=11, - message='DiskUtilization', - ) - network_utilization = proto.Field( - proto.MESSAGE, - number=12, - message='NetworkUtilization', - ) - standard_scheduler_settings = proto.Field( - proto.MESSAGE, - number=20, - message='StandardSchedulerSettings', - ) - - -class BasicScaling(proto.Message): - r"""A service with basic scaling will create an instance when the - application receives a request. The instance will be turned down - when the app becomes idle. Basic scaling is ideal for work that - is intermittent or driven by user activity. - - Attributes: - idle_timeout (google.protobuf.duration_pb2.Duration): - Duration of time after the last request that - an instance must wait before the instance is - shut down. - max_instances (int): - Maximum number of instances to create for - this version. - """ - - idle_timeout = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - max_instances = proto.Field( - proto.INT32, - number=2, - ) - - -class ManualScaling(proto.Message): - r"""A service with manual scaling runs continuously, allowing you - to perform complex initialization and rely on the state of its - memory over time. - - Attributes: - instances (int): - Number of instances to assign to the service at the start. - This number can later be altered by using the `Modules - API `__ - ``set_num_instances()`` function. - """ - - instances = proto.Field( - proto.INT32, - number=1, - ) - - -class CpuUtilization(proto.Message): - r"""Target scaling by CPU usage. - Attributes: - aggregation_window_length (google.protobuf.duration_pb2.Duration): - Period of time over which CPU utilization is - calculated. - target_utilization (float): - Target CPU utilization ratio to maintain when - scaling. Must be between 0 and 1. - """ - - aggregation_window_length = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - target_utilization = proto.Field( - proto.DOUBLE, - number=2, - ) - - -class RequestUtilization(proto.Message): - r"""Target scaling by request utilization. - Only applicable in the App Engine flexible environment. - - Attributes: - target_request_count_per_second (int): - Target requests per second. - target_concurrent_requests (int): - Target number of concurrent requests. - """ - - target_request_count_per_second = proto.Field( - proto.INT32, - number=1, - ) - target_concurrent_requests = proto.Field( - proto.INT32, - number=2, - ) - - -class DiskUtilization(proto.Message): - r"""Target scaling by disk usage. - Only applicable in the App Engine flexible environment. - - Attributes: - target_write_bytes_per_second (int): - Target bytes written per second. - target_write_ops_per_second (int): - Target ops written per second. - target_read_bytes_per_second (int): - Target bytes read per second. - target_read_ops_per_second (int): - Target ops read per seconds. - """ - - target_write_bytes_per_second = proto.Field( - proto.INT32, - number=14, - ) - target_write_ops_per_second = proto.Field( - proto.INT32, - number=15, - ) - target_read_bytes_per_second = proto.Field( - proto.INT32, - number=16, - ) - target_read_ops_per_second = proto.Field( - proto.INT32, - number=17, - ) - - -class NetworkUtilization(proto.Message): - r"""Target scaling by network usage. - Only applicable in the App Engine flexible environment. - - Attributes: - target_sent_bytes_per_second (int): - Target bytes sent per second. - target_sent_packets_per_second (int): - Target packets sent per second. - target_received_bytes_per_second (int): - Target bytes received per second. - target_received_packets_per_second (int): - Target packets received per second. - """ - - target_sent_bytes_per_second = proto.Field( - proto.INT32, - number=1, - ) - target_sent_packets_per_second = proto.Field( - proto.INT32, - number=11, - ) - target_received_bytes_per_second = proto.Field( - proto.INT32, - number=12, - ) - target_received_packets_per_second = proto.Field( - proto.INT32, - number=13, - ) - - -class StandardSchedulerSettings(proto.Message): - r"""Scheduler settings for standard environment. - Attributes: - target_cpu_utilization (float): - Target CPU utilization ratio to maintain when - scaling. - target_throughput_utilization (float): - Target throughput utilization ratio to - maintain when scaling - min_instances (int): - Minimum number of instances to run for this version. Set to - zero to disable ``min_instances`` configuration. - max_instances (int): - Maximum number of instances to run for this version. Set to - zero to disable ``max_instances`` configuration. - """ - - target_cpu_utilization = proto.Field( - proto.DOUBLE, - number=1, - ) - target_throughput_utilization = proto.Field( - proto.DOUBLE, - number=2, - ) - min_instances = proto.Field( - proto.INT32, - number=3, - ) - max_instances = proto.Field( - proto.INT32, - number=4, - ) - - -class Network(proto.Message): - r"""Extra network settings. - Only applicable in the App Engine flexible environment. - - Attributes: - forwarded_ports (Sequence[str]): - List of ports, or port pairs, to forward from - the virtual machine to the application - container. Only applicable in the App Engine - flexible environment. - instance_tag (str): - Tag to apply to the instance during creation. - Only applicable in the App Engine flexible - environment. - name (str): - Google Compute Engine network where the virtual machines are - created. Specify the short name, not the resource path. - - Defaults to ``default``. - subnetwork_name (str): - Google Cloud Platform sub-network where the virtual machines - are created. Specify the short name, not the resource path. - - If a subnetwork name is specified, a network name will also - be required unless it is for the default network. - - - If the network that the instance is being created in is a - Legacy network, then the IP address is allocated from the - IPv4Range. - - If the network that the instance is being created in is - an auto Subnet Mode Network, then only network name - should be specified (not the subnetwork_name) and the IP - address is created from the IPCidrRange of the subnetwork - that exists in that zone for that network. - - If the network that the instance is being created in is a - custom Subnet Mode Network, then the subnetwork_name must - be specified and the IP address is created from the - IPCidrRange of the subnetwork. - - If specified, the subnetwork must exist in the same region - as the App Engine flexible environment application. - session_affinity (bool): - Enable session affinity. - Only applicable in the App Engine flexible - environment. - """ - - forwarded_ports = proto.RepeatedField( - proto.STRING, - number=1, - ) - instance_tag = proto.Field( - proto.STRING, - number=2, - ) - name = proto.Field( - proto.STRING, - number=3, - ) - subnetwork_name = proto.Field( - proto.STRING, - number=4, - ) - session_affinity = proto.Field( - proto.BOOL, - number=5, - ) - - -class Volume(proto.Message): - r"""Volumes mounted within the app container. - Only applicable in the App Engine flexible environment. - - Attributes: - name (str): - Unique name for the volume. - volume_type (str): - Underlying volume type, e.g. 'tmpfs'. - size_gb (float): - Volume size in gigabytes. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - volume_type = proto.Field( - proto.STRING, - number=2, - ) - size_gb = proto.Field( - proto.DOUBLE, - number=3, - ) - - -class Resources(proto.Message): - r"""Machine resources for a version. - Attributes: - cpu (float): - Number of CPU cores needed. - disk_gb (float): - Disk size (GB) needed. - memory_gb (float): - Memory (GB) needed. - volumes (Sequence[google.cloud.appengine_admin_v1.types.Volume]): - User specified volumes. - kms_key_reference (str): - The name of the encryption key that is stored - in Google Cloud KMS. Only should be used by - Cloud Composer to encrypt the vm disk - """ - - cpu = proto.Field( - proto.DOUBLE, - number=1, - ) - disk_gb = proto.Field( - proto.DOUBLE, - number=2, - ) - memory_gb = proto.Field( - proto.DOUBLE, - number=3, - ) - volumes = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Volume', - ) - kms_key_reference = proto.Field( - proto.STRING, - number=5, - ) - - -class VpcAccessConnector(proto.Message): - r"""VPC access connector specification. - Attributes: - name (str): - Full Serverless VPC Access Connector name - e.g. /projects/my-project/locations/us- - central1/connectors/c1. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class Entrypoint(proto.Message): - r"""The entrypoint for the application. - Attributes: - shell (str): - The format should be a shell command that can be fed to - ``bash -c``. - """ - - shell = proto.Field( - proto.STRING, - number=1, - oneof='command', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini deleted file mode 100644 index 4505b48..0000000 --- a/owl-bot-staging/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py deleted file mode 100644 index f447519..0000000 --- a/owl-bot-staging/v1/noxfile.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/appengine_admin_v1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) diff --git a/owl-bot-staging/v1/scripts/fixup_appengine_admin_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_appengine_admin_v1_keywords.py deleted file mode 100644 index 977426f..0000000 --- a/owl-bot-staging/v1/scripts/fixup_appengine_admin_v1_keywords.py +++ /dev/null @@ -1,209 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class appengine_adminCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_update_ingress_rules': ('name', 'ingress_rules', ), - 'create_application': ('application', ), - 'create_authorized_certificate': ('parent', 'certificate', ), - 'create_domain_mapping': ('parent', 'domain_mapping', 'override_strategy', ), - 'create_ingress_rule': ('parent', 'rule', ), - 'create_version': ('parent', 'version', ), - 'debug_instance': ('name', 'ssh_key', ), - 'delete_authorized_certificate': ('name', ), - 'delete_domain_mapping': ('name', ), - 'delete_ingress_rule': ('name', ), - 'delete_instance': ('name', ), - 'delete_service': ('name', ), - 'delete_version': ('name', ), - 'get_application': ('name', ), - 'get_authorized_certificate': ('name', 'view', ), - 'get_domain_mapping': ('name', ), - 'get_ingress_rule': ('name', ), - 'get_instance': ('name', ), - 'get_service': ('name', ), - 'get_version': ('name', 'view', ), - 'list_authorized_certificates': ('parent', 'view', 'page_size', 'page_token', ), - 'list_authorized_domains': ('parent', 'page_size', 'page_token', ), - 'list_domain_mappings': ('parent', 'page_size', 'page_token', ), - 'list_ingress_rules': ('parent', 'page_size', 'page_token', 'matching_address', ), - 'list_instances': ('parent', 'page_size', 'page_token', ), - 'list_services': ('parent', 'page_size', 'page_token', ), - 'list_versions': ('parent', 'view', 'page_size', 'page_token', ), - 'repair_application': ('name', ), - 'update_application': ('name', 'application', 'update_mask', ), - 'update_authorized_certificate': ('name', 'certificate', 'update_mask', ), - 'update_domain_mapping': ('name', 'domain_mapping', 'update_mask', ), - 'update_ingress_rule': ('name', 'rule', 'update_mask', ), - 'update_service': ('name', 'service', 'update_mask', 'migrate_traffic', ), - 'update_version': ('name', 'version', 'update_mask', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: not a.keyword.value in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=appengine_adminCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the appengine_admin client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py deleted file mode 100644 index e549b9d..0000000 --- a/owl-bot-staging/v1/setup.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-appengine-admin', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/__init__.py deleted file mode 100644 index b54a5fc..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_applications.py b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_applications.py deleted file mode 100644 index 4365fbb..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_applications.py +++ /dev/null @@ -1,1539 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.appengine_admin_v1.services.applications import ApplicationsAsyncClient -from google.cloud.appengine_admin_v1.services.applications import ApplicationsClient -from google.cloud.appengine_admin_v1.services.applications import transports -from google.cloud.appengine_admin_v1.services.applications.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import application -from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ApplicationsClient._get_default_mtls_endpoint(None) is None - assert ApplicationsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ApplicationsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ApplicationsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ApplicationsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ApplicationsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - ApplicationsClient, - ApplicationsAsyncClient, -]) -def test_applications_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'appengine.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ApplicationsGrpcTransport, "grpc"), - (transports.ApplicationsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_applications_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class", [ - ApplicationsClient, - ApplicationsAsyncClient, -]) -def test_applications_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'appengine.googleapis.com:443' - - -def test_applications_client_get_transport_class(): - transport = ApplicationsClient.get_transport_class() - available_transports = [ - transports.ApplicationsGrpcTransport, - ] - assert transport in available_transports - - transport = ApplicationsClient.get_transport_class("grpc") - assert transport == transports.ApplicationsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ApplicationsClient, transports.ApplicationsGrpcTransport, "grpc"), - (ApplicationsAsyncClient, transports.ApplicationsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ApplicationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ApplicationsClient)) -@mock.patch.object(ApplicationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ApplicationsAsyncClient)) -def test_applications_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(ApplicationsClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(ApplicationsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ApplicationsClient, transports.ApplicationsGrpcTransport, "grpc", "true"), - (ApplicationsAsyncClient, transports.ApplicationsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ApplicationsClient, transports.ApplicationsGrpcTransport, "grpc", "false"), - (ApplicationsAsyncClient, transports.ApplicationsGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ApplicationsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ApplicationsClient)) -@mock.patch.object(ApplicationsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ApplicationsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_applications_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ApplicationsClient, transports.ApplicationsGrpcTransport, "grpc"), - (ApplicationsAsyncClient, transports.ApplicationsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_applications_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ApplicationsClient, transports.ApplicationsGrpcTransport, "grpc"), - (ApplicationsAsyncClient, transports.ApplicationsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_applications_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_applications_client_client_options_from_dict(): - with mock.patch('google.cloud.appengine_admin_v1.services.applications.transports.ApplicationsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ApplicationsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_get_application(transport: str = 'grpc', request_type=appengine.GetApplicationRequest): - client = ApplicationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_application), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = application.Application( - name='name_value', - id='id_value', - auth_domain='auth_domain_value', - location_id='location_id_value', - code_bucket='code_bucket_value', - serving_status=application.Application.ServingStatus.SERVING, - default_hostname='default_hostname_value', - default_bucket='default_bucket_value', - gcr_domain='gcr_domain_value', - database_type=application.Application.DatabaseType.CLOUD_DATASTORE, - ) - response = client.get_application(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetApplicationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, application.Application) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.auth_domain == 'auth_domain_value' - assert response.location_id == 'location_id_value' - assert response.code_bucket == 'code_bucket_value' - assert response.serving_status == application.Application.ServingStatus.SERVING - assert response.default_hostname == 'default_hostname_value' - assert response.default_bucket == 'default_bucket_value' - assert response.gcr_domain == 'gcr_domain_value' - assert response.database_type == application.Application.DatabaseType.CLOUD_DATASTORE - - -def test_get_application_from_dict(): - test_get_application(request_type=dict) - - -def test_get_application_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ApplicationsClient( - credentials=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_application), - '__call__') as call: - client.get_application() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetApplicationRequest() - - -@pytest.mark.asyncio -async def test_get_application_async(transport: str = 'grpc_asyncio', request_type=appengine.GetApplicationRequest): - client = ApplicationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_application), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(application.Application( - name='name_value', - id='id_value', - auth_domain='auth_domain_value', - location_id='location_id_value', - code_bucket='code_bucket_value', - serving_status=application.Application.ServingStatus.SERVING, - default_hostname='default_hostname_value', - default_bucket='default_bucket_value', - gcr_domain='gcr_domain_value', - database_type=application.Application.DatabaseType.CLOUD_DATASTORE, - )) - response = await client.get_application(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetApplicationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, application.Application) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.auth_domain == 'auth_domain_value' - assert response.location_id == 'location_id_value' - assert response.code_bucket == 'code_bucket_value' - assert response.serving_status == application.Application.ServingStatus.SERVING - assert response.default_hostname == 'default_hostname_value' - assert response.default_bucket == 'default_bucket_value' - assert response.gcr_domain == 'gcr_domain_value' - assert response.database_type == application.Application.DatabaseType.CLOUD_DATASTORE - - -@pytest.mark.asyncio -async def test_get_application_async_from_dict(): - await test_get_application_async(request_type=dict) - - -def test_get_application_field_headers(): - client = ApplicationsClient( - credentials=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. - request = appengine.GetApplicationRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_application), - '__call__') as call: - call.return_value = application.Application() - client.get_application(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_application_field_headers_async(): - client = ApplicationsAsyncClient( - credentials=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. - request = appengine.GetApplicationRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_application), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(application.Application()) - await client.get_application(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_create_application(transport: str = 'grpc', request_type=appengine.CreateApplicationRequest): - client = ApplicationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_application), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_application(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateApplicationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_application_from_dict(): - test_create_application(request_type=dict) - - -def test_create_application_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ApplicationsClient( - credentials=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_application), - '__call__') as call: - client.create_application() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateApplicationRequest() - - -@pytest.mark.asyncio -async def test_create_application_async(transport: str = 'grpc_asyncio', request_type=appengine.CreateApplicationRequest): - client = ApplicationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_application), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_application(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateApplicationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_application_async_from_dict(): - await test_create_application_async(request_type=dict) - - -def test_update_application(transport: str = 'grpc', request_type=appengine.UpdateApplicationRequest): - client = ApplicationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_application), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_application(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateApplicationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_application_from_dict(): - test_update_application(request_type=dict) - - -def test_update_application_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ApplicationsClient( - credentials=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_application), - '__call__') as call: - client.update_application() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateApplicationRequest() - - -@pytest.mark.asyncio -async def test_update_application_async(transport: str = 'grpc_asyncio', request_type=appengine.UpdateApplicationRequest): - client = ApplicationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_application), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_application(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateApplicationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_application_async_from_dict(): - await test_update_application_async(request_type=dict) - - -def test_update_application_field_headers(): - client = ApplicationsClient( - credentials=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. - request = appengine.UpdateApplicationRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_application), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_application(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_application_field_headers_async(): - client = ApplicationsAsyncClient( - credentials=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. - request = appengine.UpdateApplicationRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_application), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_application(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_repair_application(transport: str = 'grpc', request_type=appengine.RepairApplicationRequest): - client = ApplicationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.repair_application), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.repair_application(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.RepairApplicationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_repair_application_from_dict(): - test_repair_application(request_type=dict) - - -def test_repair_application_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ApplicationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.repair_application), - '__call__') as call: - client.repair_application() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.RepairApplicationRequest() - - -@pytest.mark.asyncio -async def test_repair_application_async(transport: str = 'grpc_asyncio', request_type=appengine.RepairApplicationRequest): - client = ApplicationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.repair_application), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.repair_application(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.RepairApplicationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_repair_application_async_from_dict(): - await test_repair_application_async(request_type=dict) - - -def test_repair_application_field_headers(): - client = ApplicationsClient( - credentials=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. - request = appengine.RepairApplicationRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.repair_application), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.repair_application(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_repair_application_field_headers_async(): - client = ApplicationsAsyncClient( - credentials=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. - request = appengine.RepairApplicationRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.repair_application), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.repair_application(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ApplicationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ApplicationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ApplicationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ApplicationsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ApplicationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ApplicationsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ApplicationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ApplicationsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ApplicationsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ApplicationsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ApplicationsGrpcTransport, - transports.ApplicationsGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ApplicationsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ApplicationsGrpcTransport, - ) - -def test_applications_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ApplicationsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_applications_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.appengine_admin_v1.services.applications.transports.ApplicationsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ApplicationsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_application', - 'create_application', - 'update_application', - 'repair_application', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_applications_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.applications.transports.ApplicationsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ApplicationsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_applications_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.applications.transports.ApplicationsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ApplicationsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ), - quota_project_id="octopus", - ) - - -def test_applications_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.appengine_admin_v1.services.applications.transports.ApplicationsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ApplicationsTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_applications_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ApplicationsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_applications_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ApplicationsClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ApplicationsGrpcTransport, - transports.ApplicationsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_applications_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ApplicationsGrpcTransport, - transports.ApplicationsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_applications_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ApplicationsGrpcTransport, grpc_helpers), - (transports.ApplicationsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_applications_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "appengine.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - scopes=["1", "2"], - default_host="appengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ApplicationsGrpcTransport, transports.ApplicationsGrpcAsyncIOTransport]) -def test_applications_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_applications_host_no_port(): - client = ApplicationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com'), - ) - assert client.transport._host == 'appengine.googleapis.com:443' - - -def test_applications_host_with_port(): - client = ApplicationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com:8000'), - ) - assert client.transport._host == 'appengine.googleapis.com:8000' - -def test_applications_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ApplicationsGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_applications_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ApplicationsGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ApplicationsGrpcTransport, transports.ApplicationsGrpcAsyncIOTransport]) -def test_applications_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ApplicationsGrpcTransport, transports.ApplicationsGrpcAsyncIOTransport]) -def test_applications_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_applications_grpc_lro_client(): - client = ApplicationsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_applications_grpc_lro_async_client(): - client = ApplicationsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ApplicationsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = ApplicationsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ApplicationsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = ApplicationsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = ApplicationsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ApplicationsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ApplicationsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = ApplicationsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ApplicationsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = ApplicationsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = ApplicationsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ApplicationsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ApplicationsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = ApplicationsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ApplicationsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.ApplicationsTransport, '_prep_wrapped_messages') as prep: - client = ApplicationsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ApplicationsTransport, '_prep_wrapped_messages') as prep: - transport_class = ApplicationsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py deleted file mode 100644 index 5dddcce..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py +++ /dev/null @@ -1,1927 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.appengine_admin_v1.services.authorized_certificates import AuthorizedCertificatesAsyncClient -from google.cloud.appengine_admin_v1.services.authorized_certificates import AuthorizedCertificatesClient -from google.cloud.appengine_admin_v1.services.authorized_certificates import pagers -from google.cloud.appengine_admin_v1.services.authorized_certificates import transports -from google.cloud.appengine_admin_v1.services.authorized_certificates.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import certificate -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert AuthorizedCertificatesClient._get_default_mtls_endpoint(None) is None - assert AuthorizedCertificatesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AuthorizedCertificatesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AuthorizedCertificatesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AuthorizedCertificatesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AuthorizedCertificatesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - AuthorizedCertificatesClient, - AuthorizedCertificatesAsyncClient, -]) -def test_authorized_certificates_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'appengine.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AuthorizedCertificatesGrpcTransport, "grpc"), - (transports.AuthorizedCertificatesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_authorized_certificates_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class", [ - AuthorizedCertificatesClient, - AuthorizedCertificatesAsyncClient, -]) -def test_authorized_certificates_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'appengine.googleapis.com:443' - - -def test_authorized_certificates_client_get_transport_class(): - transport = AuthorizedCertificatesClient.get_transport_class() - available_transports = [ - transports.AuthorizedCertificatesGrpcTransport, - ] - assert transport in available_transports - - transport = AuthorizedCertificatesClient.get_transport_class("grpc") - assert transport == transports.AuthorizedCertificatesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AuthorizedCertificatesClient, transports.AuthorizedCertificatesGrpcTransport, "grpc"), - (AuthorizedCertificatesAsyncClient, transports.AuthorizedCertificatesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(AuthorizedCertificatesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AuthorizedCertificatesClient)) -@mock.patch.object(AuthorizedCertificatesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AuthorizedCertificatesAsyncClient)) -def test_authorized_certificates_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(AuthorizedCertificatesClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(AuthorizedCertificatesClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (AuthorizedCertificatesClient, transports.AuthorizedCertificatesGrpcTransport, "grpc", "true"), - (AuthorizedCertificatesAsyncClient, transports.AuthorizedCertificatesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AuthorizedCertificatesClient, transports.AuthorizedCertificatesGrpcTransport, "grpc", "false"), - (AuthorizedCertificatesAsyncClient, transports.AuthorizedCertificatesGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(AuthorizedCertificatesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AuthorizedCertificatesClient)) -@mock.patch.object(AuthorizedCertificatesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AuthorizedCertificatesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_authorized_certificates_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AuthorizedCertificatesClient, transports.AuthorizedCertificatesGrpcTransport, "grpc"), - (AuthorizedCertificatesAsyncClient, transports.AuthorizedCertificatesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_authorized_certificates_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AuthorizedCertificatesClient, transports.AuthorizedCertificatesGrpcTransport, "grpc"), - (AuthorizedCertificatesAsyncClient, transports.AuthorizedCertificatesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_authorized_certificates_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_authorized_certificates_client_client_options_from_dict(): - with mock.patch('google.cloud.appengine_admin_v1.services.authorized_certificates.transports.AuthorizedCertificatesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AuthorizedCertificatesClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_list_authorized_certificates(transport: str = 'grpc', request_type=appengine.ListAuthorizedCertificatesRequest): - client = AuthorizedCertificatesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorized_certificates), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = appengine.ListAuthorizedCertificatesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_authorized_certificates(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListAuthorizedCertificatesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAuthorizedCertificatesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_authorized_certificates_from_dict(): - test_list_authorized_certificates(request_type=dict) - - -def test_list_authorized_certificates_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AuthorizedCertificatesClient( - credentials=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_authorized_certificates), - '__call__') as call: - client.list_authorized_certificates() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListAuthorizedCertificatesRequest() - - -@pytest.mark.asyncio -async def test_list_authorized_certificates_async(transport: str = 'grpc_asyncio', request_type=appengine.ListAuthorizedCertificatesRequest): - client = AuthorizedCertificatesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorized_certificates), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListAuthorizedCertificatesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_authorized_certificates(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListAuthorizedCertificatesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAuthorizedCertificatesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_authorized_certificates_async_from_dict(): - await test_list_authorized_certificates_async(request_type=dict) - - -def test_list_authorized_certificates_field_headers(): - client = AuthorizedCertificatesClient( - credentials=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. - request = appengine.ListAuthorizedCertificatesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorized_certificates), - '__call__') as call: - call.return_value = appengine.ListAuthorizedCertificatesResponse() - client.list_authorized_certificates(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_authorized_certificates_field_headers_async(): - client = AuthorizedCertificatesAsyncClient( - credentials=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. - request = appengine.ListAuthorizedCertificatesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorized_certificates), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListAuthorizedCertificatesResponse()) - await client.list_authorized_certificates(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_list_authorized_certificates_pager(): - client = AuthorizedCertificatesClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorized_certificates), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListAuthorizedCertificatesResponse( - certificates=[ - certificate.AuthorizedCertificate(), - certificate.AuthorizedCertificate(), - certificate.AuthorizedCertificate(), - ], - next_page_token='abc', - ), - appengine.ListAuthorizedCertificatesResponse( - certificates=[], - next_page_token='def', - ), - appengine.ListAuthorizedCertificatesResponse( - certificates=[ - certificate.AuthorizedCertificate(), - ], - next_page_token='ghi', - ), - appengine.ListAuthorizedCertificatesResponse( - certificates=[ - certificate.AuthorizedCertificate(), - certificate.AuthorizedCertificate(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_authorized_certificates(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, certificate.AuthorizedCertificate) - for i in results) - -def test_list_authorized_certificates_pages(): - client = AuthorizedCertificatesClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorized_certificates), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListAuthorizedCertificatesResponse( - certificates=[ - certificate.AuthorizedCertificate(), - certificate.AuthorizedCertificate(), - certificate.AuthorizedCertificate(), - ], - next_page_token='abc', - ), - appengine.ListAuthorizedCertificatesResponse( - certificates=[], - next_page_token='def', - ), - appengine.ListAuthorizedCertificatesResponse( - certificates=[ - certificate.AuthorizedCertificate(), - ], - next_page_token='ghi', - ), - appengine.ListAuthorizedCertificatesResponse( - certificates=[ - certificate.AuthorizedCertificate(), - certificate.AuthorizedCertificate(), - ], - ), - RuntimeError, - ) - pages = list(client.list_authorized_certificates(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_authorized_certificates_async_pager(): - client = AuthorizedCertificatesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorized_certificates), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListAuthorizedCertificatesResponse( - certificates=[ - certificate.AuthorizedCertificate(), - certificate.AuthorizedCertificate(), - certificate.AuthorizedCertificate(), - ], - next_page_token='abc', - ), - appengine.ListAuthorizedCertificatesResponse( - certificates=[], - next_page_token='def', - ), - appengine.ListAuthorizedCertificatesResponse( - certificates=[ - certificate.AuthorizedCertificate(), - ], - next_page_token='ghi', - ), - appengine.ListAuthorizedCertificatesResponse( - certificates=[ - certificate.AuthorizedCertificate(), - certificate.AuthorizedCertificate(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_authorized_certificates(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, certificate.AuthorizedCertificate) - for i in responses) - -@pytest.mark.asyncio -async def test_list_authorized_certificates_async_pages(): - client = AuthorizedCertificatesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorized_certificates), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListAuthorizedCertificatesResponse( - certificates=[ - certificate.AuthorizedCertificate(), - certificate.AuthorizedCertificate(), - certificate.AuthorizedCertificate(), - ], - next_page_token='abc', - ), - appengine.ListAuthorizedCertificatesResponse( - certificates=[], - next_page_token='def', - ), - appengine.ListAuthorizedCertificatesResponse( - certificates=[ - certificate.AuthorizedCertificate(), - ], - next_page_token='ghi', - ), - appengine.ListAuthorizedCertificatesResponse( - certificates=[ - certificate.AuthorizedCertificate(), - certificate.AuthorizedCertificate(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_authorized_certificates(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_authorized_certificate(transport: str = 'grpc', request_type=appengine.GetAuthorizedCertificateRequest): - client = AuthorizedCertificatesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_authorized_certificate), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = certificate.AuthorizedCertificate( - name='name_value', - id='id_value', - display_name='display_name_value', - domain_names=['domain_names_value'], - visible_domain_mappings=['visible_domain_mappings_value'], - domain_mappings_count=2238, - ) - response = client.get_authorized_certificate(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetAuthorizedCertificateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, certificate.AuthorizedCertificate) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.display_name == 'display_name_value' - assert response.domain_names == ['domain_names_value'] - assert response.visible_domain_mappings == ['visible_domain_mappings_value'] - assert response.domain_mappings_count == 2238 - - -def test_get_authorized_certificate_from_dict(): - test_get_authorized_certificate(request_type=dict) - - -def test_get_authorized_certificate_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AuthorizedCertificatesClient( - credentials=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_authorized_certificate), - '__call__') as call: - client.get_authorized_certificate() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetAuthorizedCertificateRequest() - - -@pytest.mark.asyncio -async def test_get_authorized_certificate_async(transport: str = 'grpc_asyncio', request_type=appengine.GetAuthorizedCertificateRequest): - client = AuthorizedCertificatesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_authorized_certificate), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(certificate.AuthorizedCertificate( - name='name_value', - id='id_value', - display_name='display_name_value', - domain_names=['domain_names_value'], - visible_domain_mappings=['visible_domain_mappings_value'], - domain_mappings_count=2238, - )) - response = await client.get_authorized_certificate(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetAuthorizedCertificateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, certificate.AuthorizedCertificate) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.display_name == 'display_name_value' - assert response.domain_names == ['domain_names_value'] - assert response.visible_domain_mappings == ['visible_domain_mappings_value'] - assert response.domain_mappings_count == 2238 - - -@pytest.mark.asyncio -async def test_get_authorized_certificate_async_from_dict(): - await test_get_authorized_certificate_async(request_type=dict) - - -def test_get_authorized_certificate_field_headers(): - client = AuthorizedCertificatesClient( - credentials=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. - request = appengine.GetAuthorizedCertificateRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_authorized_certificate), - '__call__') as call: - call.return_value = certificate.AuthorizedCertificate() - client.get_authorized_certificate(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_authorized_certificate_field_headers_async(): - client = AuthorizedCertificatesAsyncClient( - credentials=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. - request = appengine.GetAuthorizedCertificateRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_authorized_certificate), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(certificate.AuthorizedCertificate()) - await client.get_authorized_certificate(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_create_authorized_certificate(transport: str = 'grpc', request_type=appengine.CreateAuthorizedCertificateRequest): - client = AuthorizedCertificatesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_authorized_certificate), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = certificate.AuthorizedCertificate( - name='name_value', - id='id_value', - display_name='display_name_value', - domain_names=['domain_names_value'], - visible_domain_mappings=['visible_domain_mappings_value'], - domain_mappings_count=2238, - ) - response = client.create_authorized_certificate(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateAuthorizedCertificateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, certificate.AuthorizedCertificate) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.display_name == 'display_name_value' - assert response.domain_names == ['domain_names_value'] - assert response.visible_domain_mappings == ['visible_domain_mappings_value'] - assert response.domain_mappings_count == 2238 - - -def test_create_authorized_certificate_from_dict(): - test_create_authorized_certificate(request_type=dict) - - -def test_create_authorized_certificate_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AuthorizedCertificatesClient( - credentials=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_authorized_certificate), - '__call__') as call: - client.create_authorized_certificate() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateAuthorizedCertificateRequest() - - -@pytest.mark.asyncio -async def test_create_authorized_certificate_async(transport: str = 'grpc_asyncio', request_type=appengine.CreateAuthorizedCertificateRequest): - client = AuthorizedCertificatesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_authorized_certificate), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(certificate.AuthorizedCertificate( - name='name_value', - id='id_value', - display_name='display_name_value', - domain_names=['domain_names_value'], - visible_domain_mappings=['visible_domain_mappings_value'], - domain_mappings_count=2238, - )) - response = await client.create_authorized_certificate(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateAuthorizedCertificateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, certificate.AuthorizedCertificate) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.display_name == 'display_name_value' - assert response.domain_names == ['domain_names_value'] - assert response.visible_domain_mappings == ['visible_domain_mappings_value'] - assert response.domain_mappings_count == 2238 - - -@pytest.mark.asyncio -async def test_create_authorized_certificate_async_from_dict(): - await test_create_authorized_certificate_async(request_type=dict) - - -def test_create_authorized_certificate_field_headers(): - client = AuthorizedCertificatesClient( - credentials=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. - request = appengine.CreateAuthorizedCertificateRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_authorized_certificate), - '__call__') as call: - call.return_value = certificate.AuthorizedCertificate() - client.create_authorized_certificate(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_authorized_certificate_field_headers_async(): - client = AuthorizedCertificatesAsyncClient( - credentials=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. - request = appengine.CreateAuthorizedCertificateRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_authorized_certificate), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(certificate.AuthorizedCertificate()) - await client.create_authorized_certificate(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_update_authorized_certificate(transport: str = 'grpc', request_type=appengine.UpdateAuthorizedCertificateRequest): - client = AuthorizedCertificatesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_authorized_certificate), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = certificate.AuthorizedCertificate( - name='name_value', - id='id_value', - display_name='display_name_value', - domain_names=['domain_names_value'], - visible_domain_mappings=['visible_domain_mappings_value'], - domain_mappings_count=2238, - ) - response = client.update_authorized_certificate(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateAuthorizedCertificateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, certificate.AuthorizedCertificate) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.display_name == 'display_name_value' - assert response.domain_names == ['domain_names_value'] - assert response.visible_domain_mappings == ['visible_domain_mappings_value'] - assert response.domain_mappings_count == 2238 - - -def test_update_authorized_certificate_from_dict(): - test_update_authorized_certificate(request_type=dict) - - -def test_update_authorized_certificate_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AuthorizedCertificatesClient( - credentials=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_authorized_certificate), - '__call__') as call: - client.update_authorized_certificate() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateAuthorizedCertificateRequest() - - -@pytest.mark.asyncio -async def test_update_authorized_certificate_async(transport: str = 'grpc_asyncio', request_type=appengine.UpdateAuthorizedCertificateRequest): - client = AuthorizedCertificatesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_authorized_certificate), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(certificate.AuthorizedCertificate( - name='name_value', - id='id_value', - display_name='display_name_value', - domain_names=['domain_names_value'], - visible_domain_mappings=['visible_domain_mappings_value'], - domain_mappings_count=2238, - )) - response = await client.update_authorized_certificate(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateAuthorizedCertificateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, certificate.AuthorizedCertificate) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.display_name == 'display_name_value' - assert response.domain_names == ['domain_names_value'] - assert response.visible_domain_mappings == ['visible_domain_mappings_value'] - assert response.domain_mappings_count == 2238 - - -@pytest.mark.asyncio -async def test_update_authorized_certificate_async_from_dict(): - await test_update_authorized_certificate_async(request_type=dict) - - -def test_update_authorized_certificate_field_headers(): - client = AuthorizedCertificatesClient( - credentials=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. - request = appengine.UpdateAuthorizedCertificateRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_authorized_certificate), - '__call__') as call: - call.return_value = certificate.AuthorizedCertificate() - client.update_authorized_certificate(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_authorized_certificate_field_headers_async(): - client = AuthorizedCertificatesAsyncClient( - credentials=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. - request = appengine.UpdateAuthorizedCertificateRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_authorized_certificate), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(certificate.AuthorizedCertificate()) - await client.update_authorized_certificate(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_delete_authorized_certificate(transport: str = 'grpc', request_type=appengine.DeleteAuthorizedCertificateRequest): - client = AuthorizedCertificatesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_authorized_certificate), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_authorized_certificate(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteAuthorizedCertificateRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_authorized_certificate_from_dict(): - test_delete_authorized_certificate(request_type=dict) - - -def test_delete_authorized_certificate_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AuthorizedCertificatesClient( - credentials=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_authorized_certificate), - '__call__') as call: - client.delete_authorized_certificate() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteAuthorizedCertificateRequest() - - -@pytest.mark.asyncio -async def test_delete_authorized_certificate_async(transport: str = 'grpc_asyncio', request_type=appengine.DeleteAuthorizedCertificateRequest): - client = AuthorizedCertificatesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_authorized_certificate), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_authorized_certificate(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteAuthorizedCertificateRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_authorized_certificate_async_from_dict(): - await test_delete_authorized_certificate_async(request_type=dict) - - -def test_delete_authorized_certificate_field_headers(): - client = AuthorizedCertificatesClient( - credentials=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. - request = appengine.DeleteAuthorizedCertificateRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_authorized_certificate), - '__call__') as call: - call.return_value = None - client.delete_authorized_certificate(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_authorized_certificate_field_headers_async(): - client = AuthorizedCertificatesAsyncClient( - credentials=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. - request = appengine.DeleteAuthorizedCertificateRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_authorized_certificate), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_authorized_certificate(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AuthorizedCertificatesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AuthorizedCertificatesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AuthorizedCertificatesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AuthorizedCertificatesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AuthorizedCertificatesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AuthorizedCertificatesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AuthorizedCertificatesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AuthorizedCertificatesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AuthorizedCertificatesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AuthorizedCertificatesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AuthorizedCertificatesGrpcTransport, - transports.AuthorizedCertificatesGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = AuthorizedCertificatesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.AuthorizedCertificatesGrpcTransport, - ) - -def test_authorized_certificates_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AuthorizedCertificatesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_authorized_certificates_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.appengine_admin_v1.services.authorized_certificates.transports.AuthorizedCertificatesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AuthorizedCertificatesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_authorized_certificates', - 'get_authorized_certificate', - 'create_authorized_certificate', - 'update_authorized_certificate', - 'delete_authorized_certificate', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_authorized_certificates_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.authorized_certificates.transports.AuthorizedCertificatesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AuthorizedCertificatesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_authorized_certificates_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.authorized_certificates.transports.AuthorizedCertificatesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AuthorizedCertificatesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ), - quota_project_id="octopus", - ) - - -def test_authorized_certificates_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.appengine_admin_v1.services.authorized_certificates.transports.AuthorizedCertificatesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AuthorizedCertificatesTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_authorized_certificates_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - AuthorizedCertificatesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_authorized_certificates_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - AuthorizedCertificatesClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AuthorizedCertificatesGrpcTransport, - transports.AuthorizedCertificatesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_authorized_certificates_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AuthorizedCertificatesGrpcTransport, - transports.AuthorizedCertificatesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_authorized_certificates_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AuthorizedCertificatesGrpcTransport, grpc_helpers), - (transports.AuthorizedCertificatesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_authorized_certificates_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "appengine.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - scopes=["1", "2"], - default_host="appengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.AuthorizedCertificatesGrpcTransport, transports.AuthorizedCertificatesGrpcAsyncIOTransport]) -def test_authorized_certificates_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_authorized_certificates_host_no_port(): - client = AuthorizedCertificatesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com'), - ) - assert client.transport._host == 'appengine.googleapis.com:443' - - -def test_authorized_certificates_host_with_port(): - client = AuthorizedCertificatesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com:8000'), - ) - assert client.transport._host == 'appengine.googleapis.com:8000' - -def test_authorized_certificates_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AuthorizedCertificatesGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_authorized_certificates_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AuthorizedCertificatesGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.AuthorizedCertificatesGrpcTransport, transports.AuthorizedCertificatesGrpcAsyncIOTransport]) -def test_authorized_certificates_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.AuthorizedCertificatesGrpcTransport, transports.AuthorizedCertificatesGrpcAsyncIOTransport]) -def test_authorized_certificates_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AuthorizedCertificatesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = AuthorizedCertificatesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AuthorizedCertificatesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = AuthorizedCertificatesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = AuthorizedCertificatesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AuthorizedCertificatesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AuthorizedCertificatesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = AuthorizedCertificatesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AuthorizedCertificatesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = AuthorizedCertificatesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = AuthorizedCertificatesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AuthorizedCertificatesClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = AuthorizedCertificatesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = AuthorizedCertificatesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AuthorizedCertificatesClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.AuthorizedCertificatesTransport, '_prep_wrapped_messages') as prep: - client = AuthorizedCertificatesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AuthorizedCertificatesTransport, '_prep_wrapped_messages') as prep: - transport_class = AuthorizedCertificatesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py deleted file mode 100644 index 9b8b2d3..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py +++ /dev/null @@ -1,1264 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.appengine_admin_v1.services.authorized_domains import AuthorizedDomainsAsyncClient -from google.cloud.appengine_admin_v1.services.authorized_domains import AuthorizedDomainsClient -from google.cloud.appengine_admin_v1.services.authorized_domains import pagers -from google.cloud.appengine_admin_v1.services.authorized_domains import transports -from google.cloud.appengine_admin_v1.services.authorized_domains.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import domain -from google.oauth2 import service_account -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert AuthorizedDomainsClient._get_default_mtls_endpoint(None) is None - assert AuthorizedDomainsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AuthorizedDomainsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AuthorizedDomainsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AuthorizedDomainsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AuthorizedDomainsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - AuthorizedDomainsClient, - AuthorizedDomainsAsyncClient, -]) -def test_authorized_domains_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'appengine.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AuthorizedDomainsGrpcTransport, "grpc"), - (transports.AuthorizedDomainsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_authorized_domains_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class", [ - AuthorizedDomainsClient, - AuthorizedDomainsAsyncClient, -]) -def test_authorized_domains_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'appengine.googleapis.com:443' - - -def test_authorized_domains_client_get_transport_class(): - transport = AuthorizedDomainsClient.get_transport_class() - available_transports = [ - transports.AuthorizedDomainsGrpcTransport, - ] - assert transport in available_transports - - transport = AuthorizedDomainsClient.get_transport_class("grpc") - assert transport == transports.AuthorizedDomainsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AuthorizedDomainsClient, transports.AuthorizedDomainsGrpcTransport, "grpc"), - (AuthorizedDomainsAsyncClient, transports.AuthorizedDomainsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(AuthorizedDomainsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AuthorizedDomainsClient)) -@mock.patch.object(AuthorizedDomainsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AuthorizedDomainsAsyncClient)) -def test_authorized_domains_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(AuthorizedDomainsClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(AuthorizedDomainsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (AuthorizedDomainsClient, transports.AuthorizedDomainsGrpcTransport, "grpc", "true"), - (AuthorizedDomainsAsyncClient, transports.AuthorizedDomainsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AuthorizedDomainsClient, transports.AuthorizedDomainsGrpcTransport, "grpc", "false"), - (AuthorizedDomainsAsyncClient, transports.AuthorizedDomainsGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(AuthorizedDomainsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AuthorizedDomainsClient)) -@mock.patch.object(AuthorizedDomainsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AuthorizedDomainsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_authorized_domains_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AuthorizedDomainsClient, transports.AuthorizedDomainsGrpcTransport, "grpc"), - (AuthorizedDomainsAsyncClient, transports.AuthorizedDomainsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_authorized_domains_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AuthorizedDomainsClient, transports.AuthorizedDomainsGrpcTransport, "grpc"), - (AuthorizedDomainsAsyncClient, transports.AuthorizedDomainsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_authorized_domains_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_authorized_domains_client_client_options_from_dict(): - with mock.patch('google.cloud.appengine_admin_v1.services.authorized_domains.transports.AuthorizedDomainsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AuthorizedDomainsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_list_authorized_domains(transport: str = 'grpc', request_type=appengine.ListAuthorizedDomainsRequest): - client = AuthorizedDomainsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorized_domains), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = appengine.ListAuthorizedDomainsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_authorized_domains(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListAuthorizedDomainsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAuthorizedDomainsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_authorized_domains_from_dict(): - test_list_authorized_domains(request_type=dict) - - -def test_list_authorized_domains_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AuthorizedDomainsClient( - credentials=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_authorized_domains), - '__call__') as call: - client.list_authorized_domains() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListAuthorizedDomainsRequest() - - -@pytest.mark.asyncio -async def test_list_authorized_domains_async(transport: str = 'grpc_asyncio', request_type=appengine.ListAuthorizedDomainsRequest): - client = AuthorizedDomainsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorized_domains), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListAuthorizedDomainsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_authorized_domains(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListAuthorizedDomainsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAuthorizedDomainsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_authorized_domains_async_from_dict(): - await test_list_authorized_domains_async(request_type=dict) - - -def test_list_authorized_domains_field_headers(): - client = AuthorizedDomainsClient( - credentials=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. - request = appengine.ListAuthorizedDomainsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorized_domains), - '__call__') as call: - call.return_value = appengine.ListAuthorizedDomainsResponse() - client.list_authorized_domains(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_authorized_domains_field_headers_async(): - client = AuthorizedDomainsAsyncClient( - credentials=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. - request = appengine.ListAuthorizedDomainsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorized_domains), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListAuthorizedDomainsResponse()) - await client.list_authorized_domains(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_list_authorized_domains_pager(): - client = AuthorizedDomainsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorized_domains), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListAuthorizedDomainsResponse( - domains=[ - domain.AuthorizedDomain(), - domain.AuthorizedDomain(), - domain.AuthorizedDomain(), - ], - next_page_token='abc', - ), - appengine.ListAuthorizedDomainsResponse( - domains=[], - next_page_token='def', - ), - appengine.ListAuthorizedDomainsResponse( - domains=[ - domain.AuthorizedDomain(), - ], - next_page_token='ghi', - ), - appengine.ListAuthorizedDomainsResponse( - domains=[ - domain.AuthorizedDomain(), - domain.AuthorizedDomain(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_authorized_domains(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, domain.AuthorizedDomain) - for i in results) - -def test_list_authorized_domains_pages(): - client = AuthorizedDomainsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorized_domains), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListAuthorizedDomainsResponse( - domains=[ - domain.AuthorizedDomain(), - domain.AuthorizedDomain(), - domain.AuthorizedDomain(), - ], - next_page_token='abc', - ), - appengine.ListAuthorizedDomainsResponse( - domains=[], - next_page_token='def', - ), - appengine.ListAuthorizedDomainsResponse( - domains=[ - domain.AuthorizedDomain(), - ], - next_page_token='ghi', - ), - appengine.ListAuthorizedDomainsResponse( - domains=[ - domain.AuthorizedDomain(), - domain.AuthorizedDomain(), - ], - ), - RuntimeError, - ) - pages = list(client.list_authorized_domains(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_authorized_domains_async_pager(): - client = AuthorizedDomainsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorized_domains), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListAuthorizedDomainsResponse( - domains=[ - domain.AuthorizedDomain(), - domain.AuthorizedDomain(), - domain.AuthorizedDomain(), - ], - next_page_token='abc', - ), - appengine.ListAuthorizedDomainsResponse( - domains=[], - next_page_token='def', - ), - appengine.ListAuthorizedDomainsResponse( - domains=[ - domain.AuthorizedDomain(), - ], - next_page_token='ghi', - ), - appengine.ListAuthorizedDomainsResponse( - domains=[ - domain.AuthorizedDomain(), - domain.AuthorizedDomain(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_authorized_domains(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, domain.AuthorizedDomain) - for i in responses) - -@pytest.mark.asyncio -async def test_list_authorized_domains_async_pages(): - client = AuthorizedDomainsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorized_domains), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListAuthorizedDomainsResponse( - domains=[ - domain.AuthorizedDomain(), - domain.AuthorizedDomain(), - domain.AuthorizedDomain(), - ], - next_page_token='abc', - ), - appengine.ListAuthorizedDomainsResponse( - domains=[], - next_page_token='def', - ), - appengine.ListAuthorizedDomainsResponse( - domains=[ - domain.AuthorizedDomain(), - ], - next_page_token='ghi', - ), - appengine.ListAuthorizedDomainsResponse( - domains=[ - domain.AuthorizedDomain(), - domain.AuthorizedDomain(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_authorized_domains(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AuthorizedDomainsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AuthorizedDomainsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AuthorizedDomainsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AuthorizedDomainsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AuthorizedDomainsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AuthorizedDomainsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AuthorizedDomainsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AuthorizedDomainsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AuthorizedDomainsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AuthorizedDomainsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AuthorizedDomainsGrpcTransport, - transports.AuthorizedDomainsGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = AuthorizedDomainsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.AuthorizedDomainsGrpcTransport, - ) - -def test_authorized_domains_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AuthorizedDomainsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_authorized_domains_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.appengine_admin_v1.services.authorized_domains.transports.AuthorizedDomainsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AuthorizedDomainsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_authorized_domains', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_authorized_domains_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.authorized_domains.transports.AuthorizedDomainsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AuthorizedDomainsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_authorized_domains_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.authorized_domains.transports.AuthorizedDomainsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AuthorizedDomainsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ), - quota_project_id="octopus", - ) - - -def test_authorized_domains_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.appengine_admin_v1.services.authorized_domains.transports.AuthorizedDomainsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AuthorizedDomainsTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_authorized_domains_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - AuthorizedDomainsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_authorized_domains_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - AuthorizedDomainsClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AuthorizedDomainsGrpcTransport, - transports.AuthorizedDomainsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_authorized_domains_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AuthorizedDomainsGrpcTransport, - transports.AuthorizedDomainsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_authorized_domains_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AuthorizedDomainsGrpcTransport, grpc_helpers), - (transports.AuthorizedDomainsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_authorized_domains_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "appengine.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - scopes=["1", "2"], - default_host="appengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.AuthorizedDomainsGrpcTransport, transports.AuthorizedDomainsGrpcAsyncIOTransport]) -def test_authorized_domains_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_authorized_domains_host_no_port(): - client = AuthorizedDomainsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com'), - ) - assert client.transport._host == 'appengine.googleapis.com:443' - - -def test_authorized_domains_host_with_port(): - client = AuthorizedDomainsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com:8000'), - ) - assert client.transport._host == 'appengine.googleapis.com:8000' - -def test_authorized_domains_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AuthorizedDomainsGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_authorized_domains_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AuthorizedDomainsGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.AuthorizedDomainsGrpcTransport, transports.AuthorizedDomainsGrpcAsyncIOTransport]) -def test_authorized_domains_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.AuthorizedDomainsGrpcTransport, transports.AuthorizedDomainsGrpcAsyncIOTransport]) -def test_authorized_domains_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AuthorizedDomainsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = AuthorizedDomainsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AuthorizedDomainsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = AuthorizedDomainsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = AuthorizedDomainsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AuthorizedDomainsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AuthorizedDomainsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = AuthorizedDomainsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AuthorizedDomainsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = AuthorizedDomainsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = AuthorizedDomainsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AuthorizedDomainsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = AuthorizedDomainsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = AuthorizedDomainsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AuthorizedDomainsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.AuthorizedDomainsTransport, '_prep_wrapped_messages') as prep: - client = AuthorizedDomainsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AuthorizedDomainsTransport, '_prep_wrapped_messages') as prep: - transport_class = AuthorizedDomainsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py deleted file mode 100644 index 8dad54e..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py +++ /dev/null @@ -1,1908 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.appengine_admin_v1.services.domain_mappings import DomainMappingsAsyncClient -from google.cloud.appengine_admin_v1.services.domain_mappings import DomainMappingsClient -from google.cloud.appengine_admin_v1.services.domain_mappings import pagers -from google.cloud.appengine_admin_v1.services.domain_mappings import transports -from google.cloud.appengine_admin_v1.services.domain_mappings.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import domain_mapping -from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert DomainMappingsClient._get_default_mtls_endpoint(None) is None - assert DomainMappingsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DomainMappingsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DomainMappingsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DomainMappingsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DomainMappingsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - DomainMappingsClient, - DomainMappingsAsyncClient, -]) -def test_domain_mappings_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'appengine.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DomainMappingsGrpcTransport, "grpc"), - (transports.DomainMappingsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_domain_mappings_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class", [ - DomainMappingsClient, - DomainMappingsAsyncClient, -]) -def test_domain_mappings_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'appengine.googleapis.com:443' - - -def test_domain_mappings_client_get_transport_class(): - transport = DomainMappingsClient.get_transport_class() - available_transports = [ - transports.DomainMappingsGrpcTransport, - ] - assert transport in available_transports - - transport = DomainMappingsClient.get_transport_class("grpc") - assert transport == transports.DomainMappingsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DomainMappingsClient, transports.DomainMappingsGrpcTransport, "grpc"), - (DomainMappingsAsyncClient, transports.DomainMappingsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(DomainMappingsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DomainMappingsClient)) -@mock.patch.object(DomainMappingsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DomainMappingsAsyncClient)) -def test_domain_mappings_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(DomainMappingsClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(DomainMappingsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (DomainMappingsClient, transports.DomainMappingsGrpcTransport, "grpc", "true"), - (DomainMappingsAsyncClient, transports.DomainMappingsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DomainMappingsClient, transports.DomainMappingsGrpcTransport, "grpc", "false"), - (DomainMappingsAsyncClient, transports.DomainMappingsGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(DomainMappingsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DomainMappingsClient)) -@mock.patch.object(DomainMappingsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DomainMappingsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_domain_mappings_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DomainMappingsClient, transports.DomainMappingsGrpcTransport, "grpc"), - (DomainMappingsAsyncClient, transports.DomainMappingsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_domain_mappings_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DomainMappingsClient, transports.DomainMappingsGrpcTransport, "grpc"), - (DomainMappingsAsyncClient, transports.DomainMappingsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_domain_mappings_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_domain_mappings_client_client_options_from_dict(): - with mock.patch('google.cloud.appengine_admin_v1.services.domain_mappings.transports.DomainMappingsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = DomainMappingsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_list_domain_mappings(transport: str = 'grpc', request_type=appengine.ListDomainMappingsRequest): - client = DomainMappingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_domain_mappings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = appengine.ListDomainMappingsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_domain_mappings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListDomainMappingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDomainMappingsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_domain_mappings_from_dict(): - test_list_domain_mappings(request_type=dict) - - -def test_list_domain_mappings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DomainMappingsClient( - credentials=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_domain_mappings), - '__call__') as call: - client.list_domain_mappings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListDomainMappingsRequest() - - -@pytest.mark.asyncio -async def test_list_domain_mappings_async(transport: str = 'grpc_asyncio', request_type=appengine.ListDomainMappingsRequest): - client = DomainMappingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_domain_mappings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListDomainMappingsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_domain_mappings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListDomainMappingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDomainMappingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_domain_mappings_async_from_dict(): - await test_list_domain_mappings_async(request_type=dict) - - -def test_list_domain_mappings_field_headers(): - client = DomainMappingsClient( - credentials=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. - request = appengine.ListDomainMappingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_domain_mappings), - '__call__') as call: - call.return_value = appengine.ListDomainMappingsResponse() - client.list_domain_mappings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_domain_mappings_field_headers_async(): - client = DomainMappingsAsyncClient( - credentials=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. - request = appengine.ListDomainMappingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_domain_mappings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListDomainMappingsResponse()) - await client.list_domain_mappings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_list_domain_mappings_pager(): - client = DomainMappingsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_domain_mappings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListDomainMappingsResponse( - domain_mappings=[ - domain_mapping.DomainMapping(), - domain_mapping.DomainMapping(), - domain_mapping.DomainMapping(), - ], - next_page_token='abc', - ), - appengine.ListDomainMappingsResponse( - domain_mappings=[], - next_page_token='def', - ), - appengine.ListDomainMappingsResponse( - domain_mappings=[ - domain_mapping.DomainMapping(), - ], - next_page_token='ghi', - ), - appengine.ListDomainMappingsResponse( - domain_mappings=[ - domain_mapping.DomainMapping(), - domain_mapping.DomainMapping(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_domain_mappings(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, domain_mapping.DomainMapping) - for i in results) - -def test_list_domain_mappings_pages(): - client = DomainMappingsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_domain_mappings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListDomainMappingsResponse( - domain_mappings=[ - domain_mapping.DomainMapping(), - domain_mapping.DomainMapping(), - domain_mapping.DomainMapping(), - ], - next_page_token='abc', - ), - appengine.ListDomainMappingsResponse( - domain_mappings=[], - next_page_token='def', - ), - appengine.ListDomainMappingsResponse( - domain_mappings=[ - domain_mapping.DomainMapping(), - ], - next_page_token='ghi', - ), - appengine.ListDomainMappingsResponse( - domain_mappings=[ - domain_mapping.DomainMapping(), - domain_mapping.DomainMapping(), - ], - ), - RuntimeError, - ) - pages = list(client.list_domain_mappings(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_domain_mappings_async_pager(): - client = DomainMappingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_domain_mappings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListDomainMappingsResponse( - domain_mappings=[ - domain_mapping.DomainMapping(), - domain_mapping.DomainMapping(), - domain_mapping.DomainMapping(), - ], - next_page_token='abc', - ), - appengine.ListDomainMappingsResponse( - domain_mappings=[], - next_page_token='def', - ), - appengine.ListDomainMappingsResponse( - domain_mappings=[ - domain_mapping.DomainMapping(), - ], - next_page_token='ghi', - ), - appengine.ListDomainMappingsResponse( - domain_mappings=[ - domain_mapping.DomainMapping(), - domain_mapping.DomainMapping(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_domain_mappings(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, domain_mapping.DomainMapping) - for i in responses) - -@pytest.mark.asyncio -async def test_list_domain_mappings_async_pages(): - client = DomainMappingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_domain_mappings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListDomainMappingsResponse( - domain_mappings=[ - domain_mapping.DomainMapping(), - domain_mapping.DomainMapping(), - domain_mapping.DomainMapping(), - ], - next_page_token='abc', - ), - appengine.ListDomainMappingsResponse( - domain_mappings=[], - next_page_token='def', - ), - appengine.ListDomainMappingsResponse( - domain_mappings=[ - domain_mapping.DomainMapping(), - ], - next_page_token='ghi', - ), - appengine.ListDomainMappingsResponse( - domain_mappings=[ - domain_mapping.DomainMapping(), - domain_mapping.DomainMapping(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_domain_mappings(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_domain_mapping(transport: str = 'grpc', request_type=appengine.GetDomainMappingRequest): - client = DomainMappingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_domain_mapping), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = domain_mapping.DomainMapping( - name='name_value', - id='id_value', - ) - response = client.get_domain_mapping(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetDomainMappingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, domain_mapping.DomainMapping) - assert response.name == 'name_value' - assert response.id == 'id_value' - - -def test_get_domain_mapping_from_dict(): - test_get_domain_mapping(request_type=dict) - - -def test_get_domain_mapping_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DomainMappingsClient( - credentials=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_domain_mapping), - '__call__') as call: - client.get_domain_mapping() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetDomainMappingRequest() - - -@pytest.mark.asyncio -async def test_get_domain_mapping_async(transport: str = 'grpc_asyncio', request_type=appengine.GetDomainMappingRequest): - client = DomainMappingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_domain_mapping), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(domain_mapping.DomainMapping( - name='name_value', - id='id_value', - )) - response = await client.get_domain_mapping(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetDomainMappingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, domain_mapping.DomainMapping) - assert response.name == 'name_value' - assert response.id == 'id_value' - - -@pytest.mark.asyncio -async def test_get_domain_mapping_async_from_dict(): - await test_get_domain_mapping_async(request_type=dict) - - -def test_get_domain_mapping_field_headers(): - client = DomainMappingsClient( - credentials=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. - request = appengine.GetDomainMappingRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_domain_mapping), - '__call__') as call: - call.return_value = domain_mapping.DomainMapping() - client.get_domain_mapping(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_domain_mapping_field_headers_async(): - client = DomainMappingsAsyncClient( - credentials=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. - request = appengine.GetDomainMappingRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_domain_mapping), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(domain_mapping.DomainMapping()) - await client.get_domain_mapping(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_create_domain_mapping(transport: str = 'grpc', request_type=appengine.CreateDomainMappingRequest): - client = DomainMappingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_domain_mapping), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_domain_mapping(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateDomainMappingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_domain_mapping_from_dict(): - test_create_domain_mapping(request_type=dict) - - -def test_create_domain_mapping_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DomainMappingsClient( - credentials=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_domain_mapping), - '__call__') as call: - client.create_domain_mapping() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateDomainMappingRequest() - - -@pytest.mark.asyncio -async def test_create_domain_mapping_async(transport: str = 'grpc_asyncio', request_type=appengine.CreateDomainMappingRequest): - client = DomainMappingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_domain_mapping), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_domain_mapping(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateDomainMappingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_domain_mapping_async_from_dict(): - await test_create_domain_mapping_async(request_type=dict) - - -def test_create_domain_mapping_field_headers(): - client = DomainMappingsClient( - credentials=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. - request = appengine.CreateDomainMappingRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_domain_mapping), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_domain_mapping(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_domain_mapping_field_headers_async(): - client = DomainMappingsAsyncClient( - credentials=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. - request = appengine.CreateDomainMappingRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_domain_mapping), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_domain_mapping(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_update_domain_mapping(transport: str = 'grpc', request_type=appengine.UpdateDomainMappingRequest): - client = DomainMappingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_domain_mapping), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_domain_mapping(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateDomainMappingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_domain_mapping_from_dict(): - test_update_domain_mapping(request_type=dict) - - -def test_update_domain_mapping_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DomainMappingsClient( - credentials=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_domain_mapping), - '__call__') as call: - client.update_domain_mapping() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateDomainMappingRequest() - - -@pytest.mark.asyncio -async def test_update_domain_mapping_async(transport: str = 'grpc_asyncio', request_type=appengine.UpdateDomainMappingRequest): - client = DomainMappingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_domain_mapping), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_domain_mapping(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateDomainMappingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_domain_mapping_async_from_dict(): - await test_update_domain_mapping_async(request_type=dict) - - -def test_update_domain_mapping_field_headers(): - client = DomainMappingsClient( - credentials=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. - request = appengine.UpdateDomainMappingRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_domain_mapping), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_domain_mapping(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_domain_mapping_field_headers_async(): - client = DomainMappingsAsyncClient( - credentials=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. - request = appengine.UpdateDomainMappingRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_domain_mapping), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_domain_mapping(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_delete_domain_mapping(transport: str = 'grpc', request_type=appengine.DeleteDomainMappingRequest): - client = DomainMappingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_domain_mapping), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_domain_mapping(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteDomainMappingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_domain_mapping_from_dict(): - test_delete_domain_mapping(request_type=dict) - - -def test_delete_domain_mapping_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DomainMappingsClient( - credentials=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_domain_mapping), - '__call__') as call: - client.delete_domain_mapping() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteDomainMappingRequest() - - -@pytest.mark.asyncio -async def test_delete_domain_mapping_async(transport: str = 'grpc_asyncio', request_type=appengine.DeleteDomainMappingRequest): - client = DomainMappingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_domain_mapping), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_domain_mapping(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteDomainMappingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_domain_mapping_async_from_dict(): - await test_delete_domain_mapping_async(request_type=dict) - - -def test_delete_domain_mapping_field_headers(): - client = DomainMappingsClient( - credentials=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. - request = appengine.DeleteDomainMappingRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_domain_mapping), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_domain_mapping(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_domain_mapping_field_headers_async(): - client = DomainMappingsAsyncClient( - credentials=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. - request = appengine.DeleteDomainMappingRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_domain_mapping), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_domain_mapping(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DomainMappingsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DomainMappingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.DomainMappingsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DomainMappingsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DomainMappingsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DomainMappingsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DomainMappingsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DomainMappingsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DomainMappingsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DomainMappingsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DomainMappingsGrpcTransport, - transports.DomainMappingsGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = DomainMappingsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DomainMappingsGrpcTransport, - ) - -def test_domain_mappings_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DomainMappingsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_domain_mappings_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.appengine_admin_v1.services.domain_mappings.transports.DomainMappingsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DomainMappingsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_domain_mappings', - 'get_domain_mapping', - 'create_domain_mapping', - 'update_domain_mapping', - 'delete_domain_mapping', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_domain_mappings_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.domain_mappings.transports.DomainMappingsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DomainMappingsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_domain_mappings_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.domain_mappings.transports.DomainMappingsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DomainMappingsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ), - quota_project_id="octopus", - ) - - -def test_domain_mappings_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.appengine_admin_v1.services.domain_mappings.transports.DomainMappingsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DomainMappingsTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_domain_mappings_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - DomainMappingsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_domain_mappings_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - DomainMappingsClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DomainMappingsGrpcTransport, - transports.DomainMappingsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_domain_mappings_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DomainMappingsGrpcTransport, - transports.DomainMappingsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_domain_mappings_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.DomainMappingsGrpcTransport, grpc_helpers), - (transports.DomainMappingsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_domain_mappings_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "appengine.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - scopes=["1", "2"], - default_host="appengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.DomainMappingsGrpcTransport, transports.DomainMappingsGrpcAsyncIOTransport]) -def test_domain_mappings_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_domain_mappings_host_no_port(): - client = DomainMappingsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com'), - ) - assert client.transport._host == 'appengine.googleapis.com:443' - - -def test_domain_mappings_host_with_port(): - client = DomainMappingsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com:8000'), - ) - assert client.transport._host == 'appengine.googleapis.com:8000' - -def test_domain_mappings_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DomainMappingsGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_domain_mappings_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DomainMappingsGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.DomainMappingsGrpcTransport, transports.DomainMappingsGrpcAsyncIOTransport]) -def test_domain_mappings_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.DomainMappingsGrpcTransport, transports.DomainMappingsGrpcAsyncIOTransport]) -def test_domain_mappings_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_domain_mappings_grpc_lro_client(): - client = DomainMappingsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_domain_mappings_grpc_lro_async_client(): - client = DomainMappingsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DomainMappingsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = DomainMappingsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DomainMappingsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = DomainMappingsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = DomainMappingsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DomainMappingsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DomainMappingsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = DomainMappingsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DomainMappingsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = DomainMappingsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = DomainMappingsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DomainMappingsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = DomainMappingsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = DomainMappingsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DomainMappingsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.DomainMappingsTransport, '_prep_wrapped_messages') as prep: - client = DomainMappingsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DomainMappingsTransport, '_prep_wrapped_messages') as prep: - transport_class = DomainMappingsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_firewall.py b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_firewall.py deleted file mode 100644 index a4088ab..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_firewall.py +++ /dev/null @@ -1,2050 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.appengine_admin_v1.services.firewall import FirewallAsyncClient -from google.cloud.appengine_admin_v1.services.firewall import FirewallClient -from google.cloud.appengine_admin_v1.services.firewall import pagers -from google.cloud.appengine_admin_v1.services.firewall import transports -from google.cloud.appengine_admin_v1.services.firewall.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import firewall -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert FirewallClient._get_default_mtls_endpoint(None) is None - assert FirewallClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert FirewallClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert FirewallClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert FirewallClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert FirewallClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - FirewallClient, - FirewallAsyncClient, -]) -def test_firewall_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'appengine.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.FirewallGrpcTransport, "grpc"), - (transports.FirewallGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_firewall_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class", [ - FirewallClient, - FirewallAsyncClient, -]) -def test_firewall_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'appengine.googleapis.com:443' - - -def test_firewall_client_get_transport_class(): - transport = FirewallClient.get_transport_class() - available_transports = [ - transports.FirewallGrpcTransport, - ] - assert transport in available_transports - - transport = FirewallClient.get_transport_class("grpc") - assert transport == transports.FirewallGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (FirewallClient, transports.FirewallGrpcTransport, "grpc"), - (FirewallAsyncClient, transports.FirewallGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(FirewallClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FirewallClient)) -@mock.patch.object(FirewallAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FirewallAsyncClient)) -def test_firewall_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(FirewallClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(FirewallClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (FirewallClient, transports.FirewallGrpcTransport, "grpc", "true"), - (FirewallAsyncClient, transports.FirewallGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (FirewallClient, transports.FirewallGrpcTransport, "grpc", "false"), - (FirewallAsyncClient, transports.FirewallGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(FirewallClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FirewallClient)) -@mock.patch.object(FirewallAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FirewallAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_firewall_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (FirewallClient, transports.FirewallGrpcTransport, "grpc"), - (FirewallAsyncClient, transports.FirewallGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_firewall_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (FirewallClient, transports.FirewallGrpcTransport, "grpc"), - (FirewallAsyncClient, transports.FirewallGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_firewall_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_firewall_client_client_options_from_dict(): - with mock.patch('google.cloud.appengine_admin_v1.services.firewall.transports.FirewallGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = FirewallClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_list_ingress_rules(transport: str = 'grpc', request_type=appengine.ListIngressRulesRequest): - client = FirewallClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_ingress_rules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = appengine.ListIngressRulesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_ingress_rules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListIngressRulesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListIngressRulesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_ingress_rules_from_dict(): - test_list_ingress_rules(request_type=dict) - - -def test_list_ingress_rules_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FirewallClient( - credentials=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_ingress_rules), - '__call__') as call: - client.list_ingress_rules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListIngressRulesRequest() - - -@pytest.mark.asyncio -async def test_list_ingress_rules_async(transport: str = 'grpc_asyncio', request_type=appengine.ListIngressRulesRequest): - client = FirewallAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_ingress_rules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListIngressRulesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_ingress_rules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListIngressRulesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListIngressRulesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_ingress_rules_async_from_dict(): - await test_list_ingress_rules_async(request_type=dict) - - -def test_list_ingress_rules_field_headers(): - client = FirewallClient( - credentials=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. - request = appengine.ListIngressRulesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_ingress_rules), - '__call__') as call: - call.return_value = appengine.ListIngressRulesResponse() - client.list_ingress_rules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_ingress_rules_field_headers_async(): - client = FirewallAsyncClient( - credentials=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. - request = appengine.ListIngressRulesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_ingress_rules), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListIngressRulesResponse()) - await client.list_ingress_rules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_list_ingress_rules_pager(): - client = FirewallClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_ingress_rules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListIngressRulesResponse( - ingress_rules=[ - firewall.FirewallRule(), - firewall.FirewallRule(), - firewall.FirewallRule(), - ], - next_page_token='abc', - ), - appengine.ListIngressRulesResponse( - ingress_rules=[], - next_page_token='def', - ), - appengine.ListIngressRulesResponse( - ingress_rules=[ - firewall.FirewallRule(), - ], - next_page_token='ghi', - ), - appengine.ListIngressRulesResponse( - ingress_rules=[ - firewall.FirewallRule(), - firewall.FirewallRule(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_ingress_rules(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, firewall.FirewallRule) - for i in results) - -def test_list_ingress_rules_pages(): - client = FirewallClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_ingress_rules), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListIngressRulesResponse( - ingress_rules=[ - firewall.FirewallRule(), - firewall.FirewallRule(), - firewall.FirewallRule(), - ], - next_page_token='abc', - ), - appengine.ListIngressRulesResponse( - ingress_rules=[], - next_page_token='def', - ), - appengine.ListIngressRulesResponse( - ingress_rules=[ - firewall.FirewallRule(), - ], - next_page_token='ghi', - ), - appengine.ListIngressRulesResponse( - ingress_rules=[ - firewall.FirewallRule(), - firewall.FirewallRule(), - ], - ), - RuntimeError, - ) - pages = list(client.list_ingress_rules(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_ingress_rules_async_pager(): - client = FirewallAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_ingress_rules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListIngressRulesResponse( - ingress_rules=[ - firewall.FirewallRule(), - firewall.FirewallRule(), - firewall.FirewallRule(), - ], - next_page_token='abc', - ), - appengine.ListIngressRulesResponse( - ingress_rules=[], - next_page_token='def', - ), - appengine.ListIngressRulesResponse( - ingress_rules=[ - firewall.FirewallRule(), - ], - next_page_token='ghi', - ), - appengine.ListIngressRulesResponse( - ingress_rules=[ - firewall.FirewallRule(), - firewall.FirewallRule(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_ingress_rules(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, firewall.FirewallRule) - for i in responses) - -@pytest.mark.asyncio -async def test_list_ingress_rules_async_pages(): - client = FirewallAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_ingress_rules), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListIngressRulesResponse( - ingress_rules=[ - firewall.FirewallRule(), - firewall.FirewallRule(), - firewall.FirewallRule(), - ], - next_page_token='abc', - ), - appengine.ListIngressRulesResponse( - ingress_rules=[], - next_page_token='def', - ), - appengine.ListIngressRulesResponse( - ingress_rules=[ - firewall.FirewallRule(), - ], - next_page_token='ghi', - ), - appengine.ListIngressRulesResponse( - ingress_rules=[ - firewall.FirewallRule(), - firewall.FirewallRule(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_ingress_rules(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_batch_update_ingress_rules(transport: str = 'grpc', request_type=appengine.BatchUpdateIngressRulesRequest): - client = FirewallClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_update_ingress_rules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = appengine.BatchUpdateIngressRulesResponse( - ) - response = client.batch_update_ingress_rules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.BatchUpdateIngressRulesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, appengine.BatchUpdateIngressRulesResponse) - - -def test_batch_update_ingress_rules_from_dict(): - test_batch_update_ingress_rules(request_type=dict) - - -def test_batch_update_ingress_rules_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FirewallClient( - credentials=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_update_ingress_rules), - '__call__') as call: - client.batch_update_ingress_rules() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.BatchUpdateIngressRulesRequest() - - -@pytest.mark.asyncio -async def test_batch_update_ingress_rules_async(transport: str = 'grpc_asyncio', request_type=appengine.BatchUpdateIngressRulesRequest): - client = FirewallAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_update_ingress_rules), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(appengine.BatchUpdateIngressRulesResponse( - )) - response = await client.batch_update_ingress_rules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.BatchUpdateIngressRulesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, appengine.BatchUpdateIngressRulesResponse) - - -@pytest.mark.asyncio -async def test_batch_update_ingress_rules_async_from_dict(): - await test_batch_update_ingress_rules_async(request_type=dict) - - -def test_batch_update_ingress_rules_field_headers(): - client = FirewallClient( - credentials=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. - request = appengine.BatchUpdateIngressRulesRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_update_ingress_rules), - '__call__') as call: - call.return_value = appengine.BatchUpdateIngressRulesResponse() - client.batch_update_ingress_rules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_batch_update_ingress_rules_field_headers_async(): - client = FirewallAsyncClient( - credentials=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. - request = appengine.BatchUpdateIngressRulesRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_update_ingress_rules), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(appengine.BatchUpdateIngressRulesResponse()) - await client.batch_update_ingress_rules(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_create_ingress_rule(transport: str = 'grpc', request_type=appengine.CreateIngressRuleRequest): - client = FirewallClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_ingress_rule), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = firewall.FirewallRule( - priority=898, - action=firewall.FirewallRule.Action.ALLOW, - source_range='source_range_value', - description='description_value', - ) - response = client.create_ingress_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateIngressRuleRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, firewall.FirewallRule) - assert response.priority == 898 - assert response.action == firewall.FirewallRule.Action.ALLOW - assert response.source_range == 'source_range_value' - assert response.description == 'description_value' - - -def test_create_ingress_rule_from_dict(): - test_create_ingress_rule(request_type=dict) - - -def test_create_ingress_rule_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FirewallClient( - credentials=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_ingress_rule), - '__call__') as call: - client.create_ingress_rule() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateIngressRuleRequest() - - -@pytest.mark.asyncio -async def test_create_ingress_rule_async(transport: str = 'grpc_asyncio', request_type=appengine.CreateIngressRuleRequest): - client = FirewallAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_ingress_rule), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(firewall.FirewallRule( - priority=898, - action=firewall.FirewallRule.Action.ALLOW, - source_range='source_range_value', - description='description_value', - )) - response = await client.create_ingress_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateIngressRuleRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, firewall.FirewallRule) - assert response.priority == 898 - assert response.action == firewall.FirewallRule.Action.ALLOW - assert response.source_range == 'source_range_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_create_ingress_rule_async_from_dict(): - await test_create_ingress_rule_async(request_type=dict) - - -def test_create_ingress_rule_field_headers(): - client = FirewallClient( - credentials=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. - request = appengine.CreateIngressRuleRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_ingress_rule), - '__call__') as call: - call.return_value = firewall.FirewallRule() - client.create_ingress_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_ingress_rule_field_headers_async(): - client = FirewallAsyncClient( - credentials=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. - request = appengine.CreateIngressRuleRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_ingress_rule), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(firewall.FirewallRule()) - await client.create_ingress_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_get_ingress_rule(transport: str = 'grpc', request_type=appengine.GetIngressRuleRequest): - client = FirewallClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_ingress_rule), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = firewall.FirewallRule( - priority=898, - action=firewall.FirewallRule.Action.ALLOW, - source_range='source_range_value', - description='description_value', - ) - response = client.get_ingress_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetIngressRuleRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, firewall.FirewallRule) - assert response.priority == 898 - assert response.action == firewall.FirewallRule.Action.ALLOW - assert response.source_range == 'source_range_value' - assert response.description == 'description_value' - - -def test_get_ingress_rule_from_dict(): - test_get_ingress_rule(request_type=dict) - - -def test_get_ingress_rule_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FirewallClient( - credentials=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_ingress_rule), - '__call__') as call: - client.get_ingress_rule() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetIngressRuleRequest() - - -@pytest.mark.asyncio -async def test_get_ingress_rule_async(transport: str = 'grpc_asyncio', request_type=appengine.GetIngressRuleRequest): - client = FirewallAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_ingress_rule), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(firewall.FirewallRule( - priority=898, - action=firewall.FirewallRule.Action.ALLOW, - source_range='source_range_value', - description='description_value', - )) - response = await client.get_ingress_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetIngressRuleRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, firewall.FirewallRule) - assert response.priority == 898 - assert response.action == firewall.FirewallRule.Action.ALLOW - assert response.source_range == 'source_range_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_get_ingress_rule_async_from_dict(): - await test_get_ingress_rule_async(request_type=dict) - - -def test_get_ingress_rule_field_headers(): - client = FirewallClient( - credentials=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. - request = appengine.GetIngressRuleRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_ingress_rule), - '__call__') as call: - call.return_value = firewall.FirewallRule() - client.get_ingress_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_ingress_rule_field_headers_async(): - client = FirewallAsyncClient( - credentials=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. - request = appengine.GetIngressRuleRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_ingress_rule), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(firewall.FirewallRule()) - await client.get_ingress_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_update_ingress_rule(transport: str = 'grpc', request_type=appengine.UpdateIngressRuleRequest): - client = FirewallClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_ingress_rule), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = firewall.FirewallRule( - priority=898, - action=firewall.FirewallRule.Action.ALLOW, - source_range='source_range_value', - description='description_value', - ) - response = client.update_ingress_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateIngressRuleRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, firewall.FirewallRule) - assert response.priority == 898 - assert response.action == firewall.FirewallRule.Action.ALLOW - assert response.source_range == 'source_range_value' - assert response.description == 'description_value' - - -def test_update_ingress_rule_from_dict(): - test_update_ingress_rule(request_type=dict) - - -def test_update_ingress_rule_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FirewallClient( - credentials=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_ingress_rule), - '__call__') as call: - client.update_ingress_rule() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateIngressRuleRequest() - - -@pytest.mark.asyncio -async def test_update_ingress_rule_async(transport: str = 'grpc_asyncio', request_type=appengine.UpdateIngressRuleRequest): - client = FirewallAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_ingress_rule), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(firewall.FirewallRule( - priority=898, - action=firewall.FirewallRule.Action.ALLOW, - source_range='source_range_value', - description='description_value', - )) - response = await client.update_ingress_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateIngressRuleRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, firewall.FirewallRule) - assert response.priority == 898 - assert response.action == firewall.FirewallRule.Action.ALLOW - assert response.source_range == 'source_range_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_update_ingress_rule_async_from_dict(): - await test_update_ingress_rule_async(request_type=dict) - - -def test_update_ingress_rule_field_headers(): - client = FirewallClient( - credentials=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. - request = appengine.UpdateIngressRuleRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_ingress_rule), - '__call__') as call: - call.return_value = firewall.FirewallRule() - client.update_ingress_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_ingress_rule_field_headers_async(): - client = FirewallAsyncClient( - credentials=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. - request = appengine.UpdateIngressRuleRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_ingress_rule), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(firewall.FirewallRule()) - await client.update_ingress_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_delete_ingress_rule(transport: str = 'grpc', request_type=appengine.DeleteIngressRuleRequest): - client = FirewallClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_ingress_rule), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_ingress_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteIngressRuleRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_ingress_rule_from_dict(): - test_delete_ingress_rule(request_type=dict) - - -def test_delete_ingress_rule_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FirewallClient( - credentials=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_ingress_rule), - '__call__') as call: - client.delete_ingress_rule() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteIngressRuleRequest() - - -@pytest.mark.asyncio -async def test_delete_ingress_rule_async(transport: str = 'grpc_asyncio', request_type=appengine.DeleteIngressRuleRequest): - client = FirewallAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_ingress_rule), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_ingress_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteIngressRuleRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_ingress_rule_async_from_dict(): - await test_delete_ingress_rule_async(request_type=dict) - - -def test_delete_ingress_rule_field_headers(): - client = FirewallClient( - credentials=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. - request = appengine.DeleteIngressRuleRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_ingress_rule), - '__call__') as call: - call.return_value = None - client.delete_ingress_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_ingress_rule_field_headers_async(): - client = FirewallAsyncClient( - credentials=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. - request = appengine.DeleteIngressRuleRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_ingress_rule), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_ingress_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.FirewallGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FirewallClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.FirewallGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FirewallClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.FirewallGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FirewallClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.FirewallGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = FirewallClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.FirewallGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.FirewallGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.FirewallGrpcTransport, - transports.FirewallGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = FirewallClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.FirewallGrpcTransport, - ) - -def test_firewall_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.FirewallTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_firewall_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.appengine_admin_v1.services.firewall.transports.FirewallTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.FirewallTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_ingress_rules', - 'batch_update_ingress_rules', - 'create_ingress_rule', - 'get_ingress_rule', - 'update_ingress_rule', - 'delete_ingress_rule', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_firewall_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.firewall.transports.FirewallTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.FirewallTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_firewall_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.firewall.transports.FirewallTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.FirewallTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ), - quota_project_id="octopus", - ) - - -def test_firewall_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.appengine_admin_v1.services.firewall.transports.FirewallTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.FirewallTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_firewall_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - FirewallClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_firewall_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - FirewallClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.FirewallGrpcTransport, - transports.FirewallGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_firewall_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.FirewallGrpcTransport, - transports.FirewallGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_firewall_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.FirewallGrpcTransport, grpc_helpers), - (transports.FirewallGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_firewall_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "appengine.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - scopes=["1", "2"], - default_host="appengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.FirewallGrpcTransport, transports.FirewallGrpcAsyncIOTransport]) -def test_firewall_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_firewall_host_no_port(): - client = FirewallClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com'), - ) - assert client.transport._host == 'appengine.googleapis.com:443' - - -def test_firewall_host_with_port(): - client = FirewallClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com:8000'), - ) - assert client.transport._host == 'appengine.googleapis.com:8000' - -def test_firewall_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.FirewallGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_firewall_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.FirewallGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.FirewallGrpcTransport, transports.FirewallGrpcAsyncIOTransport]) -def test_firewall_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.FirewallGrpcTransport, transports.FirewallGrpcAsyncIOTransport]) -def test_firewall_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = FirewallClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = FirewallClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = FirewallClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = FirewallClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = FirewallClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = FirewallClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = FirewallClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = FirewallClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = FirewallClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = FirewallClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = FirewallClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = FirewallClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = FirewallClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = FirewallClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = FirewallClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.FirewallTransport, '_prep_wrapped_messages') as prep: - client = FirewallClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.FirewallTransport, '_prep_wrapped_messages') as prep: - transport_class = FirewallClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_instances.py b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_instances.py deleted file mode 100644 index e53c21b..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_instances.py +++ /dev/null @@ -1,1839 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.appengine_admin_v1.services.instances import InstancesAsyncClient -from google.cloud.appengine_admin_v1.services.instances import InstancesClient -from google.cloud.appengine_admin_v1.services.instances import pagers -from google.cloud.appengine_admin_v1.services.instances import transports -from google.cloud.appengine_admin_v1.services.instances.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import instance -from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert InstancesClient._get_default_mtls_endpoint(None) is None - assert InstancesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert InstancesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert InstancesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert InstancesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert InstancesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - InstancesClient, - InstancesAsyncClient, -]) -def test_instances_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'appengine.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.InstancesGrpcTransport, "grpc"), - (transports.InstancesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_instances_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class", [ - InstancesClient, - InstancesAsyncClient, -]) -def test_instances_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'appengine.googleapis.com:443' - - -def test_instances_client_get_transport_class(): - transport = InstancesClient.get_transport_class() - available_transports = [ - transports.InstancesGrpcTransport, - ] - assert transport in available_transports - - transport = InstancesClient.get_transport_class("grpc") - assert transport == transports.InstancesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (InstancesClient, transports.InstancesGrpcTransport, "grpc"), - (InstancesAsyncClient, transports.InstancesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(InstancesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(InstancesClient)) -@mock.patch.object(InstancesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(InstancesAsyncClient)) -def test_instances_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(InstancesClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(InstancesClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (InstancesClient, transports.InstancesGrpcTransport, "grpc", "true"), - (InstancesAsyncClient, transports.InstancesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (InstancesClient, transports.InstancesGrpcTransport, "grpc", "false"), - (InstancesAsyncClient, transports.InstancesGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(InstancesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(InstancesClient)) -@mock.patch.object(InstancesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(InstancesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_instances_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (InstancesClient, transports.InstancesGrpcTransport, "grpc"), - (InstancesAsyncClient, transports.InstancesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_instances_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (InstancesClient, transports.InstancesGrpcTransport, "grpc"), - (InstancesAsyncClient, transports.InstancesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_instances_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_instances_client_client_options_from_dict(): - with mock.patch('google.cloud.appengine_admin_v1.services.instances.transports.InstancesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = InstancesClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_list_instances(transport: str = 'grpc', request_type=appengine.ListInstancesRequest): - client = InstancesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instances), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = appengine.ListInstancesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_instances(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListInstancesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstancesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_instances_from_dict(): - test_list_instances(request_type=dict) - - -def test_list_instances_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = InstancesClient( - credentials=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_instances), - '__call__') as call: - client.list_instances() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListInstancesRequest() - - -@pytest.mark.asyncio -async def test_list_instances_async(transport: str = 'grpc_asyncio', request_type=appengine.ListInstancesRequest): - client = InstancesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instances), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListInstancesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_instances(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListInstancesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstancesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_instances_async_from_dict(): - await test_list_instances_async(request_type=dict) - - -def test_list_instances_field_headers(): - client = InstancesClient( - credentials=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. - request = appengine.ListInstancesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instances), - '__call__') as call: - call.return_value = appengine.ListInstancesResponse() - client.list_instances(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_instances_field_headers_async(): - client = InstancesAsyncClient( - credentials=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. - request = appengine.ListInstancesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instances), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListInstancesResponse()) - await client.list_instances(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_list_instances_pager(): - client = InstancesClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instances), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListInstancesResponse( - instances=[ - instance.Instance(), - instance.Instance(), - instance.Instance(), - ], - next_page_token='abc', - ), - appengine.ListInstancesResponse( - instances=[], - next_page_token='def', - ), - appengine.ListInstancesResponse( - instances=[ - instance.Instance(), - ], - next_page_token='ghi', - ), - appengine.ListInstancesResponse( - instances=[ - instance.Instance(), - instance.Instance(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_instances(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, instance.Instance) - for i in results) - -def test_list_instances_pages(): - client = InstancesClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instances), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListInstancesResponse( - instances=[ - instance.Instance(), - instance.Instance(), - instance.Instance(), - ], - next_page_token='abc', - ), - appengine.ListInstancesResponse( - instances=[], - next_page_token='def', - ), - appengine.ListInstancesResponse( - instances=[ - instance.Instance(), - ], - next_page_token='ghi', - ), - appengine.ListInstancesResponse( - instances=[ - instance.Instance(), - instance.Instance(), - ], - ), - RuntimeError, - ) - pages = list(client.list_instances(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_instances_async_pager(): - client = InstancesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instances), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListInstancesResponse( - instances=[ - instance.Instance(), - instance.Instance(), - instance.Instance(), - ], - next_page_token='abc', - ), - appengine.ListInstancesResponse( - instances=[], - next_page_token='def', - ), - appengine.ListInstancesResponse( - instances=[ - instance.Instance(), - ], - next_page_token='ghi', - ), - appengine.ListInstancesResponse( - instances=[ - instance.Instance(), - instance.Instance(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_instances(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, instance.Instance) - for i in responses) - -@pytest.mark.asyncio -async def test_list_instances_async_pages(): - client = InstancesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instances), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListInstancesResponse( - instances=[ - instance.Instance(), - instance.Instance(), - instance.Instance(), - ], - next_page_token='abc', - ), - appengine.ListInstancesResponse( - instances=[], - next_page_token='def', - ), - appengine.ListInstancesResponse( - instances=[ - instance.Instance(), - ], - next_page_token='ghi', - ), - appengine.ListInstancesResponse( - instances=[ - instance.Instance(), - instance.Instance(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_instances(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_instance(transport: str = 'grpc', request_type=appengine.GetInstanceRequest): - client = InstancesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = instance.Instance( - name='name_value', - id='id_value', - app_engine_release='app_engine_release_value', - availability=instance.Instance.Availability.RESIDENT, - vm_name='vm_name_value', - vm_zone_name='vm_zone_name_value', - vm_id='vm_id_value', - requests=892, - errors=669, - qps=0.340, - average_latency=1578, - memory_usage=1293, - vm_status='vm_status_value', - vm_debug_enabled=True, - vm_ip='vm_ip_value', - vm_liveness=instance.Instance.Liveness.LivenessState.UNKNOWN, - ) - response = client.get_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetInstanceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, instance.Instance) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.app_engine_release == 'app_engine_release_value' - assert response.availability == instance.Instance.Availability.RESIDENT - assert response.vm_name == 'vm_name_value' - assert response.vm_zone_name == 'vm_zone_name_value' - assert response.vm_id == 'vm_id_value' - assert response.requests == 892 - assert response.errors == 669 - assert math.isclose(response.qps, 0.340, rel_tol=1e-6) - assert response.average_latency == 1578 - assert response.memory_usage == 1293 - assert response.vm_status == 'vm_status_value' - assert response.vm_debug_enabled is True - assert response.vm_ip == 'vm_ip_value' - assert response.vm_liveness == instance.Instance.Liveness.LivenessState.UNKNOWN - - -def test_get_instance_from_dict(): - test_get_instance(request_type=dict) - - -def test_get_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = InstancesClient( - credentials=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_instance), - '__call__') as call: - client.get_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetInstanceRequest() - - -@pytest.mark.asyncio -async def test_get_instance_async(transport: str = 'grpc_asyncio', request_type=appengine.GetInstanceRequest): - client = InstancesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(instance.Instance( - name='name_value', - id='id_value', - app_engine_release='app_engine_release_value', - availability=instance.Instance.Availability.RESIDENT, - vm_name='vm_name_value', - vm_zone_name='vm_zone_name_value', - vm_id='vm_id_value', - requests=892, - errors=669, - qps=0.340, - average_latency=1578, - memory_usage=1293, - vm_status='vm_status_value', - vm_debug_enabled=True, - vm_ip='vm_ip_value', - vm_liveness=instance.Instance.Liveness.LivenessState.UNKNOWN, - )) - response = await client.get_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetInstanceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, instance.Instance) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.app_engine_release == 'app_engine_release_value' - assert response.availability == instance.Instance.Availability.RESIDENT - assert response.vm_name == 'vm_name_value' - assert response.vm_zone_name == 'vm_zone_name_value' - assert response.vm_id == 'vm_id_value' - assert response.requests == 892 - assert response.errors == 669 - assert math.isclose(response.qps, 0.340, rel_tol=1e-6) - assert response.average_latency == 1578 - assert response.memory_usage == 1293 - assert response.vm_status == 'vm_status_value' - assert response.vm_debug_enabled is True - assert response.vm_ip == 'vm_ip_value' - assert response.vm_liveness == instance.Instance.Liveness.LivenessState.UNKNOWN - - -@pytest.mark.asyncio -async def test_get_instance_async_from_dict(): - await test_get_instance_async(request_type=dict) - - -def test_get_instance_field_headers(): - client = InstancesClient( - credentials=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. - request = appengine.GetInstanceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance), - '__call__') as call: - call.return_value = instance.Instance() - client.get_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_instance_field_headers_async(): - client = InstancesAsyncClient( - credentials=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. - request = appengine.GetInstanceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(instance.Instance()) - await client.get_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_delete_instance(transport: str = 'grpc', request_type=appengine.DeleteInstanceRequest): - client = InstancesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteInstanceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_instance_from_dict(): - test_delete_instance(request_type=dict) - - -def test_delete_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = InstancesClient( - credentials=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_instance), - '__call__') as call: - client.delete_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteInstanceRequest() - - -@pytest.mark.asyncio -async def test_delete_instance_async(transport: str = 'grpc_asyncio', request_type=appengine.DeleteInstanceRequest): - client = InstancesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteInstanceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_instance_async_from_dict(): - await test_delete_instance_async(request_type=dict) - - -def test_delete_instance_field_headers(): - client = InstancesClient( - credentials=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. - request = appengine.DeleteInstanceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_instance), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_instance_field_headers_async(): - client = InstancesAsyncClient( - credentials=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. - request = appengine.DeleteInstanceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_instance), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_debug_instance(transport: str = 'grpc', request_type=appengine.DebugInstanceRequest): - client = InstancesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.debug_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.debug_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DebugInstanceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_debug_instance_from_dict(): - test_debug_instance(request_type=dict) - - -def test_debug_instance_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = InstancesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.debug_instance), - '__call__') as call: - client.debug_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DebugInstanceRequest() - - -@pytest.mark.asyncio -async def test_debug_instance_async(transport: str = 'grpc_asyncio', request_type=appengine.DebugInstanceRequest): - client = InstancesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.debug_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.debug_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DebugInstanceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_debug_instance_async_from_dict(): - await test_debug_instance_async(request_type=dict) - - -def test_debug_instance_field_headers(): - client = InstancesClient( - credentials=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. - request = appengine.DebugInstanceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.debug_instance), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.debug_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_debug_instance_field_headers_async(): - client = InstancesAsyncClient( - credentials=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. - request = appengine.DebugInstanceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.debug_instance), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.debug_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.InstancesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = InstancesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.InstancesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = InstancesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.InstancesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = InstancesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.InstancesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = InstancesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.InstancesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.InstancesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.InstancesGrpcTransport, - transports.InstancesGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = InstancesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.InstancesGrpcTransport, - ) - -def test_instances_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.InstancesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_instances_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.appengine_admin_v1.services.instances.transports.InstancesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.InstancesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_instances', - 'get_instance', - 'delete_instance', - 'debug_instance', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_instances_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.instances.transports.InstancesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.InstancesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_instances_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.instances.transports.InstancesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.InstancesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ), - quota_project_id="octopus", - ) - - -def test_instances_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.appengine_admin_v1.services.instances.transports.InstancesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.InstancesTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_instances_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - InstancesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_instances_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - InstancesClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.InstancesGrpcTransport, - transports.InstancesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_instances_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.InstancesGrpcTransport, - transports.InstancesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_instances_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.InstancesGrpcTransport, grpc_helpers), - (transports.InstancesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_instances_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "appengine.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - scopes=["1", "2"], - default_host="appengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.InstancesGrpcTransport, transports.InstancesGrpcAsyncIOTransport]) -def test_instances_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_instances_host_no_port(): - client = InstancesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com'), - ) - assert client.transport._host == 'appengine.googleapis.com:443' - - -def test_instances_host_with_port(): - client = InstancesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com:8000'), - ) - assert client.transport._host == 'appengine.googleapis.com:8000' - -def test_instances_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.InstancesGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_instances_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.InstancesGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.InstancesGrpcTransport, transports.InstancesGrpcAsyncIOTransport]) -def test_instances_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.InstancesGrpcTransport, transports.InstancesGrpcAsyncIOTransport]) -def test_instances_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_instances_grpc_lro_client(): - client = InstancesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_instances_grpc_lro_async_client(): - client = InstancesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_instance_path(): - app = "squid" - service = "clam" - version = "whelk" - instance = "octopus" - expected = "apps/{app}/services/{service}/versions/{version}/instances/{instance}".format(app=app, service=service, version=version, instance=instance, ) - actual = InstancesClient.instance_path(app, service, version, instance) - assert expected == actual - - -def test_parse_instance_path(): - expected = { - "app": "oyster", - "service": "nudibranch", - "version": "cuttlefish", - "instance": "mussel", - } - path = InstancesClient.instance_path(**expected) - - # Check that the path construction is reversible. - actual = InstancesClient.parse_instance_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = InstancesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = InstancesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = InstancesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = InstancesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = InstancesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = InstancesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = InstancesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = InstancesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = InstancesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = InstancesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = InstancesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = InstancesClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "oyster" - location = "nudibranch" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = InstancesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = InstancesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = InstancesClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.InstancesTransport, '_prep_wrapped_messages') as prep: - client = InstancesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.InstancesTransport, '_prep_wrapped_messages') as prep: - transport_class = InstancesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_services.py b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_services.py deleted file mode 100644 index e63f79e..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_services.py +++ /dev/null @@ -1,1761 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.appengine_admin_v1.services.services import ServicesAsyncClient -from google.cloud.appengine_admin_v1.services.services import ServicesClient -from google.cloud.appengine_admin_v1.services.services import pagers -from google.cloud.appengine_admin_v1.services.services import transports -from google.cloud.appengine_admin_v1.services.services.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import network_settings -from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.cloud.appengine_admin_v1.types import service -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ServicesClient._get_default_mtls_endpoint(None) is None - assert ServicesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ServicesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ServicesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ServicesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ServicesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - ServicesClient, - ServicesAsyncClient, -]) -def test_services_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'appengine.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ServicesGrpcTransport, "grpc"), - (transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_services_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class", [ - ServicesClient, - ServicesAsyncClient, -]) -def test_services_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'appengine.googleapis.com:443' - - -def test_services_client_get_transport_class(): - transport = ServicesClient.get_transport_class() - available_transports = [ - transports.ServicesGrpcTransport, - ] - assert transport in available_transports - - transport = ServicesClient.get_transport_class("grpc") - assert transport == transports.ServicesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServicesClient, transports.ServicesGrpcTransport, "grpc"), - (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ServicesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesClient)) -@mock.patch.object(ServicesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesAsyncClient)) -def test_services_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(ServicesClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(ServicesClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ServicesClient, transports.ServicesGrpcTransport, "grpc", "true"), - (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ServicesClient, transports.ServicesGrpcTransport, "grpc", "false"), - (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ServicesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesClient)) -@mock.patch.object(ServicesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServicesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_services_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServicesClient, transports.ServicesGrpcTransport, "grpc"), - (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_services_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServicesClient, transports.ServicesGrpcTransport, "grpc"), - (ServicesAsyncClient, transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_services_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_services_client_client_options_from_dict(): - with mock.patch('google.cloud.appengine_admin_v1.services.services.transports.ServicesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ServicesClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_list_services(transport: str = 'grpc', request_type=appengine.ListServicesRequest): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = appengine.ListServicesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_services(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListServicesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServicesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_services_from_dict(): - test_list_services(request_type=dict) - - -def test_list_services_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServicesClient( - credentials=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_services), - '__call__') as call: - client.list_services() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListServicesRequest() - - -@pytest.mark.asyncio -async def test_list_services_async(transport: str = 'grpc_asyncio', request_type=appengine.ListServicesRequest): - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListServicesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_services(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListServicesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServicesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_services_async_from_dict(): - await test_list_services_async(request_type=dict) - - -def test_list_services_field_headers(): - client = ServicesClient( - credentials=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. - request = appengine.ListServicesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - call.return_value = appengine.ListServicesResponse() - client.list_services(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_services_field_headers_async(): - client = ServicesAsyncClient( - credentials=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. - request = appengine.ListServicesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListServicesResponse()) - await client.list_services(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_list_services_pager(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - service.Service(), - ], - next_page_token='abc', - ), - appengine.ListServicesResponse( - services=[], - next_page_token='def', - ), - appengine.ListServicesResponse( - services=[ - service.Service(), - ], - next_page_token='ghi', - ), - appengine.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_services(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, service.Service) - for i in results) - -def test_list_services_pages(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - service.Service(), - ], - next_page_token='abc', - ), - appengine.ListServicesResponse( - services=[], - next_page_token='def', - ), - appengine.ListServicesResponse( - services=[ - service.Service(), - ], - next_page_token='ghi', - ), - appengine.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - ], - ), - RuntimeError, - ) - pages = list(client.list_services(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_services_async_pager(): - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - service.Service(), - ], - next_page_token='abc', - ), - appengine.ListServicesResponse( - services=[], - next_page_token='def', - ), - appengine.ListServicesResponse( - services=[ - service.Service(), - ], - next_page_token='ghi', - ), - appengine.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_services(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, service.Service) - for i in responses) - -@pytest.mark.asyncio -async def test_list_services_async_pages(): - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - service.Service(), - ], - next_page_token='abc', - ), - appengine.ListServicesResponse( - services=[], - next_page_token='def', - ), - appengine.ListServicesResponse( - services=[ - service.Service(), - ], - next_page_token='ghi', - ), - appengine.ListServicesResponse( - services=[ - service.Service(), - service.Service(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_services(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_service(transport: str = 'grpc', request_type=appengine.GetServiceRequest): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.Service( - name='name_value', - id='id_value', - ) - response = client.get_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.Service) - assert response.name == 'name_value' - assert response.id == 'id_value' - - -def test_get_service_from_dict(): - test_get_service(request_type=dict) - - -def test_get_service_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServicesClient( - credentials=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_service), - '__call__') as call: - client.get_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetServiceRequest() - - -@pytest.mark.asyncio -async def test_get_service_async(transport: str = 'grpc_asyncio', request_type=appengine.GetServiceRequest): - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.Service( - name='name_value', - id='id_value', - )) - response = await client.get_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.Service) - assert response.name == 'name_value' - assert response.id == 'id_value' - - -@pytest.mark.asyncio -async def test_get_service_async_from_dict(): - await test_get_service_async(request_type=dict) - - -def test_get_service_field_headers(): - client = ServicesClient( - credentials=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. - request = appengine.GetServiceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - call.return_value = service.Service() - client.get_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_service_field_headers_async(): - client = ServicesAsyncClient( - credentials=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. - request = appengine.GetServiceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Service()) - await client.get_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_update_service(transport: str = 'grpc', request_type=appengine.UpdateServiceRequest): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_service_from_dict(): - test_update_service(request_type=dict) - - -def test_update_service_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServicesClient( - credentials=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_service), - '__call__') as call: - client.update_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateServiceRequest() - - -@pytest.mark.asyncio -async def test_update_service_async(transport: str = 'grpc_asyncio', request_type=appengine.UpdateServiceRequest): - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_service_async_from_dict(): - await test_update_service_async(request_type=dict) - - -def test_update_service_field_headers(): - client = ServicesClient( - credentials=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. - request = appengine.UpdateServiceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_service), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_service_field_headers_async(): - client = ServicesAsyncClient( - credentials=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. - request = appengine.UpdateServiceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_delete_service(transport: str = 'grpc', request_type=appengine.DeleteServiceRequest): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_service_from_dict(): - test_delete_service(request_type=dict) - - -def test_delete_service_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ServicesClient( - credentials=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_service), - '__call__') as call: - client.delete_service() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteServiceRequest() - - -@pytest.mark.asyncio -async def test_delete_service_async(transport: str = 'grpc_asyncio', request_type=appengine.DeleteServiceRequest): - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteServiceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_service_async_from_dict(): - await test_delete_service_async(request_type=dict) - - -def test_delete_service_field_headers(): - client = ServicesClient( - credentials=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. - request = appengine.DeleteServiceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_service_field_headers_async(): - client = ServicesAsyncClient( - credentials=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. - request = appengine.DeleteServiceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ServicesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ServicesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServicesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ServicesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServicesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServicesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ServicesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServicesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ServicesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ServicesGrpcTransport, - transports.ServicesGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ServicesGrpcTransport, - ) - -def test_services_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ServicesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_services_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.appengine_admin_v1.services.services.transports.ServicesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ServicesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_services', - 'get_service', - 'update_service', - 'delete_service', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_services_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.services.transports.ServicesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServicesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_services_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.services.transports.ServicesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServicesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ), - quota_project_id="octopus", - ) - - -def test_services_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.appengine_admin_v1.services.services.transports.ServicesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServicesTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_services_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ServicesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_services_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ServicesClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ServicesGrpcTransport, - transports.ServicesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_services_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ServicesGrpcTransport, - transports.ServicesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_services_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ServicesGrpcTransport, grpc_helpers), - (transports.ServicesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_services_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "appengine.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - scopes=["1", "2"], - default_host="appengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ServicesGrpcTransport, transports.ServicesGrpcAsyncIOTransport]) -def test_services_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_services_host_no_port(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com'), - ) - assert client.transport._host == 'appengine.googleapis.com:443' - - -def test_services_host_with_port(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com:8000'), - ) - assert client.transport._host == 'appengine.googleapis.com:8000' - -def test_services_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServicesGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_services_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServicesGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ServicesGrpcTransport, transports.ServicesGrpcAsyncIOTransport]) -def test_services_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ServicesGrpcTransport, transports.ServicesGrpcAsyncIOTransport]) -def test_services_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_services_grpc_lro_client(): - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_services_grpc_lro_async_client(): - client = ServicesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ServicesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = ServicesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = ServicesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = ServicesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ServicesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = ServicesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = ServicesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = ServicesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ServicesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = ServicesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ServicesClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.ServicesTransport, '_prep_wrapped_messages') as prep: - client = ServicesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ServicesTransport, '_prep_wrapped_messages') as prep: - transport_class = ServicesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_versions.py b/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_versions.py deleted file mode 100644 index 74dae92..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/appengine_admin_v1/test_versions.py +++ /dev/null @@ -1,1977 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.appengine_admin_v1.services.versions import VersionsAsyncClient -from google.cloud.appengine_admin_v1.services.versions import VersionsClient -from google.cloud.appengine_admin_v1.services.versions import pagers -from google.cloud.appengine_admin_v1.services.versions import transports -from google.cloud.appengine_admin_v1.services.versions.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.appengine_admin_v1.types import app_yaml -from google.cloud.appengine_admin_v1.types import appengine -from google.cloud.appengine_admin_v1.types import deploy -from google.cloud.appengine_admin_v1.types import operation as ga_operation -from google.cloud.appengine_admin_v1.types import version -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert VersionsClient._get_default_mtls_endpoint(None) is None - assert VersionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert VersionsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert VersionsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert VersionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert VersionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - VersionsClient, - VersionsAsyncClient, -]) -def test_versions_client_from_service_account_info(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'appengine.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.VersionsGrpcTransport, "grpc"), - (transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_versions_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class", [ - VersionsClient, - VersionsAsyncClient, -]) -def test_versions_client_from_service_account_file(client_class): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'appengine.googleapis.com:443' - - -def test_versions_client_get_transport_class(): - transport = VersionsClient.get_transport_class() - available_transports = [ - transports.VersionsGrpcTransport, - ] - assert transport in available_transports - - transport = VersionsClient.get_transport_class("grpc") - assert transport == transports.VersionsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VersionsClient, transports.VersionsGrpcTransport, "grpc"), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient)) -@mock.patch.object(VersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsAsyncClient)) -def test_versions_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(VersionsClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(VersionsClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class() - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (VersionsClient, transports.VersionsGrpcTransport, "grpc", "true"), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (VersionsClient, transports.VersionsGrpcTransport, "grpc", "false"), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient)) -@mock.patch.object(VersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_versions_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VersionsClient, transports.VersionsGrpcTransport, "grpc"), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_versions_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VersionsClient, transports.VersionsGrpcTransport, "grpc"), - (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_versions_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_versions_client_client_options_from_dict(): - with mock.patch('google.cloud.appengine_admin_v1.services.versions.transports.VersionsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = VersionsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - -def test_list_versions(transport: str = 'grpc', request_type=appengine.ListVersionsRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = appengine.ListVersionsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListVersionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListVersionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_versions_from_dict(): - test_list_versions(request_type=dict) - - -def test_list_versions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = VersionsClient( - credentials=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: - client.list_versions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListVersionsRequest() - - -@pytest.mark.asyncio -async def test_list_versions_async(transport: str = 'grpc_asyncio', request_type=appengine.ListVersionsRequest): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListVersionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.ListVersionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListVersionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_versions_async_from_dict(): - await test_list_versions_async(request_type=dict) - - -def test_list_versions_field_headers(): - client = VersionsClient( - credentials=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. - request = appengine.ListVersionsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_versions), - '__call__') as call: - call.return_value = appengine.ListVersionsResponse() - client.list_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_versions_field_headers_async(): - client = VersionsAsyncClient( - credentials=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. - request = appengine.ListVersionsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_versions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(appengine.ListVersionsResponse()) - await client.list_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_list_versions_pager(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_versions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListVersionsResponse( - versions=[ - version.Version(), - version.Version(), - version.Version(), - ], - next_page_token='abc', - ), - appengine.ListVersionsResponse( - versions=[], - next_page_token='def', - ), - appengine.ListVersionsResponse( - versions=[ - version.Version(), - ], - next_page_token='ghi', - ), - appengine.ListVersionsResponse( - versions=[ - version.Version(), - version.Version(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_versions(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, version.Version) - for i in results) - -def test_list_versions_pages(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_versions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListVersionsResponse( - versions=[ - version.Version(), - version.Version(), - version.Version(), - ], - next_page_token='abc', - ), - appengine.ListVersionsResponse( - versions=[], - next_page_token='def', - ), - appengine.ListVersionsResponse( - versions=[ - version.Version(), - ], - next_page_token='ghi', - ), - appengine.ListVersionsResponse( - versions=[ - version.Version(), - version.Version(), - ], - ), - RuntimeError, - ) - pages = list(client.list_versions(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_versions_async_pager(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_versions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListVersionsResponse( - versions=[ - version.Version(), - version.Version(), - version.Version(), - ], - next_page_token='abc', - ), - appengine.ListVersionsResponse( - versions=[], - next_page_token='def', - ), - appengine.ListVersionsResponse( - versions=[ - version.Version(), - ], - next_page_token='ghi', - ), - appengine.ListVersionsResponse( - versions=[ - version.Version(), - version.Version(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_versions(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, version.Version) - for i in responses) - -@pytest.mark.asyncio -async def test_list_versions_async_pages(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_versions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - appengine.ListVersionsResponse( - versions=[ - version.Version(), - version.Version(), - version.Version(), - ], - next_page_token='abc', - ), - appengine.ListVersionsResponse( - versions=[], - next_page_token='def', - ), - appengine.ListVersionsResponse( - versions=[ - version.Version(), - ], - next_page_token='ghi', - ), - appengine.ListVersionsResponse( - versions=[ - version.Version(), - version.Version(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_versions(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_get_version(transport: str = 'grpc', request_type=appengine.GetVersionRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = version.Version( - name='name_value', - id='id_value', - inbound_services=[version.InboundServiceType.INBOUND_SERVICE_MAIL], - instance_class='instance_class_value', - zones=['zones_value'], - runtime='runtime_value', - runtime_channel='runtime_channel_value', - threadsafe=True, - vm=True, - env='env_value', - serving_status=version.ServingStatus.SERVING, - created_by='created_by_value', - disk_usage_bytes=1701, - runtime_api_version='runtime_api_version_value', - runtime_main_executable_path='runtime_main_executable_path_value', - service_account='service_account_value', - nobuild_files_regex='nobuild_files_regex_value', - version_url='version_url_value', - automatic_scaling=version.AutomaticScaling(cool_down_period=duration_pb2.Duration(seconds=751)), - ) - response = client.get_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, version.Version) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.inbound_services == [version.InboundServiceType.INBOUND_SERVICE_MAIL] - assert response.instance_class == 'instance_class_value' - assert response.zones == ['zones_value'] - assert response.runtime == 'runtime_value' - assert response.runtime_channel == 'runtime_channel_value' - assert response.threadsafe is True - assert response.vm is True - assert response.env == 'env_value' - assert response.serving_status == version.ServingStatus.SERVING - assert response.created_by == 'created_by_value' - assert response.disk_usage_bytes == 1701 - assert response.runtime_api_version == 'runtime_api_version_value' - assert response.runtime_main_executable_path == 'runtime_main_executable_path_value' - assert response.service_account == 'service_account_value' - assert response.nobuild_files_regex == 'nobuild_files_regex_value' - assert response.version_url == 'version_url_value' - - -def test_get_version_from_dict(): - test_get_version(request_type=dict) - - -def test_get_version_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = VersionsClient( - credentials=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: - client.get_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetVersionRequest() - - -@pytest.mark.asyncio -async def test_get_version_async(transport: str = 'grpc_asyncio', request_type=appengine.GetVersionRequest): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(version.Version( - name='name_value', - id='id_value', - inbound_services=[version.InboundServiceType.INBOUND_SERVICE_MAIL], - instance_class='instance_class_value', - zones=['zones_value'], - runtime='runtime_value', - runtime_channel='runtime_channel_value', - threadsafe=True, - vm=True, - env='env_value', - serving_status=version.ServingStatus.SERVING, - created_by='created_by_value', - disk_usage_bytes=1701, - runtime_api_version='runtime_api_version_value', - runtime_main_executable_path='runtime_main_executable_path_value', - service_account='service_account_value', - nobuild_files_regex='nobuild_files_regex_value', - version_url='version_url_value', - )) - response = await client.get_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.GetVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, version.Version) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.inbound_services == [version.InboundServiceType.INBOUND_SERVICE_MAIL] - assert response.instance_class == 'instance_class_value' - assert response.zones == ['zones_value'] - assert response.runtime == 'runtime_value' - assert response.runtime_channel == 'runtime_channel_value' - assert response.threadsafe is True - assert response.vm is True - assert response.env == 'env_value' - assert response.serving_status == version.ServingStatus.SERVING - assert response.created_by == 'created_by_value' - assert response.disk_usage_bytes == 1701 - assert response.runtime_api_version == 'runtime_api_version_value' - assert response.runtime_main_executable_path == 'runtime_main_executable_path_value' - assert response.service_account == 'service_account_value' - assert response.nobuild_files_regex == 'nobuild_files_regex_value' - assert response.version_url == 'version_url_value' - - -@pytest.mark.asyncio -async def test_get_version_async_from_dict(): - await test_get_version_async(request_type=dict) - - -def test_get_version_field_headers(): - client = VersionsClient( - credentials=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. - request = appengine.GetVersionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_version), - '__call__') as call: - call.return_value = version.Version() - client.get_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_version_field_headers_async(): - client = VersionsAsyncClient( - credentials=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. - request = appengine.GetVersionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.Version()) - await client.get_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_create_version(transport: str = 'grpc', request_type=appengine.CreateVersionRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_version_from_dict(): - test_create_version(request_type=dict) - - -def test_create_version_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = VersionsClient( - credentials=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: - client.create_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateVersionRequest() - - -@pytest.mark.asyncio -async def test_create_version_async(transport: str = 'grpc_asyncio', request_type=appengine.CreateVersionRequest): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.CreateVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_version_async_from_dict(): - await test_create_version_async(request_type=dict) - - -def test_create_version_field_headers(): - client = VersionsClient( - credentials=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. - request = appengine.CreateVersionRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_version_field_headers_async(): - client = VersionsAsyncClient( - credentials=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. - request = appengine.CreateVersionRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_update_version(transport: str = 'grpc', request_type=appengine.UpdateVersionRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_version_from_dict(): - test_update_version(request_type=dict) - - -def test_update_version_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = VersionsClient( - credentials=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: - client.update_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateVersionRequest() - - -@pytest.mark.asyncio -async def test_update_version_async(transport: str = 'grpc_asyncio', request_type=appengine.UpdateVersionRequest): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.UpdateVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_version_async_from_dict(): - await test_update_version_async(request_type=dict) - - -def test_update_version_field_headers(): - client = VersionsClient( - credentials=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. - request = appengine.UpdateVersionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_version_field_headers_async(): - client = VersionsAsyncClient( - credentials=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. - request = appengine.UpdateVersionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_delete_version(transport: str = 'grpc', request_type=appengine.DeleteVersionRequest): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_version_from_dict(): - test_delete_version(request_type=dict) - - -def test_delete_version_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = VersionsClient( - credentials=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: - client.delete_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteVersionRequest() - - -@pytest.mark.asyncio -async def test_delete_version_async(transport: str = 'grpc_asyncio', request_type=appengine.DeleteVersionRequest): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == appengine.DeleteVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_version_async_from_dict(): - await test_delete_version_async(request_type=dict) - - -def test_delete_version_field_headers(): - client = VersionsClient( - credentials=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. - request = appengine.DeleteVersionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_version_field_headers_async(): - client = VersionsAsyncClient( - credentials=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. - request = appengine.DeleteVersionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.VersionsGrpcTransport( - credentials=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 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( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = VersionsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.VersionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.VersionsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.VersionsGrpcTransport, - transports.VersionsGrpcAsyncIOTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.VersionsGrpcTransport, - ) - -def test_versions_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.VersionsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_versions_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.appengine_admin_v1.services.versions.transports.VersionsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.VersionsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_versions', - 'get_version', - 'create_version', - 'update_version', - 'delete_version', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_versions_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VersionsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_versions_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.appengine_admin_v1.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VersionsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - ), - quota_project_id="octopus", - ) - - -def test_versions_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.appengine_admin_v1.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VersionsTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_versions_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - VersionsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_versions_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - VersionsClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.VersionsGrpcTransport, - transports.VersionsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_versions_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/appengine.admin', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform.read-only',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.VersionsGrpcTransport, - transports.VersionsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_versions_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.VersionsGrpcTransport, grpc_helpers), - (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_versions_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "appengine.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/appengine.admin', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', -), - scopes=["1", "2"], - default_host="appengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport]) -def test_versions_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -def test_versions_host_no_port(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com'), - ) - assert client.transport._host == 'appengine.googleapis.com:443' - - -def test_versions_host_with_port(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='appengine.googleapis.com:8000'), - ) - assert client.transport._host == 'appengine.googleapis.com:8000' - -def test_versions_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.VersionsGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_versions_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.VersionsGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport]) -def test_versions_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport]) -def test_versions_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_versions_grpc_lro_client(): - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_versions_grpc_lro_async_client(): - client = VersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = VersionsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = VersionsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = VersionsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = VersionsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = VersionsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = VersionsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = VersionsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = VersionsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = VersionsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = VersionsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = VersionsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = VersionsClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = VersionsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = VersionsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = VersionsClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.VersionsTransport, '_prep_wrapped_messages') as prep: - client = VersionsClient( - credentials=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) diff --git a/tests/unit/gapic/appengine_admin_v1/test_applications.py b/tests/unit/gapic/appengine_admin_v1/test_applications.py index 1cc3f9f..fbea8f0 100644 --- a/tests/unit/gapic/appengine_admin_v1/test_applications.py +++ b/tests/unit/gapic/appengine_admin_v1/test_applications.py @@ -122,16 +122,6 @@ def test_applications_client_from_service_account_info(client_class): assert client.transport._host == "appengine.googleapis.com:443" -@pytest.mark.parametrize("client_class", [ApplicationsClient, ApplicationsAsyncClient,]) -def test_applications_client_service_account_always_use_jwt(client_class): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - @pytest.mark.parametrize( "transport_class,transport_name", [ @@ -139,7 +129,7 @@ def test_applications_client_service_account_always_use_jwt(client_class): (transports.ApplicationsGrpcAsyncIOTransport, "grpc_asyncio"), ], ) -def test_applications_client_service_account_always_use_jwt_true( +def test_applications_client_service_account_always_use_jwt( transport_class, transport_name ): with mock.patch.object( @@ -149,6 +139,13 @@ def test_applications_client_service_account_always_use_jwt_true( transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + @pytest.mark.parametrize("client_class", [ApplicationsClient, ApplicationsAsyncClient,]) def test_applications_client_from_service_account_file(client_class): @@ -225,6 +222,7 @@ def test_applications_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -241,6 +239,7 @@ def test_applications_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -257,6 +256,7 @@ def test_applications_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has @@ -285,6 +285,7 @@ def test_applications_client_client_options( client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -349,6 +350,7 @@ def test_applications_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case ADC client cert is provided. Whether client cert is used depends on @@ -382,6 +384,7 @@ def test_applications_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case client_cert_source and ADC client cert are not provided. @@ -403,6 +406,7 @@ def test_applications_client_mtls_env_auto( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -433,6 +437,7 @@ def test_applications_client_client_options_scopes( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -463,6 +468,7 @@ def test_applications_client_client_options_credentials_file( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -480,6 +486,7 @@ def test_applications_client_client_options_from_dict(): client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) diff --git a/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py b/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py index 567a1f3..a8d1ccd 100644 --- a/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py +++ b/tests/unit/gapic/appengine_admin_v1/test_authorized_certificates.py @@ -126,18 +126,6 @@ def test_authorized_certificates_client_from_service_account_info(client_class): assert client.transport._host == "appengine.googleapis.com:443" -@pytest.mark.parametrize( - "client_class", [AuthorizedCertificatesClient, AuthorizedCertificatesAsyncClient,] -) -def test_authorized_certificates_client_service_account_always_use_jwt(client_class): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - @pytest.mark.parametrize( "transport_class,transport_name", [ @@ -145,7 +133,7 @@ def test_authorized_certificates_client_service_account_always_use_jwt(client_cl (transports.AuthorizedCertificatesGrpcAsyncIOTransport, "grpc_asyncio"), ], ) -def test_authorized_certificates_client_service_account_always_use_jwt_true( +def test_authorized_certificates_client_service_account_always_use_jwt( transport_class, transport_name ): with mock.patch.object( @@ -155,6 +143,13 @@ def test_authorized_certificates_client_service_account_always_use_jwt_true( transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + @pytest.mark.parametrize( "client_class", [AuthorizedCertificatesClient, AuthorizedCertificatesAsyncClient,] @@ -239,6 +234,7 @@ def test_authorized_certificates_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -255,6 +251,7 @@ def test_authorized_certificates_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -271,6 +268,7 @@ def test_authorized_certificates_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has @@ -299,6 +297,7 @@ def test_authorized_certificates_client_client_options( client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -375,6 +374,7 @@ def test_authorized_certificates_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case ADC client cert is provided. Whether client cert is used depends on @@ -408,6 +408,7 @@ def test_authorized_certificates_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case client_cert_source and ADC client cert are not provided. @@ -429,6 +430,7 @@ def test_authorized_certificates_client_mtls_env_auto( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -463,6 +465,7 @@ def test_authorized_certificates_client_client_options_scopes( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -497,6 +500,7 @@ def test_authorized_certificates_client_client_options_credentials_file( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -516,6 +520,7 @@ def test_authorized_certificates_client_client_options_from_dict(): client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) diff --git a/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py b/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py index 037bfdd..773df28 100644 --- a/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py +++ b/tests/unit/gapic/appengine_admin_v1/test_authorized_domains.py @@ -124,18 +124,6 @@ def test_authorized_domains_client_from_service_account_info(client_class): assert client.transport._host == "appengine.googleapis.com:443" -@pytest.mark.parametrize( - "client_class", [AuthorizedDomainsClient, AuthorizedDomainsAsyncClient,] -) -def test_authorized_domains_client_service_account_always_use_jwt(client_class): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - @pytest.mark.parametrize( "transport_class,transport_name", [ @@ -143,7 +131,7 @@ def test_authorized_domains_client_service_account_always_use_jwt(client_class): (transports.AuthorizedDomainsGrpcAsyncIOTransport, "grpc_asyncio"), ], ) -def test_authorized_domains_client_service_account_always_use_jwt_true( +def test_authorized_domains_client_service_account_always_use_jwt( transport_class, transport_name ): with mock.patch.object( @@ -153,6 +141,13 @@ def test_authorized_domains_client_service_account_always_use_jwt_true( transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + @pytest.mark.parametrize( "client_class", [AuthorizedDomainsClient, AuthorizedDomainsAsyncClient,] @@ -233,6 +228,7 @@ def test_authorized_domains_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -249,6 +245,7 @@ def test_authorized_domains_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -265,6 +262,7 @@ def test_authorized_domains_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has @@ -293,6 +291,7 @@ def test_authorized_domains_client_client_options( client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -369,6 +368,7 @@ def test_authorized_domains_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case ADC client cert is provided. Whether client cert is used depends on @@ -402,6 +402,7 @@ def test_authorized_domains_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case client_cert_source and ADC client cert are not provided. @@ -423,6 +424,7 @@ def test_authorized_domains_client_mtls_env_auto( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -453,6 +455,7 @@ def test_authorized_domains_client_client_options_scopes( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -483,6 +486,7 @@ def test_authorized_domains_client_client_options_credentials_file( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -502,6 +506,7 @@ def test_authorized_domains_client_client_options_from_dict(): client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) diff --git a/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py b/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py index 2f765dc..39edd26 100644 --- a/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py +++ b/tests/unit/gapic/appengine_admin_v1/test_domain_mappings.py @@ -129,18 +129,6 @@ def test_domain_mappings_client_from_service_account_info(client_class): assert client.transport._host == "appengine.googleapis.com:443" -@pytest.mark.parametrize( - "client_class", [DomainMappingsClient, DomainMappingsAsyncClient,] -) -def test_domain_mappings_client_service_account_always_use_jwt(client_class): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - @pytest.mark.parametrize( "transport_class,transport_name", [ @@ -148,7 +136,7 @@ def test_domain_mappings_client_service_account_always_use_jwt(client_class): (transports.DomainMappingsGrpcAsyncIOTransport, "grpc_asyncio"), ], ) -def test_domain_mappings_client_service_account_always_use_jwt_true( +def test_domain_mappings_client_service_account_always_use_jwt( transport_class, transport_name ): with mock.patch.object( @@ -158,6 +146,13 @@ def test_domain_mappings_client_service_account_always_use_jwt_true( transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + @pytest.mark.parametrize( "client_class", [DomainMappingsClient, DomainMappingsAsyncClient,] @@ -238,6 +233,7 @@ def test_domain_mappings_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -254,6 +250,7 @@ def test_domain_mappings_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -270,6 +267,7 @@ def test_domain_mappings_client_client_options( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has @@ -298,6 +296,7 @@ def test_domain_mappings_client_client_options( client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -364,6 +363,7 @@ def test_domain_mappings_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case ADC client cert is provided. Whether client cert is used depends on @@ -397,6 +397,7 @@ def test_domain_mappings_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case client_cert_source and ADC client cert are not provided. @@ -418,6 +419,7 @@ def test_domain_mappings_client_mtls_env_auto( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -448,6 +450,7 @@ def test_domain_mappings_client_client_options_scopes( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -478,6 +481,7 @@ def test_domain_mappings_client_client_options_credentials_file( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -497,6 +501,7 @@ def test_domain_mappings_client_client_options_from_dict(): client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) diff --git a/tests/unit/gapic/appengine_admin_v1/test_firewall.py b/tests/unit/gapic/appengine_admin_v1/test_firewall.py index 100973b..ccbc861 100644 --- a/tests/unit/gapic/appengine_admin_v1/test_firewall.py +++ b/tests/unit/gapic/appengine_admin_v1/test_firewall.py @@ -113,16 +113,6 @@ def test_firewall_client_from_service_account_info(client_class): assert client.transport._host == "appengine.googleapis.com:443" -@pytest.mark.parametrize("client_class", [FirewallClient, FirewallAsyncClient,]) -def test_firewall_client_service_account_always_use_jwt(client_class): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - @pytest.mark.parametrize( "transport_class,transport_name", [ @@ -130,7 +120,7 @@ def test_firewall_client_service_account_always_use_jwt(client_class): (transports.FirewallGrpcAsyncIOTransport, "grpc_asyncio"), ], ) -def test_firewall_client_service_account_always_use_jwt_true( +def test_firewall_client_service_account_always_use_jwt( transport_class, transport_name ): with mock.patch.object( @@ -140,6 +130,13 @@ def test_firewall_client_service_account_always_use_jwt_true( transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + @pytest.mark.parametrize("client_class", [FirewallClient, FirewallAsyncClient,]) def test_firewall_client_from_service_account_file(client_class): @@ -210,6 +207,7 @@ def test_firewall_client_client_options(client_class, transport_class, transport client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -226,6 +224,7 @@ def test_firewall_client_client_options(client_class, transport_class, transport client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -242,6 +241,7 @@ def test_firewall_client_client_options(client_class, transport_class, transport client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has @@ -270,6 +270,7 @@ def test_firewall_client_client_options(client_class, transport_class, transport client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -334,6 +335,7 @@ def test_firewall_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case ADC client cert is provided. Whether client cert is used depends on @@ -367,6 +369,7 @@ def test_firewall_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case client_cert_source and ADC client cert are not provided. @@ -388,6 +391,7 @@ def test_firewall_client_mtls_env_auto( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -414,6 +418,7 @@ def test_firewall_client_client_options_scopes( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -440,6 +445,7 @@ def test_firewall_client_client_options_credentials_file( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -457,6 +463,7 @@ def test_firewall_client_client_options_from_dict(): client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) diff --git a/tests/unit/gapic/appengine_admin_v1/test_instances.py b/tests/unit/gapic/appengine_admin_v1/test_instances.py index 5958553..2fbe274 100644 --- a/tests/unit/gapic/appengine_admin_v1/test_instances.py +++ b/tests/unit/gapic/appengine_admin_v1/test_instances.py @@ -118,16 +118,6 @@ def test_instances_client_from_service_account_info(client_class): assert client.transport._host == "appengine.googleapis.com:443" -@pytest.mark.parametrize("client_class", [InstancesClient, InstancesAsyncClient,]) -def test_instances_client_service_account_always_use_jwt(client_class): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - @pytest.mark.parametrize( "transport_class,transport_name", [ @@ -135,7 +125,7 @@ def test_instances_client_service_account_always_use_jwt(client_class): (transports.InstancesGrpcAsyncIOTransport, "grpc_asyncio"), ], ) -def test_instances_client_service_account_always_use_jwt_true( +def test_instances_client_service_account_always_use_jwt( transport_class, transport_name ): with mock.patch.object( @@ -145,6 +135,13 @@ def test_instances_client_service_account_always_use_jwt_true( transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + @pytest.mark.parametrize("client_class", [InstancesClient, InstancesAsyncClient,]) def test_instances_client_from_service_account_file(client_class): @@ -219,6 +216,7 @@ def test_instances_client_client_options(client_class, transport_class, transpor client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -235,6 +233,7 @@ def test_instances_client_client_options(client_class, transport_class, transpor client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -251,6 +250,7 @@ def test_instances_client_client_options(client_class, transport_class, transpor client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has @@ -279,6 +279,7 @@ def test_instances_client_client_options(client_class, transport_class, transpor client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -343,6 +344,7 @@ def test_instances_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case ADC client cert is provided. Whether client cert is used depends on @@ -376,6 +378,7 @@ def test_instances_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case client_cert_source and ADC client cert are not provided. @@ -397,6 +400,7 @@ def test_instances_client_mtls_env_auto( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -427,6 +431,7 @@ def test_instances_client_client_options_scopes( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -457,6 +462,7 @@ def test_instances_client_client_options_credentials_file( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -474,6 +480,7 @@ def test_instances_client_client_options_from_dict(): client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) diff --git a/tests/unit/gapic/appengine_admin_v1/test_services.py b/tests/unit/gapic/appengine_admin_v1/test_services.py index 855a9ba..4f78a14 100644 --- a/tests/unit/gapic/appengine_admin_v1/test_services.py +++ b/tests/unit/gapic/appengine_admin_v1/test_services.py @@ -119,16 +119,6 @@ def test_services_client_from_service_account_info(client_class): assert client.transport._host == "appengine.googleapis.com:443" -@pytest.mark.parametrize("client_class", [ServicesClient, ServicesAsyncClient,]) -def test_services_client_service_account_always_use_jwt(client_class): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - @pytest.mark.parametrize( "transport_class,transport_name", [ @@ -136,7 +126,7 @@ def test_services_client_service_account_always_use_jwt(client_class): (transports.ServicesGrpcAsyncIOTransport, "grpc_asyncio"), ], ) -def test_services_client_service_account_always_use_jwt_true( +def test_services_client_service_account_always_use_jwt( transport_class, transport_name ): with mock.patch.object( @@ -146,6 +136,13 @@ def test_services_client_service_account_always_use_jwt_true( transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + @pytest.mark.parametrize("client_class", [ServicesClient, ServicesAsyncClient,]) def test_services_client_from_service_account_file(client_class): @@ -216,6 +213,7 @@ def test_services_client_client_options(client_class, transport_class, transport client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -232,6 +230,7 @@ def test_services_client_client_options(client_class, transport_class, transport client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -248,6 +247,7 @@ def test_services_client_client_options(client_class, transport_class, transport client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has @@ -276,6 +276,7 @@ def test_services_client_client_options(client_class, transport_class, transport client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -340,6 +341,7 @@ def test_services_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case ADC client cert is provided. Whether client cert is used depends on @@ -373,6 +375,7 @@ def test_services_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case client_cert_source and ADC client cert are not provided. @@ -394,6 +397,7 @@ def test_services_client_mtls_env_auto( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -420,6 +424,7 @@ def test_services_client_client_options_scopes( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -446,6 +451,7 @@ def test_services_client_client_options_credentials_file( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -463,6 +469,7 @@ def test_services_client_client_options_from_dict(): client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) diff --git a/tests/unit/gapic/appengine_admin_v1/test_versions.py b/tests/unit/gapic/appengine_admin_v1/test_versions.py index 00afb55..f47e621 100644 --- a/tests/unit/gapic/appengine_admin_v1/test_versions.py +++ b/tests/unit/gapic/appengine_admin_v1/test_versions.py @@ -122,16 +122,6 @@ def test_versions_client_from_service_account_info(client_class): assert client.transport._host == "appengine.googleapis.com:443" -@pytest.mark.parametrize("client_class", [VersionsClient, VersionsAsyncClient,]) -def test_versions_client_service_account_always_use_jwt(client_class): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - @pytest.mark.parametrize( "transport_class,transport_name", [ @@ -139,7 +129,7 @@ def test_versions_client_service_account_always_use_jwt(client_class): (transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), ], ) -def test_versions_client_service_account_always_use_jwt_true( +def test_versions_client_service_account_always_use_jwt( transport_class, transport_name ): with mock.patch.object( @@ -149,6 +139,13 @@ def test_versions_client_service_account_always_use_jwt_true( transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + @pytest.mark.parametrize("client_class", [VersionsClient, VersionsAsyncClient,]) def test_versions_client_from_service_account_file(client_class): @@ -219,6 +216,7 @@ def test_versions_client_client_options(client_class, transport_class, transport client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -235,6 +233,7 @@ def test_versions_client_client_options(client_class, transport_class, transport client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is @@ -251,6 +250,7 @@ def test_versions_client_client_options(client_class, transport_class, transport client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has @@ -279,6 +279,7 @@ def test_versions_client_client_options(client_class, transport_class, transport client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -343,6 +344,7 @@ def test_versions_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case ADC client cert is provided. Whether client cert is used depends on @@ -376,6 +378,7 @@ def test_versions_client_mtls_env_auto( client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) # Check the case client_cert_source and ADC client cert are not provided. @@ -397,6 +400,7 @@ def test_versions_client_mtls_env_auto( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -423,6 +427,7 @@ def test_versions_client_client_options_scopes( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -449,6 +454,7 @@ def test_versions_client_client_options_credentials_file( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -466,6 +472,7 @@ def test_versions_client_client_options_from_dict(): client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, )