From cb5881dac8121617fda5a4d9df9f70c80dcc8735 Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Tue, 23 Mar 2021 13:00:01 -0700 Subject: [PATCH 01/16] feat: add `from_service_account_info` (#24) PiperOrigin-RevId: 359562873 Source-Author: Google APIs Source-Date: Thu Feb 25 10:52:32 2021 -0800 Source-Repo: googleapis/googleapis Source-Sha: 07932bb995e7dc91b43620ea8402c6668c7d102c Source-Link: https://github.com/googleapis/googleapis/commit/07932bb995e7dc91b43620ea8402c6668c7d102c --- .../services/org_policy/async_client.py | 32 ++++- synth.metadata | 99 +++++++++++++- tests/unit/gapic/orgpolicy_v2/__init__.py | 15 +++ .../gapic/orgpolicy_v2/test_org_policy.py | 122 +++++++++++++++++- 4 files changed, 260 insertions(+), 8 deletions(-) diff --git a/google/cloud/orgpolicy_v2/services/org_policy/async_client.py b/google/cloud/orgpolicy_v2/services/org_policy/async_client.py index 4c14d45..7d1b013 100644 --- a/google/cloud/orgpolicy_v2/services/org_policy/async_client.py +++ b/google/cloud/orgpolicy_v2/services/org_policy/async_client.py @@ -95,8 +95,36 @@ class OrgPolicyAsyncClient: OrgPolicyClient.parse_common_location_path ) - from_service_account_info = OrgPolicyClient.from_service_account_info - from_service_account_file = OrgPolicyClient.from_service_account_file + @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: + OrgPolicyAsyncClient: The constructed client. + """ + return OrgPolicyClient.from_service_account_info.__func__(OrgPolicyAsyncClient, 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: + OrgPolicyAsyncClient: The constructed client. + """ + return OrgPolicyClient.from_service_account_file.__func__(OrgPolicyAsyncClient, filename, *args, **kwargs) # type: ignore + from_service_account_json = from_service_account_file @property diff --git a/synth.metadata b/synth.metadata index da29da1..7736efe 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,16 +3,16 @@ { "git": { "name": ".", - "remote": "git@github.com:googleapis/python-org-policy.git", - "sha": "4797e6d354848feb3b88f718c5e676929c9e4b5c" + "remote": "https://github.com/googleapis/python-org-policy.git", + "sha": "e60fdecf3b90d1a8863f996abc23683937b2e5da" } }, { "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "c06bbe28cc7287a55bf7926ee48da2565854de7f", - "internalRef": "359364666" + "sha": "07932bb995e7dc91b43620ea8402c6668c7d102c", + "internalRef": "359562873" } }, { @@ -40,5 +40,96 @@ "generator": "bazel" } } + ], + "generatedFiles": [ + ".coveragerc", + ".flake8", + ".github/CONTRIBUTING.md", + ".github/ISSUE_TEMPLATE/bug_report.md", + ".github/ISSUE_TEMPLATE/feature_request.md", + ".github/ISSUE_TEMPLATE/support_request.md", + ".github/PULL_REQUEST_TEMPLATE.md", + ".github/header-checker-lint.yml", + ".github/release-please.yml", + ".github/snippet-bot.yml", + ".gitignore", + ".kokoro/build.sh", + ".kokoro/continuous/common.cfg", + ".kokoro/continuous/continuous.cfg", + ".kokoro/docker/docs/Dockerfile", + ".kokoro/docker/docs/fetch_gpg_keys.sh", + ".kokoro/docs/common.cfg", + ".kokoro/docs/docs-presubmit.cfg", + ".kokoro/docs/docs.cfg", + ".kokoro/populate-secrets.sh", + ".kokoro/presubmit/common.cfg", + ".kokoro/presubmit/presubmit.cfg", + ".kokoro/publish-docs.sh", + ".kokoro/release.sh", + ".kokoro/release/common.cfg", + ".kokoro/release/release.cfg", + ".kokoro/samples/lint/common.cfg", + ".kokoro/samples/lint/continuous.cfg", + ".kokoro/samples/lint/periodic.cfg", + ".kokoro/samples/lint/presubmit.cfg", + ".kokoro/samples/python3.6/common.cfg", + ".kokoro/samples/python3.6/continuous.cfg", + ".kokoro/samples/python3.6/periodic.cfg", + ".kokoro/samples/python3.6/presubmit.cfg", + ".kokoro/samples/python3.7/common.cfg", + ".kokoro/samples/python3.7/continuous.cfg", + ".kokoro/samples/python3.7/periodic.cfg", + ".kokoro/samples/python3.7/presubmit.cfg", + ".kokoro/samples/python3.8/common.cfg", + ".kokoro/samples/python3.8/continuous.cfg", + ".kokoro/samples/python3.8/periodic.cfg", + ".kokoro/samples/python3.8/presubmit.cfg", + ".kokoro/test-samples.sh", + ".kokoro/trampoline.sh", + ".kokoro/trampoline_v2.sh", + ".pre-commit-config.yaml", + ".trampolinerc", + "CODE_OF_CONDUCT.md", + "CONTRIBUTING.rst", + "LICENSE", + "MANIFEST.in", + "docs/_static/custom.css", + "docs/_templates/layout.html", + "docs/conf.py", + "docs/multiprocessing.rst", + "docs/orgpolicy_v2/org_policy.rst", + "docs/orgpolicy_v2/services.rst", + "docs/orgpolicy_v2/types.rst", + "google/cloud/orgpolicy/__init__.py", + "google/cloud/orgpolicy/py.typed", + "google/cloud/orgpolicy_v2/__init__.py", + "google/cloud/orgpolicy_v2/py.typed", + "google/cloud/orgpolicy_v2/services/__init__.py", + "google/cloud/orgpolicy_v2/services/org_policy/__init__.py", + "google/cloud/orgpolicy_v2/services/org_policy/async_client.py", + "google/cloud/orgpolicy_v2/services/org_policy/client.py", + "google/cloud/orgpolicy_v2/services/org_policy/pagers.py", + "google/cloud/orgpolicy_v2/services/org_policy/transports/__init__.py", + "google/cloud/orgpolicy_v2/services/org_policy/transports/base.py", + "google/cloud/orgpolicy_v2/services/org_policy/transports/grpc.py", + "google/cloud/orgpolicy_v2/services/org_policy/transports/grpc_asyncio.py", + "google/cloud/orgpolicy_v2/types/__init__.py", + "google/cloud/orgpolicy_v2/types/constraint.py", + "google/cloud/orgpolicy_v2/types/orgpolicy.py", + "mypy.ini", + "noxfile.py", + "renovate.json", + "scripts/decrypt-secrets.sh", + "scripts/fixup_orgpolicy_v2_keywords.py", + "scripts/readme-gen/readme_gen.py", + "scripts/readme-gen/templates/README.tmpl.rst", + "scripts/readme-gen/templates/auth.tmpl.rst", + "scripts/readme-gen/templates/auth_api_key.tmpl.rst", + "scripts/readme-gen/templates/install_deps.tmpl.rst", + "scripts/readme-gen/templates/install_portaudio.tmpl.rst", + "setup.cfg", + "testing/.gitignore", + "tests/unit/gapic/orgpolicy_v2/__init__.py", + "tests/unit/gapic/orgpolicy_v2/test_org_policy.py" ] } \ No newline at end of file diff --git a/tests/unit/gapic/orgpolicy_v2/__init__.py b/tests/unit/gapic/orgpolicy_v2/__init__.py index 8b13789..42ffdf2 100644 --- a/tests/unit/gapic/orgpolicy_v2/__init__.py +++ b/tests/unit/gapic/orgpolicy_v2/__init__.py @@ -1 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/tests/unit/gapic/orgpolicy_v2/test_org_policy.py b/tests/unit/gapic/orgpolicy_v2/test_org_policy.py index 8a1417b..d533f67 100644 --- a/tests/unit/gapic/orgpolicy_v2/test_org_policy.py +++ b/tests/unit/gapic/orgpolicy_v2/test_org_policy.py @@ -82,15 +82,17 @@ def test__get_default_mtls_endpoint(): assert OrgPolicyClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi -def test_org_policy_client_from_service_account_info(): +@pytest.mark.parametrize("client_class", [OrgPolicyClient, OrgPolicyAsyncClient,]) +def test_org_policy_client_from_service_account_info(client_class): creds = credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: factory.return_value = creds info = {"valid": True} - client = OrgPolicyClient.from_service_account_info(info) + client = client_class.from_service_account_info(info) assert client.transport._credentials == creds + assert isinstance(client, client_class) assert client.transport._host == "orgpolicy.googleapis.com:443" @@ -104,9 +106,11 @@ def test_org_policy_client_from_service_account_file(client_class): 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 == "orgpolicy.googleapis.com:443" @@ -463,6 +467,22 @@ def test_list_constraints_from_dict(): test_list_constraints(request_type=dict) +def test_list_constraints_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 = OrgPolicyClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_constraints), "__call__") as call: + client.list_constraints() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == orgpolicy.ListConstraintsRequest() + + @pytest.mark.asyncio async def test_list_constraints_async( transport: str = "grpc_asyncio", request_type=orgpolicy.ListConstraintsRequest @@ -794,6 +814,22 @@ def test_list_policies_from_dict(): test_list_policies(request_type=dict) +def test_list_policies_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 = OrgPolicyClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_policies), "__call__") as call: + client.list_policies() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == orgpolicy.ListPoliciesRequest() + + @pytest.mark.asyncio async def test_list_policies_async( transport: str = "grpc_asyncio", request_type=orgpolicy.ListPoliciesRequest @@ -1105,6 +1141,22 @@ def test_get_policy_from_dict(): test_get_policy(request_type=dict) +def test_get_policy_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 = OrgPolicyClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_policy), "__call__") as call: + client.get_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == orgpolicy.GetPolicyRequest() + + @pytest.mark.asyncio async def test_get_policy_async( transport: str = "grpc_asyncio", request_type=orgpolicy.GetPolicyRequest @@ -1294,6 +1346,24 @@ def test_get_effective_policy_from_dict(): test_get_effective_policy(request_type=dict) +def test_get_effective_policy_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 = OrgPolicyClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_effective_policy), "__call__" + ) as call: + client.get_effective_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == orgpolicy.GetEffectivePolicyRequest() + + @pytest.mark.asyncio async def test_get_effective_policy_async( transport: str = "grpc_asyncio", request_type=orgpolicy.GetEffectivePolicyRequest @@ -1491,6 +1561,22 @@ def test_create_policy_from_dict(): test_create_policy(request_type=dict) +def test_create_policy_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 = OrgPolicyClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_policy), "__call__") as call: + client.create_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == orgpolicy.CreatePolicyRequest() + + @pytest.mark.asyncio async def test_create_policy_async( transport: str = "grpc_asyncio", request_type=orgpolicy.CreatePolicyRequest @@ -1690,6 +1776,22 @@ def test_update_policy_from_dict(): test_update_policy(request_type=dict) +def test_update_policy_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 = OrgPolicyClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_policy), "__call__") as call: + client.update_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == orgpolicy.UpdatePolicyRequest() + + @pytest.mark.asyncio async def test_update_policy_async( transport: str = "grpc_asyncio", request_type=orgpolicy.UpdatePolicyRequest @@ -1876,6 +1978,22 @@ def test_delete_policy_from_dict(): test_delete_policy(request_type=dict) +def test_delete_policy_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 = OrgPolicyClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_policy), "__call__") as call: + client.delete_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == orgpolicy.DeletePolicyRequest() + + @pytest.mark.asyncio async def test_delete_policy_async( transport: str = "grpc_asyncio", request_type=orgpolicy.DeletePolicyRequest From 42abf9b3612e3e85156c352a7e04faaf4b6754d1 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Tue, 30 Mar 2021 10:51:49 -0400 Subject: [PATCH 02/16] chore: add constraints file (#30) --- testing/constraints-3.10.txt | 0 testing/constraints-3.11.txt | 0 testing/constraints-3.6.txt | 23 +++++++++++++++++++++++ testing/constraints-3.7.txt | 0 testing/constraints-3.8.txt | 0 testing/constraints-3.9.txt | 0 6 files changed, 23 insertions(+) create mode 100644 testing/constraints-3.10.txt create mode 100644 testing/constraints-3.11.txt create mode 100644 testing/constraints-3.6.txt create mode 100644 testing/constraints-3.7.txt create mode 100644 testing/constraints-3.8.txt create mode 100644 testing/constraints-3.9.txt diff --git a/testing/constraints-3.10.txt b/testing/constraints-3.10.txt new file mode 100644 index 0000000..e69de29 diff --git a/testing/constraints-3.11.txt b/testing/constraints-3.11.txt new file mode 100644 index 0000000..e69de29 diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt new file mode 100644 index 0000000..3f71837 --- /dev/null +++ b/testing/constraints-3.6.txt @@ -0,0 +1,23 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List *all* library dependencies and extras in this file. +# Pin the version to the lower bound. +# +# e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", +# Then this file should have foo==1.14.0 +google-api-core==1.22.2 +proto-plus==1.10.0 diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt new file mode 100644 index 0000000..e69de29 diff --git a/testing/constraints-3.8.txt b/testing/constraints-3.8.txt new file mode 100644 index 0000000..e69de29 diff --git a/testing/constraints-3.9.txt b/testing/constraints-3.9.txt new file mode 100644 index 0000000..e69de29 From 5d1f86c3121c778f71205364af43e1f26f4c12c9 Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Wed, 31 Mar 2021 16:18:07 -0700 Subject: [PATCH 03/16] fix: use correct retry deadline (#28) --- .kokoro/samples/python3.6/periodic-head.cfg | 11 ++ .kokoro/samples/python3.7/periodic-head.cfg | 11 ++ .kokoro/samples/python3.8/periodic-head.cfg | 11 ++ .kokoro/test-samples-against-head.sh | 28 +++++ .kokoro/test-samples-impl.sh | 102 ++++++++++++++++ .kokoro/test-samples.sh | 96 +++------------ .pre-commit-config.yaml | 2 +- .../services/org_policy/async_client.py | 7 ++ .../services/org_policy/transports/base.py | 25 ++-- .../services/org_policy/transports/grpc.py | 101 ++++++---------- .../org_policy/transports/grpc_asyncio.py | 109 +++++++----------- google/cloud/orgpolicy_v2/types/__init__.py | 24 ++-- noxfile.py | 40 ++++--- renovate.json | 3 +- synth.metadata | 103 +---------------- synth.py | 10 +- testing/constraints-3.7.txt | 2 + testing/constraints-3.8.txt | 2 + testing/constraints-3.9.txt | 2 + 19 files changed, 337 insertions(+), 352 deletions(-) create mode 100644 .kokoro/samples/python3.6/periodic-head.cfg create mode 100644 .kokoro/samples/python3.7/periodic-head.cfg create mode 100644 .kokoro/samples/python3.8/periodic-head.cfg create mode 100755 .kokoro/test-samples-against-head.sh create mode 100755 .kokoro/test-samples-impl.sh diff --git a/.kokoro/samples/python3.6/periodic-head.cfg b/.kokoro/samples/python3.6/periodic-head.cfg new file mode 100644 index 0000000..f9cfcd3 --- /dev/null +++ b/.kokoro/samples/python3.6/periodic-head.cfg @@ -0,0 +1,11 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-pubsub/.kokoro/test-samples-against-head.sh" +} diff --git a/.kokoro/samples/python3.7/periodic-head.cfg b/.kokoro/samples/python3.7/periodic-head.cfg new file mode 100644 index 0000000..f9cfcd3 --- /dev/null +++ b/.kokoro/samples/python3.7/periodic-head.cfg @@ -0,0 +1,11 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-pubsub/.kokoro/test-samples-against-head.sh" +} diff --git a/.kokoro/samples/python3.8/periodic-head.cfg b/.kokoro/samples/python3.8/periodic-head.cfg new file mode 100644 index 0000000..f9cfcd3 --- /dev/null +++ b/.kokoro/samples/python3.8/periodic-head.cfg @@ -0,0 +1,11 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-pubsub/.kokoro/test-samples-against-head.sh" +} diff --git a/.kokoro/test-samples-against-head.sh b/.kokoro/test-samples-against-head.sh new file mode 100755 index 0000000..bc1d86a --- /dev/null +++ b/.kokoro/test-samples-against-head.sh @@ -0,0 +1,28 @@ +#!/bin/bash +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# A customized test runner for samples. +# +# For periodic builds, you can specify this file for testing against head. + +# `-e` enables the script to automatically fail when a command fails +# `-o pipefail` sets the exit code to the rightmost comment to exit with a non-zero +set -eo pipefail +# Enables `**` to include files nested inside sub-folders +shopt -s globstar + +cd github/python-org-policy + +exec .kokoro/test-samples-impl.sh diff --git a/.kokoro/test-samples-impl.sh b/.kokoro/test-samples-impl.sh new file mode 100755 index 0000000..cf5de74 --- /dev/null +++ b/.kokoro/test-samples-impl.sh @@ -0,0 +1,102 @@ +#!/bin/bash +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +# `-e` enables the script to automatically fail when a command fails +# `-o pipefail` sets the exit code to the rightmost comment to exit with a non-zero +set -eo pipefail +# Enables `**` to include files nested inside sub-folders +shopt -s globstar + +# Exit early if samples directory doesn't exist +if [ ! -d "./samples" ]; then + echo "No tests run. `./samples` not found" + exit 0 +fi + +# Disable buffering, so that the logs stream through. +export PYTHONUNBUFFERED=1 + +# Debug: show build environment +env | grep KOKORO + +# Install nox +python3.6 -m pip install --upgrade --quiet nox + +# Use secrets acessor service account to get secrets +if [[ -f "${KOKORO_GFILE_DIR}/secrets_viewer_service_account.json" ]]; then + gcloud auth activate-service-account \ + --key-file="${KOKORO_GFILE_DIR}/secrets_viewer_service_account.json" \ + --project="cloud-devrel-kokoro-resources" +fi + +# This script will create 3 files: +# - testing/test-env.sh +# - testing/service-account.json +# - testing/client-secrets.json +./scripts/decrypt-secrets.sh + +source ./testing/test-env.sh +export GOOGLE_APPLICATION_CREDENTIALS=$(pwd)/testing/service-account.json + +# For cloud-run session, we activate the service account for gcloud sdk. +gcloud auth activate-service-account \ + --key-file "${GOOGLE_APPLICATION_CREDENTIALS}" + +export GOOGLE_CLIENT_SECRETS=$(pwd)/testing/client-secrets.json + +echo -e "\n******************** TESTING PROJECTS ********************" + +# Switch to 'fail at end' to allow all tests to complete before exiting. +set +e +# Use RTN to return a non-zero value if the test fails. +RTN=0 +ROOT=$(pwd) +# Find all requirements.txt in the samples directory (may break on whitespace). +for file in samples/**/requirements.txt; do + cd "$ROOT" + # Navigate to the project folder. + file=$(dirname "$file") + cd "$file" + + echo "------------------------------------------------------------" + echo "- testing $file" + echo "------------------------------------------------------------" + + # Use nox to execute the tests for the project. + python3.6 -m nox -s "$RUN_TESTS_SESSION" + EXIT=$? + + # If this is a periodic build, send the test log to the FlakyBot. + # See https://github.com/googleapis/repo-automation-bots/tree/master/packages/flakybot. + if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then + chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot + $KOKORO_GFILE_DIR/linux_amd64/flakybot + fi + + if [[ $EXIT -ne 0 ]]; then + RTN=1 + echo -e "\n Testing failed: Nox returned a non-zero exit code. \n" + else + echo -e "\n Testing completed.\n" + fi + +done +cd "$ROOT" + +# Workaround for Kokoro permissions issue: delete secrets +rm testing/{test-env.sh,client-secrets.json,service-account.json} + +exit "$RTN" diff --git a/.kokoro/test-samples.sh b/.kokoro/test-samples.sh index b915e62..1011461 100755 --- a/.kokoro/test-samples.sh +++ b/.kokoro/test-samples.sh @@ -13,6 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. +# The default test runner for samples. +# +# For periodic builds, we rewinds the repo to the latest release, and +# run test-samples-impl.sh. # `-e` enables the script to automatically fail when a command fails # `-o pipefail` sets the exit code to the rightmost comment to exit with a non-zero @@ -24,87 +28,19 @@ cd github/python-org-policy # Run periodic samples tests at latest release if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then + # preserving the test runner implementation. + cp .kokoro/test-samples-impl.sh "${TMPDIR}/test-samples-impl.sh" + echo "--- IMPORTANT IMPORTANT IMPORTANT ---" + echo "Now we rewind the repo back to the latest release..." LATEST_RELEASE=$(git describe --abbrev=0 --tags) git checkout $LATEST_RELEASE -fi - -# Exit early if samples directory doesn't exist -if [ ! -d "./samples" ]; then - echo "No tests run. `./samples` not found" - exit 0 -fi - -# Disable buffering, so that the logs stream through. -export PYTHONUNBUFFERED=1 - -# Debug: show build environment -env | grep KOKORO - -# Install nox -python3.6 -m pip install --upgrade --quiet nox - -# Use secrets acessor service account to get secrets -if [[ -f "${KOKORO_GFILE_DIR}/secrets_viewer_service_account.json" ]]; then - gcloud auth activate-service-account \ - --key-file="${KOKORO_GFILE_DIR}/secrets_viewer_service_account.json" \ - --project="cloud-devrel-kokoro-resources" -fi - -# This script will create 3 files: -# - testing/test-env.sh -# - testing/service-account.json -# - testing/client-secrets.json -./scripts/decrypt-secrets.sh - -source ./testing/test-env.sh -export GOOGLE_APPLICATION_CREDENTIALS=$(pwd)/testing/service-account.json - -# For cloud-run session, we activate the service account for gcloud sdk. -gcloud auth activate-service-account \ - --key-file "${GOOGLE_APPLICATION_CREDENTIALS}" - -export GOOGLE_CLIENT_SECRETS=$(pwd)/testing/client-secrets.json - -echo -e "\n******************** TESTING PROJECTS ********************" - -# Switch to 'fail at end' to allow all tests to complete before exiting. -set +e -# Use RTN to return a non-zero value if the test fails. -RTN=0 -ROOT=$(pwd) -# Find all requirements.txt in the samples directory (may break on whitespace). -for file in samples/**/requirements.txt; do - cd "$ROOT" - # Navigate to the project folder. - file=$(dirname "$file") - cd "$file" - - echo "------------------------------------------------------------" - echo "- testing $file" - echo "------------------------------------------------------------" - - # Use nox to execute the tests for the project. - python3.6 -m nox -s "$RUN_TESTS_SESSION" - EXIT=$? - - # If this is a periodic build, send the test log to the FlakyBot. - # See https://github.com/googleapis/repo-automation-bots/tree/master/packages/flakybot. - if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then - chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot - $KOKORO_GFILE_DIR/linux_amd64/flakybot + echo "The current head is: " + echo $(git rev-parse --verify HEAD) + echo "--- IMPORTANT IMPORTANT IMPORTANT ---" + # move back the test runner implementation if there's no file. + if [ ! -f .kokoro/test-samples-impl.sh ]; then + cp "${TMPDIR}/test-samples-impl.sh" .kokoro/test-samples-impl.sh fi +fi - if [[ $EXIT -ne 0 ]]; then - RTN=1 - echo -e "\n Testing failed: Nox returned a non-zero exit code. \n" - else - echo -e "\n Testing completed.\n" - fi - -done -cd "$ROOT" - -# Workaround for Kokoro permissions issue: delete secrets -rm testing/{test-env.sh,client-secrets.json,service-account.json} - -exit "$RTN" +exec .kokoro/test-samples-impl.sh diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a9024b1..32302e4 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -12,6 +12,6 @@ repos: hooks: - id: black - repo: https://gitlab.com/pycqa/flake8 - rev: 3.8.4 + rev: 3.9.0 hooks: - id: flake8 diff --git a/google/cloud/orgpolicy_v2/services/org_policy/async_client.py b/google/cloud/orgpolicy_v2/services/org_policy/async_client.py index 7d1b013..cb43086 100644 --- a/google/cloud/orgpolicy_v2/services/org_policy/async_client.py +++ b/google/cloud/orgpolicy_v2/services/org_policy/async_client.py @@ -264,6 +264,7 @@ async def list_constraints( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -365,6 +366,7 @@ async def list_policies( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -456,6 +458,7 @@ async def get_policy( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -544,6 +547,7 @@ async def get_effective_policy( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -646,6 +650,7 @@ async def create_policy( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -736,6 +741,7 @@ async def update_policy( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -819,6 +825,7 @@ async def delete_policy( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, diff --git a/google/cloud/orgpolicy_v2/services/org_policy/transports/base.py b/google/cloud/orgpolicy_v2/services/org_policy/transports/base.py index d53f3e4..1cfd0e1 100644 --- a/google/cloud/orgpolicy_v2/services/org_policy/transports/base.py +++ b/google/cloud/orgpolicy_v2/services/org_policy/transports/base.py @@ -70,10 +70,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -81,6 +81,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -90,20 +93,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -116,6 +116,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -129,6 +130,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -142,6 +144,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -155,6 +158,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -168,6 +172,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -181,6 +186,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -194,6 +200,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, diff --git a/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc.py b/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc.py index 85a6300..1a150dc 100644 --- a/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc.py +++ b/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc.py @@ -128,7 +128,9 @@ def __init__( 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) @@ -136,70 +138,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -207,17 +189,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -231,7 +204,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc_asyncio.py b/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc_asyncio.py index 33d57ed..704fe30 100644 --- a/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc_asyncio.py +++ b/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc_asyncio.py @@ -83,7 +83,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -161,10 +161,10 @@ def __init__( 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 + 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: @@ -173,7 +173,9 @@ def __init__( 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) @@ -181,70 +183,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -252,17 +234,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/orgpolicy_v2/types/__init__.py b/google/cloud/orgpolicy_v2/types/__init__.py index c2c6ae8..7355e8e 100644 --- a/google/cloud/orgpolicy_v2/types/__init__.py +++ b/google/cloud/orgpolicy_v2/types/__init__.py @@ -17,32 +17,32 @@ from .constraint import Constraint from .orgpolicy import ( - Policy, AlternatePolicySpec, - PolicySpec, + CreatePolicyRequest, + DeletePolicyRequest, + GetEffectivePolicyRequest, + GetPolicyRequest, ListConstraintsRequest, ListConstraintsResponse, ListPoliciesRequest, ListPoliciesResponse, - GetPolicyRequest, - GetEffectivePolicyRequest, - CreatePolicyRequest, + Policy, + PolicySpec, UpdatePolicyRequest, - DeletePolicyRequest, ) __all__ = ( "Constraint", - "Policy", "AlternatePolicySpec", - "PolicySpec", + "CreatePolicyRequest", + "DeletePolicyRequest", + "GetEffectivePolicyRequest", + "GetPolicyRequest", "ListConstraintsRequest", "ListConstraintsResponse", "ListPoliciesRequest", "ListPoliciesResponse", - "GetPolicyRequest", - "GetEffectivePolicyRequest", - "CreatePolicyRequest", + "Policy", + "PolicySpec", "UpdatePolicyRequest", - "DeletePolicyRequest", ) diff --git a/noxfile.py b/noxfile.py index 51379d4..29da51d 100644 --- a/noxfile.py +++ b/noxfile.py @@ -18,6 +18,7 @@ from __future__ import absolute_import import os +import pathlib import shutil import nox @@ -30,6 +31,8 @@ SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + # 'docfx' is excluded since it only needs to run in 'docs-presubmit' nox.options.sessions = [ "unit", @@ -41,16 +44,19 @@ "docs", ] +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + @nox.session(python="3.8") def generate_protos(session): """Generates the protos using protoc. - + Some notes on the `google` directory: - 1. The `_pb2.py` files are produced by protoc. + 1. The `_pb2.py` files are produced by protoc. 2. The .proto files are non-functional but are left in the repository to make it easier to understand diffs. - 3. The `google` directory also has `__init__.py` files to create proper modules. + 3. The `google` directory also has `__init__.py` files to create proper modules. If a new subdirectory is added, you will need to create more `__init__.py` files. @@ -111,13 +117,15 @@ def lint_setup_py(session): def default(session): # Install all test dependencies, then install this package in-place. - session.install("asyncmock", "pytest-asyncio") - session.install( - "mock", "pytest", "pytest-cov", + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" ) + session.install("asyncmock", "pytest-asyncio", "-c", constraints_path) - session.install("-e", ".") + session.install("mock", "pytest", "pytest-cov", "-c", constraints_path) + + session.install("-e", ".", "-c", constraints_path) # Run py.test against the unit tests. session.run( @@ -144,6 +152,9 @@ def unit(session): @nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) def system(session): """Run the system test suite.""" + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) system_test_path = os.path.join("tests", "system.py") system_test_folder_path = os.path.join("tests", "system") @@ -153,6 +164,9 @@ def system(session): # Sanity check: Only run tests if the environment variable is set. if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""): session.skip("Credentials must be set via environment variable") + # Install pyopenssl for mTLS testing. + if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": + session.install("pyopenssl") system_test_exists = os.path.exists(system_test_path) system_test_folder_exists = os.path.exists(system_test_folder_path) @@ -165,10 +179,8 @@ def system(session): # Install all test dependencies, then install this package into the # virtualenv's dist-packages. - session.install( - "mock", "pytest", "google-cloud-testutils", - ) - session.install("-e", ".") + session.install("mock", "pytest", "google-cloud-testutils", "-c", constraints_path) + session.install("-e", ".", "-c", constraints_path) # Run py.test against the system tests. if system_test_exists: @@ -197,7 +209,7 @@ def cover(session): test runs (not system test runs), and then erases coverage data. """ session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=97") + session.run("coverage", "report", "--show-missing", "--fail-under=95") session.run("coverage", "erase") @@ -229,9 +241,7 @@ def docfx(session): """Build the docfx yaml files for this library.""" session.install("-e", ".") - # sphinx-docfx-yaml supports up to sphinx version 1.5.5. - # https://github.com/docascode/sphinx-docfx-yaml/issues/97 - session.install("sphinx==1.5.5", "alabaster", "recommonmark", "sphinx-docfx-yaml") + session.install("sphinx", "alabaster", "recommonmark", "gcp-sphinx-docfx-yaml") shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( diff --git a/renovate.json b/renovate.json index 4fa9493..f08bc22 100644 --- a/renovate.json +++ b/renovate.json @@ -1,5 +1,6 @@ { "extends": [ "config:base", ":preserveSemverRanges" - ] + ], + "ignorePaths": [".pre-commit-config.yaml"] } diff --git a/synth.metadata b/synth.metadata index 7736efe..e229f6f 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,30 +3,30 @@ { "git": { "name": ".", - "remote": "https://github.com/googleapis/python-org-policy.git", - "sha": "e60fdecf3b90d1a8863f996abc23683937b2e5da" + "remote": "git@github.com:googleapis/python-org-policy.git", + "sha": "3f311b3105c60324bf64219d1402713d33f62fb9" } }, { "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "07932bb995e7dc91b43620ea8402c6668c7d102c", - "internalRef": "359562873" + "sha": "95dd24960cf9f794ef583e59ad9f1fabe1c4a924", + "internalRef": "365882072" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "79ab0b44a2cc7d803d07c107f9faf07729fc4012" + "sha": "551dd78ca04f7989abc9e63e392f8b8cfa1a0ef9" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "79ab0b44a2cc7d803d07c107f9faf07729fc4012" + "sha": "551dd78ca04f7989abc9e63e392f8b8cfa1a0ef9" } } ], @@ -40,96 +40,5 @@ "generator": "bazel" } } - ], - "generatedFiles": [ - ".coveragerc", - ".flake8", - ".github/CONTRIBUTING.md", - ".github/ISSUE_TEMPLATE/bug_report.md", - ".github/ISSUE_TEMPLATE/feature_request.md", - ".github/ISSUE_TEMPLATE/support_request.md", - ".github/PULL_REQUEST_TEMPLATE.md", - ".github/header-checker-lint.yml", - ".github/release-please.yml", - ".github/snippet-bot.yml", - ".gitignore", - ".kokoro/build.sh", - ".kokoro/continuous/common.cfg", - ".kokoro/continuous/continuous.cfg", - ".kokoro/docker/docs/Dockerfile", - ".kokoro/docker/docs/fetch_gpg_keys.sh", - ".kokoro/docs/common.cfg", - ".kokoro/docs/docs-presubmit.cfg", - ".kokoro/docs/docs.cfg", - ".kokoro/populate-secrets.sh", - ".kokoro/presubmit/common.cfg", - ".kokoro/presubmit/presubmit.cfg", - ".kokoro/publish-docs.sh", - ".kokoro/release.sh", - ".kokoro/release/common.cfg", - ".kokoro/release/release.cfg", - ".kokoro/samples/lint/common.cfg", - ".kokoro/samples/lint/continuous.cfg", - ".kokoro/samples/lint/periodic.cfg", - ".kokoro/samples/lint/presubmit.cfg", - ".kokoro/samples/python3.6/common.cfg", - ".kokoro/samples/python3.6/continuous.cfg", - ".kokoro/samples/python3.6/periodic.cfg", - ".kokoro/samples/python3.6/presubmit.cfg", - ".kokoro/samples/python3.7/common.cfg", - ".kokoro/samples/python3.7/continuous.cfg", - ".kokoro/samples/python3.7/periodic.cfg", - ".kokoro/samples/python3.7/presubmit.cfg", - ".kokoro/samples/python3.8/common.cfg", - ".kokoro/samples/python3.8/continuous.cfg", - ".kokoro/samples/python3.8/periodic.cfg", - ".kokoro/samples/python3.8/presubmit.cfg", - ".kokoro/test-samples.sh", - ".kokoro/trampoline.sh", - ".kokoro/trampoline_v2.sh", - ".pre-commit-config.yaml", - ".trampolinerc", - "CODE_OF_CONDUCT.md", - "CONTRIBUTING.rst", - "LICENSE", - "MANIFEST.in", - "docs/_static/custom.css", - "docs/_templates/layout.html", - "docs/conf.py", - "docs/multiprocessing.rst", - "docs/orgpolicy_v2/org_policy.rst", - "docs/orgpolicy_v2/services.rst", - "docs/orgpolicy_v2/types.rst", - "google/cloud/orgpolicy/__init__.py", - "google/cloud/orgpolicy/py.typed", - "google/cloud/orgpolicy_v2/__init__.py", - "google/cloud/orgpolicy_v2/py.typed", - "google/cloud/orgpolicy_v2/services/__init__.py", - "google/cloud/orgpolicy_v2/services/org_policy/__init__.py", - "google/cloud/orgpolicy_v2/services/org_policy/async_client.py", - "google/cloud/orgpolicy_v2/services/org_policy/client.py", - "google/cloud/orgpolicy_v2/services/org_policy/pagers.py", - "google/cloud/orgpolicy_v2/services/org_policy/transports/__init__.py", - "google/cloud/orgpolicy_v2/services/org_policy/transports/base.py", - "google/cloud/orgpolicy_v2/services/org_policy/transports/grpc.py", - "google/cloud/orgpolicy_v2/services/org_policy/transports/grpc_asyncio.py", - "google/cloud/orgpolicy_v2/types/__init__.py", - "google/cloud/orgpolicy_v2/types/constraint.py", - "google/cloud/orgpolicy_v2/types/orgpolicy.py", - "mypy.ini", - "noxfile.py", - "renovate.json", - "scripts/decrypt-secrets.sh", - "scripts/fixup_orgpolicy_v2_keywords.py", - "scripts/readme-gen/readme_gen.py", - "scripts/readme-gen/templates/README.tmpl.rst", - "scripts/readme-gen/templates/auth.tmpl.rst", - "scripts/readme-gen/templates/auth_api_key.tmpl.rst", - "scripts/readme-gen/templates/install_deps.tmpl.rst", - "scripts/readme-gen/templates/install_portaudio.tmpl.rst", - "setup.cfg", - "testing/.gitignore", - "tests/unit/gapic/orgpolicy_v2/__init__.py", - "tests/unit/gapic/orgpolicy_v2/test_org_policy.py" ] } \ No newline at end of file diff --git a/synth.py b/synth.py index f8237bd..570657a 100644 --- a/synth.py +++ b/synth.py @@ -50,7 +50,7 @@ # ---------------------------------------------------------------------------- # coverage is 97 to exclude orgpolicy/v1 code -templated_files = common.py_library(microgenerator=True, cov_level=97) +templated_files = common.py_library(microgenerator=True, cov_level=95) s.move( templated_files, excludes=[".coveragerc",] ) @@ -69,12 +69,12 @@ def lint\(.+?)""", '''@nox.session(python="3.8") def generate_protos(session): """Generates the protos using protoc. - + Some notes on the `google` directory: - 1. The `_pb2.py` files are produced by protoc. + 1. The `_pb2.py` files are produced by protoc. 2. The .proto files are non-functional but are left in the repository to make it easier to understand diffs. - 3. The `google` directory also has `__init__.py` files to create proper modules. + 3. The `google` directory also has `__init__.py` files to create proper modules. If a new subdirectory is added, you will need to create more `__init__.py` files. @@ -94,7 +94,7 @@ def generate_protos(session): "--python_out=.", *protos, ) - + \g<1>''', ) s.shell.run(["nox", "-s", "blacken"], hide_output=False) diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index e69de29..da93009 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -0,0 +1,2 @@ +# This constraints file is left inentionally empty +# so the latest version of dependencies is installed \ No newline at end of file diff --git a/testing/constraints-3.8.txt b/testing/constraints-3.8.txt index e69de29..da93009 100644 --- a/testing/constraints-3.8.txt +++ b/testing/constraints-3.8.txt @@ -0,0 +1,2 @@ +# This constraints file is left inentionally empty +# so the latest version of dependencies is installed \ No newline at end of file diff --git a/testing/constraints-3.9.txt b/testing/constraints-3.9.txt index e69de29..da93009 100644 --- a/testing/constraints-3.9.txt +++ b/testing/constraints-3.9.txt @@ -0,0 +1,2 @@ +# This constraints file is left inentionally empty +# so the latest version of dependencies is installed \ No newline at end of file From ce3cab20a7a88c7b9782de2d5112ccf5800d211a Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Thu, 1 Apr 2021 07:53:07 -0700 Subject: [PATCH 04/16] chore: start tracking obsolete files (#31) --- synth.metadata | 108 ++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 102 insertions(+), 6 deletions(-) diff --git a/synth.metadata b/synth.metadata index e229f6f..21fe3e4 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,30 +3,30 @@ { "git": { "name": ".", - "remote": "git@github.com:googleapis/python-org-policy.git", - "sha": "3f311b3105c60324bf64219d1402713d33f62fb9" + "remote": "https://github.com/googleapis/python-org-policy.git", + "sha": "5d1f86c3121c778f71205364af43e1f26f4c12c9" } }, { "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "95dd24960cf9f794ef583e59ad9f1fabe1c4a924", - "internalRef": "365882072" + "sha": "915925089600094e72e4bfa8cf586c170e6b7109", + "internalRef": "366152684" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "551dd78ca04f7989abc9e63e392f8b8cfa1a0ef9" + "sha": "a22531f8364582f51485e4e9db85872d93514ab1" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "551dd78ca04f7989abc9e63e392f8b8cfa1a0ef9" + "sha": "a22531f8364582f51485e4e9db85872d93514ab1" } } ], @@ -40,5 +40,101 @@ "generator": "bazel" } } + ], + "generatedFiles": [ + ".coveragerc", + ".flake8", + ".github/CONTRIBUTING.md", + ".github/ISSUE_TEMPLATE/bug_report.md", + ".github/ISSUE_TEMPLATE/feature_request.md", + ".github/ISSUE_TEMPLATE/support_request.md", + ".github/PULL_REQUEST_TEMPLATE.md", + ".github/header-checker-lint.yml", + ".github/release-please.yml", + ".github/snippet-bot.yml", + ".gitignore", + ".kokoro/build.sh", + ".kokoro/continuous/common.cfg", + ".kokoro/continuous/continuous.cfg", + ".kokoro/docker/docs/Dockerfile", + ".kokoro/docker/docs/fetch_gpg_keys.sh", + ".kokoro/docs/common.cfg", + ".kokoro/docs/docs-presubmit.cfg", + ".kokoro/docs/docs.cfg", + ".kokoro/populate-secrets.sh", + ".kokoro/presubmit/common.cfg", + ".kokoro/presubmit/presubmit.cfg", + ".kokoro/publish-docs.sh", + ".kokoro/release.sh", + ".kokoro/release/common.cfg", + ".kokoro/release/release.cfg", + ".kokoro/samples/lint/common.cfg", + ".kokoro/samples/lint/continuous.cfg", + ".kokoro/samples/lint/periodic.cfg", + ".kokoro/samples/lint/presubmit.cfg", + ".kokoro/samples/python3.6/common.cfg", + ".kokoro/samples/python3.6/continuous.cfg", + ".kokoro/samples/python3.6/periodic-head.cfg", + ".kokoro/samples/python3.6/periodic.cfg", + ".kokoro/samples/python3.6/presubmit.cfg", + ".kokoro/samples/python3.7/common.cfg", + ".kokoro/samples/python3.7/continuous.cfg", + ".kokoro/samples/python3.7/periodic-head.cfg", + ".kokoro/samples/python3.7/periodic.cfg", + ".kokoro/samples/python3.7/presubmit.cfg", + ".kokoro/samples/python3.8/common.cfg", + ".kokoro/samples/python3.8/continuous.cfg", + ".kokoro/samples/python3.8/periodic-head.cfg", + ".kokoro/samples/python3.8/periodic.cfg", + ".kokoro/samples/python3.8/presubmit.cfg", + ".kokoro/test-samples-against-head.sh", + ".kokoro/test-samples-impl.sh", + ".kokoro/test-samples.sh", + ".kokoro/trampoline.sh", + ".kokoro/trampoline_v2.sh", + ".pre-commit-config.yaml", + ".trampolinerc", + "CODE_OF_CONDUCT.md", + "CONTRIBUTING.rst", + "LICENSE", + "MANIFEST.in", + "docs/_static/custom.css", + "docs/_templates/layout.html", + "docs/conf.py", + "docs/multiprocessing.rst", + "docs/orgpolicy_v2/org_policy.rst", + "docs/orgpolicy_v2/services.rst", + "docs/orgpolicy_v2/types.rst", + "google/cloud/orgpolicy/__init__.py", + "google/cloud/orgpolicy/py.typed", + "google/cloud/orgpolicy_v2/__init__.py", + "google/cloud/orgpolicy_v2/py.typed", + "google/cloud/orgpolicy_v2/services/__init__.py", + "google/cloud/orgpolicy_v2/services/org_policy/__init__.py", + "google/cloud/orgpolicy_v2/services/org_policy/async_client.py", + "google/cloud/orgpolicy_v2/services/org_policy/client.py", + "google/cloud/orgpolicy_v2/services/org_policy/pagers.py", + "google/cloud/orgpolicy_v2/services/org_policy/transports/__init__.py", + "google/cloud/orgpolicy_v2/services/org_policy/transports/base.py", + "google/cloud/orgpolicy_v2/services/org_policy/transports/grpc.py", + "google/cloud/orgpolicy_v2/services/org_policy/transports/grpc_asyncio.py", + "google/cloud/orgpolicy_v2/types/__init__.py", + "google/cloud/orgpolicy_v2/types/constraint.py", + "google/cloud/orgpolicy_v2/types/orgpolicy.py", + "mypy.ini", + "noxfile.py", + "renovate.json", + "scripts/decrypt-secrets.sh", + "scripts/fixup_orgpolicy_v2_keywords.py", + "scripts/readme-gen/readme_gen.py", + "scripts/readme-gen/templates/README.tmpl.rst", + "scripts/readme-gen/templates/auth.tmpl.rst", + "scripts/readme-gen/templates/auth_api_key.tmpl.rst", + "scripts/readme-gen/templates/install_deps.tmpl.rst", + "scripts/readme-gen/templates/install_portaudio.tmpl.rst", + "setup.cfg", + "testing/.gitignore", + "tests/unit/gapic/orgpolicy_v2/__init__.py", + "tests/unit/gapic/orgpolicy_v2/test_org_policy.py" ] } \ No newline at end of file From 804e8a4484e48c514fa383ced0b5f56d38f36ee7 Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Wed, 7 Apr 2021 09:00:06 -0700 Subject: [PATCH 05/16] chore: Add license headers for python config files (#33) Source-Author: Anthonios Partheniou Source-Date: Tue Apr 6 11:32:03 2021 -0400 Source-Repo: googleapis/synthtool Source-Sha: 5b5bf6d519b2d658d9f2e483d9f6f3d0ba8ee6bc Source-Link: https://github.com/googleapis/synthtool/commit/5b5bf6d519b2d658d9f2e483d9f6f3d0ba8ee6bc --- .pre-commit-config.yaml | 14 ++++++++++++++ docs/conf.py | 13 +++++++++++++ synth.metadata | 6 +++--- 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 32302e4..8912e9b 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,3 +1,17 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# # See https://pre-commit.com for more information # See https://pre-commit.com/hooks.html for more hooks repos: diff --git a/docs/conf.py b/docs/conf.py index 320e5cd..afae95e 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,4 +1,17 @@ # -*- coding: utf-8 -*- +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. # # google-cloud-org-policy documentation build configuration file # diff --git a/synth.metadata b/synth.metadata index 21fe3e4..34337b6 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,7 +4,7 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/python-org-policy.git", - "sha": "5d1f86c3121c778f71205364af43e1f26f4c12c9" + "sha": "ce3cab20a7a88c7b9782de2d5112ccf5800d211a" } }, { @@ -19,14 +19,14 @@ "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "a22531f8364582f51485e4e9db85872d93514ab1" + "sha": "5b5bf6d519b2d658d9f2e483d9f6f3d0ba8ee6bc" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "a22531f8364582f51485e4e9db85872d93514ab1" + "sha": "5b5bf6d519b2d658d9f2e483d9f6f3d0ba8ee6bc" } } ], From a4ff508d464cf3c2b797ca90a7ebed27723f3165 Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Sun, 11 Apr 2021 04:10:26 -0700 Subject: [PATCH 06/16] chore: add constraints file check for python samples (#34) This is the sibling PR to https://github.com/GoogleCloudPlatform/python-docs-samples/pull/5611 and this is the issue opened for it https://github.com/GoogleCloudPlatform/python-docs-samples/issues/5549 --- .github/header-checker-lint.yml | 2 +- renovate.json | 5 ++++- synth.metadata | 6 +++--- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/.github/header-checker-lint.yml b/.github/header-checker-lint.yml index fc281c0..6fe78aa 100644 --- a/.github/header-checker-lint.yml +++ b/.github/header-checker-lint.yml @@ -1,6 +1,6 @@ {"allowedCopyrightHolders": ["Google LLC"], "allowedLicenses": ["Apache-2.0", "MIT", "BSD-3"], - "ignoreFiles": ["**/requirements.txt", "**/requirements-test.txt"], + "ignoreFiles": ["**/requirements.txt", "**/requirements-test.txt", "**/__init__.py", "samples/**/constraints.txt", "samples/**/constraints-test.txt"], "sourceFileExtensions": [ "ts", "js", diff --git a/renovate.json b/renovate.json index f08bc22..c048955 100644 --- a/renovate.json +++ b/renovate.json @@ -2,5 +2,8 @@ "extends": [ "config:base", ":preserveSemverRanges" ], - "ignorePaths": [".pre-commit-config.yaml"] + "ignorePaths": [".pre-commit-config.yaml"], + "pip_requirements": { + "fileMatch": ["requirements-test.txt", "samples/[\\S/]*constraints.txt", "samples/[\\S/]*constraints-test.txt"] + } } diff --git a/synth.metadata b/synth.metadata index 34337b6..a4250dc 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,7 +4,7 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/python-org-policy.git", - "sha": "ce3cab20a7a88c7b9782de2d5112ccf5800d211a" + "sha": "804e8a4484e48c514fa383ced0b5f56d38f36ee7" } }, { @@ -19,14 +19,14 @@ "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "5b5bf6d519b2d658d9f2e483d9f6f3d0ba8ee6bc" + "sha": "0a071b3460344886297a304253bf924aa68ddb7e" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "5b5bf6d519b2d658d9f2e483d9f6f3d0ba8ee6bc" + "sha": "0a071b3460344886297a304253bf924aa68ddb7e" } } ], From 371b27b509e85c52318ab22c4464a27c29c45825 Mon Sep 17 00:00:00 2001 From: Dan Lee <71398022+dandhlee@users.noreply.github.com> Date: Fri, 16 Apr 2021 17:20:06 -0400 Subject: [PATCH 07/16] chore: prevent normalization of semver versioning (#36) * chore: prevent normalization of semver versioning * chore: update workaround to make sic work --- setup.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 1ee6e5e..76a57b5 100644 --- a/setup.py +++ b/setup.py @@ -19,6 +19,21 @@ import os import setuptools # type: ignore +# Disable version normalization performed by setuptools.setup() +try: + # Try the approach of using sic(), added in setuptools 46.1.0 + from setuptools import sic +except ImportError: + # Try the approach of replacing packaging.version.Version + sic = lambda v: v + try: + # setuptools >=39.0.0 uses packaging from setuptools.extern + from setuptools.extern import packaging + except ImportError: + # setuptools <39.0.0 uses packaging from pkg_resources.extern + from pkg_resources.extern import packaging + packaging.version.Version = packaging.version.LegacyVersion + version = "0.2.0" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -30,7 +45,7 @@ setuptools.setup( name="google-cloud-org-policy", - version=version, + version=sic(version), long_description=readme, author="Google LLC", author_email="googleapis-packages@google.com", From 7b27dac39dbdda9789533502356cee6f5d9303c2 Mon Sep 17 00:00:00 2001 From: Jonathan Beaulieu <123.jonathan@gmail.com> Date: Mon, 19 Apr 2021 10:50:04 -0400 Subject: [PATCH 08/16] fix: Fixed broken url for package. (#38) Fixes #37 --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 76a57b5..f4cb430 100644 --- a/setup.py +++ b/setup.py @@ -50,7 +50,7 @@ author="Google LLC", author_email="googleapis-packages@google.com", license="Apache 2.0", - url="https://github.com/googleapis/python-orgpolicy", + url="https://github.com/googleapis/python-org-policy", packages=setuptools.PEP420PackageFinder.find(), namespace_packages=("google", "google.cloud"), platforms="Posix; MacOS X; Windows", From 505dbd6b555378c6262017eefc0bce12bafc3e89 Mon Sep 17 00:00:00 2001 From: Dan Lee <71398022+dandhlee@users.noreply.github.com> Date: Mon, 26 Apr 2021 13:15:17 -0400 Subject: [PATCH 09/16] chore(revert): revert preventing normalization (#39) --- setup.py | 17 +---------------- 1 file changed, 1 insertion(+), 16 deletions(-) diff --git a/setup.py b/setup.py index f4cb430..aeffaa9 100644 --- a/setup.py +++ b/setup.py @@ -19,21 +19,6 @@ import os import setuptools # type: ignore -# Disable version normalization performed by setuptools.setup() -try: - # Try the approach of using sic(), added in setuptools 46.1.0 - from setuptools import sic -except ImportError: - # Try the approach of replacing packaging.version.Version - sic = lambda v: v - try: - # setuptools >=39.0.0 uses packaging from setuptools.extern - from setuptools.extern import packaging - except ImportError: - # setuptools <39.0.0 uses packaging from pkg_resources.extern - from pkg_resources.extern import packaging - packaging.version.Version = packaging.version.LegacyVersion - version = "0.2.0" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -45,7 +30,7 @@ setuptools.setup( name="google-cloud-org-policy", - version=sic(version), + version=version, long_description=readme, author="Google LLC", author_email="googleapis-packages@google.com", From 4fd4323adc6ddb58ef96420aff150d5ae0341f03 Mon Sep 17 00:00:00 2001 From: "google-cloud-policy-bot[bot]" <80869356+google-cloud-policy-bot[bot]@users.noreply.github.com> Date: Wed, 12 May 2021 13:14:05 +0000 Subject: [PATCH 10/16] chore: add SECURITY.md (#41) chore: add SECURITY.md --- SECURITY.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..8b58ae9 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,7 @@ +# Security Policy + +To report a security issue, please use [g.co/vulnz](https://g.co/vulnz). + +The Google Security Team will respond within 5 working days of your report on g.co/vulnz. + +We use g.co/vulnz for our intake, and do coordination and disclosure here using GitHub Security Advisory to privately discuss and fix the issue. From 42354ddb4198cd1983b93f198489ae7865167124 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 12 May 2021 11:56:03 -0400 Subject: [PATCH 11/16] chore: migrate to owl bot (#45) This PR migrates from autosynth to [owl bot](https://github.com/googleapis/repo-automation-bots/tree/master/packages/owl-bot). owl bot will save time for maintainers as it will automatically open PRs when there are updates in [googleapis-gen](https://github.com/googleapis/googleapis-gen/tree/master/google) without requiring maintainers to run `synthtool` to build the client from protos. Additionally, similar to autosynth, PRs will be automatically opened when there are template updates. --- .github/.OwlBot.lock.yaml | 4 ++ .github/.OwlBot.yaml | 26 +++++++ .kokoro/release.sh | 4 +- .kokoro/release/common.cfg | 14 +--- .pre-commit-config.yaml | 2 +- CONTRIBUTING.rst | 16 +---- docs/_static/custom.css | 13 +++- noxfile.py | 14 +--- synth.py => owlbot.py | 28 +++----- synth.metadata | 140 ------------------------------------- 10 files changed, 60 insertions(+), 201 deletions(-) create mode 100644 .github/.OwlBot.lock.yaml create mode 100644 .github/.OwlBot.yaml rename synth.py => owlbot.py (79%) delete mode 100644 synth.metadata diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml new file mode 100644 index 0000000..d49860b --- /dev/null +++ b/.github/.OwlBot.lock.yaml @@ -0,0 +1,4 @@ +docker: + digest: sha256:457583330eec64daa02aeb7a72a04d33e7be2428f646671ce4045dcbc0191b1e + image: gcr.io/repo-automation-bots/owlbot-python:latest + diff --git a/.github/.OwlBot.yaml b/.github/.OwlBot.yaml new file mode 100644 index 0000000..9157793 --- /dev/null +++ b/.github/.OwlBot.yaml @@ -0,0 +1,26 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +docker: + image: gcr.io/repo-automation-bots/owlbot-python:latest + +deep-remove-regex: + - /owl-bot-staging + +deep-copy-regex: + - source: /google/cloud/orgpolicy/(v.*)/.*-py/(.*) + dest: /owl-bot-staging/$1/$2 + +begin-after-commit-hash: b06c9034cfcbce180ba732d03be6526e5c8ea1bc + diff --git a/.kokoro/release.sh b/.kokoro/release.sh index 5eecbbe..f141bee 100755 --- a/.kokoro/release.sh +++ b/.kokoro/release.sh @@ -26,7 +26,7 @@ python3 -m pip install --upgrade twine wheel setuptools export PYTHONUNBUFFERED=1 # Move into the package, build the distribution and upload. -TWINE_PASSWORD=$(cat "${KOKORO_KEYSTORE_DIR}/73713_google_cloud_pypi_password") +TWINE_PASSWORD=$(cat "${KOKORO_GFILE_DIR}/secret_manager/google-cloud-pypi-token") cd github/python-org-policy python3 setup.py sdist bdist_wheel -twine upload --username gcloudpypi --password "${TWINE_PASSWORD}" dist/* +twine upload --username __token__ --password "${TWINE_PASSWORD}" dist/* diff --git a/.kokoro/release/common.cfg b/.kokoro/release/common.cfg index 56ce74b..8568437 100644 --- a/.kokoro/release/common.cfg +++ b/.kokoro/release/common.cfg @@ -23,18 +23,8 @@ env_vars: { value: "github/python-org-policy/.kokoro/release.sh" } -# Fetch PyPI password -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "google_cloud_pypi_password" - } - } -} - # Tokens needed to report release status back to GitHub env_vars: { key: "SECRET_MANAGER_KEYS" - value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem" -} \ No newline at end of file + value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem,google-cloud-pypi-token" +} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8912e9b..1bbd787 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -26,6 +26,6 @@ repos: hooks: - id: black - repo: https://gitlab.com/pycqa/flake8 - rev: 3.9.0 + rev: 3.9.1 hooks: - id: flake8 diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index b45e938..180886c 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -160,21 +160,7 @@ Running System Tests auth settings and change some configuration in your project to run all the tests. -- System tests will be run against an actual project and - so you'll need to provide some environment variables to facilitate - authentication to your project: - - - ``GOOGLE_APPLICATION_CREDENTIALS``: The path to a JSON key file; - Such a file can be downloaded directly from the developer's console by clicking - "Generate new JSON key". See private key - `docs `__ - for more details. - -- Once you have downloaded your json keys, set the environment variable - ``GOOGLE_APPLICATION_CREDENTIALS`` to the absolute path of the json file:: - - $ export GOOGLE_APPLICATION_CREDENTIALS="/Users//path/to/app_credentials.json" - +- System tests will be run against an actual project. You should use local credentials from gcloud when possible. See `Best practices for application authentication `__. Some tests require a service account. For those tests see `Authenticating as a service account `__. ************* Test Coverage diff --git a/docs/_static/custom.css b/docs/_static/custom.css index bcd37bb..b0a2954 100644 --- a/docs/_static/custom.css +++ b/docs/_static/custom.css @@ -1,9 +1,20 @@ div#python2-eol { border-color: red; border-width: medium; -} +} /* Ensure minimum width for 'Parameters' / 'Returns' column */ dl.field-list > dt { min-width: 100px } + +/* Insert space between methods for readability */ +dl.method { + padding-top: 10px; + padding-bottom: 10px +} + +/* Insert empty space between classes */ +dl.class { + padding-bottom: 50px +} diff --git a/noxfile.py b/noxfile.py index 29da51d..3010fda 100644 --- a/noxfile.py +++ b/noxfile.py @@ -92,16 +92,9 @@ def lint(session): session.run("flake8", "google", "tests") -@nox.session(python="3.6") +@nox.session(python=DEFAULT_PYTHON_VERSION) def blacken(session): - """Run black. - - Format code to uniform standard. - - This currently uses Python 3.6 due to the automated Kokoro run of synthtool. - That run uses an image that doesn't have 3.6 installed. Before updating this - check the state of the `gcp_ubuntu_config` we use for that Kokoro run. - """ + """Run black. Format code to uniform standard.""" session.install(BLACK_VERSION) session.run( "black", *BLACK_PATHS, @@ -161,9 +154,6 @@ def system(session): # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": session.skip("RUN_SYSTEM_TESTS is set to false, skipping") - # Sanity check: Only run tests if the environment variable is set. - if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""): - session.skip("Credentials must be set via environment variable") # Install pyopenssl for mTLS testing. if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": session.install("pyopenssl") diff --git a/synth.py b/owlbot.py similarity index 79% rename from synth.py rename to owlbot.py index 570657a..91d378c 100644 --- a/synth.py +++ b/owlbot.py @@ -20,30 +20,22 @@ from synthtool.languages import python from synthtool.sources import git - -gapic = gcp.GAPICBazel() common = gcp.CommonTemplates() -versions = ["v2"] # this package also has v1 protos, see below for note +default_version = "v2" -# ---------------------------------------------------------------------------- -# Generate orgpolicy GAPIC layer -# ---------------------------------------------------------------------------- -for version in versions: - library = gapic.py_library( - service="orgpolicy", - version=version, - bazel_target=f"//google/cloud/orgpolicy/{version}:orgpolicy-{version}-py", +for library in s.get_staging_dirs(default_version): + # Rename to google-cloud-org-policy + # TODO: use bazel option to rename package + s.replace( + library / "google/cloud/**/*", + "google-cloud-orgpolicy", + "google-cloud-org-policy" ) + s.move(library, excludes=["setup.py", "README.rst", "docs/index.rst"]) -# Rename to google-cloud-org-policy -# TODO: use bazel option to rename package -s.replace( - "google/cloud/**/*", - "google-cloud-orgpolicy", - "google-cloud-org-policy" -) +s.remove_staging_dirs() # ---------------------------------------------------------------------------- # Add templated files diff --git a/synth.metadata b/synth.metadata deleted file mode 100644 index a4250dc..0000000 --- a/synth.metadata +++ /dev/null @@ -1,140 +0,0 @@ -{ - "sources": [ - { - "git": { - "name": ".", - "remote": "https://github.com/googleapis/python-org-policy.git", - "sha": "804e8a4484e48c514fa383ced0b5f56d38f36ee7" - } - }, - { - "git": { - "name": "googleapis", - "remote": "https://github.com/googleapis/googleapis.git", - "sha": "915925089600094e72e4bfa8cf586c170e6b7109", - "internalRef": "366152684" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "0a071b3460344886297a304253bf924aa68ddb7e" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "0a071b3460344886297a304253bf924aa68ddb7e" - } - } - ], - "destinations": [ - { - "client": { - "source": "googleapis", - "apiName": "orgpolicy", - "apiVersion": "v2", - "language": "python", - "generator": "bazel" - } - } - ], - "generatedFiles": [ - ".coveragerc", - ".flake8", - ".github/CONTRIBUTING.md", - ".github/ISSUE_TEMPLATE/bug_report.md", - ".github/ISSUE_TEMPLATE/feature_request.md", - ".github/ISSUE_TEMPLATE/support_request.md", - ".github/PULL_REQUEST_TEMPLATE.md", - ".github/header-checker-lint.yml", - ".github/release-please.yml", - ".github/snippet-bot.yml", - ".gitignore", - ".kokoro/build.sh", - ".kokoro/continuous/common.cfg", - ".kokoro/continuous/continuous.cfg", - ".kokoro/docker/docs/Dockerfile", - ".kokoro/docker/docs/fetch_gpg_keys.sh", - ".kokoro/docs/common.cfg", - ".kokoro/docs/docs-presubmit.cfg", - ".kokoro/docs/docs.cfg", - ".kokoro/populate-secrets.sh", - ".kokoro/presubmit/common.cfg", - ".kokoro/presubmit/presubmit.cfg", - ".kokoro/publish-docs.sh", - ".kokoro/release.sh", - ".kokoro/release/common.cfg", - ".kokoro/release/release.cfg", - ".kokoro/samples/lint/common.cfg", - ".kokoro/samples/lint/continuous.cfg", - ".kokoro/samples/lint/periodic.cfg", - ".kokoro/samples/lint/presubmit.cfg", - ".kokoro/samples/python3.6/common.cfg", - ".kokoro/samples/python3.6/continuous.cfg", - ".kokoro/samples/python3.6/periodic-head.cfg", - ".kokoro/samples/python3.6/periodic.cfg", - ".kokoro/samples/python3.6/presubmit.cfg", - ".kokoro/samples/python3.7/common.cfg", - ".kokoro/samples/python3.7/continuous.cfg", - ".kokoro/samples/python3.7/periodic-head.cfg", - ".kokoro/samples/python3.7/periodic.cfg", - ".kokoro/samples/python3.7/presubmit.cfg", - ".kokoro/samples/python3.8/common.cfg", - ".kokoro/samples/python3.8/continuous.cfg", - ".kokoro/samples/python3.8/periodic-head.cfg", - ".kokoro/samples/python3.8/periodic.cfg", - ".kokoro/samples/python3.8/presubmit.cfg", - ".kokoro/test-samples-against-head.sh", - ".kokoro/test-samples-impl.sh", - ".kokoro/test-samples.sh", - ".kokoro/trampoline.sh", - ".kokoro/trampoline_v2.sh", - ".pre-commit-config.yaml", - ".trampolinerc", - "CODE_OF_CONDUCT.md", - "CONTRIBUTING.rst", - "LICENSE", - "MANIFEST.in", - "docs/_static/custom.css", - "docs/_templates/layout.html", - "docs/conf.py", - "docs/multiprocessing.rst", - "docs/orgpolicy_v2/org_policy.rst", - "docs/orgpolicy_v2/services.rst", - "docs/orgpolicy_v2/types.rst", - "google/cloud/orgpolicy/__init__.py", - "google/cloud/orgpolicy/py.typed", - "google/cloud/orgpolicy_v2/__init__.py", - "google/cloud/orgpolicy_v2/py.typed", - "google/cloud/orgpolicy_v2/services/__init__.py", - "google/cloud/orgpolicy_v2/services/org_policy/__init__.py", - "google/cloud/orgpolicy_v2/services/org_policy/async_client.py", - "google/cloud/orgpolicy_v2/services/org_policy/client.py", - "google/cloud/orgpolicy_v2/services/org_policy/pagers.py", - "google/cloud/orgpolicy_v2/services/org_policy/transports/__init__.py", - "google/cloud/orgpolicy_v2/services/org_policy/transports/base.py", - "google/cloud/orgpolicy_v2/services/org_policy/transports/grpc.py", - "google/cloud/orgpolicy_v2/services/org_policy/transports/grpc_asyncio.py", - "google/cloud/orgpolicy_v2/types/__init__.py", - "google/cloud/orgpolicy_v2/types/constraint.py", - "google/cloud/orgpolicy_v2/types/orgpolicy.py", - "mypy.ini", - "noxfile.py", - "renovate.json", - "scripts/decrypt-secrets.sh", - "scripts/fixup_orgpolicy_v2_keywords.py", - "scripts/readme-gen/readme_gen.py", - "scripts/readme-gen/templates/README.tmpl.rst", - "scripts/readme-gen/templates/auth.tmpl.rst", - "scripts/readme-gen/templates/auth_api_key.tmpl.rst", - "scripts/readme-gen/templates/install_deps.tmpl.rst", - "scripts/readme-gen/templates/install_portaudio.tmpl.rst", - "setup.cfg", - "testing/.gitignore", - "tests/unit/gapic/orgpolicy_v2/__init__.py", - "tests/unit/gapic/orgpolicy_v2/test_org_policy.py" - ] -} \ No newline at end of file From 21b1448d3fe3d4fe33272cb460347d3ea132dac0 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 12 May 2021 12:24:04 -0400 Subject: [PATCH 12/16] chore: add library type to .repo-metadata.json (#44) --- .repo-metadata.json | 1 + 1 file changed, 1 insertion(+) diff --git a/.repo-metadata.json b/.repo-metadata.json index a51d12b..25a6bc0 100644 --- a/.repo-metadata.json +++ b/.repo-metadata.json @@ -6,6 +6,7 @@ "issue_tracker": "", "release_level": "beta", "language": "python", + "library_type": "GAPIC_AUTO", "repo": "googleapis/python-org-policy", "distribution_name": "google-cloud-org-policy", "api_id": "orgpolicy.googleapis.com" From aade679d6c04808408110292a3de805fa3364286 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 14 May 2021 14:26:05 +0000 Subject: [PATCH 13/16] chore: upgrade gapic-generator-python to 0.46.3 (#47) PiperOrigin-RevId: 373649163 Source-Link: https://github.com/googleapis/googleapis/commit/7e1b14e6c7a9ab96d2db7e4a131981f162446d34 Source-Link: https://github.com/googleapis/googleapis-gen/commit/0a3c7d272d697796db75857bac73905c68e498c3 fix: add async client to %name_%version/init.py chore: add autogenerated snippets chore: remove auth, policy, and options from the reserved names list feat: support self-signed JWT flow for service accounts chore: enable GAPIC metadata generation chore: sort subpackages in %namespace/%name/init.py --- docs/orgpolicy_v2/org_policy.rst | 1 - google/cloud/orgpolicy/__init__.py | 10 +- google/cloud/orgpolicy_v2/__init__.py | 7 +- google/cloud/orgpolicy_v2/gapic_metadata.json | 93 +++ .../cloud/orgpolicy_v2/services/__init__.py | 1 - .../services/org_policy/__init__.py | 2 - .../services/org_policy/async_client.py | 59 +- .../services/org_policy/client.py | 86 ++- .../services/org_policy/pagers.py | 6 +- .../org_policy/transports/__init__.py | 2 - .../services/org_policy/transports/base.py | 154 +++-- .../services/org_policy/transports/grpc.py | 30 +- .../org_policy/transports/grpc_asyncio.py | 29 +- google/cloud/orgpolicy_v2/types/__init__.py | 2 - google/cloud/orgpolicy_v2/types/constraint.py | 20 +- google/cloud/orgpolicy_v2/types/orgpolicy.py | 75 +-- scripts/fixup_orgpolicy_v2_keywords.py | 19 +- tests/__init__.py | 15 + tests/unit/__init__.py | 15 + tests/unit/gapic/__init__.py | 15 + tests/unit/gapic/orgpolicy_v2/__init__.py | 1 - .../gapic/orgpolicy_v2/test_org_policy.py | 528 +++++++++++------- 22 files changed, 704 insertions(+), 466 deletions(-) create mode 100644 google/cloud/orgpolicy_v2/gapic_metadata.json create mode 100644 tests/__init__.py create mode 100644 tests/unit/__init__.py create mode 100644 tests/unit/gapic/__init__.py diff --git a/docs/orgpolicy_v2/org_policy.rst b/docs/orgpolicy_v2/org_policy.rst index 18c078a..8a8771c 100644 --- a/docs/orgpolicy_v2/org_policy.rst +++ b/docs/orgpolicy_v2/org_policy.rst @@ -5,7 +5,6 @@ OrgPolicy :members: :inherited-members: - .. automodule:: google.cloud.orgpolicy_v2.services.org_policy.pagers :members: :inherited-members: diff --git a/google/cloud/orgpolicy/__init__.py b/google/cloud/orgpolicy/__init__.py index 0cce5a0..7a85f07 100644 --- a/google/cloud/orgpolicy/__init__.py +++ b/google/cloud/orgpolicy/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,10 +14,11 @@ # limitations under the License. # +from google.cloud.orgpolicy_v2.services.org_policy.client import OrgPolicyClient from google.cloud.orgpolicy_v2.services.org_policy.async_client import ( OrgPolicyAsyncClient, ) -from google.cloud.orgpolicy_v2.services.org_policy.client import OrgPolicyClient + from google.cloud.orgpolicy_v2.types.constraint import Constraint from google.cloud.orgpolicy_v2.types.orgpolicy import AlternatePolicySpec from google.cloud.orgpolicy_v2.types.orgpolicy import CreatePolicyRequest @@ -34,8 +34,10 @@ from google.cloud.orgpolicy_v2.types.orgpolicy import UpdatePolicyRequest __all__ = ( - "AlternatePolicySpec", + "OrgPolicyClient", + "OrgPolicyAsyncClient", "Constraint", + "AlternatePolicySpec", "CreatePolicyRequest", "DeletePolicyRequest", "GetEffectivePolicyRequest", @@ -44,8 +46,6 @@ "ListConstraintsResponse", "ListPoliciesRequest", "ListPoliciesResponse", - "OrgPolicyAsyncClient", - "OrgPolicyClient", "Policy", "PolicySpec", "UpdatePolicyRequest", diff --git a/google/cloud/orgpolicy_v2/__init__.py b/google/cloud/orgpolicy_v2/__init__.py index 35f8011..2fe7952 100644 --- a/google/cloud/orgpolicy_v2/__init__.py +++ b/google/cloud/orgpolicy_v2/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,6 +15,8 @@ # from .services.org_policy import OrgPolicyClient +from .services.org_policy import OrgPolicyAsyncClient + from .types.constraint import Constraint from .types.orgpolicy import AlternatePolicySpec from .types.orgpolicy import CreatePolicyRequest @@ -30,8 +31,8 @@ from .types.orgpolicy import PolicySpec from .types.orgpolicy import UpdatePolicyRequest - __all__ = ( + "OrgPolicyAsyncClient", "AlternatePolicySpec", "Constraint", "CreatePolicyRequest", @@ -42,8 +43,8 @@ "ListConstraintsResponse", "ListPoliciesRequest", "ListPoliciesResponse", + "OrgPolicyClient", "Policy", "PolicySpec", "UpdatePolicyRequest", - "OrgPolicyClient", ) diff --git a/google/cloud/orgpolicy_v2/gapic_metadata.json b/google/cloud/orgpolicy_v2/gapic_metadata.json new file mode 100644 index 0000000..352a38a --- /dev/null +++ b/google/cloud/orgpolicy_v2/gapic_metadata.json @@ -0,0 +1,93 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.orgpolicy_v2", + "protoPackage": "google.cloud.orgpolicy.v2", + "schema": "1.0", + "services": { + "OrgPolicy": { + "clients": { + "grpc": { + "libraryClient": "OrgPolicyClient", + "rpcs": { + "CreatePolicy": { + "methods": [ + "create_policy" + ] + }, + "DeletePolicy": { + "methods": [ + "delete_policy" + ] + }, + "GetEffectivePolicy": { + "methods": [ + "get_effective_policy" + ] + }, + "GetPolicy": { + "methods": [ + "get_policy" + ] + }, + "ListConstraints": { + "methods": [ + "list_constraints" + ] + }, + "ListPolicies": { + "methods": [ + "list_policies" + ] + }, + "UpdatePolicy": { + "methods": [ + "update_policy" + ] + } + } + }, + "grpc-async": { + "libraryClient": "OrgPolicyAsyncClient", + "rpcs": { + "CreatePolicy": { + "methods": [ + "create_policy" + ] + }, + "DeletePolicy": { + "methods": [ + "delete_policy" + ] + }, + "GetEffectivePolicy": { + "methods": [ + "get_effective_policy" + ] + }, + "GetPolicy": { + "methods": [ + "get_policy" + ] + }, + "ListConstraints": { + "methods": [ + "list_constraints" + ] + }, + "ListPolicies": { + "methods": [ + "list_policies" + ] + }, + "UpdatePolicy": { + "methods": [ + "update_policy" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/orgpolicy_v2/services/__init__.py b/google/cloud/orgpolicy_v2/services/__init__.py index 42ffdf2..4de6597 100644 --- a/google/cloud/orgpolicy_v2/services/__init__.py +++ b/google/cloud/orgpolicy_v2/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/orgpolicy_v2/services/org_policy/__init__.py b/google/cloud/orgpolicy_v2/services/org_policy/__init__.py index 7f5da48..6c7c6e7 100644 --- a/google/cloud/orgpolicy_v2/services/org_policy/__init__.py +++ b/google/cloud/orgpolicy_v2/services/org_policy/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import OrgPolicyClient from .async_client import OrgPolicyAsyncClient diff --git a/google/cloud/orgpolicy_v2/services/org_policy/async_client.py b/google/cloud/orgpolicy_v2/services/org_policy/async_client.py index cb43086..e7ed930 100644 --- a/google/cloud/orgpolicy_v2/services/org_policy/async_client.py +++ b/google/cloud/orgpolicy_v2/services/org_policy/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,16 +20,15 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.orgpolicy_v2.services.org_policy import pagers from google.cloud.orgpolicy_v2.types import constraint from google.cloud.orgpolicy_v2.types import orgpolicy - from .transports.base import OrgPolicyTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import OrgPolicyGrpcAsyncIOTransport from .client import OrgPolicyClient @@ -71,25 +68,20 @@ class OrgPolicyAsyncClient: parse_constraint_path = staticmethod(OrgPolicyClient.parse_constraint_path) policy_path = staticmethod(OrgPolicyClient.policy_path) parse_policy_path = staticmethod(OrgPolicyClient.parse_policy_path) - common_billing_account_path = staticmethod( OrgPolicyClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( OrgPolicyClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(OrgPolicyClient.common_folder_path) parse_common_folder_path = staticmethod(OrgPolicyClient.parse_common_folder_path) - common_organization_path = staticmethod(OrgPolicyClient.common_organization_path) parse_common_organization_path = staticmethod( OrgPolicyClient.parse_common_organization_path ) - common_project_path = staticmethod(OrgPolicyClient.common_project_path) parse_common_project_path = staticmethod(OrgPolicyClient.parse_common_project_path) - common_location_path = staticmethod(OrgPolicyClient.common_location_path) parse_common_location_path = staticmethod( OrgPolicyClient.parse_common_location_path @@ -97,7 +89,8 @@ class OrgPolicyAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -112,7 +105,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -129,7 +122,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> OrgPolicyTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: OrgPolicyTransport: The transport used by the client instance. @@ -143,12 +136,12 @@ def transport(self) -> OrgPolicyTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, OrgPolicyTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the org policy client. + """Instantiates the org policy client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -180,7 +173,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = OrgPolicyClient( credentials=credentials, transport=transport, @@ -218,7 +210,6 @@ async def list_constraints( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -249,7 +240,6 @@ async def list_constraints( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -262,7 +252,8 @@ async def list_constraints( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -319,7 +310,6 @@ async def list_policies( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -351,7 +341,6 @@ async def list_policies( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -364,7 +353,8 @@ async def list_policies( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -416,7 +406,6 @@ async def get_policy( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -443,7 +432,6 @@ async def get_policy( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -456,7 +444,8 @@ async def get_policy( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -505,7 +494,6 @@ async def get_effective_policy( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -532,7 +520,6 @@ async def get_effective_policy( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -545,7 +532,8 @@ async def get_effective_policy( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -606,7 +594,6 @@ async def create_policy( This corresponds to the ``policy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -633,7 +620,6 @@ async def create_policy( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if policy is not None: @@ -648,7 +634,8 @@ async def create_policy( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -699,7 +686,6 @@ async def update_policy( This corresponds to the ``policy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -726,7 +712,6 @@ async def update_policy( # If we have keyword arguments corresponding to fields on the # request, apply these. - if policy is not None: request.policy = policy @@ -739,7 +724,8 @@ async def update_policy( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -789,7 +775,6 @@ async def delete_policy( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -810,7 +795,6 @@ async def delete_policy( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -823,7 +807,8 @@ async def delete_policy( maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), diff --git a/google/cloud/orgpolicy_v2/services/org_policy/client.py b/google/cloud/orgpolicy_v2/services/org_policy/client.py index 276a12d..34741d4 100644 --- a/google/cloud/orgpolicy_v2/services/org_policy/client.py +++ b/google/cloud/orgpolicy_v2/services/org_policy/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # 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 # 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 @@ -35,7 +33,6 @@ from google.cloud.orgpolicy_v2.services.org_policy import pagers from google.cloud.orgpolicy_v2.types import constraint from google.cloud.orgpolicy_v2.types import orgpolicy - from .transports.base import OrgPolicyTransport, DEFAULT_CLIENT_INFO from .transports.grpc import OrgPolicyGrpcTransport from .transports.grpc_asyncio import OrgPolicyGrpcAsyncIOTransport @@ -54,7 +51,7 @@ class OrgPolicyClientMeta(type): _transport_registry["grpc_asyncio"] = OrgPolicyGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[OrgPolicyTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -99,7 +96,8 @@ class OrgPolicyClient(metaclass=OrgPolicyClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -133,7 +131,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -150,7 +149,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -169,23 +168,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> OrgPolicyTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - OrgPolicyTransport: The transport used by the client instance. + OrgPolicyTransport: The transport used by the client + instance. """ return self._transport @staticmethod def constraint_path(project: str, constraint: str,) -> str: - """Return a fully-qualified constraint string.""" + """Returns a fully-qualified constraint string.""" return "projects/{project}/constraints/{constraint}".format( project=project, constraint=constraint, ) @staticmethod def parse_constraint_path(path: str) -> Dict[str, str]: - """Parse a constraint path into its component segments.""" + """Parses a constraint path into its component segments.""" m = re.match( r"^projects/(?P.+?)/constraints/(?P.+?)$", path ) @@ -193,20 +193,20 @@ def parse_constraint_path(path: str) -> Dict[str, str]: @staticmethod def policy_path(project: str, policy: str,) -> str: - """Return a fully-qualified policy string.""" + """Returns a fully-qualified policy string.""" return "projects/{project}/policies/{policy}".format( project=project, policy=policy, ) @staticmethod def parse_policy_path(path: str) -> Dict[str, str]: - """Parse a policy path into its component segments.""" + """Parses a policy path into its component segments.""" m = re.match(r"^projects/(?P.+?)/policies/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -219,7 +219,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -230,7 +230,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -241,7 +241,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -252,7 +252,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -266,12 +266,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, OrgPolicyTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the org policy client. + """Instantiates the org policy client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -326,9 +326,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -340,12 +341,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -360,8 +363,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -406,7 +409,6 @@ def list_constraints( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -439,10 +441,8 @@ def list_constraints( # there are no flattened fields. if not isinstance(request, orgpolicy.ListConstraintsRequest): request = orgpolicy.ListConstraintsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -499,7 +499,6 @@ def list_policies( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -533,10 +532,8 @@ def list_policies( # there are no flattened fields. if not isinstance(request, orgpolicy.ListPoliciesRequest): request = orgpolicy.ListPoliciesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -588,7 +585,6 @@ def get_policy( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -617,10 +613,8 @@ def get_policy( # there are no flattened fields. if not isinstance(request, orgpolicy.GetPolicyRequest): request = orgpolicy.GetPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -669,7 +663,6 @@ def get_effective_policy( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -698,10 +691,8 @@ def get_effective_policy( # there are no flattened fields. if not isinstance(request, orgpolicy.GetEffectivePolicyRequest): request = orgpolicy.GetEffectivePolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -762,7 +753,6 @@ def create_policy( This corresponds to the ``policy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -791,10 +781,8 @@ def create_policy( # there are no flattened fields. if not isinstance(request, orgpolicy.CreatePolicyRequest): request = orgpolicy.CreatePolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if policy is not None: @@ -847,7 +835,6 @@ def update_policy( This corresponds to the ``policy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -876,10 +863,8 @@ def update_policy( # there are no flattened fields. if not isinstance(request, orgpolicy.UpdatePolicyRequest): request = orgpolicy.UpdatePolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if policy is not None: request.policy = policy @@ -929,7 +914,6 @@ def delete_policy( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -952,10 +936,8 @@ def delete_policy( # there are no flattened fields. if not isinstance(request, orgpolicy.DeletePolicyRequest): request = orgpolicy.DeletePolicyRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/orgpolicy_v2/services/org_policy/pagers.py b/google/cloud/orgpolicy_v2/services/org_policy/pagers.py index df568a9..ffac98e 100644 --- a/google/cloud/orgpolicy_v2/services/org_policy/pagers.py +++ b/google/cloud/orgpolicy_v2/services/org_policy/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -246,7 +244,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/orgpolicy_v2/services/org_policy/transports/__init__.py b/google/cloud/orgpolicy_v2/services/org_policy/transports/__init__.py index 0a3112a..c2d7440 100644 --- a/google/cloud/orgpolicy_v2/services/org_policy/transports/__init__.py +++ b/google/cloud/orgpolicy_v2/services/org_policy/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/orgpolicy_v2/services/org_policy/transports/base.py b/google/cloud/orgpolicy_v2/services/org_policy/transports/base.py index 1cfd0e1..8b0c00f 100644 --- a/google/cloud/orgpolicy_v2/services/org_policy/transports/base.py +++ b/google/cloud/orgpolicy_v2/services/org_policy/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.orgpolicy_v2.types import orgpolicy -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -38,27 +37,41 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class OrgPolicyTransport(abc.ABC): """Abstract transport class for OrgPolicy.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "orgpolicy.googleapis.com" + def __init__( self, *, - host: str = "orgpolicy.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -67,7 +80,7 @@ def __init__( 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. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -81,29 +94,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -114,7 +174,8 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -128,7 +189,8 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -142,7 +204,8 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -156,7 +219,8 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -170,7 +234,8 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -184,7 +249,8 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -198,7 +264,8 @@ def _prep_wrapped_messages(self, client_info): maximum=10.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -210,11 +277,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_constraints( self, - ) -> typing.Callable[ + ) -> Callable[ [orgpolicy.ListConstraintsRequest], - typing.Union[ + Union[ orgpolicy.ListConstraintsResponse, - typing.Awaitable[orgpolicy.ListConstraintsResponse], + Awaitable[orgpolicy.ListConstraintsResponse], ], ]: raise NotImplementedError() @@ -222,11 +289,10 @@ def list_constraints( @property def list_policies( self, - ) -> typing.Callable[ + ) -> Callable[ [orgpolicy.ListPoliciesRequest], - typing.Union[ - orgpolicy.ListPoliciesResponse, - typing.Awaitable[orgpolicy.ListPoliciesResponse], + Union[ + orgpolicy.ListPoliciesResponse, Awaitable[orgpolicy.ListPoliciesResponse] ], ]: raise NotImplementedError() @@ -234,45 +300,45 @@ def list_policies( @property def get_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [orgpolicy.GetPolicyRequest], - typing.Union[orgpolicy.Policy, typing.Awaitable[orgpolicy.Policy]], + Union[orgpolicy.Policy, Awaitable[orgpolicy.Policy]], ]: raise NotImplementedError() @property def get_effective_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [orgpolicy.GetEffectivePolicyRequest], - typing.Union[orgpolicy.Policy, typing.Awaitable[orgpolicy.Policy]], + Union[orgpolicy.Policy, Awaitable[orgpolicy.Policy]], ]: raise NotImplementedError() @property def create_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [orgpolicy.CreatePolicyRequest], - typing.Union[orgpolicy.Policy, typing.Awaitable[orgpolicy.Policy]], + Union[orgpolicy.Policy, Awaitable[orgpolicy.Policy]], ]: raise NotImplementedError() @property def update_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [orgpolicy.UpdatePolicyRequest], - typing.Union[orgpolicy.Policy, typing.Awaitable[orgpolicy.Policy]], + Union[orgpolicy.Policy, Awaitable[orgpolicy.Policy]], ]: raise NotImplementedError() @property def delete_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [orgpolicy.DeletePolicyRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc.py b/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc.py index 1a150dc..c84a650 100644 --- a/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc.py +++ b/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,19 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +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 -from google import auth # type: ignore -from google.auth import credentials # 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.orgpolicy_v2.types import orgpolicy -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import OrgPolicyTransport, DEFAULT_CLIENT_INFO @@ -72,7 +69,7 @@ def __init__( self, *, host: str = "orgpolicy.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -86,7 +83,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -196,7 +194,7 @@ def __init__( def create_channel( cls, host: str = "orgpolicy.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -227,13 +225,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -426,7 +426,9 @@ def update_policy( return self._stubs["update_policy"] @property - def delete_policy(self) -> Callable[[orgpolicy.DeletePolicyRequest], empty.Empty]: + def delete_policy( + self, + ) -> Callable[[orgpolicy.DeletePolicyRequest], empty_pb2.Empty]: r"""Return a callable for the delete policy method over gRPC. Deletes a Policy. @@ -449,7 +451,7 @@ def delete_policy(self) -> Callable[[orgpolicy.DeletePolicyRequest], empty.Empty self._stubs["delete_policy"] = self.grpc_channel.unary_unary( "/google.cloud.orgpolicy.v2.OrgPolicy/DeletePolicy", request_serializer=orgpolicy.DeletePolicyRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_policy"] diff --git a/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc_asyncio.py b/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc_asyncio.py index 704fe30..c868a74 100644 --- a/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc_asyncio.py +++ b/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # 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 +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 import auth # type: ignore -from google.auth import credentials # 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.orgpolicy_v2.types import orgpolicy -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import OrgPolicyTransport, DEFAULT_CLIENT_INFO from .grpc import OrgPolicyGrpcTransport @@ -75,7 +72,7 @@ class OrgPolicyGrpcAsyncIOTransport(OrgPolicyTransport): def create_channel( cls, host: str = "orgpolicy.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -102,13 +99,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -116,7 +115,7 @@ def __init__( self, *, host: str = "orgpolicy.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -130,7 +129,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -188,7 +188,6 @@ def __init__( # 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 @@ -436,7 +435,7 @@ def update_policy( @property def delete_policy( self, - ) -> Callable[[orgpolicy.DeletePolicyRequest], Awaitable[empty.Empty]]: + ) -> Callable[[orgpolicy.DeletePolicyRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete policy method over gRPC. Deletes a Policy. @@ -459,7 +458,7 @@ def delete_policy( self._stubs["delete_policy"] = self.grpc_channel.unary_unary( "/google.cloud.orgpolicy.v2.OrgPolicy/DeletePolicy", request_serializer=orgpolicy.DeletePolicyRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_policy"] diff --git a/google/cloud/orgpolicy_v2/types/__init__.py b/google/cloud/orgpolicy_v2/types/__init__.py index 7355e8e..92bbba8 100644 --- a/google/cloud/orgpolicy_v2/types/__init__.py +++ b/google/cloud/orgpolicy_v2/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .constraint import Constraint from .orgpolicy import ( AlternatePolicySpec, diff --git a/google/cloud/orgpolicy_v2/types/constraint.py b/google/cloud/orgpolicy_v2/types/constraint.py index 1414ec0..d09029c 100644 --- a/google/cloud/orgpolicy_v2/types/constraint.py +++ b/google/cloud/orgpolicy_v2/types/constraint.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -102,9 +100,8 @@ class ListConstraint(proto.Message): 'folders/123' folder. """ - supports_in = proto.Field(proto.BOOL, number=1) - - supports_under = proto.Field(proto.BOOL, number=2) + supports_in = proto.Field(proto.BOOL, number=1,) + supports_under = proto.Field(proto.BOOL, number=2,) class BooleanConstraint(proto.Message): r"""A ``Constraint`` that is either enforced or not. @@ -113,20 +110,15 @@ class BooleanConstraint(proto.Message): ``constraints/compute.disableSerialPortAccess``. If it is enforced on a VM instance, serial port connections will not be opened to that instance. - """ - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) + """ + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) constraint_default = proto.Field(proto.ENUM, number=4, enum=ConstraintDefault,) - list_constraint = proto.Field( proto.MESSAGE, number=5, oneof="constraint_type", message=ListConstraint, ) - boolean_constraint = proto.Field( proto.MESSAGE, number=6, oneof="constraint_type", message=BooleanConstraint, ) diff --git a/google/cloud/orgpolicy_v2/types/orgpolicy.py b/google/cloud/orgpolicy_v2/types/orgpolicy.py index ad5db56..cd83288 100644 --- a/google/cloud/orgpolicy_v2/types/orgpolicy.py +++ b/google/cloud/orgpolicy_v2/types/orgpolicy.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.orgpolicy_v2.types import constraint -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.type import expr_pb2 as expr # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore __protobuf__ = proto.module( @@ -74,10 +71,8 @@ class Policy(proto.Message): run/darklaunch. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) spec = proto.Field(proto.MESSAGE, number=2, message="PolicySpec",) - alternate = proto.Field(proto.MESSAGE, number=3, message="AlternatePolicySpec",) @@ -96,8 +91,7 @@ class AlternatePolicySpec(proto.Message): resources. """ - launch = proto.Field(proto.STRING, number=1) - + launch = proto.Field(proto.STRING, number=1,) spec = proto.Field(proto.MESSAGE, number=2, message="PolicySpec",) @@ -155,7 +149,6 @@ class PolicySpec(proto.Message): class PolicyRule(proto.Message): r"""A rule used to express this policy. - Attributes: values (google.cloud.orgpolicy_v2.types.PolicySpec.PolicyRule.StringValues): List of values to be used for this @@ -208,9 +201,8 @@ class StringValues(proto.Message): List of values denied at this resource. """ - allowed_values = proto.RepeatedField(proto.STRING, number=1) - - denied_values = proto.RepeatedField(proto.STRING, number=2) + allowed_values = proto.RepeatedField(proto.STRING, number=1,) + denied_values = proto.RepeatedField(proto.STRING, number=2,) values = proto.Field( proto.MESSAGE, @@ -218,24 +210,16 @@ class StringValues(proto.Message): oneof="kind", message="PolicySpec.PolicyRule.StringValues", ) + allow_all = proto.Field(proto.BOOL, number=2, oneof="kind",) + deny_all = proto.Field(proto.BOOL, number=3, oneof="kind",) + enforce = proto.Field(proto.BOOL, number=4, oneof="kind",) + condition = proto.Field(proto.MESSAGE, number=5, message=expr_pb2.Expr,) - allow_all = proto.Field(proto.BOOL, number=2, oneof="kind") - - deny_all = proto.Field(proto.BOOL, number=3, oneof="kind") - - enforce = proto.Field(proto.BOOL, number=4, oneof="kind") - - condition = proto.Field(proto.MESSAGE, number=5, message=expr.Expr,) - - etag = proto.Field(proto.STRING, number=1) - - update_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - + etag = proto.Field(proto.STRING, number=1,) + update_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) rules = proto.RepeatedField(proto.MESSAGE, number=3, message=PolicyRule,) - - inherit_from_parent = proto.Field(proto.BOOL, number=4) - - reset = proto.Field(proto.BOOL, number=5) + inherit_from_parent = proto.Field(proto.BOOL, number=4,) + reset = proto.Field(proto.BOOL, number=5,) class ListConstraintsRequest(proto.Message): @@ -263,11 +247,9 @@ class ListConstraintsRequest(proto.Message): this field. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListConstraintsResponse(proto.Message): @@ -290,8 +272,7 @@ def raw_page(self): constraints = proto.RepeatedField( proto.MESSAGE, number=1, message=constraint.Constraint, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class ListPoliciesRequest(proto.Message): @@ -320,11 +301,9 @@ class ListPoliciesRequest(proto.Message): this field. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListPoliciesResponse(proto.Message): @@ -347,8 +326,7 @@ def raw_page(self): return self policies = proto.RepeatedField(proto.MESSAGE, number=1, message="Policy",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetPolicyRequest(proto.Message): @@ -361,7 +339,7 @@ class GetPolicyRequest(proto.Message): naming requirements. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class GetEffectivePolicyRequest(proto.Message): @@ -374,7 +352,7 @@ class GetEffectivePolicyRequest(proto.Message): for naming rules. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreatePolicyRequest(proto.Message): @@ -394,8 +372,7 @@ class CreatePolicyRequest(proto.Message): Required. ``Policy`` to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) policy = proto.Field(proto.MESSAGE, number=3, message="Policy",) @@ -421,7 +398,7 @@ class DeletePolicyRequest(proto.Message): naming rules. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/scripts/fixup_orgpolicy_v2_keywords.py b/scripts/fixup_orgpolicy_v2_keywords.py index e85a43c..d8d5fa6 100644 --- a/scripts/fixup_orgpolicy_v2_keywords.py +++ b/scripts/fixup_orgpolicy_v2_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,14 +39,13 @@ def partition( class orgpolicyCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_policy': ('parent', 'policy', ), - 'delete_policy': ('name', ), - 'get_effective_policy': ('name', ), - 'get_policy': ('name', ), - 'list_constraints': ('parent', 'page_size', 'page_token', ), - 'list_policies': ('parent', 'page_size', 'page_token', ), - 'update_policy': ('policy', ), - + 'create_policy': ('parent', 'policy', ), + 'delete_policy': ('name', ), + 'get_effective_policy': ('name', ), + 'get_policy': ('name', ), + 'list_constraints': ('parent', 'page_size', 'page_token', ), + 'list_policies': ('parent', 'page_size', 'page_token', ), + 'update_policy': ('policy', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -79,7 +76,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +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 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..4de6597 --- /dev/null +++ b/tests/__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/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 0000000..4de6597 --- /dev/null +++ b/tests/unit/__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/tests/unit/gapic/__init__.py b/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..4de6597 --- /dev/null +++ b/tests/unit/gapic/__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/tests/unit/gapic/orgpolicy_v2/__init__.py b/tests/unit/gapic/orgpolicy_v2/__init__.py index 42ffdf2..4de6597 100644 --- a/tests/unit/gapic/orgpolicy_v2/__init__.py +++ b/tests/unit/gapic/orgpolicy_v2/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/orgpolicy_v2/test_org_policy.py b/tests/unit/gapic/orgpolicy_v2/test_org_policy.py index d533f67..4465ebd 100644 --- a/tests/unit/gapic/orgpolicy_v2/test_org_policy.py +++ b/tests/unit/gapic/orgpolicy_v2/test_org_policy.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # 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 @@ -24,23 +23,53 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import 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 +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.orgpolicy_v2.services.org_policy import OrgPolicyAsyncClient from google.cloud.orgpolicy_v2.services.org_policy import OrgPolicyClient from google.cloud.orgpolicy_v2.services.org_policy import pagers from google.cloud.orgpolicy_v2.services.org_policy import transports +from google.cloud.orgpolicy_v2.services.org_policy.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.orgpolicy_v2.services.org_policy.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.orgpolicy_v2.types import constraint from google.cloud.orgpolicy_v2.types import orgpolicy from google.oauth2 import service_account -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.type import expr_pb2 as expr # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [OrgPolicyClient, OrgPolicyAsyncClient,]) def test_org_policy_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -99,7 +128,7 @@ def test_org_policy_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [OrgPolicyClient, OrgPolicyAsyncClient,]) def test_org_policy_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -150,7 +179,7 @@ def test_org_policy_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(OrgPolicyClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -434,7 +463,7 @@ def test_list_constraints( transport: str = "grpc", request_type=orgpolicy.ListConstraintsRequest ): client = OrgPolicyClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -447,19 +476,15 @@ def test_list_constraints( call.return_value = orgpolicy.ListConstraintsResponse( next_page_token="next_page_token_value", ) - response = client.list_constraints(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.ListConstraintsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConstraintsPager) - assert response.next_page_token == "next_page_token_value" @@ -471,7 +496,7 @@ def test_list_constraints_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 = OrgPolicyClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -479,7 +504,6 @@ def test_list_constraints_empty_call(): client.list_constraints() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.ListConstraintsRequest() @@ -488,7 +512,7 @@ async def test_list_constraints_async( transport: str = "grpc_asyncio", request_type=orgpolicy.ListConstraintsRequest ): client = OrgPolicyAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -501,18 +525,15 @@ async def test_list_constraints_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( orgpolicy.ListConstraintsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_constraints(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.ListConstraintsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListConstraintsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -522,17 +543,17 @@ async def test_list_constraints_async_from_dict(): def test_list_constraints_field_headers(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(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 = orgpolicy.ListConstraintsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_constraints), "__call__") as call: call.return_value = orgpolicy.ListConstraintsResponse() - client.list_constraints(request) # Establish that the underlying gRPC stub method was called. @@ -547,11 +568,12 @@ def test_list_constraints_field_headers(): @pytest.mark.asyncio async def test_list_constraints_field_headers_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(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 = orgpolicy.ListConstraintsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -559,7 +581,6 @@ async def test_list_constraints_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( orgpolicy.ListConstraintsResponse() ) - await client.list_constraints(request) # Establish that the underlying gRPC stub method was called. @@ -573,13 +594,12 @@ async def test_list_constraints_field_headers_async(): def test_list_constraints_flattened(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_constraints), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = orgpolicy.ListConstraintsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_constraints(parent="parent_value",) @@ -588,12 +608,11 @@ def test_list_constraints_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_constraints_flattened_error(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -605,7 +624,7 @@ def test_list_constraints_flattened_error(): @pytest.mark.asyncio async def test_list_constraints_flattened_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_constraints), "__call__") as call: @@ -623,13 +642,12 @@ async def test_list_constraints_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_constraints_flattened_error_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -640,7 +658,7 @@ async def test_list_constraints_flattened_error_async(): def test_list_constraints_pager(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials,) + client = OrgPolicyClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_constraints), "__call__") as call: @@ -678,7 +696,7 @@ def test_list_constraints_pager(): def test_list_constraints_pages(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials,) + client = OrgPolicyClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_constraints), "__call__") as call: @@ -708,7 +726,7 @@ def test_list_constraints_pages(): @pytest.mark.asyncio async def test_list_constraints_async_pager(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials,) + client = OrgPolicyAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -745,7 +763,7 @@ async def test_list_constraints_async_pager(): @pytest.mark.asyncio async def test_list_constraints_async_pages(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials,) + client = OrgPolicyAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -781,7 +799,7 @@ def test_list_policies( transport: str = "grpc", request_type=orgpolicy.ListPoliciesRequest ): client = OrgPolicyClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -794,19 +812,15 @@ def test_list_policies( call.return_value = orgpolicy.ListPoliciesResponse( next_page_token="next_page_token_value", ) - response = client.list_policies(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.ListPoliciesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPoliciesPager) - assert response.next_page_token == "next_page_token_value" @@ -818,7 +832,7 @@ def test_list_policies_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 = OrgPolicyClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -826,7 +840,6 @@ def test_list_policies_empty_call(): client.list_policies() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.ListPoliciesRequest() @@ -835,7 +848,7 @@ async def test_list_policies_async( transport: str = "grpc_asyncio", request_type=orgpolicy.ListPoliciesRequest ): client = OrgPolicyAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -848,18 +861,15 @@ async def test_list_policies_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( orgpolicy.ListPoliciesResponse(next_page_token="next_page_token_value",) ) - response = await client.list_policies(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.ListPoliciesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListPoliciesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -869,17 +879,17 @@ async def test_list_policies_async_from_dict(): def test_list_policies_field_headers(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(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 = orgpolicy.ListPoliciesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_policies), "__call__") as call: call.return_value = orgpolicy.ListPoliciesResponse() - client.list_policies(request) # Establish that the underlying gRPC stub method was called. @@ -894,11 +904,12 @@ def test_list_policies_field_headers(): @pytest.mark.asyncio async def test_list_policies_field_headers_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(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 = orgpolicy.ListPoliciesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -906,7 +917,6 @@ async def test_list_policies_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( orgpolicy.ListPoliciesResponse() ) - await client.list_policies(request) # Establish that the underlying gRPC stub method was called. @@ -920,13 +930,12 @@ async def test_list_policies_field_headers_async(): def test_list_policies_flattened(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_policies), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = orgpolicy.ListPoliciesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_policies(parent="parent_value",) @@ -935,12 +944,11 @@ def test_list_policies_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_policies_flattened_error(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -952,7 +960,7 @@ def test_list_policies_flattened_error(): @pytest.mark.asyncio async def test_list_policies_flattened_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_policies), "__call__") as call: @@ -970,13 +978,12 @@ async def test_list_policies_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_policies_flattened_error_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -987,7 +994,7 @@ async def test_list_policies_flattened_error_async(): def test_list_policies_pager(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials,) + client = OrgPolicyClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_policies), "__call__") as call: @@ -1021,7 +1028,7 @@ def test_list_policies_pager(): def test_list_policies_pages(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials,) + client = OrgPolicyClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_policies), "__call__") as call: @@ -1047,7 +1054,7 @@ def test_list_policies_pages(): @pytest.mark.asyncio async def test_list_policies_async_pager(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials,) + client = OrgPolicyAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1080,7 +1087,7 @@ async def test_list_policies_async_pager(): @pytest.mark.asyncio async def test_list_policies_async_pages(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials,) + client = OrgPolicyAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1110,7 +1117,7 @@ async def test_list_policies_async_pages(): def test_get_policy(transport: str = "grpc", request_type=orgpolicy.GetPolicyRequest): client = OrgPolicyClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1121,19 +1128,15 @@ def test_get_policy(transport: str = "grpc", request_type=orgpolicy.GetPolicyReq with mock.patch.object(type(client.transport.get_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = orgpolicy.Policy(name="name_value",) - response = client.get_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.GetPolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, orgpolicy.Policy) - assert response.name == "name_value" @@ -1145,7 +1148,7 @@ def test_get_policy_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 = OrgPolicyClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1153,7 +1156,6 @@ def test_get_policy_empty_call(): client.get_policy() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.GetPolicyRequest() @@ -1162,7 +1164,7 @@ async def test_get_policy_async( transport: str = "grpc_asyncio", request_type=orgpolicy.GetPolicyRequest ): client = OrgPolicyAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1175,18 +1177,15 @@ async def test_get_policy_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( orgpolicy.Policy(name="name_value",) ) - response = await client.get_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.GetPolicyRequest() # Establish that the response is the type that we expect. assert isinstance(response, orgpolicy.Policy) - assert response.name == "name_value" @@ -1196,17 +1195,17 @@ async def test_get_policy_async_from_dict(): def test_get_policy_field_headers(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(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 = orgpolicy.GetPolicyRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_policy), "__call__") as call: call.return_value = orgpolicy.Policy() - client.get_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1221,17 +1220,17 @@ def test_get_policy_field_headers(): @pytest.mark.asyncio async def test_get_policy_field_headers_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(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 = orgpolicy.GetPolicyRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_policy), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(orgpolicy.Policy()) - await client.get_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1245,13 +1244,12 @@ async def test_get_policy_field_headers_async(): def test_get_policy_flattened(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = orgpolicy.Policy() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_policy(name="name_value",) @@ -1260,12 +1258,11 @@ def test_get_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_policy_flattened_error(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1277,7 +1274,7 @@ def test_get_policy_flattened_error(): @pytest.mark.asyncio async def test_get_policy_flattened_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_policy), "__call__") as call: @@ -1293,13 +1290,12 @@ async def test_get_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_policy_flattened_error_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1313,7 +1309,7 @@ def test_get_effective_policy( transport: str = "grpc", request_type=orgpolicy.GetEffectivePolicyRequest ): client = OrgPolicyClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1326,19 +1322,15 @@ def test_get_effective_policy( ) as call: # Designate an appropriate return value for the call. call.return_value = orgpolicy.Policy(name="name_value",) - response = client.get_effective_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.GetEffectivePolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, orgpolicy.Policy) - assert response.name == "name_value" @@ -1350,7 +1342,7 @@ def test_get_effective_policy_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 = OrgPolicyClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1360,7 +1352,6 @@ def test_get_effective_policy_empty_call(): client.get_effective_policy() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.GetEffectivePolicyRequest() @@ -1369,7 +1360,7 @@ async def test_get_effective_policy_async( transport: str = "grpc_asyncio", request_type=orgpolicy.GetEffectivePolicyRequest ): client = OrgPolicyAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1384,18 +1375,15 @@ async def test_get_effective_policy_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( orgpolicy.Policy(name="name_value",) ) - response = await client.get_effective_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.GetEffectivePolicyRequest() # Establish that the response is the type that we expect. assert isinstance(response, orgpolicy.Policy) - assert response.name == "name_value" @@ -1405,11 +1393,12 @@ async def test_get_effective_policy_async_from_dict(): def test_get_effective_policy_field_headers(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(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 = orgpolicy.GetEffectivePolicyRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1417,7 +1406,6 @@ def test_get_effective_policy_field_headers(): type(client.transport.get_effective_policy), "__call__" ) as call: call.return_value = orgpolicy.Policy() - client.get_effective_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1432,11 +1420,12 @@ def test_get_effective_policy_field_headers(): @pytest.mark.asyncio async def test_get_effective_policy_field_headers_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(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 = orgpolicy.GetEffectivePolicyRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1444,7 +1433,6 @@ async def test_get_effective_policy_field_headers_async(): type(client.transport.get_effective_policy), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(orgpolicy.Policy()) - await client.get_effective_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1458,7 +1446,7 @@ async def test_get_effective_policy_field_headers_async(): def test_get_effective_policy_flattened(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1466,7 +1454,6 @@ def test_get_effective_policy_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = orgpolicy.Policy() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_effective_policy(name="name_value",) @@ -1475,12 +1462,11 @@ def test_get_effective_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_effective_policy_flattened_error(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1492,7 +1478,7 @@ def test_get_effective_policy_flattened_error(): @pytest.mark.asyncio async def test_get_effective_policy_flattened_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1510,13 +1496,12 @@ async def test_get_effective_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_effective_policy_flattened_error_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1530,7 +1515,7 @@ def test_create_policy( transport: str = "grpc", request_type=orgpolicy.CreatePolicyRequest ): client = OrgPolicyClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1541,19 +1526,15 @@ def test_create_policy( with mock.patch.object(type(client.transport.create_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = orgpolicy.Policy(name="name_value",) - response = client.create_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.CreatePolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, orgpolicy.Policy) - assert response.name == "name_value" @@ -1565,7 +1546,7 @@ def test_create_policy_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 = OrgPolicyClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1573,7 +1554,6 @@ def test_create_policy_empty_call(): client.create_policy() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.CreatePolicyRequest() @@ -1582,7 +1562,7 @@ async def test_create_policy_async( transport: str = "grpc_asyncio", request_type=orgpolicy.CreatePolicyRequest ): client = OrgPolicyAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1595,18 +1575,15 @@ async def test_create_policy_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( orgpolicy.Policy(name="name_value",) ) - response = await client.create_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.CreatePolicyRequest() # Establish that the response is the type that we expect. assert isinstance(response, orgpolicy.Policy) - assert response.name == "name_value" @@ -1616,17 +1593,17 @@ async def test_create_policy_async_from_dict(): def test_create_policy_field_headers(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(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 = orgpolicy.CreatePolicyRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_policy), "__call__") as call: call.return_value = orgpolicy.Policy() - client.create_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1641,17 +1618,17 @@ def test_create_policy_field_headers(): @pytest.mark.asyncio async def test_create_policy_field_headers_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(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 = orgpolicy.CreatePolicyRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_policy), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(orgpolicy.Policy()) - await client.create_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1665,13 +1642,12 @@ async def test_create_policy_field_headers_async(): def test_create_policy_flattened(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = orgpolicy.Policy() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_policy( @@ -1682,14 +1658,12 @@ def test_create_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].policy == orgpolicy.Policy(name="name_value") def test_create_policy_flattened_error(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1703,7 +1677,7 @@ def test_create_policy_flattened_error(): @pytest.mark.asyncio async def test_create_policy_flattened_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_policy), "__call__") as call: @@ -1721,15 +1695,13 @@ async def test_create_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].policy == orgpolicy.Policy(name="name_value") @pytest.mark.asyncio async def test_create_policy_flattened_error_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1745,7 +1717,7 @@ def test_update_policy( transport: str = "grpc", request_type=orgpolicy.UpdatePolicyRequest ): client = OrgPolicyClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1756,19 +1728,15 @@ def test_update_policy( with mock.patch.object(type(client.transport.update_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = orgpolicy.Policy(name="name_value",) - response = client.update_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.UpdatePolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, orgpolicy.Policy) - assert response.name == "name_value" @@ -1780,7 +1748,7 @@ def test_update_policy_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 = OrgPolicyClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1788,7 +1756,6 @@ def test_update_policy_empty_call(): client.update_policy() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.UpdatePolicyRequest() @@ -1797,7 +1764,7 @@ async def test_update_policy_async( transport: str = "grpc_asyncio", request_type=orgpolicy.UpdatePolicyRequest ): client = OrgPolicyAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1810,18 +1777,15 @@ async def test_update_policy_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( orgpolicy.Policy(name="name_value",) ) - response = await client.update_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.UpdatePolicyRequest() # Establish that the response is the type that we expect. assert isinstance(response, orgpolicy.Policy) - assert response.name == "name_value" @@ -1831,17 +1795,17 @@ async def test_update_policy_async_from_dict(): def test_update_policy_field_headers(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(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 = orgpolicy.UpdatePolicyRequest() + request.policy.name = "policy.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_policy), "__call__") as call: call.return_value = orgpolicy.Policy() - client.update_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1856,17 +1820,17 @@ def test_update_policy_field_headers(): @pytest.mark.asyncio async def test_update_policy_field_headers_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(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 = orgpolicy.UpdatePolicyRequest() + request.policy.name = "policy.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_policy), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(orgpolicy.Policy()) - await client.update_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1880,13 +1844,12 @@ async def test_update_policy_field_headers_async(): def test_update_policy_flattened(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = orgpolicy.Policy() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_policy(policy=orgpolicy.Policy(name="name_value"),) @@ -1895,12 +1858,11 @@ def test_update_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].policy == orgpolicy.Policy(name="name_value") def test_update_policy_flattened_error(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1912,7 +1874,7 @@ def test_update_policy_flattened_error(): @pytest.mark.asyncio async def test_update_policy_flattened_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_policy), "__call__") as call: @@ -1930,13 +1892,12 @@ async def test_update_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].policy == orgpolicy.Policy(name="name_value") @pytest.mark.asyncio async def test_update_policy_flattened_error_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1950,7 +1911,7 @@ def test_delete_policy( transport: str = "grpc", request_type=orgpolicy.DeletePolicyRequest ): client = OrgPolicyClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1961,13 +1922,11 @@ def test_delete_policy( with mock.patch.object(type(client.transport.delete_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.DeletePolicyRequest() # Establish that the response is the type that we expect. @@ -1982,7 +1941,7 @@ def test_delete_policy_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 = OrgPolicyClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1990,7 +1949,6 @@ def test_delete_policy_empty_call(): client.delete_policy() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.DeletePolicyRequest() @@ -1999,7 +1957,7 @@ async def test_delete_policy_async( transport: str = "grpc_asyncio", request_type=orgpolicy.DeletePolicyRequest ): client = OrgPolicyAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2010,13 +1968,11 @@ async def test_delete_policy_async( with mock.patch.object(type(client.transport.delete_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == orgpolicy.DeletePolicyRequest() # Establish that the response is the type that we expect. @@ -2029,17 +1985,17 @@ async def test_delete_policy_async_from_dict(): def test_delete_policy_field_headers(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(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 = orgpolicy.DeletePolicyRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_policy), "__call__") as call: call.return_value = None - client.delete_policy(request) # Establish that the underlying gRPC stub method was called. @@ -2054,17 +2010,17 @@ def test_delete_policy_field_headers(): @pytest.mark.asyncio async def test_delete_policy_field_headers_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(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 = orgpolicy.DeletePolicyRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_policy), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_policy(request) # Establish that the underlying gRPC stub method was called. @@ -2078,13 +2034,12 @@ async def test_delete_policy_field_headers_async(): def test_delete_policy_flattened(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_policy(name="name_value",) @@ -2093,12 +2048,11 @@ def test_delete_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_policy_flattened_error(): - client = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2110,7 +2064,7 @@ def test_delete_policy_flattened_error(): @pytest.mark.asyncio async def test_delete_policy_flattened_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_policy), "__call__") as call: @@ -2126,13 +2080,12 @@ async def test_delete_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_policy_flattened_error_async(): - client = OrgPolicyAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2145,16 +2098,16 @@ async def test_delete_policy_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.OrgPolicyGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = OrgPolicyClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.OrgPolicyGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = OrgPolicyClient( @@ -2164,7 +2117,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.OrgPolicyGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = OrgPolicyClient( @@ -2175,7 +2128,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.OrgPolicyGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = OrgPolicyClient(transport=transport) assert client.transport is transport @@ -2184,13 +2137,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.OrgPolicyGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.OrgPolicyGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2202,23 +2155,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = OrgPolicyClient(credentials=credentials.AnonymousCredentials(),) + client = OrgPolicyClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.OrgPolicyGrpcTransport,) def test_org_policy_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.OrgPolicyTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2230,7 +2183,7 @@ def test_org_policy_base_transport(): ) as Transport: Transport.return_value = None transport = transports.OrgPolicyTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2249,15 +2202,37 @@ def test_org_policy_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_org_policy_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.orgpolicy_v2.services.org_policy.transports.OrgPolicyTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OrgPolicyTransport( + 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/cloud-platform",), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_org_policy_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.orgpolicy_v2.services.org_policy.transports.OrgPolicyTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.OrgPolicyTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2270,19 +2245,33 @@ def test_org_policy_base_transport_with_credentials_file(): def test_org_policy_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.orgpolicy_v2.services.org_policy.transports.OrgPolicyTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.OrgPolicyTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_org_policy_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + OrgPolicyClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_org_policy_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) OrgPolicyClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -2290,26 +2279,154 @@ def test_org_policy_auth_adc(): ) -def test_org_policy_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.OrgPolicyGrpcTransport, transports.OrgPolicyGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_org_policy_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.OrgPolicyGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + 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/cloud-platform",), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.OrgPolicyGrpcTransport, transports.OrgPolicyGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_org_policy_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/cloud-platform",), quota_project_id="octopus", ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.OrgPolicyGrpcTransport, grpc_helpers), + (transports.OrgPolicyGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_org_policy_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( + "orgpolicy.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="orgpolicy.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.OrgPolicyGrpcTransport, grpc_helpers), + (transports.OrgPolicyGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_org_policy_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "orgpolicy.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.OrgPolicyGrpcTransport, grpc_helpers), + (transports.OrgPolicyGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_org_policy_transport_create_channel_user_scopes(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( + "orgpolicy.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.OrgPolicyGrpcTransport, transports.OrgPolicyGrpcAsyncIOTransport], ) def test_org_policy_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2348,7 +2465,7 @@ def test_org_policy_grpc_transport_client_cert_source_for_mtls(transport_class): def test_org_policy_host_no_port(): client = OrgPolicyClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="orgpolicy.googleapis.com" ), @@ -2358,7 +2475,7 @@ def test_org_policy_host_no_port(): def test_org_policy_host_with_port(): client = OrgPolicyClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="orgpolicy.googleapis.com:8000" ), @@ -2409,9 +2526,9 @@ def test_org_policy_transport_channel_mtls_with_client_cert_source(transport_cla mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2485,7 +2602,6 @@ def test_org_policy_transport_channel_mtls_with_adc(transport_class): def test_constraint_path(): project = "squid" constraint = "clam" - expected = "projects/{project}/constraints/{constraint}".format( project=project, constraint=constraint, ) @@ -2508,7 +2624,6 @@ def test_parse_constraint_path(): def test_policy_path(): project = "oyster" policy = "nudibranch" - expected = "projects/{project}/policies/{policy}".format( project=project, policy=policy, ) @@ -2530,7 +2645,6 @@ def test_parse_policy_path(): def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2551,7 +2665,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format(folder=folder,) actual = OrgPolicyClient.common_folder_path(folder) assert expected == actual @@ -2570,7 +2683,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format(organization=organization,) actual = OrgPolicyClient.common_organization_path(organization) assert expected == actual @@ -2589,7 +2701,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format(project=project,) actual = OrgPolicyClient.common_project_path(project) assert expected == actual @@ -2609,7 +2720,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "oyster" location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2636,7 +2746,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.OrgPolicyTransport, "_prep_wrapped_messages" ) as prep: client = OrgPolicyClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2645,6 +2755,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = OrgPolicyClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) From 3056b54822f11f0b3e2caa220a115f223bac438b Mon Sep 17 00:00:00 2001 From: Bu Sun Kim <8822365+busunkim96@users.noreply.github.com> Date: Fri, 14 May 2021 19:10:09 -0600 Subject: [PATCH 14/16] fix(deps): add packaging requirement (#48) Add packaging requirement. packaging.version is used for a version comparison in transports/base.py --- setup.py | 1 + testing/constraints-3.6.txt | 1 + 2 files changed, 2 insertions(+) diff --git a/setup.py b/setup.py index aeffaa9..69a511a 100644 --- a/setup.py +++ b/setup.py @@ -43,6 +43,7 @@ install_requires=( "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", "proto-plus >= 1.10.0", + "packaging >= 14.3", ), python_requires=">=3.6", classifiers=[ diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index 3f71837..30d4943 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -21,3 +21,4 @@ # Then this file should have foo==1.14.0 google-api-core==1.22.2 proto-plus==1.10.0 +packaging==14.3 From 3434a4e33338a445b92fd92ef500f635214ae7ae Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sun, 16 May 2021 14:04:05 +0000 Subject: [PATCH 15/16] chore: new owl bot post processor docker image (#49) gcr.io/repo-automation-bots/owlbot-python:latest@sha256:4c981a6b6f2b8914a448d7b3a01688365be03e3ed26dfee399a6aa77fb112eaa --- .github/.OwlBot.lock.yaml | 5 ++--- .pre-commit-config.yaml | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index d49860b..864c176 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,4 +1,3 @@ docker: - digest: sha256:457583330eec64daa02aeb7a72a04d33e7be2428f646671ce4045dcbc0191b1e - image: gcr.io/repo-automation-bots/owlbot-python:latest - + image: gcr.io/repo-automation-bots/owlbot-python:latest + digest: sha256:4c981a6b6f2b8914a448d7b3a01688365be03e3ed26dfee399a6aa77fb112eaa diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1bbd787..4f00c7c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -26,6 +26,6 @@ repos: hooks: - id: black - repo: https://gitlab.com/pycqa/flake8 - rev: 3.9.1 + rev: 3.9.2 hooks: - id: flake8 From aa333b73855ab552acf64d877a02c7f0b342ebdb Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Tue, 18 May 2021 16:36:04 +0000 Subject: [PATCH 16/16] chore: release 0.3.0 (#27) :robot: I have created a release \*beep\* \*boop\* --- ## [0.3.0](https://www.github.com/googleapis/python-org-policy/compare/v0.2.0...v0.3.0) (2021-05-16) ### Features * add `from_service_account_info` ([#24](https://www.github.com/googleapis/python-org-policy/issues/24)) ([cb5881d](https://www.github.com/googleapis/python-org-policy/commit/cb5881dac8121617fda5a4d9df9f70c80dcc8735)) * support self-signed JWT flow for service accounts ([aade679](https://www.github.com/googleapis/python-org-policy/commit/aade679d6c04808408110292a3de805fa3364286)) ### Bug Fixes * add async client to %name_%version/init.py chore: add autogenerated snippets ([aade679](https://www.github.com/googleapis/python-org-policy/commit/aade679d6c04808408110292a3de805fa3364286)) * **deps:** add packaging requirement ([#48](https://www.github.com/googleapis/python-org-policy/issues/48)) ([3056b54](https://www.github.com/googleapis/python-org-policy/commit/3056b54822f11f0b3e2caa220a115f223bac438b)) * Fixed broken url for package. ([#38](https://www.github.com/googleapis/python-org-policy/issues/38)) ([7b27dac](https://www.github.com/googleapis/python-org-policy/commit/7b27dac39dbdda9789533502356cee6f5d9303c2)), closes [#37](https://www.github.com/googleapis/python-org-policy/issues/37) * use correct retry deadline ([#28](https://www.github.com/googleapis/python-org-policy/issues/28)) ([5d1f86c](https://www.github.com/googleapis/python-org-policy/commit/5d1f86c3121c778f71205364af43e1f26f4c12c9)) --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). --- CHANGELOG.md | 16 ++++++++++++++++ setup.py | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eb1becc..775c7cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## [0.3.0](https://www.github.com/googleapis/python-org-policy/compare/v0.2.0...v0.3.0) (2021-05-16) + + +### Features + +* add `from_service_account_info` ([#24](https://www.github.com/googleapis/python-org-policy/issues/24)) ([cb5881d](https://www.github.com/googleapis/python-org-policy/commit/cb5881dac8121617fda5a4d9df9f70c80dcc8735)) +* support self-signed JWT flow for service accounts ([aade679](https://www.github.com/googleapis/python-org-policy/commit/aade679d6c04808408110292a3de805fa3364286)) + + +### Bug Fixes + +* add async client to %name_%version/init.py chore: add autogenerated snippets ([aade679](https://www.github.com/googleapis/python-org-policy/commit/aade679d6c04808408110292a3de805fa3364286)) +* **deps:** add packaging requirement ([#48](https://www.github.com/googleapis/python-org-policy/issues/48)) ([3056b54](https://www.github.com/googleapis/python-org-policy/commit/3056b54822f11f0b3e2caa220a115f223bac438b)) +* Fixed broken url for package. ([#38](https://www.github.com/googleapis/python-org-policy/issues/38)) ([7b27dac](https://www.github.com/googleapis/python-org-policy/commit/7b27dac39dbdda9789533502356cee6f5d9303c2)), closes [#37](https://www.github.com/googleapis/python-org-policy/issues/37) +* use correct retry deadline ([#28](https://www.github.com/googleapis/python-org-policy/issues/28)) ([5d1f86c](https://www.github.com/googleapis/python-org-policy/commit/5d1f86c3121c778f71205364af43e1f26f4c12c9)) + ## [0.2.0](https://www.github.com/googleapis/python-org-policy/compare/v0.1.2...v0.2.0) (2021-03-01) diff --git a/setup.py b/setup.py index 69a511a..0871385 100644 --- a/setup.py +++ b/setup.py @@ -19,7 +19,7 @@ import os import setuptools # type: ignore -version = "0.2.0" +version = "0.3.0" package_root = os.path.abspath(os.path.dirname(__file__))