From c5b90525f673f898be484ecfbe7e51c93e425e49 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Wed, 23 Dec 2020 00:18:53 +0100 Subject: [PATCH 01/23] chore(deps): update dependency google-cloud-securitycenter to v1.1.0 (#90) --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index e5ab9c9d..fcb6d25d 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1,2 +1,2 @@ google-cloud-pubsub==2.2.0 -google-cloud-securitycenter==1.0.0 \ No newline at end of file +google-cloud-securitycenter==1.1.0 \ No newline at end of file From e5d1aab799bc0c6f0f29eb26b3fdbd44aafe31a7 Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Tue, 22 Dec 2020 15:28:04 -0800 Subject: [PATCH 02/23] chore: update templates (#88) This PR was generated using Autosynth. :rainbow: Synth log will be available here: https://source.cloud.google.com/results/invocations/f632d5d1-d20c-4ae6-90f5-18e53f0f588a/targets - [ ] To automatically regenerate this PR, check this box. Source-Link: https://github.com/googleapis/synthtool/commit/18c5dbdb4ac8cf75d4d8174e7b4558f48e76f8a1 Source-Link: https://github.com/googleapis/synthtool/commit/f94318521f63085b9ccb43d42af89f153fb39f15 Source-Link: https://github.com/googleapis/synthtool/commit/69629b64b83c6421d616be2b8e11795738ec8a6c Source-Link: https://github.com/googleapis/synthtool/commit/32af6da519a6b042e3da62008e2a75e991efb6b4 Source-Link: https://github.com/googleapis/synthtool/commit/a073c873f3928c561bdf87fdfbf1d081d1998984 Source-Link: https://github.com/googleapis/synthtool/commit/9a7d9fbb7045c34c9d3d22c1ff766eeae51f04c9 Source-Link: https://github.com/googleapis/synthtool/commit/e89175cf074dccc4babb4eca66ae913696e47a71 Source-Link: https://github.com/googleapis/synthtool/commit/1f1148d3c7a7a52f0c98077f976bd9b3c948ee2b Source-Link: https://github.com/googleapis/synthtool/commit/3d3e94c4e02370f307a9a200b0c743c3d8d19f29 Source-Link: https://github.com/googleapis/synthtool/commit/6542bd723403513626f61642fc02ddca528409aa Source-Link: https://github.com/googleapis/synthtool/commit/ea52b8a0bd560f72f376efcf45197fb7c8869120 Source-Link: https://github.com/googleapis/synthtool/commit/5f6ef0ec5501d33c4667885b37a7685a30d41a76 Source-Link: https://github.com/googleapis/synthtool/commit/da5c6050d13b4950c82666a81d8acd25157664ae Source-Link: https://github.com/googleapis/synthtool/commit/477764cc4ee6db346d3febef2bb1ea0abf27de52 Source-Link: https://github.com/googleapis/synthtool/commit/e0ae456852bf22f38796deb79cff30b516fde244 Source-Link: https://github.com/googleapis/synthtool/commit/9b0da5204ab90bcc36f8cd4e5689eff1a54cc3e4 --- .kokoro/docs/common.cfg | 2 +- .kokoro/test-samples.sh | 8 ++- .pre-commit-config.yaml | 17 +++++ CODE_OF_CONDUCT.md | 123 +++++++++++++++++++++++++----------- CONTRIBUTING.rst | 10 +++ docs/conf.py | 7 +- noxfile.py | 9 +-- samples/snippets/noxfile.py | 39 +++++++++--- synth.metadata | 5 +- 9 files changed, 165 insertions(+), 55 deletions(-) create mode 100644 .pre-commit-config.yaml diff --git a/.kokoro/docs/common.cfg b/.kokoro/docs/common.cfg index 571f0e74..2b6c6e51 100644 --- a/.kokoro/docs/common.cfg +++ b/.kokoro/docs/common.cfg @@ -30,7 +30,7 @@ env_vars: { env_vars: { key: "V2_STAGING_BUCKET" - value: "docs-staging-v2-staging" + value: "docs-staging-v2" } # It will upload the docker image after successful builds. diff --git a/.kokoro/test-samples.sh b/.kokoro/test-samples.sh index 6b4a8fe5..32deb636 100755 --- a/.kokoro/test-samples.sh +++ b/.kokoro/test-samples.sh @@ -28,6 +28,12 @@ if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then 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 @@ -101,4 +107,4 @@ cd "$ROOT" # Workaround for Kokoro permissions issue: delete secrets rm testing/{test-env.sh,client-secrets.json,service-account.json} -exit "$RTN" \ No newline at end of file +exit "$RTN" diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000..6ad83346 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,17 @@ +# See https://pre-commit.com for more information +# See https://pre-commit.com/hooks.html for more hooks +repos: +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v3.3.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml +- repo: https://github.com/psf/black + rev: 19.10b0 + hooks: + - id: black +- repo: https://gitlab.com/pycqa/flake8 + rev: 3.8.4 + hooks: + - id: flake8 diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index b3d1f602..039f4368 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,44 +1,95 @@ -# Contributor Code of Conduct +# Code of Conduct -As contributors and maintainers of this project, -and in the interest of fostering an open and welcoming community, -we pledge to respect all people who contribute through reporting issues, -posting feature requests, updating documentation, -submitting pull requests or patches, and other activities. +## Our Pledge -We are committed to making participation in this project -a harassment-free experience for everyone, -regardless of level of experience, gender, gender identity and expression, -sexual orientation, disability, personal appearance, -body size, race, ethnicity, age, religion, or nationality. +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of +experience, education, socio-economic status, nationality, personal appearance, +race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members Examples of unacceptable behavior by participants include: -* The use of sexualized language or imagery -* Personal attacks -* Trolling or insulting/derogatory comments -* Public or private harassment -* Publishing other's private information, -such as physical or electronic -addresses, without explicit permission -* Other unethical or unprofessional conduct. +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct. -By adopting this Code of Conduct, -project maintainers commit themselves to fairly and consistently -applying these principles to every aspect of managing this project. -Project maintainers who do not follow or enforce the Code of Conduct -may be permanently removed from the project team. - -This code of conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. - -Instances of abusive, harassing, or otherwise unacceptable behavior -may be reported by opening an issue -or contacting one or more of the project maintainers. - -This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, -available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/) +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, or to ban temporarily or permanently any +contributor for other behaviors that they deem inappropriate, threatening, +offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +This Code of Conduct also applies outside the project spaces when the Project +Steward has a reasonable belief that an individual's behavior may have a +negative impact on the project or its community. + +## Conflict Resolution + +We do not believe that all conflict is bad; healthy debate and disagreement +often yield positive results. However, it is never okay to be disrespectful or +to engage in behavior that violates the project’s code of conduct. + +If you see someone violating the code of conduct, you are encouraged to address +the behavior directly with those involved. Many issues can be resolved quickly +and easily, and this gives people more control over the outcome of their +dispute. If you are unable to resolve the matter for any reason, or if the +behavior is threatening or harassing, report it. We are dedicated to providing +an environment where participants feel welcome and safe. + + +Reports should be directed to *googleapis-stewards@google.com*, the +Project Steward(s) for *Google Cloud Client Libraries*. It is the Project Steward’s duty to +receive and address reported violations of the code of conduct. They will then +work with a committee consisting of representatives from the Open Source +Programs Office and the Google Open Source Strategy team. If for any reason you +are uncomfortable reaching out to the Project Steward, please email +opensource@google.com. + +We will investigate every complaint, but you may not receive a direct response. +We will use our discretion in determining when and how to follow up on reported +incidents, which may range from not taking action to permanent expulsion from +the project and project-sponsored spaces. We will notify the accused of the +report and provide them an opportunity to discuss it before any action is taken. +The identity of the reporter will be omitted from the details of the report +supplied to the accused. In potentially harmful situations, such as ongoing +harassment or threats to anyone's safety, we may take action without notice. + +## Attribution + +This Code of Conduct is adapted from the Contributor Covenant, version 1.4, +available at +https://www.contributor-covenant.org/version/1/4/code-of-conduct.html \ No newline at end of file diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 1d8fa16d..d9352cba 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -111,6 +111,16 @@ Coding Style should point to the official ``googleapis`` checkout and the the branch should be the main branch on that remote (``master``). +- This repository contains configuration for the + `pre-commit `__ tool, which automates checking + our linters during a commit. If you have it installed on your ``$PATH``, + you can enable enforcing those checks via: + +.. code-block:: bash + + $ pre-commit install + pre-commit installed at .git/hooks/pre-commit + Exceptions to PEP8: - Many unit tests use a helper method, ``_call_fut`` ("FUT" is short for diff --git a/docs/conf.py b/docs/conf.py index 060155c0..fc36779f 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -345,10 +345,11 @@ # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "python": ("https://python.readthedocs.org/en/latest/", None), + "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None,), - "grpc": ("https://grpc.io/grpc/python/", None), + "grpc": ("https://grpc.github.io/grpc/python/", None), + "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), } diff --git a/noxfile.py b/noxfile.py index bf5b92d4..a57e24be 100644 --- a/noxfile.py +++ b/noxfile.py @@ -72,16 +72,17 @@ def default(session): # Install all test dependencies, then install this package in-place. session.install("asyncmock", "pytest-asyncio") - session.install("mock", "pytest", "pytest-cov") + session.install( + "mock", "pytest", "pytest-cov", + ) session.install("-e", ".") # Run py.test against the unit tests. session.run( "py.test", "--quiet", - "--cov=google.cloud.securitycenter", - "--cov=google.cloud", - "--cov=tests.unit", + "--cov=google/cloud", + "--cov=tests/unit", "--cov-append", "--cov-config=.coveragerc", "--cov-report=", diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py index ba55d7ce..bca0522e 100644 --- a/samples/snippets/noxfile.py +++ b/samples/snippets/noxfile.py @@ -17,6 +17,7 @@ import os from pathlib import Path import sys +from typing import Callable, Dict, List, Optional import nox @@ -39,6 +40,10 @@ # You can opt out from the test for specific Python versions. 'ignored_versions': ["2.7"], + # Old samples are opted out of enforcing Python type hints + # All new samples should feature them + 'enforce_type_hints': False, + # An envvar key for determining the project id to use. Change it # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a # build specific Cloud project. You can also use your own string @@ -64,7 +69,7 @@ TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) -def get_pytest_env_vars(): +def get_pytest_env_vars() -> Dict[str, str]: """Returns a dict for pytest invocation.""" ret = {} @@ -93,7 +98,7 @@ def get_pytest_env_vars(): # -def _determine_local_import_names(start_dir): +def _determine_local_import_names(start_dir: str) -> List[str]: """Determines all import names that should be considered "local". This is used when running the linter to insure that import order is @@ -131,8 +136,11 @@ def _determine_local_import_names(start_dir): @nox.session -def lint(session): - session.install("flake8", "flake8-import-order") +def lint(session: nox.sessions.Session) -> None: + if not TEST_CONFIG['enforce_type_hints']: + session.install("flake8", "flake8-import-order") + else: + session.install("flake8", "flake8-import-order", "flake8-annotations") local_names = _determine_local_import_names(".") args = FLAKE8_COMMON_ARGS + [ @@ -141,8 +149,18 @@ def lint(session): "." ] session.run("flake8", *args) +# +# Black +# +@nox.session +def blacken(session: nox.sessions.Session) -> None: + session.install("black") + python_files = [path for path in os.listdir(".") if path.endswith(".py")] + + session.run("black", *python_files) + # # Sample Tests # @@ -151,7 +169,7 @@ def lint(session): PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] -def _session_tests(session, post_install=None): +def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None: """Runs py.test for a particular project.""" if os.path.exists("requirements.txt"): session.install("-r", "requirements.txt") @@ -177,7 +195,7 @@ def _session_tests(session, post_install=None): @nox.session(python=ALL_VERSIONS) -def py(session): +def py(session: nox.sessions.Session) -> None: """Runs py.test for a sample using the specified version of Python.""" if session.python in TESTED_VERSIONS: _session_tests(session) @@ -192,7 +210,7 @@ def py(session): # -def _get_repo_root(): +def _get_repo_root() -> Optional[str]: """ Returns the root folder of the project. """ # Get root of this repository. Assume we don't have directories nested deeper than 10 items. p = Path(os.getcwd()) @@ -201,6 +219,11 @@ def _get_repo_root(): break if Path(p / ".git").exists(): return str(p) + # .git is not available in repos cloned via Cloud Build + # setup.py is always in the library's root, so use that instead + # https://github.com/googleapis/synthtool/issues/792 + if Path(p / "setup.py").exists(): + return str(p) p = p.parent raise Exception("Unable to detect repository root.") @@ -210,7 +233,7 @@ def _get_repo_root(): @nox.session @nox.parametrize("path", GENERATED_READMES) -def readmegen(session, path): +def readmegen(session: nox.sessions.Session, path: str) -> None: """(Re-)generates the readme for a sample.""" session.install("jinja2", "pyyaml") dir_ = os.path.dirname(path) diff --git a/synth.metadata b/synth.metadata index 77673e83..41d2c725 100644 --- a/synth.metadata +++ b/synth.metadata @@ -19,14 +19,14 @@ "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "9b0da5204ab90bcc36f8cd4e5689eff1a54cc3e4" + "sha": "18c5dbdb4ac8cf75d4d8174e7b4558f48e76f8a1" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "9b0da5204ab90bcc36f8cd4e5689eff1a54cc3e4" + "sha": "18c5dbdb4ac8cf75d4d8174e7b4558f48e76f8a1" } } ], @@ -103,6 +103,7 @@ ".kokoro/test-samples.sh", ".kokoro/trampoline.sh", ".kokoro/trampoline_v2.sh", + ".pre-commit-config.yaml", ".trampolinerc", "CODE_OF_CONDUCT.md", "CONTRIBUTING.rst", From 7656848e706166a8e3b43a78b860a5979e3524e6 Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Wed, 23 Dec 2020 13:38:08 -0800 Subject: [PATCH 03/23] chore: exclude `.nox` from linting; update python versions in CONTRIBUTING (#92) * chore(deps): update precommit hook pre-commit/pre-commit-hooks to v3.4.0 Co-authored-by: Tres Seaver Source-Author: WhiteSource Renovate Source-Date: Wed Dec 16 18:13:24 2020 +0100 Source-Repo: googleapis/synthtool Source-Sha: aa255b15d52b6d8950cca48cfdf58f7d27a60c8a Source-Link: https://github.com/googleapis/synthtool/commit/aa255b15d52b6d8950cca48cfdf58f7d27a60c8a * docs(python): document adding Python 3.9 support, dropping 3.5 support Closes #787 Source-Author: Tres Seaver Source-Date: Thu Dec 17 16:08:02 2020 -0500 Source-Repo: googleapis/synthtool Source-Sha: b670a77a454f415d247907908e8ee7943e06d718 Source-Link: https://github.com/googleapis/synthtool/commit/b670a77a454f415d247907908e8ee7943e06d718 * chore: exclude `.nox` directories from linting The samples tests create `.nox` directories with all dependencies installed. These directories should be excluded from linting. I've tested this change locally, and it significantly speeds up linting on my machine. Source-Author: Tim Swast Source-Date: Tue Dec 22 13:04:04 2020 -0600 Source-Repo: googleapis/synthtool Source-Sha: 373861061648b5fe5e0ac4f8a38b32d639ee93e4 Source-Link: https://github.com/googleapis/synthtool/commit/373861061648b5fe5e0ac4f8a38b32d639ee93e4 --- .flake8 | 1 + .pre-commit-config.yaml | 2 +- CONTRIBUTING.rst | 11 +++++------ synth.metadata | 6 +++--- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.flake8 b/.flake8 index ed931638..29227d4c 100644 --- a/.flake8 +++ b/.flake8 @@ -26,6 +26,7 @@ exclude = *_pb2.py # Standard linting exemptions. + **/.nox/** __pycache__, .git, *.pyc, diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 6ad83346..a9024b15 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -2,7 +2,7 @@ # See https://pre-commit.com/hooks.html for more hooks repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v3.3.0 + rev: v3.4.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index d9352cba..373badc1 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -21,8 +21,8 @@ In order to add a feature: - The feature must be documented in both the API and narrative documentation. -- The feature must work fully on the following CPython versions: 2.7, - 3.5, 3.6, 3.7 and 3.8 on both UNIX and Windows. +- The feature must work fully on the following CPython versions: + 3.6, 3.7, 3.8 and 3.9 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -202,25 +202,24 @@ Supported Python Versions We support: -- `Python 3.5`_ - `Python 3.6`_ - `Python 3.7`_ - `Python 3.8`_ +- `Python 3.9`_ -.. _Python 3.5: https://docs.python.org/3.5/ .. _Python 3.6: https://docs.python.org/3.6/ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ +.. _Python 3.9: https://docs.python.org/3.9/ Supported versions can be found in our ``noxfile.py`` `config`_. .. _config: https://github.com/googleapis/python-securitycenter/blob/master/noxfile.py -Python 2.7 support is deprecated. All code changes should maintain Python 2.7 compatibility until January 1, 2020. We also explicitly decided to support Python 3 beginning with version -3.5. Reasons for this include: +3.6. Reasons for this include: - Encouraging use of newest versions of Python 3 - Taking the lead of `prominent`_ open-source `projects`_ diff --git a/synth.metadata b/synth.metadata index 41d2c725..f8f8b91e 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,7 +4,7 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/python-securitycenter.git", - "sha": "553dfbb89f7e72ad280aaa5d59cc4a054aa1948e" + "sha": "e5d1aab799bc0c6f0f29eb26b3fdbd44aafe31a7" } }, { @@ -19,14 +19,14 @@ "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "18c5dbdb4ac8cf75d4d8174e7b4558f48e76f8a1" + "sha": "373861061648b5fe5e0ac4f8a38b32d639ee93e4" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "18c5dbdb4ac8cf75d4d8174e7b4558f48e76f8a1" + "sha": "373861061648b5fe5e0ac4f8a38b32d639ee93e4" } } ], From 8d37bea1658bda9a646277aca90b812ddeee5494 Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Wed, 30 Dec 2020 08:09:59 -0800 Subject: [PATCH 04/23] chore: add tar (#93) --- securitycenter-v1beta1-py.tar.gz | 0 synth.metadata | 3 ++- 2 files changed, 2 insertions(+), 1 deletion(-) create mode 100644 securitycenter-v1beta1-py.tar.gz diff --git a/securitycenter-v1beta1-py.tar.gz b/securitycenter-v1beta1-py.tar.gz new file mode 100644 index 00000000..e69de29b diff --git a/synth.metadata b/synth.metadata index f8f8b91e..4e9e0c76 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,7 +4,7 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/python-securitycenter.git", - "sha": "e5d1aab799bc0c6f0f29eb26b3fdbd44aafe31a7" + "sha": "7656848e706166a8e3b43a78b860a5979e3524e6" } }, { @@ -227,6 +227,7 @@ "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", + "securitycenter-v1beta1-py.tar.gz", "setup.cfg", "testing/.gitignore", "tests/unit/gapic/securitycenter_v1/__init__.py", From d26df73c0fe82e35f73c6ce8607475ac6279bde1 Mon Sep 17 00:00:00 2001 From: Justin Beckwith Date: Fri, 29 Jan 2021 08:14:00 -0800 Subject: [PATCH 05/23] build: migrate to flakybot (#100) --- .kokoro/test-samples.sh | 8 ++++---- .kokoro/trampoline_v2.sh | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.kokoro/test-samples.sh b/.kokoro/test-samples.sh index 32deb636..92115ca2 100755 --- a/.kokoro/test-samples.sh +++ b/.kokoro/test-samples.sh @@ -87,11 +87,11 @@ for file in samples/**/requirements.txt; do python3.6 -m nox -s "$RUN_TESTS_SESSION" EXIT=$? - # If this is a periodic build, send the test log to the Build Cop Bot. - # See https://github.com/googleapis/repo-automation-bots/tree/master/packages/buildcop. + # 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/buildcop - $KOKORO_GFILE_DIR/linux_amd64/buildcop + chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot + $KOKORO_GFILE_DIR/linux_amd64/flakybot fi if [[ $EXIT -ne 0 ]]; then diff --git a/.kokoro/trampoline_v2.sh b/.kokoro/trampoline_v2.sh index 719bcd5b..4af6cdc2 100755 --- a/.kokoro/trampoline_v2.sh +++ b/.kokoro/trampoline_v2.sh @@ -159,7 +159,7 @@ if [[ -n "${KOKORO_BUILD_ID:-}" ]]; then "KOKORO_GITHUB_COMMIT" "KOKORO_GITHUB_PULL_REQUEST_NUMBER" "KOKORO_GITHUB_PULL_REQUEST_COMMIT" - # For Build Cop Bot + # For FlakyBot "KOKORO_GITHUB_COMMIT_URL" "KOKORO_GITHUB_PULL_REQUEST_URL" ) From a43ec373571b2fbe92aa24fac81b32e04eed02d4 Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Mon, 8 Feb 2021 09:36:02 -0800 Subject: [PATCH 06/23] chore: update templates (#97) This PR was generated using Autosynth. :rainbow: Synth log will be available here: https://source.cloud.google.com/results/invocations/008ce5bf-87d6-4df6-a516-9e6d6ecebea4/targets - [ ] To automatically regenerate this PR, check this box. Source-Link: https://github.com/googleapis/synthtool/commit/41a4e56982620d3edcf110d76f4fcdfdec471ac8 Source-Link: https://github.com/googleapis/synthtool/commit/f15b57ccfd71106c2299e9b89835fe6e55015662 --- LICENSE | 7 ++++--- docs/_static/custom.css | 7 ++++++- securitycenter-v1beta1-py.tar.gz | 0 synth.metadata | 7 +++---- 4 files changed, 13 insertions(+), 8 deletions(-) delete mode 100644 securitycenter-v1beta1-py.tar.gz diff --git a/LICENSE b/LICENSE index a8ee855d..d6456956 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,7 @@ - Apache License + + Apache License Version 2.0, January 2004 - https://www.apache.org/licenses/ + http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION @@ -192,7 +193,7 @@ 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 + 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, diff --git a/docs/_static/custom.css b/docs/_static/custom.css index 0abaf229..bcd37bbd 100644 --- a/docs/_static/custom.css +++ b/docs/_static/custom.css @@ -1,4 +1,9 @@ div#python2-eol { border-color: red; border-width: medium; -} \ No newline at end of file +} + +/* Ensure minimum width for 'Parameters' / 'Returns' column */ +dl.field-list > dt { + min-width: 100px +} diff --git a/securitycenter-v1beta1-py.tar.gz b/securitycenter-v1beta1-py.tar.gz deleted file mode 100644 index e69de29b..00000000 diff --git a/synth.metadata b/synth.metadata index 4e9e0c76..cb1fa7e9 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,7 +4,7 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/python-securitycenter.git", - "sha": "7656848e706166a8e3b43a78b860a5979e3524e6" + "sha": "8d37bea1658bda9a646277aca90b812ddeee5494" } }, { @@ -19,14 +19,14 @@ "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "373861061648b5fe5e0ac4f8a38b32d639ee93e4" + "sha": "41a4e56982620d3edcf110d76f4fcdfdec471ac8" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "373861061648b5fe5e0ac4f8a38b32d639ee93e4" + "sha": "41a4e56982620d3edcf110d76f4fcdfdec471ac8" } } ], @@ -227,7 +227,6 @@ "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", - "securitycenter-v1beta1-py.tar.gz", "setup.cfg", "testing/.gitignore", "tests/unit/gapic/securitycenter_v1/__init__.py", From 4bdaa5f9e48d295ab1d85e3594c79ee78335f889 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Tue, 9 Feb 2021 17:54:53 +0100 Subject: [PATCH 07/23] chore(deps): update dependency google-cloud-pubsub to v2.3.0 (#102) --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index fcb6d25d..6bc8372b 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1,2 +1,2 @@ -google-cloud-pubsub==2.2.0 +google-cloud-pubsub==2.3.0 google-cloud-securitycenter==1.1.0 \ No newline at end of file From 5f2f22d28e7a463af5d8cc3c021d63b79532235b Mon Sep 17 00:00:00 2001 From: Bu Sun Kim <8822365+busunkim96@users.noreply.github.com> Date: Thu, 11 Feb 2021 10:34:02 -0700 Subject: [PATCH 08/23] chore: add constraints file (#94) Add constraints file to test lower bounds. These files will not be used until the noxfile is changed in googleapis/synthtool#869. --- testing/constraints-3.10.txt | 0 testing/constraints-3.11.txt | 0 testing/constraints-3.6.txt | 11 +++++++++++ testing/constraints-3.7.txt | 0 testing/constraints-3.8.txt | 0 testing/constraints-3.9.txt | 0 6 files changed, 11 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 00000000..e69de29b diff --git a/testing/constraints-3.11.txt b/testing/constraints-3.11.txt new file mode 100644 index 00000000..e69de29b diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt new file mode 100644 index 00000000..caba91f9 --- /dev/null +++ b/testing/constraints-3.6.txt @@ -0,0 +1,11 @@ +# 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.0 +grpc-google-iam-v1==0.12.3 +proto-plus==1.10.0 +libcst==0.2.5 \ No newline at end of file diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt new file mode 100644 index 00000000..e69de29b diff --git a/testing/constraints-3.8.txt b/testing/constraints-3.8.txt new file mode 100644 index 00000000..e69de29b diff --git a/testing/constraints-3.9.txt b/testing/constraints-3.9.txt new file mode 100644 index 00000000..e69de29b From 55582acd814f7cd290580d5caa531725d2ff58b8 Mon Sep 17 00:00:00 2001 From: Anthony Date: Thu, 18 Feb 2021 10:38:04 -0800 Subject: [PATCH 09/23] docs: standardize new tag with existing tags from other languages (#104) Updates the tags to be identical to the tag most-used in other language-repos. This is the final step in wrangling all the cats into logical groupings of identical tags. Cleans up and finalizes work started in PR #85. --- samples/snippets/snippets_findings.py | 28 ++++++++++----------- samples/snippets/snippets_list_assets.py | 16 ++++++------ samples/snippets/snippets_orgs.py | 4 +-- samples/snippets/snippets_security_marks.py | 24 +++++++++--------- 4 files changed, 36 insertions(+), 36 deletions(-) diff --git a/samples/snippets/snippets_findings.py b/samples/snippets/snippets_findings.py index eba61f59..92175b05 100644 --- a/samples/snippets/snippets_findings.py +++ b/samples/snippets/snippets_findings.py @@ -97,7 +97,7 @@ def update_source(source_name): def add_user_to_source(source_name): """Gives a user findingsEditor permission to the source.""" user_email = "csccclienttest@gmail.com" - # [START securitycenter_update_source_iam] + # [START securitycenter_set_source_iam] # [START update_source_iam] from google.cloud import securitycenter from google.iam.v1 import policy_pb2 @@ -132,7 +132,7 @@ def add_user_to_source(source_name): print("Updated Policy: {}".format(updated)) # [END update_source_iam] - # [END securitycenter_update_source_iam] + # [END securitycenter_set_source_iam] return binding, updated @@ -210,7 +210,7 @@ def create_finding(source_name): def create_finding_with_source_properties(source_name): """Demonstrate creating a new finding with source properties. """ - # [START securitycenter_create_finding_with_properties] + # [START securitycenter_create_finding_with_source_properties] # [START create_finding_with_properties] import datetime @@ -262,11 +262,11 @@ def create_finding_with_source_properties(source_name): ) print(created_finding) # [END create_finding_with_properties] - # [END securitycenter_create_finding_with_properties] + # [END securitycenter_create_finding_with_source_properties] def update_finding(source_name): - # [START securitycenter_update_finding] + # [START securitycenter_update_finding_source_properties] # [START update_finding] import datetime @@ -310,7 +310,7 @@ def update_finding(source_name): ) ) # [END update_finding] - # [END securitycenter_update_finding] + # [END securitycenter_update_finding_source_properties] def update_finding_state(source_name): @@ -347,7 +347,7 @@ def update_finding_state(source_name): def trouble_shoot(source_name): """Demonstrate calling test_iam_permissions to determine if the service account has the correct permisions.""" - # [START securitycenter_test_iam_permissions] + # [START securitycenter_test_iam] # [START test_iam_permissions] from google.cloud import securitycenter @@ -374,9 +374,9 @@ def trouble_shoot(source_name): ) ) # [END test_iam_permissions] - # [END securitycenter_test_iam_permissions] + # [END securitycenter_test_iam] assert len(permission_response.permissions) > 0 - # [START securitycenter_test_iam_permissions] + # [START securitycenter_test_iam] # [START test_iam_permissions] # Check for permissions necessary to call set_finding_state. permission_response = client.test_iam_permissions( @@ -389,7 +389,7 @@ def trouble_shoot(source_name): "Permision to update state? {}".format(len(permission_response.permissions) > 0) ) # [END test_iam_permissions] - # [END securitycenter_test_iam_permissions] + # [END securitycenter_test_iam] return permission_response assert len(permission_response.permissions) > 0 @@ -453,7 +453,7 @@ def list_filtered_findings(source_name): def list_findings_at_time(source_name): - # [START securitycenter_list_findings_at_a_time] + # [START securitycenter_list_findings_at_time] # [START list_findings_at_a_time] from google.cloud import securitycenter from datetime import timedelta, datetime @@ -471,9 +471,9 @@ def list_findings_at_time(source_name): # source_name = "organizations/111122222444/sources/-" five_days_ago = str(datetime.now() - timedelta(days=5)) # [END list_findings_at_a_time] - # [END securitycenter_list_findings_at_a_time] + # [END securitycenter_list_findings_at_time] i = -1 - # [START securitycenter_list_findings_at_a_time] + # [START securitycenter_list_findings_at_time] # [START list_findings_at_a_time] finding_result_iterator = client.list_findings( @@ -486,7 +486,7 @@ def list_findings_at_time(source_name): ) ) # [END list_findings_at_a_time] - # [END securitycenter_list_findings_at_a_time] + # [END securitycenter_list_findings_at_time] return i diff --git a/samples/snippets/snippets_list_assets.py b/samples/snippets/snippets_list_assets.py index f4cac878..7665ea01 100644 --- a/samples/snippets/snippets_list_assets.py +++ b/samples/snippets/snippets_list_assets.py @@ -20,7 +20,7 @@ def list_all_assets(organization_id): """Demonstrate listing and printing all assets.""" i = 0 - # [START securitycenter_demo_list_all_assets] + # [START securitycenter_list_all_assets] # [START demo_list_all_assets] from google.cloud import securitycenter @@ -34,14 +34,14 @@ def list_all_assets(organization_id): for i, asset_result in enumerate(asset_iterator): print(i, asset_result) # [END demo_list_all_assets] - # [END securitycenter_demo_list_all_assets] + # [END securitycenter_list_all_assets] return i def list_assets_with_filters(organization_id): """Demonstrate listing assets with a filter.""" i = 0 - # [START securitycenter_demo_list_assets_with_filter] + # [START securitycenter_list_assets_with_filter] # [START demo_list_assets_with_filter] from google.cloud import securitycenter @@ -62,14 +62,14 @@ def list_assets_with_filters(organization_id): for i, asset_result in enumerate(asset_iterator): print(i, asset_result) # [END demo_list_assets_with_filter] - # [END securitycenter_demo_list_assets_with_filter] + # [END securitycenter_list_assets_with_filter] return i def list_assets_with_filters_and_read_time(organization_id): """Demonstrate listing assets with a filter.""" i = 0 - # [START securitycenter_demo_list_assets_with_filter_and_time] + # [START securitycenter_list_assets_at_time] # [START demo_list_assets_with_filter_and_time] from datetime import datetime, timedelta @@ -100,14 +100,14 @@ def list_assets_with_filters_and_read_time(organization_id): for i, asset_result in enumerate(asset_iterator): print(i, asset_result) # [END demo_list_assets_with_filter_and_time] - # [END securitycenter_demo_list_assets_with_filter_and_time] + # [END securitycenter_list_assets_at_time] return i def list_point_in_time_changes(organization_id): """Demonstrate listing assets along with their state changes.""" i = 0 - # [START securitycenter_demo_list_assets_changes] + # [START securitycenter_list_assets_and_changes] # [START demo_list_assets_changes] from datetime import timedelta @@ -138,7 +138,7 @@ def list_point_in_time_changes(organization_id): print(i, asset) # [END demo_list_assets_changes] - # [END securitycenter_demo_list_assets_changes] + # [END securitycenter_list_assets_and_changes] return i diff --git a/samples/snippets/snippets_orgs.py b/samples/snippets/snippets_orgs.py index e66b6f52..b155d768 100644 --- a/samples/snippets/snippets_orgs.py +++ b/samples/snippets/snippets_orgs.py @@ -37,7 +37,7 @@ def get_settings(organization_id): def update_asset_discovery_org_settings(organization_id): """Example showing how to update the asset discovery configuration for an organization.""" - # [START securitycenter_update_org_settings] + # [START securitycenter_enable_asset_discovery] # [START update_org_settings] from google.cloud import securitycenter from google.protobuf import field_mask_pb2 @@ -63,5 +63,5 @@ def update_asset_discovery_org_settings(organization_id): ) print("Asset Discovery Enabled? {}".format(updated.enable_asset_discovery)) # [END update_org_settings] - # [END securitycenter_update_org_settings] + # [END securitycenter_enable_asset_discovery] return updated diff --git a/samples/snippets/snippets_security_marks.py b/samples/snippets/snippets_security_marks.py index 1009eb02..ab1a1bd9 100644 --- a/samples/snippets/snippets_security_marks.py +++ b/samples/snippets/snippets_security_marks.py @@ -18,7 +18,7 @@ def add_to_asset(asset_name): """Add new security marks to an asset.""" - # [START securitycenter_add_marks_to_asset] + # [START securitycenter_add_security_marks] # [START add_marks_to_asset] from google.cloud import securitycenter from google.protobuf import field_mask_pb2 @@ -45,7 +45,7 @@ def add_to_asset(asset_name): ) print(updated_marks) # [END add_marks_to_asset] - # [END securitycenter_add_marks_to_asset] + # [END securitycenter_add_security_marks] return updated_marks, marks @@ -53,7 +53,7 @@ def clear_from_asset(asset_name): """Removes security marks from an asset.""" # Make sure they are there first add_to_asset(asset_name) - # [START securitycenter_clear_marks_asset] + # [START securitycenter_delete_security_marks] # [START clear_marks_asset] from google.cloud import securitycenter from google.protobuf import field_mask_pb2 @@ -81,7 +81,7 @@ def clear_from_asset(asset_name): ) print(updated_marks) # [END clear_marks_asset] - # [END securitycenter_clear_marks_asset] + # [END securitycenter_delete_security_marks] return updated_marks @@ -89,7 +89,7 @@ def delete_and_update_marks(asset_name): """Updates and deletes security marks from an asset in the same call.""" # Make sure they are there first add_to_asset(asset_name) - # [START securitycenter_delete_and_update_marks] + # [START securitycenter_add_delete_security_marks] # [START delete_and_update_marks] from google.cloud import securitycenter from google.protobuf import field_mask_pb2 @@ -112,13 +112,13 @@ def delete_and_update_marks(asset_name): ) print(updated_marks) # [END delete_and_update_marks] - # [END securitycenter_delete_and_update_marks] + # [END securitycenter_add_delete_security_marks] return updated_marks def add_to_finding(finding_name): """Adds security marks to a finding. """ - # [START securitycenter_add_marks_to_finding] + # [START securitycenter_add_security_marks] # [START add_marks_to_finding] from google.cloud import securitycenter from google.protobuf import field_mask_pb2 @@ -145,7 +145,7 @@ def add_to_finding(finding_name): } ) # [END add_marks_to_finding] - # [END securitycenter_add_marks_to_finding] + # [END securitycenter_add_security_marks] return updated_marks, marks @@ -153,7 +153,7 @@ def list_assets_with_query_marks(organization_id, asset_name): """Lists assets with a filter on security marks. """ add_to_asset(asset_name) i = -1 - # [START securitycenter_demo_list_assets_with_security_marks] + # [START securitycenter_list_assets_with_security_marks] # [START demo_list_assets_with_security_marks] from google.cloud import securitycenter @@ -176,7 +176,7 @@ def list_assets_with_query_marks(organization_id, asset_name): for i, asset_result in enumerate(asset_iterator): print(i, asset_result) # [END demo_list_assets_with_security_marks] - # [END securitycenter_demo_list_assets_with_security_marks] + # [END securitycenter_list_assets_with_security_marks] return i @@ -185,7 +185,7 @@ def list_findings_with_query_marks(source_name, finding_name): # ensure marks are set on finding. add_to_finding(finding_name) i = -1 - # [START securitycenter_demo_list_findings_with_security_marks] + # [START securitycenter_list_findings_with_security_marks] # [START demo_list_findings_with_security_marks] from google.cloud import securitycenter @@ -206,7 +206,7 @@ def list_findings_with_query_marks(source_name, finding_name): for i, finding_result in enumerate(finding_iterator): print(i, finding_result) # [END demo_list_findings_with_security_marks] - # [END securitycenter_demo_list_findings_with_security_marks] + # [END securitycenter_list_findings_with_security_marks] # one finding should have been updated with keys, and one should be # untouched. return i From 0c416509586bc48f3c12ba648ea8c7b8ace7a56a Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Wed, 24 Feb 2021 05:41:24 +0100 Subject: [PATCH 10/23] chore(deps): update dependency google-cloud-pubsub to v2.4.0 (#107) --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 6bc8372b..7a1ca63f 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1,2 +1,2 @@ -google-cloud-pubsub==2.3.0 +google-cloud-pubsub==2.4.0 google-cloud-securitycenter==1.1.0 \ No newline at end of file From f4f14ee32602aad7b7a4837e330919b4276d7b18 Mon Sep 17 00:00:00 2001 From: Anthony Date: Wed, 24 Feb 2021 12:25:30 -0800 Subject: [PATCH 11/23] docs: Fix conflict tag introduced in PR 104 (#106) * add securitycenter prefix to samples, wrap published samples and replace unpublished entirely. * Fix unmatched region tags * Fix more unmatched region tags * fix lint issue with function antipattern * docs: standardize new tags with most-used tag from other languages * fix conflicting tag by making more explicit to the contained function --- samples/snippets/snippets_security_marks.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/snippets/snippets_security_marks.py b/samples/snippets/snippets_security_marks.py index ab1a1bd9..7a3de409 100644 --- a/samples/snippets/snippets_security_marks.py +++ b/samples/snippets/snippets_security_marks.py @@ -118,7 +118,7 @@ def delete_and_update_marks(asset_name): def add_to_finding(finding_name): """Adds security marks to a finding. """ - # [START securitycenter_add_security_marks] + # [START securitycenter_add_finding_security_marks] # [START add_marks_to_finding] from google.cloud import securitycenter from google.protobuf import field_mask_pb2 @@ -145,7 +145,7 @@ def add_to_finding(finding_name): } ) # [END add_marks_to_finding] - # [END securitycenter_add_security_marks] + # [END securitycenter_add_finding_security_marks] return updated_marks, marks From 6df8799bd7122e24aa9b5ef10a093fe3f1ffd5b2 Mon Sep 17 00:00:00 2001 From: Bu Sun Kim <8822365+busunkim96@users.noreply.github.com> Date: Tue, 2 Mar 2021 23:53:07 -0700 Subject: [PATCH 12/23] chore: require samples checks (#80) Co-authored-by: Leah E. Cole <6719667+leahecole@users.noreply.github.com> --- .github/sync-repo-settings.yaml | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 .github/sync-repo-settings.yaml diff --git a/.github/sync-repo-settings.yaml b/.github/sync-repo-settings.yaml new file mode 100644 index 00000000..af599353 --- /dev/null +++ b/.github/sync-repo-settings.yaml @@ -0,0 +1,13 @@ +# https://github.com/googleapis/repo-automation-bots/tree/master/packages/sync-repo-settings +# Rules for master branch protection +branchProtectionRules: +# Identifies the protection rule pattern. Name of the branch to be protected. +# Defaults to `master` +- pattern: master + requiredStatusCheckContexts: + - 'Kokoro' + - 'cla/google' + - 'Samples - Lint' + - 'Samples - Python 3.6' + - 'Samples - Python 3.7' + - 'Samples - Python 3.8' From 970174efea1476bd548523d7dc3154922ba34294 Mon Sep 17 00:00:00 2001 From: Bu Sun Kim <8822365+busunkim96@users.noreply.github.com> Date: Thu, 18 Mar 2021 03:30:01 -0600 Subject: [PATCH 13/23] chore: cleanup synth.py (#111) --- synth.py | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/synth.py b/synth.py index d3514f3b..b5771bae 100644 --- a/synth.py +++ b/synth.py @@ -34,13 +34,6 @@ s.move(library, excludes=["README.rst", "docs/index.rst", "setup.py"]) -# TODO(busunkim): Remove once https://github.com/googleapis/gapic-generator-python/pull/555 is merged -s.replace( - "google/**/base.py", - """from google\.api_core import gapic_v1\s+# type: ignore""", - """from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore""", -) # fix bad indentation s.replace( @@ -51,10 +44,6 @@ \g<1>If empty all mutable fields will be updated.""", ) -# fix bulleted lists -s.replace("google/**/*client.py", "\- state_change", "- state_change\n") -s.replace("google/**/*client.py", "\- parent", "- parent\n") - # ---------------------------------------------------------------------------- # Add templated files # ---------------------------------------------------------------------------- From 25c5693599360cab02707997c570838579d7b57f Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Thu, 18 Mar 2021 10:34:02 +0100 Subject: [PATCH 14/23] chore(deps): update precommit hook pycqa/flake8 to v3.9.0 (#110) [![WhiteSource Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Type | Update | Change | |---|---|---|---| | [pycqa/flake8](https://gitlab.com/pycqa/flake8) | repository | minor | `3.8.4` -> `3.9.0` | --- ### Release Notes
pycqa/flake8 ### [`v3.9.0`](https://gitlab.com/pycqa/flake8/compare/3.8.4...3.9.0) [Compare Source](https://gitlab.com/pycqa/flake8/compare/3.8.4...3.9.0)
--- ### Renovate configuration :date: **Schedule**: At any time (no schedule defined). :vertical_traffic_light: **Automerge**: Disabled by config. Please merge this manually once you are satisfied. :recycle: **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. :no_bell: **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/python-securitycenter). --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a9024b15..32302e48 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 From 15c28e88f5b52a6e4f608198446b0753bf48734e Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Tue, 30 Mar 2021 12:19:49 -0700 Subject: [PATCH 15/23] fix: fix retry deadlines (#116) * changes without context autosynth cannot find the source of changes triggered by earlier changes in this repository, or by version upgrades to tools such as linters. * chore: upgrade gapic-generator-python to 0.39.1 feat: add 'from_service_account_info' factory to clients fix: fix sphinx identifiers PiperOrigin-RevId: 350246057 Source-Author: Google APIs Source-Date: Tue Jan 5 16:44:11 2021 -0800 Source-Repo: googleapis/googleapis Source-Sha: 520682435235d9c503983a360a2090025aa47cd1 Source-Link: https://github.com/googleapis/googleapis/commit/520682435235d9c503983a360a2090025aa47cd1 * chore: update Go generator, rules_go, and protobuf PiperOrigin-RevId: 352816749 Source-Author: Google APIs Source-Date: Wed Jan 20 10:06:23 2021 -0800 Source-Repo: googleapis/googleapis Source-Sha: ceaaf31b3d13badab7cf9d3b570f5639db5593d9 Source-Link: https://github.com/googleapis/googleapis/commit/ceaaf31b3d13badab7cf9d3b570f5639db5593d9 * chore: upgrade gapic-generator-python to 0.40.5 PiperOrigin-RevId: 354996675 Source-Author: Google APIs Source-Date: Mon Feb 1 12:11:49 2021 -0800 Source-Repo: googleapis/googleapis Source-Sha: 20712b8fe95001b312f62c6c5f33e3e3ec92cfaf Source-Link: https://github.com/googleapis/googleapis/commit/20712b8fe95001b312f62c6c5f33e3e3ec92cfaf * chore: update gapic-generator-python PiperOrigin-RevId: 355923884 Source-Author: Google APIs Source-Date: Fri Feb 5 14:04:52 2021 -0800 Source-Repo: googleapis/googleapis Source-Sha: 5e3dacee19405529b841b53797df799c2383536c Source-Link: https://github.com/googleapis/googleapis/commit/5e3dacee19405529b841b53797df799c2383536c * chore: update gapic-generator-python to 0.40.11 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 * chore: upgrade gapic-generator-python to 0.42.2 PiperOrigin-RevId: 361662015 Source-Author: Google APIs Source-Date: Mon Mar 8 14:47:18 2021 -0800 Source-Repo: googleapis/googleapis Source-Sha: 28a591963253d52ce3a25a918cafbdd9928de8cf Source-Link: https://github.com/googleapis/googleapis/commit/28a591963253d52ce3a25a918cafbdd9928de8cf * chore: upgrade gapic-generator-python to 0.43.1 PiperOrigin-RevId: 364411656 Source-Author: Google APIs Source-Date: Mon Mar 22 14:40:22 2021 -0700 Source-Repo: googleapis/googleapis Source-Sha: 149a3a84c29c9b8189576c7442ccb6dcf6a8f95b Source-Link: https://github.com/googleapis/googleapis/commit/149a3a84c29c9b8189576c7442ccb6dcf6a8f95b * fix: fix dependencies Co-authored-by: Bu Sun Kim --- .coveragerc | 5 +- .github/header-checker-lint.yml | 15 + .gitignore | 4 +- .kokoro/build.sh | 26 +- .kokoro/docs/docs-presubmit.cfg | 11 + .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 +-- .trampolinerc | 1 + CONTRIBUTING.rst | 22 +- MANIFEST.in | 4 +- UPGRADING.md | 6 +- docs/securitycenter_v1/security_center.rst | 11 + docs/securitycenter_v1/services.rst | 6 +- docs/securitycenter_v1/types.rst | 1 + .../security_center.rst | 11 + docs/securitycenter_v1beta1/services.rst | 6 +- docs/securitycenter_v1beta1/types.rst | 1 + .../security_center.rst | 11 + docs/securitycenter_v1p1beta1/services.rst | 6 +- docs/securitycenter_v1p1beta1/types.rst | 1 + .../services/security_center/async_client.py | 430 +++++++------ .../services/security_center/client.py | 504 ++++++++------- .../services/security_center/pagers.py | 107 ++-- .../security_center/transports/base.py | 30 +- .../security_center/transports/grpc.py | 114 ++-- .../transports/grpc_asyncio.py | 122 ++-- .../cloud/securitycenter_v1/types/__init__.py | 36 +- google/cloud/securitycenter_v1/types/asset.py | 12 +- .../cloud/securitycenter_v1/types/finding.py | 12 +- .../types/notification_config.py | 2 +- .../types/notification_message.py | 4 +- .../types/organization_settings.py | 4 +- .../types/run_asset_discovery_response.py | 4 +- .../securitycenter_v1/types/security_marks.py | 2 +- .../types/securitycenter_service.py | 84 +-- .../services/security_center/async_client.py | 415 ++++++------ .../services/security_center/client.py | 481 +++++++------- .../services/security_center/pagers.py | 91 +-- .../security_center/transports/base.py | 28 +- .../security_center/transports/grpc.py | 114 ++-- .../transports/grpc_asyncio.py | 122 ++-- .../securitycenter_v1beta1/types/__init__.py | 24 +- .../securitycenter_v1beta1/types/asset.py | 10 +- .../securitycenter_v1beta1/types/finding.py | 10 +- .../types/organization_settings.py | 4 +- .../types/run_asset_discovery_response.py | 4 +- .../types/security_marks.py | 2 +- .../types/securitycenter_service.py | 66 +- .../services/security_center/async_client.py | 441 +++++++------ .../services/security_center/client.py | 519 ++++++++------- .../services/security_center/pagers.py | 107 ++-- .../security_center/transports/base.py | 30 +- .../security_center/transports/grpc.py | 114 ++-- .../transports/grpc_asyncio.py | 122 ++-- .../types/__init__.py | 36 +- .../securitycenter_v1p1beta1/types/asset.py | 12 +- .../securitycenter_v1p1beta1/types/finding.py | 12 +- .../types/notification_config.py | 4 +- .../types/notification_message.py | 4 +- .../types/organization_settings.py | 4 +- .../types/run_asset_discovery_response.py | 4 +- .../types/security_marks.py | 2 +- .../types/securitycenter_service.py | 84 +-- noxfile.py | 59 +- renovate.json | 3 +- samples/snippets/noxfile.py | 2 +- setup.py | 5 +- synth.metadata | 189 +----- synth.py | 2 +- testing/constraints-3.6.txt | 4 +- .../unit/gapic/securitycenter_v1/__init__.py | 15 + .../securitycenter_v1/test_security_center.py | 606 +++++++++++++++--- .../gapic/securitycenter_v1beta1/__init__.py | 15 + .../test_security_center.py | 516 ++++++++++++--- .../securitycenter_v1p1beta1/__init__.py | 15 + .../test_security_center.py | 606 +++++++++++++++--- 80 files changed, 4151 insertions(+), 2626 deletions(-) create mode 100644 .github/header-checker-lint.yml 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 create mode 100644 docs/securitycenter_v1/security_center.rst create mode 100644 docs/securitycenter_v1beta1/security_center.rst create mode 100644 docs/securitycenter_v1p1beta1/security_center.rst diff --git a/.coveragerc b/.coveragerc index 2f4aeed0..f9eb6a20 100644 --- a/.coveragerc +++ b/.coveragerc @@ -4,7 +4,8 @@ branch = True [report] fail_under = 100 show_missing = True -omit = google/cloud/securitycenter/__init__.py +omit = + google/cloud/securitycenter/__init__.py exclude_lines = # Re-enable the standard pragma pragma: NO COVER @@ -14,4 +15,4 @@ exclude_lines = # This is added at the module level as a safeguard for if someone # generates the code and tries to run it without pip installing. This # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound \ No newline at end of file + except pkg_resources.DistributionNotFound diff --git a/.github/header-checker-lint.yml b/.github/header-checker-lint.yml new file mode 100644 index 00000000..fc281c05 --- /dev/null +++ b/.github/header-checker-lint.yml @@ -0,0 +1,15 @@ +{"allowedCopyrightHolders": ["Google LLC"], + "allowedLicenses": ["Apache-2.0", "MIT", "BSD-3"], + "ignoreFiles": ["**/requirements.txt", "**/requirements-test.txt"], + "sourceFileExtensions": [ + "ts", + "js", + "java", + "sh", + "Dockerfile", + "yaml", + "py", + "html", + "txt" + ] +} \ No newline at end of file diff --git a/.gitignore b/.gitignore index b9daa52f..b4243ced 100644 --- a/.gitignore +++ b/.gitignore @@ -50,8 +50,10 @@ docs.metadata # Virtual environment env/ + +# Test logs coverage.xml -sponge_log.xml +*sponge_log.xml # System test environment variables. system_tests/local_test_setup diff --git a/.kokoro/build.sh b/.kokoro/build.sh index 662b06bc..3b55f5c8 100755 --- a/.kokoro/build.sh +++ b/.kokoro/build.sh @@ -15,7 +15,11 @@ set -eo pipefail -cd github/python-securitycenter +if [[ -z "${PROJECT_ROOT:-}" ]]; then + PROJECT_ROOT="github/python-securitycenter" +fi + +cd "${PROJECT_ROOT}" # Disable buffering, so that the logs stream through. export PYTHONUNBUFFERED=1 @@ -30,16 +34,26 @@ export GOOGLE_APPLICATION_CREDENTIALS=${KOKORO_GFILE_DIR}/service-account.json export PROJECT_ID=$(cat "${KOKORO_GFILE_DIR}/project-id.json") # Remove old nox -python3.6 -m pip uninstall --yes --quiet nox-automation +python3 -m pip uninstall --yes --quiet nox-automation # Install nox -python3.6 -m pip install --upgrade --quiet nox -python3.6 -m nox --version +python3 -m pip install --upgrade --quiet nox +python3 -m nox --version + +# If this is a continuous 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 = *"continuous"* ]]; then + cleanup() { + chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot + $KOKORO_GFILE_DIR/linux_amd64/flakybot + } + trap cleanup EXIT HUP +fi # If NOX_SESSION is set, it only runs the specified session, # otherwise run all the sessions. if [[ -n "${NOX_SESSION:-}" ]]; then - python3.6 -m nox -s "${NOX_SESSION:-}" + python3 -m nox -s ${NOX_SESSION:-} else - python3.6 -m nox + python3 -m nox fi diff --git a/.kokoro/docs/docs-presubmit.cfg b/.kokoro/docs/docs-presubmit.cfg index 11181078..5713bf2f 100644 --- a/.kokoro/docs/docs-presubmit.cfg +++ b/.kokoro/docs/docs-presubmit.cfg @@ -15,3 +15,14 @@ env_vars: { key: "TRAMPOLINE_IMAGE_UPLOAD" value: "false" } + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-securitycenter/.kokoro/build.sh" +} + +# Only run this nox session. +env_vars: { + key: "NOX_SESSION" + value: "docs docfx" +} diff --git a/.kokoro/samples/python3.6/periodic-head.cfg b/.kokoro/samples/python3.6/periodic-head.cfg new file mode 100644 index 00000000..f9cfcd33 --- /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 00000000..f9cfcd33 --- /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 00000000..f9cfcd33 --- /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 00000000..8df9b139 --- /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-securitycenter + +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 00000000..cf5de74c --- /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 92115ca2..348ce519 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-securitycenter # 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/.trampolinerc b/.trampolinerc index 995ee291..383b6ec8 100644 --- a/.trampolinerc +++ b/.trampolinerc @@ -24,6 +24,7 @@ required_envvars+=( pass_down_envvars+=( "STAGING_BUCKET" "V2_STAGING_BUCKET" + "NOX_SESSION" ) # Prevent unintentional override on the default image. diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 373badc1..d5b4b7f3 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -70,9 +70,14 @@ We use `nox `__ to instrument our tests. - To test your changes, run unit tests with ``nox``:: $ nox -s unit-2.7 - $ nox -s unit-3.7 + $ nox -s unit-3.8 $ ... +- Args to pytest can be passed through the nox command separated by a `--`. For + example, to run a single test:: + + $ nox -s unit-3.8 -- -k + .. note:: The unit tests and system tests are described in the @@ -93,8 +98,12 @@ On Debian/Ubuntu:: ************ Coding Style ************ +- We use the automatic code formatter ``black``. You can run it using + the nox session ``blacken``. This will eliminate many lint errors. Run via:: + + $ nox -s blacken -- PEP8 compliance, with exceptions defined in the linter configuration. +- PEP8 compliance is required, with exceptions defined in the linter configuration. If you have ``nox`` installed, you can test that you have not introduced any non-compliant code via:: @@ -133,13 +142,18 @@ Running System Tests - To run system tests, you can execute:: - $ nox -s system-3.7 + # Run all system tests + $ nox -s system-3.8 $ nox -s system-2.7 + # Run a single system test + $ nox -s system-3.8 -- -k + + .. note:: System tests are only configured to run under Python 2.7 and - Python 3.7. For expediency, we do not run them in older versions + Python 3.8. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local diff --git a/MANIFEST.in b/MANIFEST.in index e9e29d12..e783f4c6 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -16,10 +16,10 @@ # Generated by synthtool. DO NOT EDIT! include README.rst LICENSE -recursive-include google *.json *.proto +recursive-include google *.json *.proto py.typed recursive-include tests * global-exclude *.py[co] global-exclude __pycache__ # Exclude scripts for samples readmegen -prune scripts/readme-gen \ No newline at end of file +prune scripts/readme-gen diff --git a/UPGRADING.md b/UPGRADING.md index 15a2ee0c..dec82d7d 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -17,10 +17,10 @@ The 1.0.0 release requires Python 3.6+. Methods expect request objects. We provide a script that will convert most common use cases. -* Install the library +* Install the library with `libcst`. ```py -python3 -m pip install google-cloud-securitycenter +python3 -m pip install google-cloud-securitycenter[libcst] ``` * The script `fixup_securitycenter_v1_keywords.py` is shipped with the library. It expects @@ -50,7 +50,7 @@ client = securitycenter.securitycenterClient() assets = client.list_assets( request={ - "org_name": org_name, + "org_name": org_name, "filter_:": project_filter, "read_time": timestamp_proto } diff --git a/docs/securitycenter_v1/security_center.rst b/docs/securitycenter_v1/security_center.rst new file mode 100644 index 00000000..0d7d0e97 --- /dev/null +++ b/docs/securitycenter_v1/security_center.rst @@ -0,0 +1,11 @@ +SecurityCenter +-------------------------------- + +.. automodule:: google.cloud.securitycenter_v1.services.security_center + :members: + :inherited-members: + + +.. automodule:: google.cloud.securitycenter_v1.services.security_center.pagers + :members: + :inherited-members: diff --git a/docs/securitycenter_v1/services.rst b/docs/securitycenter_v1/services.rst index d1a1378e..295acede 100644 --- a/docs/securitycenter_v1/services.rst +++ b/docs/securitycenter_v1/services.rst @@ -1,6 +1,6 @@ Services for Google Cloud Securitycenter v1 API =============================================== +.. toctree:: + :maxdepth: 2 -.. automodule:: google.cloud.securitycenter_v1.services.security_center - :members: - :inherited-members: + security_center diff --git a/docs/securitycenter_v1/types.rst b/docs/securitycenter_v1/types.rst index f7497757..460aec08 100644 --- a/docs/securitycenter_v1/types.rst +++ b/docs/securitycenter_v1/types.rst @@ -3,4 +3,5 @@ Types for Google Cloud Securitycenter v1 API .. automodule:: google.cloud.securitycenter_v1.types :members: + :undoc-members: :show-inheritance: diff --git a/docs/securitycenter_v1beta1/security_center.rst b/docs/securitycenter_v1beta1/security_center.rst new file mode 100644 index 00000000..f7b00994 --- /dev/null +++ b/docs/securitycenter_v1beta1/security_center.rst @@ -0,0 +1,11 @@ +SecurityCenter +-------------------------------- + +.. automodule:: google.cloud.securitycenter_v1beta1.services.security_center + :members: + :inherited-members: + + +.. automodule:: google.cloud.securitycenter_v1beta1.services.security_center.pagers + :members: + :inherited-members: diff --git a/docs/securitycenter_v1beta1/services.rst b/docs/securitycenter_v1beta1/services.rst index 212796c8..a09a4b86 100644 --- a/docs/securitycenter_v1beta1/services.rst +++ b/docs/securitycenter_v1beta1/services.rst @@ -1,6 +1,6 @@ Services for Google Cloud Securitycenter v1beta1 API ==================================================== +.. toctree:: + :maxdepth: 2 -.. automodule:: google.cloud.securitycenter_v1beta1.services.security_center - :members: - :inherited-members: + security_center diff --git a/docs/securitycenter_v1beta1/types.rst b/docs/securitycenter_v1beta1/types.rst index 0bbeba06..44bb4fec 100644 --- a/docs/securitycenter_v1beta1/types.rst +++ b/docs/securitycenter_v1beta1/types.rst @@ -3,4 +3,5 @@ Types for Google Cloud Securitycenter v1beta1 API .. automodule:: google.cloud.securitycenter_v1beta1.types :members: + :undoc-members: :show-inheritance: diff --git a/docs/securitycenter_v1p1beta1/security_center.rst b/docs/securitycenter_v1p1beta1/security_center.rst new file mode 100644 index 00000000..afda133c --- /dev/null +++ b/docs/securitycenter_v1p1beta1/security_center.rst @@ -0,0 +1,11 @@ +SecurityCenter +-------------------------------- + +.. automodule:: google.cloud.securitycenter_v1p1beta1.services.security_center + :members: + :inherited-members: + + +.. automodule:: google.cloud.securitycenter_v1p1beta1.services.security_center.pagers + :members: + :inherited-members: diff --git a/docs/securitycenter_v1p1beta1/services.rst b/docs/securitycenter_v1p1beta1/services.rst index 5034b831..7f537e85 100644 --- a/docs/securitycenter_v1p1beta1/services.rst +++ b/docs/securitycenter_v1p1beta1/services.rst @@ -1,6 +1,6 @@ Services for Google Cloud Securitycenter v1p1beta1 API ====================================================== +.. toctree:: + :maxdepth: 2 -.. automodule:: google.cloud.securitycenter_v1p1beta1.services.security_center - :members: - :inherited-members: + security_center diff --git a/docs/securitycenter_v1p1beta1/types.rst b/docs/securitycenter_v1p1beta1/types.rst index a68ac5c6..1facc905 100644 --- a/docs/securitycenter_v1p1beta1/types.rst +++ b/docs/securitycenter_v1p1beta1/types.rst @@ -3,4 +3,5 @@ Types for Google Cloud Securitycenter v1p1beta1 API .. automodule:: google.cloud.securitycenter_v1p1beta1.types :members: + :undoc-members: :show-inheritance: diff --git a/google/cloud/securitycenter_v1/services/security_center/async_client.py b/google/cloud/securitycenter_v1/services/security_center/async_client.py index b0b01027..644bdf4c 100644 --- a/google/cloud/securitycenter_v1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1/services/security_center/async_client.py @@ -120,7 +120,36 @@ class SecurityCenterAsyncClient: SecurityCenterClient.parse_common_location_path ) - from_service_account_file = SecurityCenterClient.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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, filename, *args, **kwargs) # type: ignore + from_service_account_json = from_service_account_file @property @@ -197,19 +226,21 @@ async def create_source( r"""Creates a source. Args: - request (:class:`~.securitycenter_service.CreateSourceRequest`): + request (:class:`google.cloud.securitycenter_v1.types.CreateSourceRequest`): The request object. Request message for creating a source. parent (:class:`str`): Required. Resource name of the new source's parent. Its format should be "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - source (:class:`~.gcs_source.Source`): + source (:class:`google.cloud.securitycenter_v1.types.Source`): Required. The Source being created, only the display_name and description will be used. All other fields will be ignored. + This corresponds to the ``source`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -221,7 +252,7 @@ async def create_source( sent along with the request as metadata. Returns: - ~.gcs_source.Source: + google.cloud.securitycenter_v1.types.Source: Security Command Center finding source. A finding source is an entity or a mechanism that can produce a finding. @@ -285,13 +316,14 @@ async def create_finding( exist for finding creation to succeed. Args: - request (:class:`~.securitycenter_service.CreateFindingRequest`): + request (:class:`google.cloud.securitycenter_v1.types.CreateFindingRequest`): The request object. Request message for creating a finding. parent (:class:`str`): Required. Resource name of the new finding's parent. Its format should be "organizations/[organization_id]/sources/[source_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -301,13 +333,15 @@ async def create_finding( It must be alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. + This corresponds to the ``finding_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - finding (:class:`~.gcs_finding.Finding`): + finding (:class:`google.cloud.securitycenter_v1.types.Finding`): Required. The Finding being created. The name and security_marks will be ignored as they are both output only fields on this resource. + This corresponds to the ``finding`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -319,7 +353,7 @@ async def create_finding( sent along with the request as metadata. Returns: - ~.gcs_finding.Finding: + google.cloud.securitycenter_v1.types.Finding: Security Command Center finding. A finding is a record of assessment data like security, risk, health, or privacy, @@ -387,12 +421,13 @@ async def create_notification_config( r"""Creates a notification config. Args: - request (:class:`~.securitycenter_service.CreateNotificationConfigRequest`): + request (:class:`google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest`): The request object. Request message for creating a notification config. parent (:class:`str`): Required. Resource name of the new notification config's parent. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -403,14 +438,16 @@ async def create_notification_config( between 1 and 128 characters, and contains alphanumeric characters, underscores or hyphens only. + This corresponds to the ``config_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - notification_config (:class:`~.gcs_notification_config.NotificationConfig`): + notification_config (:class:`google.cloud.securitycenter_v1.types.NotificationConfig`): Required. The notification config being created. The name and the service account will be ignored as they are both output only fields on this resource. + This corresponds to the ``notification_config`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -422,7 +459,7 @@ async def create_notification_config( sent along with the request as metadata. Returns: - ~.gcs_notification_config.NotificationConfig: + google.cloud.securitycenter_v1.types.NotificationConfig: Cloud Security Command Center (Cloud SCC) notification configs. A notification config is a Cloud SCC @@ -485,13 +522,14 @@ async def delete_notification_config( r"""Deletes a notification config. Args: - request (:class:`~.securitycenter_service.DeleteNotificationConfigRequest`): + request (:class:`google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest`): The request object. Request message for deleting a notification config. name (:class:`str`): Required. Name of the notification config to delete. Its format is "organizations/[organization_id]/notificationConfigs/[config_id]". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -552,7 +590,7 @@ async def get_iam_policy( Source. Args: - request (:class:`~.iam_policy.GetIamPolicyRequest`): + request (:class:`google.iam.v1.iam_policy_pb2.GetIamPolicyRequest`): The request object. Request message for `GetIamPolicy` method. resource (:class:`str`): @@ -560,6 +598,7 @@ async def get_iam_policy( policy is being requested. See the operation documentation for the appropriate value for this field. + This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -571,72 +610,62 @@ async def get_iam_policy( sent along with the request as metadata. Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). """ # Create or coerce a protobuf request object. @@ -668,6 +697,7 @@ async def get_iam_policy( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -697,13 +727,14 @@ async def get_notification_config( r"""Gets a notification config. Args: - request (:class:`~.securitycenter_service.GetNotificationConfigRequest`): + request (:class:`google.cloud.securitycenter_v1.types.GetNotificationConfigRequest`): The request object. Request message for getting a notification config. name (:class:`str`): Required. Name of the notification config to get. Its format is "organizations/[organization_id]/notificationConfigs/[config_id]". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -715,7 +746,7 @@ async def get_notification_config( sent along with the request as metadata. Returns: - ~.notification_config.NotificationConfig: + google.cloud.securitycenter_v1.types.NotificationConfig: Cloud Security Command Center (Cloud SCC) notification configs. A notification config is a Cloud SCC @@ -753,6 +784,7 @@ async def get_notification_config( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -782,13 +814,14 @@ async def get_organization_settings( r"""Gets the settings for an organization. Args: - request (:class:`~.securitycenter_service.GetOrganizationSettingsRequest`): + request (:class:`google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest`): The request object. Request message for getting organization settings. name (:class:`str`): Required. Name of the organization to get organization settings for. Its format is "organizations/[organization_id]/organizationSettings". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -800,7 +833,7 @@ async def get_organization_settings( sent along with the request as metadata. Returns: - ~.organization_settings.OrganizationSettings: + google.cloud.securitycenter_v1.types.OrganizationSettings: User specified settings that are attached to the Security Command Center organization. @@ -835,6 +868,7 @@ async def get_organization_settings( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -864,13 +898,14 @@ async def get_source( r"""Gets a source. Args: - request (:class:`~.securitycenter_service.GetSourceRequest`): + request (:class:`google.cloud.securitycenter_v1.types.GetSourceRequest`): The request object. Request message for getting a source. name (:class:`str`): Required. Relative resource name of the source. Its format is "organizations/[organization_id]/source/[source_id]". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -882,7 +917,7 @@ async def get_source( sent along with the request as metadata. Returns: - ~.source.Source: + google.cloud.securitycenter_v1.types.Source: Security Command Center finding source. A finding source is an entity or a mechanism that can produce a finding. @@ -920,6 +955,7 @@ async def get_source( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -949,7 +985,7 @@ async def group_assets( their specified properties. Args: - request (:class:`~.securitycenter_service.GroupAssetsRequest`): + request (:class:`google.cloud.securitycenter_v1.types.GroupAssetsRequest`): The request object. Request message for grouping by assets. @@ -960,7 +996,7 @@ async def group_assets( sent along with the request as metadata. Returns: - ~.pagers.GroupAssetsAsyncPager: + google.cloud.securitycenter_v1.services.security_center.pagers.GroupAssetsAsyncPager: Response message for grouping by assets. Iterating over this object will yield @@ -983,6 +1019,7 @@ async def group_assets( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=DEFAULT_CLIENT_INFO, @@ -1023,7 +1060,7 @@ async def group_findings( Example: /v1/organizations/{organization_id}/sources/-/findings Args: - request (:class:`~.securitycenter_service.GroupFindingsRequest`): + request (:class:`google.cloud.securitycenter_v1.types.GroupFindingsRequest`): The request object. Request message for grouping by findings. parent (:class:`str`): @@ -1032,6 +1069,7 @@ async def group_findings( To groupBy across all sources provide a source_id of ``-``. For example: organizations/{organization_id}/sources/- + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1046,8 +1084,7 @@ async def group_findings( - resource_name - category - state - - parent - + - parent - severity The following fields are supported when compare_duration @@ -1066,7 +1103,7 @@ async def group_findings( sent along with the request as metadata. Returns: - ~.pagers.GroupFindingsAsyncPager: + google.cloud.securitycenter_v1.services.security_center.pagers.GroupFindingsAsyncPager: Response message for group by findings. Iterating over this object will yield @@ -1105,6 +1142,7 @@ async def group_findings( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=DEFAULT_CLIENT_INFO, @@ -1139,7 +1177,7 @@ async def list_assets( r"""Lists an organization's assets. Args: - request (:class:`~.securitycenter_service.ListAssetsRequest`): + request (:class:`google.cloud.securitycenter_v1.types.ListAssetsRequest`): The request object. Request message for listing assets. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -1149,7 +1187,7 @@ async def list_assets( sent along with the request as metadata. Returns: - ~.pagers.ListAssetsAsyncPager: + google.cloud.securitycenter_v1.services.security_center.pagers.ListAssetsAsyncPager: Response message for listing assets. Iterating over this object will yield results and resolve additional pages @@ -1171,6 +1209,7 @@ async def list_assets( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=DEFAULT_CLIENT_INFO, @@ -1208,7 +1247,7 @@ async def list_findings( Example: /v1/organizations/{organization_id}/sources/-/findings Args: - request (:class:`~.securitycenter_service.ListFindingsRequest`): + request (:class:`google.cloud.securitycenter_v1.types.ListFindingsRequest`): The request object. Request message for listing findings. @@ -1219,7 +1258,7 @@ async def list_findings( sent along with the request as metadata. Returns: - ~.pagers.ListFindingsAsyncPager: + google.cloud.securitycenter_v1.services.security_center.pagers.ListFindingsAsyncPager: Response message for listing findings. Iterating over this object will yield @@ -1242,6 +1281,7 @@ async def list_findings( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=DEFAULT_CLIENT_INFO, @@ -1277,13 +1317,14 @@ async def list_notification_configs( r"""Lists notification configs. Args: - request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): + request (:class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest`): The request object. Request message for listing notification configs. parent (:class:`str`): Required. Name of the organization to list notification configs. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1295,7 +1336,7 @@ async def list_notification_configs( sent along with the request as metadata. Returns: - ~.pagers.ListNotificationConfigsAsyncPager: + google.cloud.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsAsyncPager: Response message for listing notification configs. Iterating over this object will yield @@ -1332,6 +1373,7 @@ async def list_notification_configs( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -1367,12 +1409,13 @@ async def list_sources( r"""Lists all sources belonging to an organization. Args: - request (:class:`~.securitycenter_service.ListSourcesRequest`): + request (:class:`google.cloud.securitycenter_v1.types.ListSourcesRequest`): The request object. Request message for listing sources. parent (:class:`str`): Required. Resource name of the parent of sources to list. Its format should be "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1384,7 +1427,7 @@ async def list_sources( sent along with the request as metadata. Returns: - ~.pagers.ListSourcesAsyncPager: + google.cloud.securitycenter_v1.services.security_center.pagers.ListSourcesAsyncPager: Response message for listing sources. Iterating over this object will yield results and resolve additional pages @@ -1420,6 +1463,7 @@ async def list_sources( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -1460,13 +1504,14 @@ async def run_asset_discovery( receive a TOO_MANY_REQUESTS error. Args: - request (:class:`~.securitycenter_service.RunAssetDiscoveryRequest`): + request (:class:`google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest`): The request object. Request message for running asset discovery for an organization. parent (:class:`str`): Required. Name of the organization to run asset discovery for. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1478,11 +1523,11 @@ async def run_asset_discovery( sent along with the request as metadata. Returns: - ~.operation_async.AsyncOperation: + google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. The result type for the operation will be - :class:``~.run_asset_discovery_response.RunAssetDiscoveryResponse``: + :class:`google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse` Response of asset discovery run """ @@ -1546,7 +1591,7 @@ async def set_finding_state( r"""Updates the state of a finding. Args: - request (:class:`~.securitycenter_service.SetFindingStateRequest`): + request (:class:`google.cloud.securitycenter_v1.types.SetFindingStateRequest`): The request object. Request message for updating a finding's state. name (:class:`str`): @@ -1555,18 +1600,21 @@ async def set_finding_state( https://cloud.google.com/apis/design/resource_names#relative_resource_name Example: "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - state (:class:`~.finding.Finding.State`): + state (:class:`google.cloud.securitycenter_v1.types.Finding.State`): Required. The desired State of the finding. + This corresponds to the ``state`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - start_time (:class:`~.timestamp.Timestamp`): + start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): Required. The time at which the updated state takes effect. + This corresponds to the ``start_time`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1578,7 +1626,7 @@ async def set_finding_state( sent along with the request as metadata. Returns: - ~.finding.Finding: + google.cloud.securitycenter_v1.types.Finding: Security Command Center finding. A finding is a record of assessment data like security, risk, health, or privacy, @@ -1645,7 +1693,7 @@ async def set_iam_policy( Source. Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): + request (:class:`google.iam.v1.iam_policy_pb2.SetIamPolicyRequest`): The request object. Request message for `SetIamPolicy` method. resource (:class:`str`): @@ -1653,6 +1701,7 @@ async def set_iam_policy( policy is being specified. See the operation documentation for the appropriate value for this field. + This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1664,72 +1713,62 @@ async def set_iam_policy( sent along with the request as metadata. Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). """ # Create or coerce a protobuf request object. @@ -1784,7 +1823,7 @@ async def test_iam_permissions( specified source. Args: - request (:class:`~.iam_policy.TestIamPermissionsRequest`): + request (:class:`google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest`): The request object. Request message for `TestIamPermissions` method. resource (:class:`str`): @@ -1792,6 +1831,7 @@ async def test_iam_permissions( policy detail is being requested. See the operation documentation for the appropriate value for this field. + This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1800,6 +1840,7 @@ async def test_iam_permissions( Permissions with wildcards (such as '*' or 'storage.*') are not allowed. For more information see `IAM Overview `__. + This corresponds to the ``permissions`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1811,8 +1852,8 @@ async def test_iam_permissions( sent along with the request as metadata. Returns: - ~.iam_policy.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have @@ -1845,6 +1886,7 @@ async def test_iam_permissions( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -1875,10 +1917,10 @@ async def update_finding( source must exist for a finding creation to succeed. Args: - request (:class:`~.securitycenter_service.UpdateFindingRequest`): + request (:class:`google.cloud.securitycenter_v1.types.UpdateFindingRequest`): The request object. Request message for updating or creating a finding. - finding (:class:`~.gcs_finding.Finding`): + finding (:class:`google.cloud.securitycenter_v1.types.Finding`): Required. The finding resource to update or create if it does not already exist. parent, security_marks, and update_time will be ignored. @@ -1886,6 +1928,7 @@ async def update_finding( In the case of creation, the finding id portion of the name must be alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. + This corresponds to the ``finding`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1897,7 +1940,7 @@ async def update_finding( sent along with the request as metadata. Returns: - ~.gcs_finding.Finding: + google.cloud.securitycenter_v1.types.Finding: Security Command Center finding. A finding is a record of assessment data like security, risk, health, or privacy, @@ -1963,20 +2006,22 @@ async def update_notification_config( allowed: description, pubsub_topic, streaming_config.filter Args: - request (:class:`~.securitycenter_service.UpdateNotificationConfigRequest`): + request (:class:`google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest`): The request object. Request message for updating a notification config. - notification_config (:class:`~.gcs_notification_config.NotificationConfig`): + notification_config (:class:`google.cloud.securitycenter_v1.types.NotificationConfig`): Required. The notification config to update. + This corresponds to the ``notification_config`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - update_mask (:class:`~.field_mask.FieldMask`): + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): The FieldMask to use when updating the notification config. If empty all mutable fields will be updated. + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1988,7 +2033,7 @@ async def update_notification_config( sent along with the request as metadata. Returns: - ~.gcs_notification_config.NotificationConfig: + google.cloud.securitycenter_v1.types.NotificationConfig: Cloud Security Command Center (Cloud SCC) notification configs. A notification config is a Cloud SCC @@ -2051,12 +2096,13 @@ async def update_organization_settings( r"""Updates an organization's settings. Args: - request (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): + request (:class:`google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest`): The request object. Request message for updating an organization's settings. - organization_settings (:class:`~.gcs_organization_settings.OrganizationSettings`): + organization_settings (:class:`google.cloud.securitycenter_v1.types.OrganizationSettings`): Required. The organization settings resource to update. + This corresponds to the ``organization_settings`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2068,7 +2114,7 @@ async def update_organization_settings( sent along with the request as metadata. Returns: - ~.gcs_organization_settings.OrganizationSettings: + google.cloud.securitycenter_v1.types.OrganizationSettings: User specified settings that are attached to the Security Command Center organization. @@ -2126,12 +2172,13 @@ async def update_source( r"""Updates a source. Args: - request (:class:`~.securitycenter_service.UpdateSourceRequest`): + request (:class:`google.cloud.securitycenter_v1.types.UpdateSourceRequest`): The request object. Request message for updating a source. - source (:class:`~.gcs_source.Source`): + source (:class:`google.cloud.securitycenter_v1.types.Source`): Required. The source resource to update. + This corresponds to the ``source`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2143,7 +2190,7 @@ async def update_source( sent along with the request as metadata. Returns: - ~.gcs_source.Source: + google.cloud.securitycenter_v1.types.Source: Security Command Center finding source. A finding source is an entity or a mechanism that can produce a finding. @@ -2204,12 +2251,13 @@ async def update_security_marks( r"""Updates security marks. Args: - request (:class:`~.securitycenter_service.UpdateSecurityMarksRequest`): + request (:class:`google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest`): The request object. Request message for updating a SecurityMarks resource. - security_marks (:class:`~.gcs_security_marks.SecurityMarks`): + security_marks (:class:`google.cloud.securitycenter_v1.types.SecurityMarks`): Required. The security marks resource to update. + This corresponds to the ``security_marks`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2221,7 +2269,7 @@ async def update_security_marks( sent along with the request as metadata. Returns: - ~.gcs_security_marks.SecurityMarks: + google.cloud.securitycenter_v1.types.SecurityMarks: User specified security marks that are attached to the parent Security Command Center resource. Security marks diff --git a/google/cloud/securitycenter_v1/services/security_center/client.py b/google/cloud/securitycenter_v1/services/security_center/client.py index 319ca077..5e85db59 100644 --- a/google/cloud/securitycenter_v1/services/security_center/client.py +++ b/google/cloud/securitycenter_v1/services/security_center/client.py @@ -132,6 +132,22 @@ def _get_default_mtls_endpoint(api_endpoint): DEFAULT_ENDPOINT ) + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SecurityCenterClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -144,7 +160,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): kwargs: Additional arguments to pass to the constructor. Returns: - {@api.name}: The constructed client. + SecurityCenterClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials @@ -340,10 +356,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - transport (Union[str, ~.SecurityCenterTransport]): The + transport (Union[str, SecurityCenterTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (client_options_lib.ClientOptions): Custom options for the + client_options (google.api_core.client_options.ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT @@ -379,21 +395,17 @@ def __init__( util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) ) - ssl_credentials = None + client_cert_source_func = None is_mtls = False if use_client_cert: if client_options.client_cert_source: - import grpc # type: ignore - - cert, key = client_options.client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) is_mtls = True + client_cert_source_func = client_options.client_cert_source else: - creds = SslCredentials() - is_mtls = creds.is_mtls - ssl_credentials = creds.ssl_credentials if is_mtls else None + is_mtls = mtls.has_default_client_cert_source() + client_cert_source_func = ( + mtls.default_client_cert_source() if is_mtls else None + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -436,7 +448,7 @@ def __init__( credentials_file=client_options.credentials_file, host=api_endpoint, scopes=client_options.scopes, - ssl_channel_credentials=ssl_credentials, + client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, ) @@ -454,19 +466,21 @@ def create_source( r"""Creates a source. Args: - request (:class:`~.securitycenter_service.CreateSourceRequest`): + request (google.cloud.securitycenter_v1.types.CreateSourceRequest): The request object. Request message for creating a source. - parent (:class:`str`): + parent (str): Required. Resource name of the new source's parent. Its format should be "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - source (:class:`~.gcs_source.Source`): + source (google.cloud.securitycenter_v1.types.Source): Required. The Source being created, only the display_name and description will be used. All other fields will be ignored. + This corresponds to the ``source`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -478,7 +492,7 @@ def create_source( sent along with the request as metadata. Returns: - ~.gcs_source.Source: + google.cloud.securitycenter_v1.types.Source: Security Command Center finding source. A finding source is an entity or a mechanism that can produce a finding. @@ -543,29 +557,32 @@ def create_finding( exist for finding creation to succeed. Args: - request (:class:`~.securitycenter_service.CreateFindingRequest`): + request (google.cloud.securitycenter_v1.types.CreateFindingRequest): The request object. Request message for creating a finding. - parent (:class:`str`): + parent (str): Required. Resource name of the new finding's parent. Its format should be "organizations/[organization_id]/sources/[source_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - finding_id (:class:`str`): + finding_id (str): Required. Unique identifier provided by the client within the parent scope. It must be alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. + This corresponds to the ``finding_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - finding (:class:`~.gcs_finding.Finding`): + finding (google.cloud.securitycenter_v1.types.Finding): Required. The Finding being created. The name and security_marks will be ignored as they are both output only fields on this resource. + This corresponds to the ``finding`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -577,7 +594,7 @@ def create_finding( sent along with the request as metadata. Returns: - ~.gcs_finding.Finding: + google.cloud.securitycenter_v1.types.Finding: Security Command Center finding. A finding is a record of assessment data like security, risk, health, or privacy, @@ -646,30 +663,33 @@ def create_notification_config( r"""Creates a notification config. Args: - request (:class:`~.securitycenter_service.CreateNotificationConfigRequest`): + request (google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest): The request object. Request message for creating a notification config. - parent (:class:`str`): + parent (str): Required. Resource name of the new notification config's parent. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - config_id (:class:`str`): + config_id (str): Required. Unique identifier provided by the client within the parent scope. It must be between 1 and 128 characters, and contains alphanumeric characters, underscores or hyphens only. + This corresponds to the ``config_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - notification_config (:class:`~.gcs_notification_config.NotificationConfig`): + notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): Required. The notification config being created. The name and the service account will be ignored as they are both output only fields on this resource. + This corresponds to the ``notification_config`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -681,7 +701,7 @@ def create_notification_config( sent along with the request as metadata. Returns: - ~.gcs_notification_config.NotificationConfig: + google.cloud.securitycenter_v1.types.NotificationConfig: Cloud Security Command Center (Cloud SCC) notification configs. A notification config is a Cloud SCC @@ -749,13 +769,14 @@ def delete_notification_config( r"""Deletes a notification config. Args: - request (:class:`~.securitycenter_service.DeleteNotificationConfigRequest`): + request (google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest): The request object. Request message for deleting a notification config. - name (:class:`str`): + name (str): Required. Name of the notification config to delete. Its format is "organizations/[organization_id]/notificationConfigs/[config_id]". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -821,14 +842,15 @@ def get_iam_policy( Source. Args: - request (:class:`~.iam_policy.GetIamPolicyRequest`): + request (google.iam.v1.iam_policy_pb2.GetIamPolicyRequest): The request object. Request message for `GetIamPolicy` method. - resource (:class:`str`): + resource (str): REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field. + This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -840,72 +862,62 @@ def get_iam_policy( sent along with the request as metadata. Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). """ # Create or coerce a protobuf request object. @@ -918,13 +930,16 @@ def get_iam_policy( "the individual field arguments should be set." ) - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. request = iam_policy.GetIamPolicyRequest(**request) - elif not request: - request = iam_policy.GetIamPolicyRequest(resource=resource,) + # Null request, just make one. + request = iam_policy.GetIamPolicyRequest() + + if resource is not None: + request.resource = resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -954,13 +969,14 @@ def get_notification_config( r"""Gets a notification config. Args: - request (:class:`~.securitycenter_service.GetNotificationConfigRequest`): + request (google.cloud.securitycenter_v1.types.GetNotificationConfigRequest): The request object. Request message for getting a notification config. - name (:class:`str`): + name (str): Required. Name of the notification config to get. Its format is "organizations/[organization_id]/notificationConfigs/[config_id]". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -972,7 +988,7 @@ def get_notification_config( sent along with the request as metadata. Returns: - ~.notification_config.NotificationConfig: + google.cloud.securitycenter_v1.types.NotificationConfig: Cloud Security Command Center (Cloud SCC) notification configs. A notification config is a Cloud SCC @@ -1032,13 +1048,14 @@ def get_organization_settings( r"""Gets the settings for an organization. Args: - request (:class:`~.securitycenter_service.GetOrganizationSettingsRequest`): + request (google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest): The request object. Request message for getting organization settings. - name (:class:`str`): + name (str): Required. Name of the organization to get organization settings for. Its format is "organizations/[organization_id]/organizationSettings". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1050,7 +1067,7 @@ def get_organization_settings( sent along with the request as metadata. Returns: - ~.organization_settings.OrganizationSettings: + google.cloud.securitycenter_v1.types.OrganizationSettings: User specified settings that are attached to the Security Command Center organization. @@ -1111,13 +1128,14 @@ def get_source( r"""Gets a source. Args: - request (:class:`~.securitycenter_service.GetSourceRequest`): + request (google.cloud.securitycenter_v1.types.GetSourceRequest): The request object. Request message for getting a source. - name (:class:`str`): + name (str): Required. Relative resource name of the source. Its format is "organizations/[organization_id]/source/[source_id]". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1129,7 +1147,7 @@ def get_source( sent along with the request as metadata. Returns: - ~.source.Source: + google.cloud.securitycenter_v1.types.Source: Security Command Center finding source. A finding source is an entity or a mechanism that can produce a finding. @@ -1189,7 +1207,7 @@ def group_assets( their specified properties. Args: - request (:class:`~.securitycenter_service.GroupAssetsRequest`): + request (google.cloud.securitycenter_v1.types.GroupAssetsRequest): The request object. Request message for grouping by assets. @@ -1200,7 +1218,7 @@ def group_assets( sent along with the request as metadata. Returns: - ~.pagers.GroupAssetsPager: + google.cloud.securitycenter_v1.services.security_center.pagers.GroupAssetsPager: Response message for grouping by assets. Iterating over this object will yield @@ -1256,19 +1274,20 @@ def group_findings( Example: /v1/organizations/{organization_id}/sources/-/findings Args: - request (:class:`~.securitycenter_service.GroupFindingsRequest`): + request (google.cloud.securitycenter_v1.types.GroupFindingsRequest): The request object. Request message for grouping by findings. - parent (:class:`str`): + parent (str): Required. Name of the source to groupBy. Its format is "organizations/[organization_id]/sources/[source_id]". To groupBy across all sources provide a source_id of ``-``. For example: organizations/{organization_id}/sources/- + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - group_by (:class:`str`): + group_by (str): Required. Expression that defines what assets fields to use for grouping (including ``state_change``). The string value should follow SQL syntax: comma separated @@ -1279,8 +1298,7 @@ def group_findings( - resource_name - category - state - - parent - + - parent - severity The following fields are supported when compare_duration @@ -1299,7 +1317,7 @@ def group_findings( sent along with the request as metadata. Returns: - ~.pagers.GroupFindingsPager: + google.cloud.securitycenter_v1.services.security_center.pagers.GroupFindingsPager: Response message for group by findings. Iterating over this object will yield @@ -1365,7 +1383,7 @@ def list_assets( r"""Lists an organization's assets. Args: - request (:class:`~.securitycenter_service.ListAssetsRequest`): + request (google.cloud.securitycenter_v1.types.ListAssetsRequest): The request object. Request message for listing assets. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -1375,7 +1393,7 @@ def list_assets( sent along with the request as metadata. Returns: - ~.pagers.ListAssetsPager: + google.cloud.securitycenter_v1.services.security_center.pagers.ListAssetsPager: Response message for listing assets. Iterating over this object will yield results and resolve additional pages @@ -1427,7 +1445,7 @@ def list_findings( Example: /v1/organizations/{organization_id}/sources/-/findings Args: - request (:class:`~.securitycenter_service.ListFindingsRequest`): + request (google.cloud.securitycenter_v1.types.ListFindingsRequest): The request object. Request message for listing findings. @@ -1438,7 +1456,7 @@ def list_findings( sent along with the request as metadata. Returns: - ~.pagers.ListFindingsPager: + google.cloud.securitycenter_v1.services.security_center.pagers.ListFindingsPager: Response message for listing findings. Iterating over this object will yield @@ -1489,13 +1507,14 @@ def list_notification_configs( r"""Lists notification configs. Args: - request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): + request (google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest): The request object. Request message for listing notification configs. - parent (:class:`str`): + parent (str): Required. Name of the organization to list notification configs. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1507,7 +1526,7 @@ def list_notification_configs( sent along with the request as metadata. Returns: - ~.pagers.ListNotificationConfigsPager: + google.cloud.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsPager: Response message for listing notification configs. Iterating over this object will yield @@ -1576,12 +1595,13 @@ def list_sources( r"""Lists all sources belonging to an organization. Args: - request (:class:`~.securitycenter_service.ListSourcesRequest`): + request (google.cloud.securitycenter_v1.types.ListSourcesRequest): The request object. Request message for listing sources. - parent (:class:`str`): + parent (str): Required. Resource name of the parent of sources to list. Its format should be "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1593,7 +1613,7 @@ def list_sources( sent along with the request as metadata. Returns: - ~.pagers.ListSourcesPager: + google.cloud.securitycenter_v1.services.security_center.pagers.ListSourcesPager: Response message for listing sources. Iterating over this object will yield results and resolve additional pages @@ -1662,13 +1682,14 @@ def run_asset_discovery( receive a TOO_MANY_REQUESTS error. Args: - request (:class:`~.securitycenter_service.RunAssetDiscoveryRequest`): + request (google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest): The request object. Request message for running asset discovery for an organization. - parent (:class:`str`): + parent (str): Required. Name of the organization to run asset discovery for. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1680,11 +1701,11 @@ def run_asset_discovery( sent along with the request as metadata. Returns: - ~.operation.Operation: + google.api_core.operation.Operation: An object representing a long-running operation. The result type for the operation will be - :class:``~.run_asset_discovery_response.RunAssetDiscoveryResponse``: + :class:`google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse` Response of asset discovery run """ @@ -1749,27 +1770,30 @@ def set_finding_state( r"""Updates the state of a finding. Args: - request (:class:`~.securitycenter_service.SetFindingStateRequest`): + request (google.cloud.securitycenter_v1.types.SetFindingStateRequest): The request object. Request message for updating a finding's state. - name (:class:`str`): + name (str): Required. The relative resource name of the finding. See: https://cloud.google.com/apis/design/resource_names#relative_resource_name Example: "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - state (:class:`~.finding.Finding.State`): + state (google.cloud.securitycenter_v1.types.Finding.State): Required. The desired State of the finding. + This corresponds to the ``state`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - start_time (:class:`~.timestamp.Timestamp`): + start_time (google.protobuf.timestamp_pb2.Timestamp): Required. The time at which the updated state takes effect. + This corresponds to the ``start_time`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1781,7 +1805,7 @@ def set_finding_state( sent along with the request as metadata. Returns: - ~.finding.Finding: + google.cloud.securitycenter_v1.types.Finding: Security Command Center finding. A finding is a record of assessment data like security, risk, health, or privacy, @@ -1849,14 +1873,15 @@ def set_iam_policy( Source. Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): + request (google.iam.v1.iam_policy_pb2.SetIamPolicyRequest): The request object. Request message for `SetIamPolicy` method. - resource (:class:`str`): + resource (str): REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field. + This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1868,72 +1893,62 @@ def set_iam_policy( sent along with the request as metadata. Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). """ # Create or coerce a protobuf request object. @@ -1946,13 +1961,16 @@ def set_iam_policy( "the individual field arguments should be set." ) - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. request = iam_policy.SetIamPolicyRequest(**request) - elif not request: - request = iam_policy.SetIamPolicyRequest(resource=resource,) + # Null request, just make one. + request = iam_policy.SetIamPolicyRequest() + + if resource is not None: + request.resource = resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1984,22 +2002,24 @@ def test_iam_permissions( specified source. Args: - request (:class:`~.iam_policy.TestIamPermissionsRequest`): + request (google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest): The request object. Request message for `TestIamPermissions` method. - resource (:class:`str`): + resource (str): REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field. + This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - permissions (:class:`Sequence[str]`): + permissions (Sequence[str]): The set of permissions to check for the ``resource``. Permissions with wildcards (such as '*' or 'storage.*') are not allowed. For more information see `IAM Overview `__. + This corresponds to the ``permissions`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2011,8 +2031,8 @@ def test_iam_permissions( sent along with the request as metadata. Returns: - ~.iam_policy.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have @@ -2024,15 +2044,19 @@ def test_iam_permissions( "the individual field arguments should be set." ) - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. request = iam_policy.TestIamPermissionsRequest(**request) - elif not request: - request = iam_policy.TestIamPermissionsRequest( - resource=resource, permissions=permissions, - ) + # Null request, just make one. + request = iam_policy.TestIamPermissionsRequest() + + if resource is not None: + request.resource = resource + + if permissions: + request.permissions.extend(permissions) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2063,10 +2087,10 @@ def update_finding( source must exist for a finding creation to succeed. Args: - request (:class:`~.securitycenter_service.UpdateFindingRequest`): + request (google.cloud.securitycenter_v1.types.UpdateFindingRequest): The request object. Request message for updating or creating a finding. - finding (:class:`~.gcs_finding.Finding`): + finding (google.cloud.securitycenter_v1.types.Finding): Required. The finding resource to update or create if it does not already exist. parent, security_marks, and update_time will be ignored. @@ -2074,6 +2098,7 @@ def update_finding( In the case of creation, the finding id portion of the name must be alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. + This corresponds to the ``finding`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2085,7 +2110,7 @@ def update_finding( sent along with the request as metadata. Returns: - ~.gcs_finding.Finding: + google.cloud.securitycenter_v1.types.Finding: Security Command Center finding. A finding is a record of assessment data like security, risk, health, or privacy, @@ -2152,20 +2177,22 @@ def update_notification_config( allowed: description, pubsub_topic, streaming_config.filter Args: - request (:class:`~.securitycenter_service.UpdateNotificationConfigRequest`): + request (google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest): The request object. Request message for updating a notification config. - notification_config (:class:`~.gcs_notification_config.NotificationConfig`): + notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): Required. The notification config to update. + This corresponds to the ``notification_config`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - update_mask (:class:`~.field_mask.FieldMask`): + update_mask (google.protobuf.field_mask_pb2.FieldMask): The FieldMask to use when updating the notification config. If empty all mutable fields will be updated. + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2177,7 +2204,7 @@ def update_notification_config( sent along with the request as metadata. Returns: - ~.gcs_notification_config.NotificationConfig: + google.cloud.securitycenter_v1.types.NotificationConfig: Cloud Security Command Center (Cloud SCC) notification configs. A notification config is a Cloud SCC @@ -2245,12 +2272,13 @@ def update_organization_settings( r"""Updates an organization's settings. Args: - request (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): + request (google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest): The request object. Request message for updating an organization's settings. - organization_settings (:class:`~.gcs_organization_settings.OrganizationSettings`): + organization_settings (google.cloud.securitycenter_v1.types.OrganizationSettings): Required. The organization settings resource to update. + This corresponds to the ``organization_settings`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2262,7 +2290,7 @@ def update_organization_settings( sent along with the request as metadata. Returns: - ~.gcs_organization_settings.OrganizationSettings: + google.cloud.securitycenter_v1.types.OrganizationSettings: User specified settings that are attached to the Security Command Center organization. @@ -2325,12 +2353,13 @@ def update_source( r"""Updates a source. Args: - request (:class:`~.securitycenter_service.UpdateSourceRequest`): + request (google.cloud.securitycenter_v1.types.UpdateSourceRequest): The request object. Request message for updating a source. - source (:class:`~.gcs_source.Source`): + source (google.cloud.securitycenter_v1.types.Source): Required. The source resource to update. + This corresponds to the ``source`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2342,7 +2371,7 @@ def update_source( sent along with the request as metadata. Returns: - ~.gcs_source.Source: + google.cloud.securitycenter_v1.types.Source: Security Command Center finding source. A finding source is an entity or a mechanism that can produce a finding. @@ -2404,12 +2433,13 @@ def update_security_marks( r"""Updates security marks. Args: - request (:class:`~.securitycenter_service.UpdateSecurityMarksRequest`): + request (google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest): The request object. Request message for updating a SecurityMarks resource. - security_marks (:class:`~.gcs_security_marks.SecurityMarks`): + security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): Required. The security marks resource to update. + This corresponds to the ``security_marks`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2421,7 +2451,7 @@ def update_security_marks( sent along with the request as metadata. Returns: - ~.gcs_security_marks.SecurityMarks: + google.cloud.securitycenter_v1.types.SecurityMarks: User specified security marks that are attached to the parent Security Command Center resource. Security marks diff --git a/google/cloud/securitycenter_v1/services/security_center/pagers.py b/google/cloud/securitycenter_v1/services/security_center/pagers.py index 98a0cc03..e887de53 100644 --- a/google/cloud/securitycenter_v1/services/security_center/pagers.py +++ b/google/cloud/securitycenter_v1/services/security_center/pagers.py @@ -15,7 +15,16 @@ # limitations under the License. # -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple +from typing import ( + Any, + AsyncIterable, + Awaitable, + Callable, + Iterable, + Sequence, + Tuple, + Optional, +) from google.cloud.securitycenter_v1.types import notification_config from google.cloud.securitycenter_v1.types import securitycenter_service @@ -26,7 +35,7 @@ class GroupAssetsPager: """A pager for iterating through ``group_assets`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.GroupAssetsResponse` object, and + :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` object, and provides an ``__iter__`` method to iterate through its ``group_by_results`` field. @@ -35,7 +44,7 @@ class GroupAssetsPager: through the ``group_by_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.GroupAssetsResponse` + All the usual :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -53,9 +62,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.GroupAssetsRequest`): + request (google.cloud.securitycenter_v1.types.GroupAssetsRequest): The initial request object. - response (:class:`~.securitycenter_service.GroupAssetsResponse`): + response (google.cloud.securitycenter_v1.types.GroupAssetsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -88,7 +97,7 @@ class GroupAssetsAsyncPager: """A pager for iterating through ``group_assets`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.GroupAssetsResponse` object, and + :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` object, and provides an ``__aiter__`` method to iterate through its ``group_by_results`` field. @@ -97,7 +106,7 @@ class GroupAssetsAsyncPager: through the ``group_by_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.GroupAssetsResponse` + All the usual :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -115,9 +124,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.GroupAssetsRequest`): + request (google.cloud.securitycenter_v1.types.GroupAssetsRequest): The initial request object. - response (:class:`~.securitycenter_service.GroupAssetsResponse`): + response (google.cloud.securitycenter_v1.types.GroupAssetsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -154,7 +163,7 @@ class GroupFindingsPager: """A pager for iterating through ``group_findings`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.GroupFindingsResponse` object, and + :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` object, and provides an ``__iter__`` method to iterate through its ``group_by_results`` field. @@ -163,7 +172,7 @@ class GroupFindingsPager: through the ``group_by_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.GroupFindingsResponse` + All the usual :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -181,9 +190,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.GroupFindingsRequest`): + request (google.cloud.securitycenter_v1.types.GroupFindingsRequest): The initial request object. - response (:class:`~.securitycenter_service.GroupFindingsResponse`): + response (google.cloud.securitycenter_v1.types.GroupFindingsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -216,7 +225,7 @@ class GroupFindingsAsyncPager: """A pager for iterating through ``group_findings`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.GroupFindingsResponse` object, and + :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` object, and provides an ``__aiter__`` method to iterate through its ``group_by_results`` field. @@ -225,7 +234,7 @@ class GroupFindingsAsyncPager: through the ``group_by_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.GroupFindingsResponse` + All the usual :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -243,9 +252,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.GroupFindingsRequest`): + request (google.cloud.securitycenter_v1.types.GroupFindingsRequest): The initial request object. - response (:class:`~.securitycenter_service.GroupFindingsResponse`): + response (google.cloud.securitycenter_v1.types.GroupFindingsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -284,7 +293,7 @@ class ListAssetsPager: """A pager for iterating through ``list_assets`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListAssetsResponse` object, and + :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` object, and provides an ``__iter__`` method to iterate through its ``list_assets_results`` field. @@ -293,7 +302,7 @@ class ListAssetsPager: through the ``list_assets_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListAssetsResponse` + All the usual :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -311,9 +320,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListAssetsRequest`): + request (google.cloud.securitycenter_v1.types.ListAssetsRequest): The initial request object. - response (:class:`~.securitycenter_service.ListAssetsResponse`): + response (google.cloud.securitycenter_v1.types.ListAssetsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -348,7 +357,7 @@ class ListAssetsAsyncPager: """A pager for iterating through ``list_assets`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListAssetsResponse` object, and + :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` object, and provides an ``__aiter__`` method to iterate through its ``list_assets_results`` field. @@ -357,7 +366,7 @@ class ListAssetsAsyncPager: through the ``list_assets_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListAssetsResponse` + All the usual :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -375,9 +384,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListAssetsRequest`): + request (google.cloud.securitycenter_v1.types.ListAssetsRequest): The initial request object. - response (:class:`~.securitycenter_service.ListAssetsResponse`): + response (google.cloud.securitycenter_v1.types.ListAssetsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -416,7 +425,7 @@ class ListFindingsPager: """A pager for iterating through ``list_findings`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListFindingsResponse` object, and + :class:`google.cloud.securitycenter_v1.types.ListFindingsResponse` object, and provides an ``__iter__`` method to iterate through its ``list_findings_results`` field. @@ -425,7 +434,7 @@ class ListFindingsPager: through the ``list_findings_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListFindingsResponse` + All the usual :class:`google.cloud.securitycenter_v1.types.ListFindingsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -443,9 +452,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListFindingsRequest`): + request (google.cloud.securitycenter_v1.types.ListFindingsRequest): The initial request object. - response (:class:`~.securitycenter_service.ListFindingsResponse`): + response (google.cloud.securitycenter_v1.types.ListFindingsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -480,7 +489,7 @@ class ListFindingsAsyncPager: """A pager for iterating through ``list_findings`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListFindingsResponse` object, and + :class:`google.cloud.securitycenter_v1.types.ListFindingsResponse` object, and provides an ``__aiter__`` method to iterate through its ``list_findings_results`` field. @@ -489,7 +498,7 @@ class ListFindingsAsyncPager: through the ``list_findings_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListFindingsResponse` + All the usual :class:`google.cloud.securitycenter_v1.types.ListFindingsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -507,9 +516,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListFindingsRequest`): + request (google.cloud.securitycenter_v1.types.ListFindingsRequest): The initial request object. - response (:class:`~.securitycenter_service.ListFindingsResponse`): + response (google.cloud.securitycenter_v1.types.ListFindingsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -548,7 +557,7 @@ class ListNotificationConfigsPager: """A pager for iterating through ``list_notification_configs`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListNotificationConfigsResponse` object, and + :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` object, and provides an ``__iter__`` method to iterate through its ``notification_configs`` field. @@ -557,7 +566,7 @@ class ListNotificationConfigsPager: through the ``notification_configs`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListNotificationConfigsResponse` + All the usual :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -575,9 +584,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): + request (google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest): The initial request object. - response (:class:`~.securitycenter_service.ListNotificationConfigsResponse`): + response (google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -610,7 +619,7 @@ class ListNotificationConfigsAsyncPager: """A pager for iterating through ``list_notification_configs`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListNotificationConfigsResponse` object, and + :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` object, and provides an ``__aiter__`` method to iterate through its ``notification_configs`` field. @@ -619,7 +628,7 @@ class ListNotificationConfigsAsyncPager: through the ``notification_configs`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListNotificationConfigsResponse` + All the usual :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -639,9 +648,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): + request (google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest): The initial request object. - response (:class:`~.securitycenter_service.ListNotificationConfigsResponse`): + response (google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -680,7 +689,7 @@ class ListSourcesPager: """A pager for iterating through ``list_sources`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListSourcesResponse` object, and + :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` object, and provides an ``__iter__`` method to iterate through its ``sources`` field. @@ -689,7 +698,7 @@ class ListSourcesPager: through the ``sources`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListSourcesResponse` + All the usual :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -707,9 +716,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListSourcesRequest`): + request (google.cloud.securitycenter_v1.types.ListSourcesRequest): The initial request object. - response (:class:`~.securitycenter_service.ListSourcesResponse`): + response (google.cloud.securitycenter_v1.types.ListSourcesResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -742,7 +751,7 @@ class ListSourcesAsyncPager: """A pager for iterating through ``list_sources`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListSourcesResponse` object, and + :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` object, and provides an ``__aiter__`` method to iterate through its ``sources`` field. @@ -751,7 +760,7 @@ class ListSourcesAsyncPager: through the ``sources`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListSourcesResponse` + All the usual :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -769,9 +778,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListSourcesRequest`): + request (google.cloud.securitycenter_v1.types.ListSourcesRequest): The initial request object. - response (:class:`~.securitycenter_service.ListSourcesResponse`): + response (google.cloud.securitycenter_v1.types.ListSourcesResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. diff --git a/google/cloud/securitycenter_v1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1/services/security_center/transports/base.py index 896b834a..82541447 100644 --- a/google/cloud/securitycenter_v1/services/security_center/transports/base.py +++ b/google/cloud/securitycenter_v1/services/security_center/transports/base.py @@ -23,7 +23,6 @@ from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore from google.auth import credentials # type: ignore @@ -88,10 +87,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. @@ -99,6 +98,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: @@ -108,20 +110,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 = { @@ -150,6 +149,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, @@ -163,6 +163,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, @@ -176,6 +177,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, @@ -189,6 +191,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, @@ -202,6 +205,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=client_info, @@ -215,6 +219,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=client_info, @@ -228,6 +233,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=client_info, @@ -241,6 +247,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=client_info, @@ -254,6 +261,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, @@ -267,6 +275,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, @@ -289,6 +298,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/securitycenter_v1/services/security_center/transports/grpc.py b/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py index 8d8c03c3..59612c98 100644 --- a/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py +++ b/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py @@ -75,6 +75,7 @@ def __init__( api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -105,6 +106,10 @@ def __init__( ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -119,72 +124,61 @@ 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] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # 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: - warnings.warn( - "api_mtls_endpoint and client_cert_source are deprecated", - DeprecationWarning, - ) - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials - 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 + 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 + ) - # 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 credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + # 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, - ssl_credentials=ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -192,18 +186,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # 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( @@ -217,7 +201,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/securitycenter_v1/services/security_center/transports/grpc_asyncio.py b/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py index b44d5ce1..8c4e9bef 100644 --- a/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py +++ b/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py @@ -79,7 +79,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 @@ -119,6 +119,7 @@ def __init__( api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -150,12 +151,16 @@ def __init__( ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing + 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: @@ -164,72 +169,61 @@ 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] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # 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: - warnings.warn( - "api_mtls_endpoint and client_cert_source are deprecated", - DeprecationWarning, - ) - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials - 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 + 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 + ) - # 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 credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + # 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, - ssl_credentials=ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -237,18 +231,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 = {} - self._operations_client = None + # 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/securitycenter_v1/types/__init__.py b/google/cloud/securitycenter_v1/types/__init__.py index 1a1ebb24..0d3cb34a 100644 --- a/google/cloud/securitycenter_v1/types/__init__.py +++ b/google/cloud/securitycenter_v1/types/__init__.py @@ -15,15 +15,14 @@ # limitations under the License. # -from .security_marks import SecurityMarks from .asset import Asset from .finding import Finding from .notification_config import NotificationConfig -from .resource import Resource from .notification_message import NotificationMessage from .organization_settings import OrganizationSettings +from .resource import Resource from .run_asset_discovery_response import RunAssetDiscoveryResponse -from .source import Source +from .security_marks import SecurityMarks from .securitycenter_service import ( CreateFindingRequest, CreateNotificationConfigRequest, @@ -37,33 +36,33 @@ GroupFindingsRequest, GroupFindingsResponse, GroupResult, - ListNotificationConfigsRequest, - ListNotificationConfigsResponse, - ListSourcesRequest, - ListSourcesResponse, ListAssetsRequest, ListAssetsResponse, ListFindingsRequest, ListFindingsResponse, - SetFindingStateRequest, + ListNotificationConfigsRequest, + ListNotificationConfigsResponse, + ListSourcesRequest, + ListSourcesResponse, RunAssetDiscoveryRequest, + SetFindingStateRequest, UpdateFindingRequest, UpdateNotificationConfigRequest, UpdateOrganizationSettingsRequest, - UpdateSourceRequest, UpdateSecurityMarksRequest, + UpdateSourceRequest, ) +from .source import Source __all__ = ( - "SecurityMarks", "Asset", "Finding", "NotificationConfig", - "Resource", "NotificationMessage", "OrganizationSettings", + "Resource", "RunAssetDiscoveryResponse", - "Source", + "SecurityMarks", "CreateFindingRequest", "CreateNotificationConfigRequest", "CreateSourceRequest", @@ -76,19 +75,20 @@ "GroupFindingsRequest", "GroupFindingsResponse", "GroupResult", - "ListNotificationConfigsRequest", - "ListNotificationConfigsResponse", - "ListSourcesRequest", - "ListSourcesResponse", "ListAssetsRequest", "ListAssetsResponse", "ListFindingsRequest", "ListFindingsResponse", - "SetFindingStateRequest", + "ListNotificationConfigsRequest", + "ListNotificationConfigsResponse", + "ListSourcesRequest", + "ListSourcesResponse", "RunAssetDiscoveryRequest", + "SetFindingStateRequest", "UpdateFindingRequest", "UpdateNotificationConfigRequest", "UpdateOrganizationSettingsRequest", - "UpdateSourceRequest", "UpdateSecurityMarksRequest", + "UpdateSourceRequest", + "Source", ) diff --git a/google/cloud/securitycenter_v1/types/asset.py b/google/cloud/securitycenter_v1/types/asset.py index d1992e53..7ec5e67c 100644 --- a/google/cloud/securitycenter_v1/types/asset.py +++ b/google/cloud/securitycenter_v1/types/asset.py @@ -44,26 +44,26 @@ class Asset(proto.Message): https://cloud.google.com/apis/design/resource_names#relative_resource_name Example: "organizations/{organization_id}/assets/{asset_id}". - security_center_properties (~.asset.Asset.SecurityCenterProperties): + security_center_properties (google.cloud.securitycenter_v1.types.Asset.SecurityCenterProperties): Security Command Center managed properties. These properties are managed by Security Command Center and cannot be modified by the user. - resource_properties (Sequence[~.asset.Asset.ResourcePropertiesEntry]): + resource_properties (Sequence[google.cloud.securitycenter_v1.types.Asset.ResourcePropertiesEntry]): Resource managed properties. These properties are managed and defined by the Google Cloud resource and cannot be modified by the user. - security_marks (~.gcs_security_marks.SecurityMarks): + security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): User specified security marks. These marks are entirely managed by the user and come from the SecurityMarks resource that belongs to the asset. - create_time (~.timestamp.Timestamp): + create_time (google.protobuf.timestamp_pb2.Timestamp): The time at which the asset was created in Security Command Center. - update_time (~.timestamp.Timestamp): + update_time (google.protobuf.timestamp_pb2.Timestamp): The time at which the asset was last updated, added, or deleted in Security Command Center. - iam_policy (~.asset.Asset.IamPolicy): + iam_policy (google.cloud.securitycenter_v1.types.Asset.IamPolicy): Cloud IAM Policy information associated with the Google Cloud resource described by the Security Command Center asset. This information diff --git a/google/cloud/securitycenter_v1/types/finding.py b/google/cloud/securitycenter_v1/types/finding.py index 5c5e3146..7fb6a109 100644 --- a/google/cloud/securitycenter_v1/types/finding.py +++ b/google/cloud/securitycenter_v1/types/finding.py @@ -55,7 +55,7 @@ class Finding(proto.Message): When the finding is for a non-Google Cloud resource, the resourceName can be a customer or partner defined string. This field is immutable after creation time. - state (~.finding.Finding.State): + state (google.cloud.securitycenter_v1.types.Finding.State): The state of the finding. category (str): The additional taxonomy group within findings from a given @@ -67,18 +67,18 @@ class Finding(proto.Message): additional information about the finding can be found. This field is guaranteed to be either empty or a well formed URL. - source_properties (Sequence[~.finding.Finding.SourcePropertiesEntry]): + source_properties (Sequence[google.cloud.securitycenter_v1.types.Finding.SourcePropertiesEntry]): Source specific properties. These properties are managed by the source that writes the finding. The key names in the source_properties map must be between 1 and 255 characters, and must start with a letter and contain alphanumeric characters or underscores only. - security_marks (~.gcs_security_marks.SecurityMarks): + security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): Output only. User specified security marks. These marks are entirely managed by the user and come from the SecurityMarks resource that belongs to the finding. - event_time (~.timestamp.Timestamp): + event_time (google.protobuf.timestamp_pb2.Timestamp): The time at which the event took place, or when an update to the finding occurred. For example, if the finding represents an open @@ -87,10 +87,10 @@ class Finding(proto.Message): is determined by the detector. If the finding were to be resolved afterward, this time would reflect when the finding was resolved. - create_time (~.timestamp.Timestamp): + create_time (google.protobuf.timestamp_pb2.Timestamp): The time at which the finding was created in Security Command Center. - severity (~.finding.Finding.Severity): + severity (google.cloud.securitycenter_v1.types.Finding.Severity): The severity of the finding. This field is managed by the source that writes the finding. """ diff --git a/google/cloud/securitycenter_v1/types/notification_config.py b/google/cloud/securitycenter_v1/types/notification_config.py index 13cd5c90..d6876046 100644 --- a/google/cloud/securitycenter_v1/types/notification_config.py +++ b/google/cloud/securitycenter_v1/types/notification_config.py @@ -46,7 +46,7 @@ class NotificationConfig(proto.Message): Output only. The service account that needs "pubsub.topics.publish" permission to publish to the Pub/Sub topic. - streaming_config (~.notification_config.NotificationConfig.StreamingConfig): + streaming_config (google.cloud.securitycenter_v1.types.NotificationConfig.StreamingConfig): The config for triggering streaming-based notifications. """ diff --git a/google/cloud/securitycenter_v1/types/notification_message.py b/google/cloud/securitycenter_v1/types/notification_message.py index c836cad9..c3a6436f 100644 --- a/google/cloud/securitycenter_v1/types/notification_message.py +++ b/google/cloud/securitycenter_v1/types/notification_message.py @@ -34,10 +34,10 @@ class NotificationMessage(proto.Message): notification_config_name (str): Name of the notification config that generated current notification. - finding (~.gcs_finding.Finding): + finding (google.cloud.securitycenter_v1.types.Finding): If it's a Finding based notification config, this field will be populated. - resource (~.gcs_resource.Resource): + resource (google.cloud.securitycenter_v1.types.Resource): The Cloud resource tied to this notification's Finding. """ diff --git a/google/cloud/securitycenter_v1/types/organization_settings.py b/google/cloud/securitycenter_v1/types/organization_settings.py index ad4bc9f8..a1135a8d 100644 --- a/google/cloud/securitycenter_v1/types/organization_settings.py +++ b/google/cloud/securitycenter_v1/types/organization_settings.py @@ -38,7 +38,7 @@ class OrganizationSettings(proto.Message): If the flag is set to ``true``, then discovery of assets will occur. If it is set to \`false, all historical assets will remain, but discovery of future assets will not occur. - asset_discovery_config (~.organization_settings.OrganizationSettings.AssetDiscoveryConfig): + asset_discovery_config (google.cloud.securitycenter_v1.types.OrganizationSettings.AssetDiscoveryConfig): The configuration used for Asset Discovery runs. """ @@ -50,7 +50,7 @@ class AssetDiscoveryConfig(proto.Message): project_ids (Sequence[str]): The project ids to use for filtering asset discovery. - inclusion_mode (~.organization_settings.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): + inclusion_mode (google.cloud.securitycenter_v1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): The mode to use for filtering asset discovery. """ diff --git a/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py b/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py index eeed56ef..845adafd 100644 --- a/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py +++ b/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py @@ -30,9 +30,9 @@ class RunAssetDiscoveryResponse(proto.Message): r"""Response of asset discovery run Attributes: - state (~.run_asset_discovery_response.RunAssetDiscoveryResponse.State): + state (google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse.State): The state of an asset discovery run. - duration (~.gp_duration.Duration): + duration (google.protobuf.duration_pb2.Duration): The duration between asset discovery run start and end """ diff --git a/google/cloud/securitycenter_v1/types/security_marks.py b/google/cloud/securitycenter_v1/types/security_marks.py index 21bf0b0a..181d1d74 100644 --- a/google/cloud/securitycenter_v1/types/security_marks.py +++ b/google/cloud/securitycenter_v1/types/security_marks.py @@ -37,7 +37,7 @@ class SecurityMarks(proto.Message): Examples: "organizations/{organization_id}/assets/{asset_id}/securityMarks" "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". - marks (Sequence[~.security_marks.SecurityMarks.MarksEntry]): + marks (Sequence[google.cloud.securitycenter_v1.types.SecurityMarks.MarksEntry]): Mutable user specified security marks belonging to the parent resource. Constraints are as follows: diff --git a/google/cloud/securitycenter_v1/types/securitycenter_service.py b/google/cloud/securitycenter_v1/types/securitycenter_service.py index 486003a5..9b80e842 100644 --- a/google/cloud/securitycenter_v1/types/securitycenter_service.py +++ b/google/cloud/securitycenter_v1/types/securitycenter_service.py @@ -82,7 +82,7 @@ class CreateFindingRequest(proto.Message): alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. - finding (~.gcs_finding.Finding): + finding (google.cloud.securitycenter_v1.types.Finding): Required. The Finding being created. The name and security_marks will be ignored as they are both output only fields on this resource. @@ -108,7 +108,7 @@ class CreateNotificationConfigRequest(proto.Message): the parent scope. It must be between 1 and 128 characters, and contains alphanumeric characters, underscores or hyphens only. - notification_config (~.gcs_notification_config.NotificationConfig): + notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): Required. The notification config being created. The name and the service account will be ignored as they are both output only fields @@ -131,7 +131,7 @@ class CreateSourceRequest(proto.Message): parent (str): Required. Resource name of the new source's parent. Its format should be "organizations/[organization_id]". - source (~.gcs_source.Source): + source (google.cloud.securitycenter_v1.types.Source): Required. The Source being created, only the display_name and description will be used. All other fields will be ignored. @@ -303,7 +303,7 @@ class GroupAssetsRequest(proto.Message): - security_center_properties.resource_type - security_center_properties.resource_project_display_name - security_center_properties.resource_parent_display_name - compare_duration (~.duration.Duration): + compare_duration (google.protobuf.duration_pb2.Duration): When compare_duration is set, the GroupResult's "state_change" property is updated to indicate whether the asset was added, removed, or remained present during the @@ -335,7 +335,7 @@ class GroupAssetsRequest(proto.Message): If this field is set then ``state_change`` must be a specified field in ``group_by``. - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used as a reference point when filtering assets. The filter is limited to assets existing at the supplied time and their values are those @@ -371,13 +371,13 @@ class GroupAssetsResponse(proto.Message): r"""Response message for grouping by assets. Attributes: - group_by_results (Sequence[~.securitycenter_service.GroupResult]): + group_by_results (Sequence[google.cloud.securitycenter_v1.types.GroupResult]): Group results. There exists an element for each existing unique combination of property/values. The element contains a count for the number of times those specific property/values appear. - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used for executing the groupBy request. next_page_token (str): Token to retrieve the next page of results, @@ -493,13 +493,13 @@ class GroupFindingsRequest(proto.Message): set: - state_change - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used as a reference point when filtering findings. The filter is limited to findings existing at the supplied time and their values are those at that specific time. Absence of this field will default to the API's version of NOW. - compare_duration (~.duration.Duration): + compare_duration (google.protobuf.duration_pb2.Duration): When compare_duration is set, the GroupResult's "state_change" attribute is updated to indicate whether the finding had its state changed, the finding's state remained @@ -566,13 +566,13 @@ class GroupFindingsResponse(proto.Message): r"""Response message for group by findings. Attributes: - group_by_results (Sequence[~.securitycenter_service.GroupResult]): + group_by_results (Sequence[google.cloud.securitycenter_v1.types.GroupResult]): Group results. There exists an element for each existing unique combination of property/values. The element contains a count for the number of times those specific property/values appear. - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used for executing the groupBy request. next_page_token (str): Token to retrieve the next page of results, @@ -602,7 +602,7 @@ class GroupResult(proto.Message): request. Attributes: - properties (Sequence[~.securitycenter_service.GroupResult.PropertiesEntry]): + properties (Sequence[google.cloud.securitycenter_v1.types.GroupResult.PropertiesEntry]): Properties matching the groupBy fields in the request. count (int): @@ -646,7 +646,7 @@ class ListNotificationConfigsResponse(proto.Message): r"""Response message for listing notification configs. Attributes: - notification_configs (Sequence[~.gcs_notification_config.NotificationConfig]): + notification_configs (Sequence[google.cloud.securitycenter_v1.types.NotificationConfig]): Notification configs belonging to the requested parent. next_page_token (str): @@ -694,7 +694,7 @@ class ListSourcesResponse(proto.Message): r"""Response message for listing sources. Attributes: - sources (Sequence[~.gcs_source.Source]): + sources (Sequence[google.cloud.securitycenter_v1.types.Source]): Sources belonging to the requested parent. next_page_token (str): Token to retrieve the next page of results, @@ -821,13 +821,13 @@ class ListAssetsRequest(proto.Message): security_center_properties.resource_project security_center_properties.resource_project_display_name security_center_properties.resource_type - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used as a reference point when filtering assets. The filter is limited to assets existing at the supplied time and their values are those at that specific time. Absence of this field will default to the API's version of NOW. - compare_duration (~.duration.Duration): + compare_duration (google.protobuf.duration_pb2.Duration): When compare_duration is set, the ListAssetsResult's "state_change" attribute is updated to indicate whether the asset was added, removed, or remained present during the @@ -855,7 +855,7 @@ class ListAssetsRequest(proto.Message): If compare_duration is not specified, then the only possible state_change is "UNUSED", which will be the state_change set for all assets present at read_time. - field_mask (~.gp_field_mask.FieldMask): + field_mask (google.protobuf.field_mask_pb2.FieldMask): A field mask to specify the ListAssetsResult fields to be listed in the response. An empty field mask will list all fields. @@ -891,9 +891,9 @@ class ListAssetsResponse(proto.Message): r"""Response message for listing assets. Attributes: - list_assets_results (Sequence[~.securitycenter_service.ListAssetsResponse.ListAssetsResult]): + list_assets_results (Sequence[google.cloud.securitycenter_v1.types.ListAssetsResponse.ListAssetsResult]): Assets matching the list request. - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used for executing the list request. next_page_token (str): Token to retrieve the next page of results, @@ -907,9 +907,9 @@ class ListAssetsResult(proto.Message): r"""Result containing the Asset and its State. Attributes: - asset (~.gcs_asset.Asset): + asset (google.cloud.securitycenter_v1.types.Asset): Asset matching the search request. - state_change (~.securitycenter_service.ListAssetsResponse.ListAssetsResult.StateChange): + state_change (google.cloud.securitycenter_v1.types.ListAssetsResponse.ListAssetsResult.StateChange): State change of the asset between the points in time. """ @@ -1037,13 +1037,13 @@ class ListFindingsRequest(proto.Message): The following fields are supported: name parent state category resource_name event_time source_properties security_marks.marks - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used as a reference point when filtering findings. The filter is limited to findings existing at the supplied time and their values are those at that specific time. Absence of this field will default to the API's version of NOW. - compare_duration (~.duration.Duration): + compare_duration (google.protobuf.duration_pb2.Duration): When compare_duration is set, the ListFindingsResult's "state_change" attribute is updated to indicate whether the finding had its state changed, the finding's state remained @@ -1077,7 +1077,7 @@ class ListFindingsRequest(proto.Message): If compare_duration is not specified, then the only possible state_change is "UNUSED", which will be the state_change set for all findings present at read_time. - field_mask (~.gp_field_mask.FieldMask): + field_mask (google.protobuf.field_mask_pb2.FieldMask): A field mask to specify the Finding fields to be listed in the response. An empty field mask will list all fields. @@ -1113,9 +1113,9 @@ class ListFindingsResponse(proto.Message): r"""Response message for listing findings. Attributes: - list_findings_results (Sequence[~.securitycenter_service.ListFindingsResponse.ListFindingsResult]): + list_findings_results (Sequence[google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult]): Findings matching the list request. - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used for executing the list request. next_page_token (str): Token to retrieve the next page of results, @@ -1129,12 +1129,12 @@ class ListFindingsResult(proto.Message): r"""Result containing the Finding and its StateChange. Attributes: - finding (~.gcs_finding.Finding): + finding (google.cloud.securitycenter_v1.types.Finding): Finding matching the search request. - state_change (~.securitycenter_service.ListFindingsResponse.ListFindingsResult.StateChange): + state_change (google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult.StateChange): State change of the finding between the points in time. - resource (~.securitycenter_service.ListFindingsResponse.ListFindingsResult.Resource): + resource (google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult.Resource): Output only. Resource that is associated with this finding. """ @@ -1223,9 +1223,9 @@ class SetFindingStateRequest(proto.Message): https://cloud.google.com/apis/design/resource_names#relative_resource_name Example: "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - state (~.gcs_finding.Finding.State): + state (google.cloud.securitycenter_v1.types.Finding.State): Required. The desired State of the finding. - start_time (~.timestamp.Timestamp): + start_time (google.protobuf.timestamp_pb2.Timestamp): Required. The time at which the updated state takes effect. """ @@ -1254,7 +1254,7 @@ class UpdateFindingRequest(proto.Message): r"""Request message for updating or creating a finding. Attributes: - finding (~.gcs_finding.Finding): + finding (google.cloud.securitycenter_v1.types.Finding): Required. The finding resource to update or create if it does not already exist. parent, security_marks, and update_time will be ignored. @@ -1262,7 +1262,7 @@ class UpdateFindingRequest(proto.Message): In the case of creation, the finding id portion of the name must be alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. - update_mask (~.gp_field_mask.FieldMask): + update_mask (google.protobuf.field_mask_pb2.FieldMask): The FieldMask to use when updating the finding resource. This field should not be specified when creating a finding. @@ -1281,9 +1281,9 @@ class UpdateNotificationConfigRequest(proto.Message): r"""Request message for updating a notification config. Attributes: - notification_config (~.gcs_notification_config.NotificationConfig): + notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): Required. The notification config to update. - update_mask (~.gp_field_mask.FieldMask): + update_mask (google.protobuf.field_mask_pb2.FieldMask): The FieldMask to use when updating the notification config. If empty all mutable fields will be updated. @@ -1300,10 +1300,10 @@ class UpdateOrganizationSettingsRequest(proto.Message): r"""Request message for updating an organization's settings. Attributes: - organization_settings (~.gcs_organization_settings.OrganizationSettings): + organization_settings (google.cloud.securitycenter_v1.types.OrganizationSettings): Required. The organization settings resource to update. - update_mask (~.gp_field_mask.FieldMask): + update_mask (google.protobuf.field_mask_pb2.FieldMask): The FieldMask to use when updating the settings resource. @@ -1321,9 +1321,9 @@ class UpdateSourceRequest(proto.Message): r"""Request message for updating a source. Attributes: - source (~.gcs_source.Source): + source (google.cloud.securitycenter_v1.types.Source): Required. The source resource to update. - update_mask (~.gp_field_mask.FieldMask): + update_mask (google.protobuf.field_mask_pb2.FieldMask): The FieldMask to use when updating the source resource. If empty all mutable fields will be updated. @@ -1338,17 +1338,17 @@ class UpdateSecurityMarksRequest(proto.Message): r"""Request message for updating a SecurityMarks resource. Attributes: - security_marks (~.gcs_security_marks.SecurityMarks): + security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): Required. The security marks resource to update. - update_mask (~.gp_field_mask.FieldMask): + update_mask (google.protobuf.field_mask_pb2.FieldMask): The FieldMask to use when updating the security marks resource. The field mask must not contain duplicate fields. If empty or set to "marks", all marks will be replaced. Individual marks can be updated using "marks.". - start_time (~.timestamp.Timestamp): + start_time (google.protobuf.timestamp_pb2.Timestamp): The time at which the updated SecurityMarks take effect. If not set uses current server time. Updates will be applied to the diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py index c9dccb0d..14c5d94f 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py @@ -108,7 +108,36 @@ class SecurityCenterAsyncClient: SecurityCenterClient.parse_common_location_path ) - from_service_account_file = SecurityCenterClient.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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, filename, *args, **kwargs) # type: ignore + from_service_account_json = from_service_account_file @property @@ -185,19 +214,21 @@ async def create_source( r"""Creates a source. Args: - request (:class:`~.securitycenter_service.CreateSourceRequest`): + request (:class:`google.cloud.securitycenter_v1beta1.types.CreateSourceRequest`): The request object. Request message for creating a source. parent (:class:`str`): Required. Resource name of the new source's parent. Its format should be "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - source (:class:`~.gcs_source.Source`): + source (:class:`google.cloud.securitycenter_v1beta1.types.Source`): Required. The Source being created, only the display_name and description will be used. All other fields will be ignored. + This corresponds to the ``source`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -209,7 +240,7 @@ async def create_source( sent along with the request as metadata. Returns: - ~.gcs_source.Source: + google.cloud.securitycenter_v1beta1.types.Source: Security Command Center finding source. A finding source is an entity or a mechanism that can produce a finding. @@ -273,13 +304,14 @@ async def create_finding( exist for finding creation to succeed. Args: - request (:class:`~.securitycenter_service.CreateFindingRequest`): + request (:class:`google.cloud.securitycenter_v1beta1.types.CreateFindingRequest`): The request object. Request message for creating a finding. parent (:class:`str`): Required. Resource name of the new finding's parent. Its format should be "organizations/[organization_id]/sources/[source_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -289,13 +321,15 @@ async def create_finding( It must be alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. + This corresponds to the ``finding_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - finding (:class:`~.gcs_finding.Finding`): + finding (:class:`google.cloud.securitycenter_v1beta1.types.Finding`): Required. The Finding being created. The name and security_marks will be ignored as they are both output only fields on this resource. + This corresponds to the ``finding`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -307,7 +341,7 @@ async def create_finding( sent along with the request as metadata. Returns: - ~.gcs_finding.Finding: + google.cloud.securitycenter_v1beta1.types.Finding: Security Command Center finding. A finding is a record of assessment data (security, risk, health or privacy) @@ -374,7 +408,7 @@ async def get_iam_policy( Source. Args: - request (:class:`~.iam_policy.GetIamPolicyRequest`): + request (:class:`google.iam.v1.iam_policy_pb2.GetIamPolicyRequest`): The request object. Request message for `GetIamPolicy` method. resource (:class:`str`): @@ -382,6 +416,7 @@ async def get_iam_policy( policy is being requested. See the operation documentation for the appropriate value for this field. + This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -393,72 +428,62 @@ async def get_iam_policy( sent along with the request as metadata. Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). """ # Create or coerce a protobuf request object. @@ -490,6 +515,7 @@ async def get_iam_policy( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -519,13 +545,14 @@ async def get_organization_settings( r"""Gets the settings for an organization. Args: - request (:class:`~.securitycenter_service.GetOrganizationSettingsRequest`): + request (:class:`google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest`): The request object. Request message for getting organization settings. name (:class:`str`): Required. Name of the organization to get organization settings for. Its format is "organizations/[organization_id]/organizationSettings". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -537,7 +564,7 @@ async def get_organization_settings( sent along with the request as metadata. Returns: - ~.organization_settings.OrganizationSettings: + google.cloud.securitycenter_v1beta1.types.OrganizationSettings: User specified settings that are attached to the Security Command Center organization. @@ -572,6 +599,7 @@ async def get_organization_settings( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -601,13 +629,14 @@ async def get_source( r"""Gets a source. Args: - request (:class:`~.securitycenter_service.GetSourceRequest`): + request (:class:`google.cloud.securitycenter_v1beta1.types.GetSourceRequest`): The request object. Request message for getting a source. name (:class:`str`): Required. Relative resource name of the source. Its format is "organizations/[organization_id]/source/[source_id]". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -619,7 +648,7 @@ async def get_source( sent along with the request as metadata. Returns: - ~.source.Source: + google.cloud.securitycenter_v1beta1.types.Source: Security Command Center finding source. A finding source is an entity or a mechanism that can produce a finding. @@ -657,6 +686,7 @@ async def get_source( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -686,7 +716,7 @@ async def group_assets( their specified properties. Args: - request (:class:`~.securitycenter_service.GroupAssetsRequest`): + request (:class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest`): The request object. Request message for grouping by assets. @@ -697,7 +727,7 @@ async def group_assets( sent along with the request as metadata. Returns: - ~.pagers.GroupAssetsAsyncPager: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsAsyncPager: Response message for grouping by assets. Iterating over this object will yield @@ -720,6 +750,7 @@ async def group_assets( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=DEFAULT_CLIENT_INFO, @@ -761,7 +792,7 @@ async def group_findings( /v1beta1/organizations/{organization_id}/sources/-/findings Args: - request (:class:`~.securitycenter_service.GroupFindingsRequest`): + request (:class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest`): The request object. Request message for grouping by findings. parent (:class:`str`): @@ -770,6 +801,7 @@ async def group_findings( To groupBy across all sources provide a source_id of ``-``. For example: organizations/{organization_id}/sources/- + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -784,7 +816,7 @@ async def group_findings( - resource_name - category - state - - parent + - parent This corresponds to the ``group_by`` field on the ``request`` instance; if ``request`` is provided, this @@ -797,7 +829,7 @@ async def group_findings( sent along with the request as metadata. Returns: - ~.pagers.GroupFindingsAsyncPager: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsAsyncPager: Response message for group by findings. Iterating over this object will yield @@ -836,6 +868,7 @@ async def group_findings( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=DEFAULT_CLIENT_INFO, @@ -870,7 +903,7 @@ async def list_assets( r"""Lists an organization's assets. Args: - request (:class:`~.securitycenter_service.ListAssetsRequest`): + request (:class:`google.cloud.securitycenter_v1beta1.types.ListAssetsRequest`): The request object. Request message for listing assets. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -880,7 +913,7 @@ async def list_assets( sent along with the request as metadata. Returns: - ~.pagers.ListAssetsAsyncPager: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListAssetsAsyncPager: Response message for listing assets. Iterating over this object will yield results and resolve additional pages @@ -902,6 +935,7 @@ async def list_assets( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=DEFAULT_CLIENT_INFO, @@ -940,7 +974,7 @@ async def list_findings( /v1beta1/organizations/{organization_id}/sources/-/findings Args: - request (:class:`~.securitycenter_service.ListFindingsRequest`): + request (:class:`google.cloud.securitycenter_v1beta1.types.ListFindingsRequest`): The request object. Request message for listing findings. @@ -951,7 +985,7 @@ async def list_findings( sent along with the request as metadata. Returns: - ~.pagers.ListFindingsAsyncPager: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListFindingsAsyncPager: Response message for listing findings. Iterating over this object will yield @@ -974,6 +1008,7 @@ async def list_findings( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=DEFAULT_CLIENT_INFO, @@ -1009,12 +1044,13 @@ async def list_sources( r"""Lists all sources belonging to an organization. Args: - request (:class:`~.securitycenter_service.ListSourcesRequest`): + request (:class:`google.cloud.securitycenter_v1beta1.types.ListSourcesRequest`): The request object. Request message for listing sources. parent (:class:`str`): Required. Resource name of the parent of sources to list. Its format should be "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1026,7 +1062,7 @@ async def list_sources( sent along with the request as metadata. Returns: - ~.pagers.ListSourcesAsyncPager: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListSourcesAsyncPager: Response message for listing sources. Iterating over this object will yield results and resolve additional pages @@ -1062,6 +1098,7 @@ async def list_sources( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -1102,13 +1139,14 @@ async def run_asset_discovery( receive a TOO_MANY_REQUESTS error. Args: - request (:class:`~.securitycenter_service.RunAssetDiscoveryRequest`): + request (:class:`google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest`): The request object. Request message for running asset discovery for an organization. parent (:class:`str`): Required. Name of the organization to run asset discovery for. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1120,24 +1158,22 @@ async def run_asset_discovery( sent along with the request as metadata. Returns: - ~.operation_async.AsyncOperation: + google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be - :class:``~.empty.Empty``: A generic empty message that - you can re-use to avoid defining duplicated empty - messages in your APIs. A typical example is to use it as - the request or the response type of an API method. For - instance: + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: - :: + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); - service Foo { - rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); - } + } - The JSON representation for ``Empty`` is empty JSON - object ``{}``. + The JSON representation for Empty is empty JSON + object {}. """ # Create or coerce a protobuf request object. @@ -1200,7 +1236,7 @@ async def set_finding_state( r"""Updates the state of a finding. Args: - request (:class:`~.securitycenter_service.SetFindingStateRequest`): + request (:class:`google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest`): The request object. Request message for updating a finding's state. name (:class:`str`): @@ -1209,18 +1245,21 @@ async def set_finding_state( https://cloud.google.com/apis/design/resource_names#relative_resource_name Example: "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - state (:class:`~.finding.Finding.State`): + state (:class:`google.cloud.securitycenter_v1beta1.types.Finding.State`): Required. The desired State of the finding. + This corresponds to the ``state`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - start_time (:class:`~.timestamp.Timestamp`): + start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): Required. The time at which the updated state takes effect. + This corresponds to the ``start_time`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1232,7 +1271,7 @@ async def set_finding_state( sent along with the request as metadata. Returns: - ~.finding.Finding: + google.cloud.securitycenter_v1beta1.types.Finding: Security Command Center finding. A finding is a record of assessment data (security, risk, health or privacy) @@ -1299,7 +1338,7 @@ async def set_iam_policy( Source. Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): + request (:class:`google.iam.v1.iam_policy_pb2.SetIamPolicyRequest`): The request object. Request message for `SetIamPolicy` method. resource (:class:`str`): @@ -1307,6 +1346,7 @@ async def set_iam_policy( policy is being specified. See the operation documentation for the appropriate value for this field. + This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1318,72 +1358,62 @@ async def set_iam_policy( sent along with the request as metadata. Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). """ # Create or coerce a protobuf request object. @@ -1438,7 +1468,7 @@ async def test_iam_permissions( specified source. Args: - request (:class:`~.iam_policy.TestIamPermissionsRequest`): + request (:class:`google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest`): The request object. Request message for `TestIamPermissions` method. resource (:class:`str`): @@ -1446,6 +1476,7 @@ async def test_iam_permissions( policy detail is being requested. See the operation documentation for the appropriate value for this field. + This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1454,6 +1485,7 @@ async def test_iam_permissions( Permissions with wildcards (such as '*' or 'storage.*') are not allowed. For more information see `IAM Overview `__. + This corresponds to the ``permissions`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1465,8 +1497,8 @@ async def test_iam_permissions( sent along with the request as metadata. Returns: - ~.iam_policy.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have @@ -1499,6 +1531,7 @@ async def test_iam_permissions( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -1529,10 +1562,10 @@ async def update_finding( source must exist for a finding creation to succeed. Args: - request (:class:`~.securitycenter_service.UpdateFindingRequest`): + request (:class:`google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest`): The request object. Request message for updating or creating a finding. - finding (:class:`~.gcs_finding.Finding`): + finding (:class:`google.cloud.securitycenter_v1beta1.types.Finding`): Required. The finding resource to update or create if it does not already exist. parent, security_marks, and update_time will be ignored. @@ -1540,6 +1573,7 @@ async def update_finding( In the case of creation, the finding id portion of the name must alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. + This corresponds to the ``finding`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1551,7 +1585,7 @@ async def update_finding( sent along with the request as metadata. Returns: - ~.gcs_finding.Finding: + google.cloud.securitycenter_v1beta1.types.Finding: Security Command Center finding. A finding is a record of assessment data (security, risk, health or privacy) @@ -1615,12 +1649,13 @@ async def update_organization_settings( r"""Updates an organization's settings. Args: - request (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): + request (:class:`google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest`): The request object. Request message for updating an organization's settings. - organization_settings (:class:`~.gcs_organization_settings.OrganizationSettings`): + organization_settings (:class:`google.cloud.securitycenter_v1beta1.types.OrganizationSettings`): Required. The organization settings resource to update. + This corresponds to the ``organization_settings`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1632,7 +1667,7 @@ async def update_organization_settings( sent along with the request as metadata. Returns: - ~.gcs_organization_settings.OrganizationSettings: + google.cloud.securitycenter_v1beta1.types.OrganizationSettings: User specified settings that are attached to the Security Command Center organization. @@ -1690,12 +1725,13 @@ async def update_source( r"""Updates a source. Args: - request (:class:`~.securitycenter_service.UpdateSourceRequest`): + request (:class:`google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest`): The request object. Request message for updating a source. - source (:class:`~.gcs_source.Source`): + source (:class:`google.cloud.securitycenter_v1beta1.types.Source`): Required. The source resource to update. + This corresponds to the ``source`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1707,7 +1743,7 @@ async def update_source( sent along with the request as metadata. Returns: - ~.gcs_source.Source: + google.cloud.securitycenter_v1beta1.types.Source: Security Command Center finding source. A finding source is an entity or a mechanism that can produce a finding. @@ -1768,12 +1804,13 @@ async def update_security_marks( r"""Updates security marks. Args: - request (:class:`~.securitycenter_service.UpdateSecurityMarksRequest`): + request (:class:`google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest`): The request object. Request message for updating a SecurityMarks resource. - security_marks (:class:`~.gcs_security_marks.SecurityMarks`): + security_marks (:class:`google.cloud.securitycenter_v1beta1.types.SecurityMarks`): Required. The security marks resource to update. + This corresponds to the ``security_marks`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1785,7 +1822,7 @@ async def update_security_marks( sent along with the request as metadata. Returns: - ~.gcs_security_marks.SecurityMarks: + google.cloud.securitycenter_v1beta1.types.SecurityMarks: User specified security marks that are attached to the parent Security Command Center resource. Security marks diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/client.py b/google/cloud/securitycenter_v1beta1/services/security_center/client.py index a27f307b..73dd2f2a 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/client.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/client.py @@ -128,6 +128,22 @@ def _get_default_mtls_endpoint(api_endpoint): DEFAULT_ENDPOINT ) + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SecurityCenterClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -140,7 +156,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): kwargs: Additional arguments to pass to the constructor. Returns: - {@api.name}: The constructed client. + SecurityCenterClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials @@ -309,10 +325,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - transport (Union[str, ~.SecurityCenterTransport]): The + transport (Union[str, SecurityCenterTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (client_options_lib.ClientOptions): Custom options for the + client_options (google.api_core.client_options.ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT @@ -348,21 +364,17 @@ def __init__( util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) ) - ssl_credentials = None + client_cert_source_func = None is_mtls = False if use_client_cert: if client_options.client_cert_source: - import grpc # type: ignore - - cert, key = client_options.client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) is_mtls = True + client_cert_source_func = client_options.client_cert_source else: - creds = SslCredentials() - is_mtls = creds.is_mtls - ssl_credentials = creds.ssl_credentials if is_mtls else None + is_mtls = mtls.has_default_client_cert_source() + client_cert_source_func = ( + mtls.default_client_cert_source() if is_mtls else None + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -405,7 +417,7 @@ def __init__( credentials_file=client_options.credentials_file, host=api_endpoint, scopes=client_options.scopes, - ssl_channel_credentials=ssl_credentials, + client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, ) @@ -423,19 +435,21 @@ def create_source( r"""Creates a source. Args: - request (:class:`~.securitycenter_service.CreateSourceRequest`): + request (google.cloud.securitycenter_v1beta1.types.CreateSourceRequest): The request object. Request message for creating a source. - parent (:class:`str`): + parent (str): Required. Resource name of the new source's parent. Its format should be "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - source (:class:`~.gcs_source.Source`): + source (google.cloud.securitycenter_v1beta1.types.Source): Required. The Source being created, only the display_name and description will be used. All other fields will be ignored. + This corresponds to the ``source`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -447,7 +461,7 @@ def create_source( sent along with the request as metadata. Returns: - ~.gcs_source.Source: + google.cloud.securitycenter_v1beta1.types.Source: Security Command Center finding source. A finding source is an entity or a mechanism that can produce a finding. @@ -512,29 +526,32 @@ def create_finding( exist for finding creation to succeed. Args: - request (:class:`~.securitycenter_service.CreateFindingRequest`): + request (google.cloud.securitycenter_v1beta1.types.CreateFindingRequest): The request object. Request message for creating a finding. - parent (:class:`str`): + parent (str): Required. Resource name of the new finding's parent. Its format should be "organizations/[organization_id]/sources/[source_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - finding_id (:class:`str`): + finding_id (str): Required. Unique identifier provided by the client within the parent scope. It must be alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. + This corresponds to the ``finding_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - finding (:class:`~.gcs_finding.Finding`): + finding (google.cloud.securitycenter_v1beta1.types.Finding): Required. The Finding being created. The name and security_marks will be ignored as they are both output only fields on this resource. + This corresponds to the ``finding`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -546,7 +563,7 @@ def create_finding( sent along with the request as metadata. Returns: - ~.gcs_finding.Finding: + google.cloud.securitycenter_v1beta1.types.Finding: Security Command Center finding. A finding is a record of assessment data (security, risk, health or privacy) @@ -614,14 +631,15 @@ def get_iam_policy( Source. Args: - request (:class:`~.iam_policy.GetIamPolicyRequest`): + request (google.iam.v1.iam_policy_pb2.GetIamPolicyRequest): The request object. Request message for `GetIamPolicy` method. - resource (:class:`str`): + resource (str): REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field. + This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -633,72 +651,62 @@ def get_iam_policy( sent along with the request as metadata. Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). """ # Create or coerce a protobuf request object. @@ -711,13 +719,16 @@ def get_iam_policy( "the individual field arguments should be set." ) - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. request = iam_policy.GetIamPolicyRequest(**request) - elif not request: - request = iam_policy.GetIamPolicyRequest(resource=resource,) + # Null request, just make one. + request = iam_policy.GetIamPolicyRequest() + + if resource is not None: + request.resource = resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -747,13 +758,14 @@ def get_organization_settings( r"""Gets the settings for an organization. Args: - request (:class:`~.securitycenter_service.GetOrganizationSettingsRequest`): + request (google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest): The request object. Request message for getting organization settings. - name (:class:`str`): + name (str): Required. Name of the organization to get organization settings for. Its format is "organizations/[organization_id]/organizationSettings". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -765,7 +777,7 @@ def get_organization_settings( sent along with the request as metadata. Returns: - ~.organization_settings.OrganizationSettings: + google.cloud.securitycenter_v1beta1.types.OrganizationSettings: User specified settings that are attached to the Security Command Center organization. @@ -826,13 +838,14 @@ def get_source( r"""Gets a source. Args: - request (:class:`~.securitycenter_service.GetSourceRequest`): + request (google.cloud.securitycenter_v1beta1.types.GetSourceRequest): The request object. Request message for getting a source. - name (:class:`str`): + name (str): Required. Relative resource name of the source. Its format is "organizations/[organization_id]/source/[source_id]". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -844,7 +857,7 @@ def get_source( sent along with the request as metadata. Returns: - ~.source.Source: + google.cloud.securitycenter_v1beta1.types.Source: Security Command Center finding source. A finding source is an entity or a mechanism that can produce a finding. @@ -904,7 +917,7 @@ def group_assets( their specified properties. Args: - request (:class:`~.securitycenter_service.GroupAssetsRequest`): + request (google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest): The request object. Request message for grouping by assets. @@ -915,7 +928,7 @@ def group_assets( sent along with the request as metadata. Returns: - ~.pagers.GroupAssetsPager: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsPager: Response message for grouping by assets. Iterating over this object will yield @@ -972,19 +985,20 @@ def group_findings( /v1beta1/organizations/{organization_id}/sources/-/findings Args: - request (:class:`~.securitycenter_service.GroupFindingsRequest`): + request (google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest): The request object. Request message for grouping by findings. - parent (:class:`str`): + parent (str): Required. Name of the source to groupBy. Its format is "organizations/[organization_id]/sources/[source_id]". To groupBy across all sources provide a source_id of ``-``. For example: organizations/{organization_id}/sources/- + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - group_by (:class:`str`): + group_by (str): Required. Expression that defines what assets fields to use for grouping (including ``state``). The string value should follow SQL syntax: comma separated list of @@ -995,7 +1009,7 @@ def group_findings( - resource_name - category - state - - parent + - parent This corresponds to the ``group_by`` field on the ``request`` instance; if ``request`` is provided, this @@ -1008,7 +1022,7 @@ def group_findings( sent along with the request as metadata. Returns: - ~.pagers.GroupFindingsPager: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsPager: Response message for group by findings. Iterating over this object will yield @@ -1074,7 +1088,7 @@ def list_assets( r"""Lists an organization's assets. Args: - request (:class:`~.securitycenter_service.ListAssetsRequest`): + request (google.cloud.securitycenter_v1beta1.types.ListAssetsRequest): The request object. Request message for listing assets. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -1084,7 +1098,7 @@ def list_assets( sent along with the request as metadata. Returns: - ~.pagers.ListAssetsPager: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListAssetsPager: Response message for listing assets. Iterating over this object will yield results and resolve additional pages @@ -1137,7 +1151,7 @@ def list_findings( /v1beta1/organizations/{organization_id}/sources/-/findings Args: - request (:class:`~.securitycenter_service.ListFindingsRequest`): + request (google.cloud.securitycenter_v1beta1.types.ListFindingsRequest): The request object. Request message for listing findings. @@ -1148,7 +1162,7 @@ def list_findings( sent along with the request as metadata. Returns: - ~.pagers.ListFindingsPager: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListFindingsPager: Response message for listing findings. Iterating over this object will yield @@ -1199,12 +1213,13 @@ def list_sources( r"""Lists all sources belonging to an organization. Args: - request (:class:`~.securitycenter_service.ListSourcesRequest`): + request (google.cloud.securitycenter_v1beta1.types.ListSourcesRequest): The request object. Request message for listing sources. - parent (:class:`str`): + parent (str): Required. Resource name of the parent of sources to list. Its format should be "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1216,7 +1231,7 @@ def list_sources( sent along with the request as metadata. Returns: - ~.pagers.ListSourcesPager: + google.cloud.securitycenter_v1beta1.services.security_center.pagers.ListSourcesPager: Response message for listing sources. Iterating over this object will yield results and resolve additional pages @@ -1285,13 +1300,14 @@ def run_asset_discovery( receive a TOO_MANY_REQUESTS error. Args: - request (:class:`~.securitycenter_service.RunAssetDiscoveryRequest`): + request (google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest): The request object. Request message for running asset discovery for an organization. - parent (:class:`str`): + parent (str): Required. Name of the organization to run asset discovery for. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1303,24 +1319,22 @@ def run_asset_discovery( sent along with the request as metadata. Returns: - ~.operation.Operation: + google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be - :class:``~.empty.Empty``: A generic empty message that - you can re-use to avoid defining duplicated empty - messages in your APIs. A typical example is to use it as - the request or the response type of an API method. For - instance: + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: - :: + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); - service Foo { - rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); - } + } - The JSON representation for ``Empty`` is empty JSON - object ``{}``. + The JSON representation for Empty is empty JSON + object {}. """ # Create or coerce a protobuf request object. @@ -1384,27 +1398,30 @@ def set_finding_state( r"""Updates the state of a finding. Args: - request (:class:`~.securitycenter_service.SetFindingStateRequest`): + request (google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest): The request object. Request message for updating a finding's state. - name (:class:`str`): + name (str): Required. The relative resource name of the finding. See: https://cloud.google.com/apis/design/resource_names#relative_resource_name Example: "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - state (:class:`~.finding.Finding.State`): + state (google.cloud.securitycenter_v1beta1.types.Finding.State): Required. The desired State of the finding. + This corresponds to the ``state`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - start_time (:class:`~.timestamp.Timestamp`): + start_time (google.protobuf.timestamp_pb2.Timestamp): Required. The time at which the updated state takes effect. + This corresponds to the ``start_time`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1416,7 +1433,7 @@ def set_finding_state( sent along with the request as metadata. Returns: - ~.finding.Finding: + google.cloud.securitycenter_v1beta1.types.Finding: Security Command Center finding. A finding is a record of assessment data (security, risk, health or privacy) @@ -1484,14 +1501,15 @@ def set_iam_policy( Source. Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): + request (google.iam.v1.iam_policy_pb2.SetIamPolicyRequest): The request object. Request message for `SetIamPolicy` method. - resource (:class:`str`): + resource (str): REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field. + This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1503,72 +1521,62 @@ def set_iam_policy( sent along with the request as metadata. Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). """ # Create or coerce a protobuf request object. @@ -1581,13 +1589,16 @@ def set_iam_policy( "the individual field arguments should be set." ) - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. request = iam_policy.SetIamPolicyRequest(**request) - elif not request: - request = iam_policy.SetIamPolicyRequest(resource=resource,) + # Null request, just make one. + request = iam_policy.SetIamPolicyRequest() + + if resource is not None: + request.resource = resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1619,22 +1630,24 @@ def test_iam_permissions( specified source. Args: - request (:class:`~.iam_policy.TestIamPermissionsRequest`): + request (google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest): The request object. Request message for `TestIamPermissions` method. - resource (:class:`str`): + resource (str): REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field. + This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - permissions (:class:`Sequence[str]`): + permissions (Sequence[str]): The set of permissions to check for the ``resource``. Permissions with wildcards (such as '*' or 'storage.*') are not allowed. For more information see `IAM Overview `__. + This corresponds to the ``permissions`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1646,8 +1659,8 @@ def test_iam_permissions( sent along with the request as metadata. Returns: - ~.iam_policy.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have @@ -1659,15 +1672,19 @@ def test_iam_permissions( "the individual field arguments should be set." ) - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. request = iam_policy.TestIamPermissionsRequest(**request) - elif not request: - request = iam_policy.TestIamPermissionsRequest( - resource=resource, permissions=permissions, - ) + # Null request, just make one. + request = iam_policy.TestIamPermissionsRequest() + + if resource is not None: + request.resource = resource + + if permissions: + request.permissions.extend(permissions) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1698,10 +1715,10 @@ def update_finding( source must exist for a finding creation to succeed. Args: - request (:class:`~.securitycenter_service.UpdateFindingRequest`): + request (google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest): The request object. Request message for updating or creating a finding. - finding (:class:`~.gcs_finding.Finding`): + finding (google.cloud.securitycenter_v1beta1.types.Finding): Required. The finding resource to update or create if it does not already exist. parent, security_marks, and update_time will be ignored. @@ -1709,6 +1726,7 @@ def update_finding( In the case of creation, the finding id portion of the name must alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. + This corresponds to the ``finding`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1720,7 +1738,7 @@ def update_finding( sent along with the request as metadata. Returns: - ~.gcs_finding.Finding: + google.cloud.securitycenter_v1beta1.types.Finding: Security Command Center finding. A finding is a record of assessment data (security, risk, health or privacy) @@ -1785,12 +1803,13 @@ def update_organization_settings( r"""Updates an organization's settings. Args: - request (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): + request (google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest): The request object. Request message for updating an organization's settings. - organization_settings (:class:`~.gcs_organization_settings.OrganizationSettings`): + organization_settings (google.cloud.securitycenter_v1beta1.types.OrganizationSettings): Required. The organization settings resource to update. + This corresponds to the ``organization_settings`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1802,7 +1821,7 @@ def update_organization_settings( sent along with the request as metadata. Returns: - ~.gcs_organization_settings.OrganizationSettings: + google.cloud.securitycenter_v1beta1.types.OrganizationSettings: User specified settings that are attached to the Security Command Center organization. @@ -1865,12 +1884,13 @@ def update_source( r"""Updates a source. Args: - request (:class:`~.securitycenter_service.UpdateSourceRequest`): + request (google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest): The request object. Request message for updating a source. - source (:class:`~.gcs_source.Source`): + source (google.cloud.securitycenter_v1beta1.types.Source): Required. The source resource to update. + This corresponds to the ``source`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1882,7 +1902,7 @@ def update_source( sent along with the request as metadata. Returns: - ~.gcs_source.Source: + google.cloud.securitycenter_v1beta1.types.Source: Security Command Center finding source. A finding source is an entity or a mechanism that can produce a finding. @@ -1944,12 +1964,13 @@ def update_security_marks( r"""Updates security marks. Args: - request (:class:`~.securitycenter_service.UpdateSecurityMarksRequest`): + request (google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest): The request object. Request message for updating a SecurityMarks resource. - security_marks (:class:`~.gcs_security_marks.SecurityMarks`): + security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): Required. The security marks resource to update. + This corresponds to the ``security_marks`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1961,7 +1982,7 @@ def update_security_marks( sent along with the request as metadata. Returns: - ~.gcs_security_marks.SecurityMarks: + google.cloud.securitycenter_v1beta1.types.SecurityMarks: User specified security marks that are attached to the parent Security Command Center resource. Security marks diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py b/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py index 64ef79bd..a3a18cc4 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py @@ -15,7 +15,16 @@ # limitations under the License. # -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple +from typing import ( + Any, + AsyncIterable, + Awaitable, + Callable, + Iterable, + Sequence, + Tuple, + Optional, +) from google.cloud.securitycenter_v1beta1.types import finding from google.cloud.securitycenter_v1beta1.types import securitycenter_service @@ -26,7 +35,7 @@ class GroupAssetsPager: """A pager for iterating through ``group_assets`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.GroupAssetsResponse` object, and + :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` object, and provides an ``__iter__`` method to iterate through its ``group_by_results`` field. @@ -35,7 +44,7 @@ class GroupAssetsPager: through the ``group_by_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.GroupAssetsResponse` + All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -53,9 +62,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.GroupAssetsRequest`): + request (google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest): The initial request object. - response (:class:`~.securitycenter_service.GroupAssetsResponse`): + response (google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -88,7 +97,7 @@ class GroupAssetsAsyncPager: """A pager for iterating through ``group_assets`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.GroupAssetsResponse` object, and + :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` object, and provides an ``__aiter__`` method to iterate through its ``group_by_results`` field. @@ -97,7 +106,7 @@ class GroupAssetsAsyncPager: through the ``group_by_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.GroupAssetsResponse` + All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -115,9 +124,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.GroupAssetsRequest`): + request (google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest): The initial request object. - response (:class:`~.securitycenter_service.GroupAssetsResponse`): + response (google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -154,7 +163,7 @@ class GroupFindingsPager: """A pager for iterating through ``group_findings`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.GroupFindingsResponse` object, and + :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` object, and provides an ``__iter__`` method to iterate through its ``group_by_results`` field. @@ -163,7 +172,7 @@ class GroupFindingsPager: through the ``group_by_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.GroupFindingsResponse` + All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -181,9 +190,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.GroupFindingsRequest`): + request (google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest): The initial request object. - response (:class:`~.securitycenter_service.GroupFindingsResponse`): + response (google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -216,7 +225,7 @@ class GroupFindingsAsyncPager: """A pager for iterating through ``group_findings`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.GroupFindingsResponse` object, and + :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` object, and provides an ``__aiter__`` method to iterate through its ``group_by_results`` field. @@ -225,7 +234,7 @@ class GroupFindingsAsyncPager: through the ``group_by_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.GroupFindingsResponse` + All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -243,9 +252,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.GroupFindingsRequest`): + request (google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest): The initial request object. - response (:class:`~.securitycenter_service.GroupFindingsResponse`): + response (google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -284,7 +293,7 @@ class ListAssetsPager: """A pager for iterating through ``list_assets`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListAssetsResponse` object, and + :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` object, and provides an ``__iter__`` method to iterate through its ``list_assets_results`` field. @@ -293,7 +302,7 @@ class ListAssetsPager: through the ``list_assets_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListAssetsResponse` + All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -311,9 +320,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListAssetsRequest`): + request (google.cloud.securitycenter_v1beta1.types.ListAssetsRequest): The initial request object. - response (:class:`~.securitycenter_service.ListAssetsResponse`): + response (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -348,7 +357,7 @@ class ListAssetsAsyncPager: """A pager for iterating through ``list_assets`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListAssetsResponse` object, and + :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` object, and provides an ``__aiter__`` method to iterate through its ``list_assets_results`` field. @@ -357,7 +366,7 @@ class ListAssetsAsyncPager: through the ``list_assets_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListAssetsResponse` + All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -375,9 +384,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListAssetsRequest`): + request (google.cloud.securitycenter_v1beta1.types.ListAssetsRequest): The initial request object. - response (:class:`~.securitycenter_service.ListAssetsResponse`): + response (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -416,7 +425,7 @@ class ListFindingsPager: """A pager for iterating through ``list_findings`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListFindingsResponse` object, and + :class:`google.cloud.securitycenter_v1beta1.types.ListFindingsResponse` object, and provides an ``__iter__`` method to iterate through its ``findings`` field. @@ -425,7 +434,7 @@ class ListFindingsPager: through the ``findings`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListFindingsResponse` + All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListFindingsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -443,9 +452,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListFindingsRequest`): + request (google.cloud.securitycenter_v1beta1.types.ListFindingsRequest): The initial request object. - response (:class:`~.securitycenter_service.ListFindingsResponse`): + response (google.cloud.securitycenter_v1beta1.types.ListFindingsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -478,7 +487,7 @@ class ListFindingsAsyncPager: """A pager for iterating through ``list_findings`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListFindingsResponse` object, and + :class:`google.cloud.securitycenter_v1beta1.types.ListFindingsResponse` object, and provides an ``__aiter__`` method to iterate through its ``findings`` field. @@ -487,7 +496,7 @@ class ListFindingsAsyncPager: through the ``findings`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListFindingsResponse` + All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListFindingsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -505,9 +514,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListFindingsRequest`): + request (google.cloud.securitycenter_v1beta1.types.ListFindingsRequest): The initial request object. - response (:class:`~.securitycenter_service.ListFindingsResponse`): + response (google.cloud.securitycenter_v1beta1.types.ListFindingsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -544,7 +553,7 @@ class ListSourcesPager: """A pager for iterating through ``list_sources`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListSourcesResponse` object, and + :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` object, and provides an ``__iter__`` method to iterate through its ``sources`` field. @@ -553,7 +562,7 @@ class ListSourcesPager: through the ``sources`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListSourcesResponse` + All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -571,9 +580,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListSourcesRequest`): + request (google.cloud.securitycenter_v1beta1.types.ListSourcesRequest): The initial request object. - response (:class:`~.securitycenter_service.ListSourcesResponse`): + response (google.cloud.securitycenter_v1beta1.types.ListSourcesResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -606,7 +615,7 @@ class ListSourcesAsyncPager: """A pager for iterating through ``list_sources`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListSourcesResponse` object, and + :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` object, and provides an ``__aiter__`` method to iterate through its ``sources`` field. @@ -615,7 +624,7 @@ class ListSourcesAsyncPager: through the ``sources`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListSourcesResponse` + All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -633,9 +642,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListSourcesRequest`): + request (google.cloud.securitycenter_v1beta1.types.ListSourcesRequest): The initial request object. - response (:class:`~.securitycenter_service.ListSourcesResponse`): + response (google.cloud.securitycenter_v1beta1.types.ListSourcesResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py index df35096b..3a22dfc9 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py @@ -23,7 +23,6 @@ from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore from google.auth import credentials # type: ignore @@ -85,10 +84,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. @@ -96,6 +95,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: @@ -105,20 +107,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 = { @@ -137,6 +136,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, @@ -150,6 +150,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, @@ -163,6 +164,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, @@ -176,6 +178,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=client_info, @@ -189,6 +192,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=client_info, @@ -202,6 +206,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=client_info, @@ -215,6 +220,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=client_info, @@ -228,6 +234,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, @@ -250,6 +257,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/securitycenter_v1beta1/services/security_center/transports/grpc.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py index a7447d0b..2bcfb198 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py @@ -72,6 +72,7 @@ def __init__( api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -102,6 +103,10 @@ def __init__( ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -116,72 +121,61 @@ 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] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # 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: - warnings.warn( - "api_mtls_endpoint and client_cert_source are deprecated", - DeprecationWarning, - ) - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials - 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 + 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 + ) - # 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 credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + # 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, - ssl_credentials=ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -189,18 +183,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # 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( @@ -214,7 +198,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/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py index 2a2d3551..f401d887 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py @@ -76,7 +76,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 @@ -116,6 +116,7 @@ def __init__( api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -147,12 +148,16 @@ def __init__( ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing + 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: @@ -161,72 +166,61 @@ 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] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # 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: - warnings.warn( - "api_mtls_endpoint and client_cert_source are deprecated", - DeprecationWarning, - ) - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials - 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 + 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 + ) - # 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 credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + # 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, - ssl_credentials=ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -234,18 +228,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 = {} - self._operations_client = None + # 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/securitycenter_v1beta1/types/__init__.py b/google/cloud/securitycenter_v1beta1/types/__init__.py index 11c4424f..1f373080 100644 --- a/google/cloud/securitycenter_v1beta1/types/__init__.py +++ b/google/cloud/securitycenter_v1beta1/types/__init__.py @@ -15,12 +15,11 @@ # limitations under the License. # -from .security_marks import SecurityMarks from .asset import Asset from .finding import Finding from .organization_settings import OrganizationSettings from .run_asset_discovery_response import RunAssetDiscoveryResponse -from .source import Source +from .security_marks import SecurityMarks from .securitycenter_service import ( CreateFindingRequest, CreateSourceRequest, @@ -31,27 +30,27 @@ GroupFindingsRequest, GroupFindingsResponse, GroupResult, - ListSourcesRequest, - ListSourcesResponse, ListAssetsRequest, ListAssetsResponse, ListFindingsRequest, ListFindingsResponse, - SetFindingStateRequest, + ListSourcesRequest, + ListSourcesResponse, RunAssetDiscoveryRequest, + SetFindingStateRequest, UpdateFindingRequest, UpdateOrganizationSettingsRequest, - UpdateSourceRequest, UpdateSecurityMarksRequest, + UpdateSourceRequest, ) +from .source import Source __all__ = ( - "SecurityMarks", "Asset", "Finding", "OrganizationSettings", "RunAssetDiscoveryResponse", - "Source", + "SecurityMarks", "CreateFindingRequest", "CreateSourceRequest", "GetOrganizationSettingsRequest", @@ -61,16 +60,17 @@ "GroupFindingsRequest", "GroupFindingsResponse", "GroupResult", - "ListSourcesRequest", - "ListSourcesResponse", "ListAssetsRequest", "ListAssetsResponse", "ListFindingsRequest", "ListFindingsResponse", - "SetFindingStateRequest", + "ListSourcesRequest", + "ListSourcesResponse", "RunAssetDiscoveryRequest", + "SetFindingStateRequest", "UpdateFindingRequest", "UpdateOrganizationSettingsRequest", - "UpdateSourceRequest", "UpdateSecurityMarksRequest", + "UpdateSourceRequest", + "Source", ) diff --git a/google/cloud/securitycenter_v1beta1/types/asset.py b/google/cloud/securitycenter_v1beta1/types/asset.py index 80b4082d..75d676b8 100644 --- a/google/cloud/securitycenter_v1beta1/types/asset.py +++ b/google/cloud/securitycenter_v1beta1/types/asset.py @@ -46,23 +46,23 @@ class Asset(proto.Message): https://cloud.google.com/apis/design/resource_names#relative_resource_name Example: "organizations/{organization_id}/assets/{asset_id}". - security_center_properties (~.asset.Asset.SecurityCenterProperties): + security_center_properties (google.cloud.securitycenter_v1beta1.types.Asset.SecurityCenterProperties): Security Command Center managed properties. These properties are managed by Security Command Center and cannot be modified by the user. - resource_properties (Sequence[~.asset.Asset.ResourcePropertiesEntry]): + resource_properties (Sequence[google.cloud.securitycenter_v1beta1.types.Asset.ResourcePropertiesEntry]): Resource managed properties. These properties are managed and defined by the Google Cloud resource and cannot be modified by the user. - security_marks (~.gcs_security_marks.SecurityMarks): + security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): User specified security marks. These marks are entirely managed by the user and come from the SecurityMarks resource that belongs to the asset. - create_time (~.timestamp.Timestamp): + create_time (google.protobuf.timestamp_pb2.Timestamp): The time at which the asset was created in Security Command Center. - update_time (~.timestamp.Timestamp): + update_time (google.protobuf.timestamp_pb2.Timestamp): The time at which the asset was last updated, added, or deleted in Security Command Center. """ diff --git a/google/cloud/securitycenter_v1beta1/types/finding.py b/google/cloud/securitycenter_v1beta1/types/finding.py index b2a07a64..6b48d620 100644 --- a/google/cloud/securitycenter_v1beta1/types/finding.py +++ b/google/cloud/securitycenter_v1beta1/types/finding.py @@ -57,7 +57,7 @@ class Finding(proto.Message): When the finding is for a non-Google Cloud resource, the resourceName can be a customer or partner defined string. This field is immutable after creation time. - state (~.finding.Finding.State): + state (google.cloud.securitycenter_v1beta1.types.Finding.State): The state of the finding. category (str): The additional taxonomy group within findings from a given @@ -69,18 +69,18 @@ class Finding(proto.Message): additional information about the finding can be found. This field is guaranteed to be either empty or a well formed URL. - source_properties (Sequence[~.finding.Finding.SourcePropertiesEntry]): + source_properties (Sequence[google.cloud.securitycenter_v1beta1.types.Finding.SourcePropertiesEntry]): Source specific properties. These properties are managed by the source that writes the finding. The key names in the source_properties map must be between 1 and 255 characters, and must start with a letter and contain alphanumeric characters or underscores only. - security_marks (~.gcs_security_marks.SecurityMarks): + security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): Output only. User specified security marks. These marks are entirely managed by the user and come from the SecurityMarks resource that belongs to the finding. - event_time (~.timestamp.Timestamp): + event_time (google.protobuf.timestamp_pb2.Timestamp): The time at which the event took place, or when an update to the finding occurred. For example, if the finding represents an open @@ -89,7 +89,7 @@ class Finding(proto.Message): is determined by the detector. If the finding were to be resolved afterward, this time would reflect when the finding was resolved. - create_time (~.timestamp.Timestamp): + create_time (google.protobuf.timestamp_pb2.Timestamp): The time at which the finding was created in Security Command Center. """ diff --git a/google/cloud/securitycenter_v1beta1/types/organization_settings.py b/google/cloud/securitycenter_v1beta1/types/organization_settings.py index 3b3ae0b1..f8a2a563 100644 --- a/google/cloud/securitycenter_v1beta1/types/organization_settings.py +++ b/google/cloud/securitycenter_v1beta1/types/organization_settings.py @@ -38,7 +38,7 @@ class OrganizationSettings(proto.Message): If the flag is set to ``true``, then discovery of assets will occur. If it is set to \`false, all historical assets will remain, but discovery of future assets will not occur. - asset_discovery_config (~.organization_settings.OrganizationSettings.AssetDiscoveryConfig): + asset_discovery_config (google.cloud.securitycenter_v1beta1.types.OrganizationSettings.AssetDiscoveryConfig): The configuration used for Asset Discovery runs. """ @@ -50,7 +50,7 @@ class AssetDiscoveryConfig(proto.Message): project_ids (Sequence[str]): The project ids to use for filtering asset discovery. - inclusion_mode (~.organization_settings.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): + inclusion_mode (google.cloud.securitycenter_v1beta1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): The mode to use for filtering asset discovery. """ diff --git a/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py b/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py index 0b9e9d95..5d444d6b 100644 --- a/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py +++ b/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py @@ -31,9 +31,9 @@ class RunAssetDiscoveryResponse(proto.Message): r"""Response of asset discovery run Attributes: - state (~.run_asset_discovery_response.RunAssetDiscoveryResponse.State): + state (google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryResponse.State): The state of an asset discovery run. - duration (~.gp_duration.Duration): + duration (google.protobuf.duration_pb2.Duration): The duration between asset discovery run start and end """ diff --git a/google/cloud/securitycenter_v1beta1/types/security_marks.py b/google/cloud/securitycenter_v1beta1/types/security_marks.py index 7964b095..fa5b1795 100644 --- a/google/cloud/securitycenter_v1beta1/types/security_marks.py +++ b/google/cloud/securitycenter_v1beta1/types/security_marks.py @@ -37,7 +37,7 @@ class SecurityMarks(proto.Message): Examples: "organizations/{organization_id}/assets/{asset_id}/securityMarks" "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". - marks (Sequence[~.security_marks.SecurityMarks.MarksEntry]): + marks (Sequence[google.cloud.securitycenter_v1beta1.types.SecurityMarks.MarksEntry]): Mutable user specified security marks belonging to the parent resource. Constraints are as follows: diff --git a/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py b/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py index 833f60fc..dec898c5 100644 --- a/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py +++ b/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py @@ -75,7 +75,7 @@ class CreateFindingRequest(proto.Message): alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. - finding (~.gcs_finding.Finding): + finding (google.cloud.securitycenter_v1beta1.types.Finding): Required. The Finding being created. The name and security_marks will be ignored as they are both output only fields on this resource. @@ -95,7 +95,7 @@ class CreateSourceRequest(proto.Message): parent (str): Required. Resource name of the new source's parent. Its format should be "organizations/[organization_id]". - source (~.gcs_source.Source): + source (google.cloud.securitycenter_v1beta1.types.Source): Required. The Source being created, only the display_name and description will be used. All other fields will be ignored. @@ -186,7 +186,7 @@ class GroupAssetsRequest(proto.Message): set: - security_center_properties.resource_type - compare_duration (~.duration.Duration): + compare_duration (google.protobuf.duration_pb2.Duration): When compare_duration is set, the Asset's "state" property is updated to indicate whether the asset was added, removed, or remained present during the compare_duration period of @@ -212,7 +212,7 @@ class GroupAssetsRequest(proto.Message): This field is ignored if ``state`` is not a field in ``group_by``. - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used as a reference point when filtering assets. The filter is limited to assets existing at the supplied time and their values are those @@ -248,13 +248,13 @@ class GroupAssetsResponse(proto.Message): r"""Response message for grouping by assets. Attributes: - group_by_results (Sequence[~.securitycenter_service.GroupResult]): + group_by_results (Sequence[google.cloud.securitycenter_v1beta1.types.GroupResult]): Group results. There exists an element for each existing unique combination of property/values. The element contains a count for the number of times those specific property/values appear. - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used for executing the groupBy request. next_page_token (str): Token to retrieve the next page of results, @@ -324,7 +324,7 @@ class GroupFindingsRequest(proto.Message): - category - state - parent - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used as a reference point when filtering findings. The filter is limited to findings existing at the supplied time and their values @@ -358,13 +358,13 @@ class GroupFindingsResponse(proto.Message): r"""Response message for group by findings. Attributes: - group_by_results (Sequence[~.securitycenter_service.GroupResult]): + group_by_results (Sequence[google.cloud.securitycenter_v1beta1.types.GroupResult]): Group results. There exists an element for each existing unique combination of property/values. The element contains a count for the number of times those specific property/values appear. - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used for executing the groupBy request. next_page_token (str): Token to retrieve the next page of results, @@ -389,7 +389,7 @@ class GroupResult(proto.Message): request. Attributes: - properties (Sequence[~.securitycenter_service.GroupResult.PropertiesEntry]): + properties (Sequence[google.cloud.securitycenter_v1beta1.types.GroupResult.PropertiesEntry]): Properties matching the groupBy fields in the request. count (int): @@ -433,7 +433,7 @@ class ListSourcesResponse(proto.Message): r"""Response message for listing sources. Attributes: - sources (Sequence[~.gcs_source.Source]): + sources (Sequence[google.cloud.securitycenter_v1beta1.types.Source]): Sources belonging to the requested parent. next_page_token (str): Token to retrieve the next page of results, @@ -498,13 +498,13 @@ class ListAssetsRequest(proto.Message): Redundant space characters in the syntax are insignificant. "name desc,resource_properties.a_property" and " name desc , resource_properties.a_property " are equivalent. - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used as a reference point when filtering assets. The filter is limited to assets existing at the supplied time and their values are those at that specific time. Absence of this field will default to the API's version of NOW. - compare_duration (~.duration.Duration): + compare_duration (google.protobuf.duration_pb2.Duration): When compare_duration is set, the ListAssetResult's "state" attribute is updated to indicate whether the asset was added, removed, or remained present during the @@ -531,7 +531,7 @@ class ListAssetsRequest(proto.Message): If compare_duration is not specified, then the only possible state is "UNUSED", which indicates that the asset is present at read_time. - field_mask (~.gp_field_mask.FieldMask): + field_mask (google.protobuf.field_mask_pb2.FieldMask): Optional. A field mask to specify the ListAssetsResult fields to be listed in the response. An empty field mask will list all @@ -568,9 +568,9 @@ class ListAssetsResponse(proto.Message): r"""Response message for listing assets. Attributes: - list_assets_results (Sequence[~.securitycenter_service.ListAssetsResponse.ListAssetsResult]): + list_assets_results (Sequence[google.cloud.securitycenter_v1beta1.types.ListAssetsResponse.ListAssetsResult]): Assets matching the list request. - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used for executing the list request. next_page_token (str): Token to retrieve the next page of results, @@ -584,9 +584,9 @@ class ListAssetsResult(proto.Message): r"""Result containing the Asset and its State. Attributes: - asset (~.gcs_asset.Asset): + asset (google.cloud.securitycenter_v1beta1.types.Asset): Asset matching the search request. - state (~.securitycenter_service.ListAssetsResponse.ListAssetsResult.State): + state (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse.ListAssetsResult.State): State of the asset. """ @@ -674,13 +674,13 @@ class ListFindingsRequest(proto.Message): space characters in the syntax are insignificant. "name desc,source_properties.a_property" and " name desc , source_properties.a_property " are equivalent. - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used as a reference point when filtering findings. The filter is limited to findings existing at the supplied time and their values are those at that specific time. Absence of this field will default to the API's version of NOW. - field_mask (~.gp_field_mask.FieldMask): + field_mask (google.protobuf.field_mask_pb2.FieldMask): Optional. A field mask to specify the Finding fields to be listed in the response. An empty field mask will list all fields. @@ -714,9 +714,9 @@ class ListFindingsResponse(proto.Message): r"""Response message for listing findings. Attributes: - findings (Sequence[~.gcs_finding.Finding]): + findings (Sequence[google.cloud.securitycenter_v1beta1.types.Finding]): Findings matching the list request. - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used for executing the list request. next_page_token (str): Token to retrieve the next page of results, @@ -750,9 +750,9 @@ class SetFindingStateRequest(proto.Message): https://cloud.google.com/apis/design/resource_names#relative_resource_name Example: "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - state (~.gcs_finding.Finding.State): + state (google.cloud.securitycenter_v1beta1.types.Finding.State): Required. The desired State of the finding. - start_time (~.timestamp.Timestamp): + start_time (google.protobuf.timestamp_pb2.Timestamp): Required. The time at which the updated state takes effect. """ @@ -781,7 +781,7 @@ class UpdateFindingRequest(proto.Message): r"""Request message for updating or creating a finding. Attributes: - finding (~.gcs_finding.Finding): + finding (google.cloud.securitycenter_v1beta1.types.Finding): Required. The finding resource to update or create if it does not already exist. parent, security_marks, and update_time will be ignored. @@ -789,7 +789,7 @@ class UpdateFindingRequest(proto.Message): In the case of creation, the finding id portion of the name must alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. - update_mask (~.gp_field_mask.FieldMask): + update_mask (google.protobuf.field_mask_pb2.FieldMask): The FieldMask to use when updating the finding resource. This field should not be specified when creating a finding. @@ -804,10 +804,10 @@ class UpdateOrganizationSettingsRequest(proto.Message): r"""Request message for updating an organization's settings. Attributes: - organization_settings (~.gcs_organization_settings.OrganizationSettings): + organization_settings (google.cloud.securitycenter_v1beta1.types.OrganizationSettings): Required. The organization settings resource to update. - update_mask (~.gp_field_mask.FieldMask): + update_mask (google.protobuf.field_mask_pb2.FieldMask): The FieldMask to use when updating the settings resource. """ @@ -823,9 +823,9 @@ class UpdateSourceRequest(proto.Message): r"""Request message for updating a source. Attributes: - source (~.gcs_source.Source): + source (google.cloud.securitycenter_v1beta1.types.Source): Required. The source resource to update. - update_mask (~.gp_field_mask.FieldMask): + update_mask (google.protobuf.field_mask_pb2.FieldMask): The FieldMask to use when updating the source resource. """ @@ -839,13 +839,13 @@ class UpdateSecurityMarksRequest(proto.Message): r"""Request message for updating a SecurityMarks resource. Attributes: - security_marks (~.gcs_security_marks.SecurityMarks): + security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): Required. The security marks resource to update. - update_mask (~.gp_field_mask.FieldMask): + update_mask (google.protobuf.field_mask_pb2.FieldMask): The FieldMask to use when updating the security marks resource. - start_time (~.timestamp.Timestamp): + start_time (google.protobuf.timestamp_pb2.Timestamp): The time at which the updated SecurityMarks take effect. """ diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py index a3a51ca4..ac8719ec 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py @@ -122,7 +122,36 @@ class SecurityCenterAsyncClient: SecurityCenterClient.parse_common_location_path ) - from_service_account_file = SecurityCenterClient.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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, filename, *args, **kwargs) # type: ignore + from_service_account_json = from_service_account_file @property @@ -199,19 +228,21 @@ async def create_source( r"""Creates a source. Args: - request (:class:`~.securitycenter_service.CreateSourceRequest`): + request (:class:`google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest`): The request object. Request message for creating a source. parent (:class:`str`): Required. Resource name of the new source's parent. Its format should be "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - source (:class:`~.gcs_source.Source`): + source (:class:`google.cloud.securitycenter_v1p1beta1.types.Source`): Required. The Source being created, only the display_name and description will be used. All other fields will be ignored. + This corresponds to the ``source`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -223,7 +254,7 @@ async def create_source( sent along with the request as metadata. Returns: - ~.gcs_source.Source: + google.cloud.securitycenter_v1p1beta1.types.Source: Security Command Center finding source. A finding source is an entity or a mechanism that can produce a finding. @@ -287,26 +318,29 @@ async def create_finding( exist for finding creation to succeed. Args: - request (:class:`~.securitycenter_service.CreateFindingRequest`): + request (:class:`google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest`): The request object. Request message for creating a finding. parent (:class:`str`): Required. Resource name of the new finding's parent. Its format should be "organizations/[organization_id]/sources/[source_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. finding_id (:class:`str`): Required. Unique identifier provided by the client within the parent scope. + This corresponds to the ``finding_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - finding (:class:`~.gcs_finding.Finding`): + finding (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding`): Required. The Finding being created. The name and security_marks will be ignored as they are both output only fields on this resource. + This corresponds to the ``finding`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -318,7 +352,7 @@ async def create_finding( sent along with the request as metadata. Returns: - ~.gcs_finding.Finding: + google.cloud.securitycenter_v1p1beta1.types.Finding: Security Command Center finding. A finding is a record of assessment data (security, risk, health or privacy) @@ -386,12 +420,13 @@ async def create_notification_config( r"""Creates a notification config. Args: - request (:class:`~.securitycenter_service.CreateNotificationConfigRequest`): + request (:class:`google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest`): The request object. Request message for creating a notification config. parent (:class:`str`): Required. Resource name of the new notification config's parent. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -401,14 +436,16 @@ async def create_notification_config( It must be between 1 and 128 characters, and contains alphanumeric characters, underscores or hyphens only. + This corresponds to the ``config_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - notification_config (:class:`~.gcs_notification_config.NotificationConfig`): + notification_config (:class:`google.cloud.securitycenter_v1p1beta1.types.NotificationConfig`): Required. The notification config being created. The name and the service account will be ignored as they are both output only fields on this resource. + This corresponds to the ``notification_config`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -420,7 +457,7 @@ async def create_notification_config( sent along with the request as metadata. Returns: - ~.gcs_notification_config.NotificationConfig: + google.cloud.securitycenter_v1p1beta1.types.NotificationConfig: Security Command Center notification configs. A notification config is a Security @@ -484,13 +521,14 @@ async def delete_notification_config( r"""Deletes a notification config. Args: - request (:class:`~.securitycenter_service.DeleteNotificationConfigRequest`): + request (:class:`google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest`): The request object. Request message for deleting a notification config. name (:class:`str`): Required. Name of the notification config to delete. Its format is "organizations/[organization_id]/notificationConfigs/[config_id]". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -551,7 +589,7 @@ async def get_iam_policy( Source. Args: - request (:class:`~.iam_policy.GetIamPolicyRequest`): + request (:class:`google.iam.v1.iam_policy_pb2.GetIamPolicyRequest`): The request object. Request message for `GetIamPolicy` method. resource (:class:`str`): @@ -559,6 +597,7 @@ async def get_iam_policy( policy is being requested. See the operation documentation for the appropriate value for this field. + This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -570,72 +609,62 @@ async def get_iam_policy( sent along with the request as metadata. Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). """ # Create or coerce a protobuf request object. @@ -667,6 +696,7 @@ async def get_iam_policy( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -696,13 +726,14 @@ async def get_notification_config( r"""Gets a notification config. Args: - request (:class:`~.securitycenter_service.GetNotificationConfigRequest`): + request (:class:`google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest`): The request object. Request message for getting a notification config. name (:class:`str`): Required. Name of the notification config to get. Its format is "organizations/[organization_id]/notificationConfigs/[config_id]". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -714,7 +745,7 @@ async def get_notification_config( sent along with the request as metadata. Returns: - ~.notification_config.NotificationConfig: + google.cloud.securitycenter_v1p1beta1.types.NotificationConfig: Security Command Center notification configs. A notification config is a Security @@ -753,6 +784,7 @@ async def get_notification_config( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -782,13 +814,14 @@ async def get_organization_settings( r"""Gets the settings for an organization. Args: - request (:class:`~.securitycenter_service.GetOrganizationSettingsRequest`): + request (:class:`google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest`): The request object. Request message for getting organization settings. name (:class:`str`): Required. Name of the organization to get organization settings for. Its format is "organizations/[organization_id]/organizationSettings". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -800,7 +833,7 @@ async def get_organization_settings( sent along with the request as metadata. Returns: - ~.organization_settings.OrganizationSettings: + google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings: User specified settings that are attached to the Security Command Center organization. @@ -835,6 +868,7 @@ async def get_organization_settings( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -864,13 +898,14 @@ async def get_source( r"""Gets a source. Args: - request (:class:`~.securitycenter_service.GetSourceRequest`): + request (:class:`google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest`): The request object. Request message for getting a source. name (:class:`str`): Required. Relative resource name of the source. Its format is "organizations/[organization_id]/source/[source_id]". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -882,7 +917,7 @@ async def get_source( sent along with the request as metadata. Returns: - ~.source.Source: + google.cloud.securitycenter_v1p1beta1.types.Source: Security Command Center finding source. A finding source is an entity or a mechanism that can produce a finding. @@ -920,6 +955,7 @@ async def get_source( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -949,7 +985,7 @@ async def group_assets( their specified properties. Args: - request (:class:`~.securitycenter_service.GroupAssetsRequest`): + request (:class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest`): The request object. Request message for grouping by assets. @@ -960,7 +996,7 @@ async def group_assets( sent along with the request as metadata. Returns: - ~.pagers.GroupAssetsAsyncPager: + google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsAsyncPager: Response message for grouping by assets. Iterating over this object will yield @@ -983,6 +1019,7 @@ async def group_assets( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=DEFAULT_CLIENT_INFO, @@ -1024,7 +1061,7 @@ async def group_findings( /v1p1beta1/organizations/{organization_id}/sources/-/findings Args: - request (:class:`~.securitycenter_service.GroupFindingsRequest`): + request (:class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest`): The request object. Request message for grouping by findings. parent (:class:`str`): @@ -1033,6 +1070,7 @@ async def group_findings( To groupBy across all sources provide a source_id of ``-``. For example: organizations/{organization_id}/sources/- + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1047,8 +1085,7 @@ async def group_findings( - resource_name - category - state - - parent - + - parent - severity The following fields are supported when compare_duration @@ -1067,7 +1104,7 @@ async def group_findings( sent along with the request as metadata. Returns: - ~.pagers.GroupFindingsAsyncPager: + google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsAsyncPager: Response message for group by findings. Iterating over this object will yield @@ -1106,6 +1143,7 @@ async def group_findings( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=DEFAULT_CLIENT_INFO, @@ -1141,11 +1179,12 @@ async def list_assets( r"""Lists an organization's assets. Args: - request (:class:`~.securitycenter_service.ListAssetsRequest`): + request (:class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest`): The request object. Request message for listing assets. parent (:class:`str`): Required. Name of the organization assets should belong to. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1157,7 +1196,7 @@ async def list_assets( sent along with the request as metadata. Returns: - ~.pagers.ListAssetsAsyncPager: + google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsAsyncPager: Response message for listing assets. Iterating over this object will yield results and resolve additional pages @@ -1193,6 +1232,7 @@ async def list_assets( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=DEFAULT_CLIENT_INFO, @@ -1232,7 +1272,7 @@ async def list_findings( /v1p1beta1/organizations/{organization_id}/sources/-/findings Args: - request (:class:`~.securitycenter_service.ListFindingsRequest`): + request (:class:`google.cloud.securitycenter_v1p1beta1.types.ListFindingsRequest`): The request object. Request message for listing findings. parent (:class:`str`): @@ -1241,6 +1281,7 @@ async def list_findings( "organizations/[organization_id]/sources/[source_id]". To list across all sources provide a source_id of ``-``. For example: organizations/{organization_id}/sources/- + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1252,7 +1293,7 @@ async def list_findings( sent along with the request as metadata. Returns: - ~.pagers.ListFindingsAsyncPager: + google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsAsyncPager: Response message for listing findings. Iterating over this object will yield @@ -1289,6 +1330,7 @@ async def list_findings( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=DEFAULT_CLIENT_INFO, @@ -1324,13 +1366,14 @@ async def list_notification_configs( r"""Lists notification configs. Args: - request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): + request (:class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest`): The request object. Request message for listing notification configs. parent (:class:`str`): Required. Name of the organization to list notification configs. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1342,7 +1385,7 @@ async def list_notification_configs( sent along with the request as metadata. Returns: - ~.pagers.ListNotificationConfigsAsyncPager: + google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsAsyncPager: Response message for listing notification configs. Iterating over this object will yield @@ -1379,6 +1422,7 @@ async def list_notification_configs( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -1414,12 +1458,13 @@ async def list_sources( r"""Lists all sources belonging to an organization. Args: - request (:class:`~.securitycenter_service.ListSourcesRequest`): + request (:class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest`): The request object. Request message for listing sources. parent (:class:`str`): Required. Resource name of the parent of sources to list. Its format should be "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1431,7 +1476,7 @@ async def list_sources( sent along with the request as metadata. Returns: - ~.pagers.ListSourcesAsyncPager: + google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesAsyncPager: Response message for listing sources. Iterating over this object will yield results and resolve additional pages @@ -1467,6 +1512,7 @@ async def list_sources( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -1507,13 +1553,14 @@ async def run_asset_discovery( receive a TOO_MANY_REQUESTS error. Args: - request (:class:`~.securitycenter_service.RunAssetDiscoveryRequest`): + request (:class:`google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest`): The request object. Request message for running asset discovery for an organization. parent (:class:`str`): Required. Name of the organization to run asset discovery for. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1525,11 +1572,11 @@ async def run_asset_discovery( sent along with the request as metadata. Returns: - ~.operation_async.AsyncOperation: + google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. The result type for the operation will be - :class:``~.run_asset_discovery_response.RunAssetDiscoveryResponse``: + :class:`google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse` Response of asset discovery run """ @@ -1593,7 +1640,7 @@ async def set_finding_state( r"""Updates the state of a finding. Args: - request (:class:`~.securitycenter_service.SetFindingStateRequest`): + request (:class:`google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest`): The request object. Request message for updating a finding's state. name (:class:`str`): @@ -1602,18 +1649,21 @@ async def set_finding_state( https://cloud.google.com/apis/design/resource_names#relative_resource_name Example: "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - state (:class:`~.finding.Finding.State`): + state (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding.State`): Required. The desired State of the finding. + This corresponds to the ``state`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - start_time (:class:`~.timestamp.Timestamp`): + start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): Required. The time at which the updated state takes effect. + This corresponds to the ``start_time`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1625,7 +1675,7 @@ async def set_finding_state( sent along with the request as metadata. Returns: - ~.finding.Finding: + google.cloud.securitycenter_v1p1beta1.types.Finding: Security Command Center finding. A finding is a record of assessment data (security, risk, health or privacy) @@ -1692,7 +1742,7 @@ async def set_iam_policy( Source. Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): + request (:class:`google.iam.v1.iam_policy_pb2.SetIamPolicyRequest`): The request object. Request message for `SetIamPolicy` method. resource (:class:`str`): @@ -1700,6 +1750,7 @@ async def set_iam_policy( policy is being specified. See the operation documentation for the appropriate value for this field. + This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1711,72 +1762,62 @@ async def set_iam_policy( sent along with the request as metadata. Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). """ # Create or coerce a protobuf request object. @@ -1831,7 +1872,7 @@ async def test_iam_permissions( specified source. Args: - request (:class:`~.iam_policy.TestIamPermissionsRequest`): + request (:class:`google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest`): The request object. Request message for `TestIamPermissions` method. resource (:class:`str`): @@ -1839,6 +1880,7 @@ async def test_iam_permissions( policy detail is being requested. See the operation documentation for the appropriate value for this field. + This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1847,6 +1889,7 @@ async def test_iam_permissions( Permissions with wildcards (such as '*' or 'storage.*') are not allowed. For more information see `IAM Overview `__. + This corresponds to the ``permissions`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1858,8 +1901,8 @@ async def test_iam_permissions( sent along with the request as metadata. Returns: - ~.iam_policy.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have @@ -1892,6 +1935,7 @@ async def test_iam_permissions( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -1923,10 +1967,10 @@ async def update_finding( source must exist for a finding creation to succeed. Args: - request (:class:`~.securitycenter_service.UpdateFindingRequest`): + request (:class:`google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest`): The request object. Request message for updating or creating a finding. - finding (:class:`~.gcs_finding.Finding`): + finding (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding`): Required. The finding resource to update or create if it does not already exist. parent, security_marks, and update_time will be ignored. @@ -1934,10 +1978,11 @@ async def update_finding( In the case of creation, the finding id portion of the name must be alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. + This corresponds to the ``finding`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - update_mask (:class:`~.field_mask.FieldMask`): + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): The FieldMask to use when updating the finding resource. This field should not be specified when creating a finding. @@ -1947,6 +1992,7 @@ async def update_finding( source_properties. Individual source_properties can be added/updated by using "source_properties." in the field mask. + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1958,7 +2004,7 @@ async def update_finding( sent along with the request as metadata. Returns: - ~.gcs_finding.Finding: + google.cloud.securitycenter_v1p1beta1.types.Finding: Security Command Center finding. A finding is a record of assessment data (security, risk, health or privacy) @@ -2026,20 +2072,22 @@ async def update_notification_config( allowed: description, pubsub_topic, streaming_config.filter Args: - request (:class:`~.securitycenter_service.UpdateNotificationConfigRequest`): + request (:class:`google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest`): The request object. Request message for updating a notification config. - notification_config (:class:`~.gcs_notification_config.NotificationConfig`): + notification_config (:class:`google.cloud.securitycenter_v1p1beta1.types.NotificationConfig`): Required. The notification config to update. + This corresponds to the ``notification_config`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - update_mask (:class:`~.field_mask.FieldMask`): + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): The FieldMask to use when updating the notification config. If empty all mutable fields will be updated. + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2051,7 +2099,7 @@ async def update_notification_config( sent along with the request as metadata. Returns: - ~.gcs_notification_config.NotificationConfig: + google.cloud.securitycenter_v1p1beta1.types.NotificationConfig: Security Command Center notification configs. A notification config is a Security @@ -2115,12 +2163,13 @@ async def update_organization_settings( r"""Updates an organization's settings. Args: - request (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): + request (:class:`google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest`): The request object. Request message for updating an organization's settings. - organization_settings (:class:`~.gcs_organization_settings.OrganizationSettings`): + organization_settings (:class:`google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings`): Required. The organization settings resource to update. + This corresponds to the ``organization_settings`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2132,7 +2181,7 @@ async def update_organization_settings( sent along with the request as metadata. Returns: - ~.gcs_organization_settings.OrganizationSettings: + google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings: User specified settings that are attached to the Security Command Center organization. @@ -2191,20 +2240,22 @@ async def update_source( r"""Updates a source. Args: - request (:class:`~.securitycenter_service.UpdateSourceRequest`): + request (:class:`google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest`): The request object. Request message for updating a source. - source (:class:`~.gcs_source.Source`): + source (:class:`google.cloud.securitycenter_v1p1beta1.types.Source`): Required. The source resource to update. + This corresponds to the ``source`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - update_mask (:class:`~.field_mask.FieldMask`): + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): The FieldMask to use when updating the source resource. If empty all mutable fields will be updated. + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2216,7 +2267,7 @@ async def update_source( sent along with the request as metadata. Returns: - ~.gcs_source.Source: + google.cloud.securitycenter_v1p1beta1.types.Source: Security Command Center finding source. A finding source is an entity or a mechanism that can produce a finding. @@ -2280,16 +2331,17 @@ async def update_security_marks( r"""Updates security marks. Args: - request (:class:`~.securitycenter_service.UpdateSecurityMarksRequest`): + request (:class:`google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest`): The request object. Request message for updating a SecurityMarks resource. - security_marks (:class:`~.gcs_security_marks.SecurityMarks`): + security_marks (:class:`google.cloud.securitycenter_v1p1beta1.types.SecurityMarks`): Required. The security marks resource to update. + This corresponds to the ``security_marks`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - update_mask (:class:`~.field_mask.FieldMask`): + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): The FieldMask to use when updating the security marks resource. @@ -2297,6 +2349,7 @@ async def update_security_marks( empty or set to "marks", all marks will be replaced. Individual marks can be updated using "marks.". + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2308,7 +2361,7 @@ async def update_security_marks( sent along with the request as metadata. Returns: - ~.gcs_security_marks.SecurityMarks: + google.cloud.securitycenter_v1p1beta1.types.SecurityMarks: User specified security marks that are attached to the parent Security Command Center resource. Security marks diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py index b2b042e8..bbee6898 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py @@ -134,6 +134,22 @@ def _get_default_mtls_endpoint(api_endpoint): DEFAULT_ENDPOINT ) + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SecurityCenterClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials @@ -146,7 +162,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): kwargs: Additional arguments to pass to the constructor. Returns: - {@api.name}: The constructed client. + SecurityCenterClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials @@ -342,10 +358,10 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - transport (Union[str, ~.SecurityCenterTransport]): The + transport (Union[str, SecurityCenterTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (client_options_lib.ClientOptions): Custom options for the + client_options (google.api_core.client_options.ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT @@ -381,21 +397,17 @@ def __init__( util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) ) - ssl_credentials = None + client_cert_source_func = None is_mtls = False if use_client_cert: if client_options.client_cert_source: - import grpc # type: ignore - - cert, key = client_options.client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) is_mtls = True + client_cert_source_func = client_options.client_cert_source else: - creds = SslCredentials() - is_mtls = creds.is_mtls - ssl_credentials = creds.ssl_credentials if is_mtls else None + is_mtls = mtls.has_default_client_cert_source() + client_cert_source_func = ( + mtls.default_client_cert_source() if is_mtls else None + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -438,7 +450,7 @@ def __init__( credentials_file=client_options.credentials_file, host=api_endpoint, scopes=client_options.scopes, - ssl_channel_credentials=ssl_credentials, + client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, ) @@ -456,19 +468,21 @@ def create_source( r"""Creates a source. Args: - request (:class:`~.securitycenter_service.CreateSourceRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest): The request object. Request message for creating a source. - parent (:class:`str`): + parent (str): Required. Resource name of the new source's parent. Its format should be "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - source (:class:`~.gcs_source.Source`): + source (google.cloud.securitycenter_v1p1beta1.types.Source): Required. The Source being created, only the display_name and description will be used. All other fields will be ignored. + This corresponds to the ``source`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -480,7 +494,7 @@ def create_source( sent along with the request as metadata. Returns: - ~.gcs_source.Source: + google.cloud.securitycenter_v1p1beta1.types.Source: Security Command Center finding source. A finding source is an entity or a mechanism that can produce a finding. @@ -545,26 +559,29 @@ def create_finding( exist for finding creation to succeed. Args: - request (:class:`~.securitycenter_service.CreateFindingRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest): The request object. Request message for creating a finding. - parent (:class:`str`): + parent (str): Required. Resource name of the new finding's parent. Its format should be "organizations/[organization_id]/sources/[source_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - finding_id (:class:`str`): + finding_id (str): Required. Unique identifier provided by the client within the parent scope. + This corresponds to the ``finding_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - finding (:class:`~.gcs_finding.Finding`): + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): Required. The Finding being created. The name and security_marks will be ignored as they are both output only fields on this resource. + This corresponds to the ``finding`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -576,7 +593,7 @@ def create_finding( sent along with the request as metadata. Returns: - ~.gcs_finding.Finding: + google.cloud.securitycenter_v1p1beta1.types.Finding: Security Command Center finding. A finding is a record of assessment data (security, risk, health or privacy) @@ -645,29 +662,32 @@ def create_notification_config( r"""Creates a notification config. Args: - request (:class:`~.securitycenter_service.CreateNotificationConfigRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest): The request object. Request message for creating a notification config. - parent (:class:`str`): + parent (str): Required. Resource name of the new notification config's parent. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - config_id (:class:`str`): + config_id (str): Required. Unique identifier provided by the client within the parent scope. It must be between 1 and 128 characters, and contains alphanumeric characters, underscores or hyphens only. + This corresponds to the ``config_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - notification_config (:class:`~.gcs_notification_config.NotificationConfig`): + notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): Required. The notification config being created. The name and the service account will be ignored as they are both output only fields on this resource. + This corresponds to the ``notification_config`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -679,7 +699,7 @@ def create_notification_config( sent along with the request as metadata. Returns: - ~.gcs_notification_config.NotificationConfig: + google.cloud.securitycenter_v1p1beta1.types.NotificationConfig: Security Command Center notification configs. A notification config is a Security @@ -748,13 +768,14 @@ def delete_notification_config( r"""Deletes a notification config. Args: - request (:class:`~.securitycenter_service.DeleteNotificationConfigRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest): The request object. Request message for deleting a notification config. - name (:class:`str`): + name (str): Required. Name of the notification config to delete. Its format is "organizations/[organization_id]/notificationConfigs/[config_id]". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -820,14 +841,15 @@ def get_iam_policy( Source. Args: - request (:class:`~.iam_policy.GetIamPolicyRequest`): + request (google.iam.v1.iam_policy_pb2.GetIamPolicyRequest): The request object. Request message for `GetIamPolicy` method. - resource (:class:`str`): + resource (str): REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field. + This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -839,72 +861,62 @@ def get_iam_policy( sent along with the request as metadata. Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). """ # Create or coerce a protobuf request object. @@ -917,13 +929,16 @@ def get_iam_policy( "the individual field arguments should be set." ) - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. request = iam_policy.GetIamPolicyRequest(**request) - elif not request: - request = iam_policy.GetIamPolicyRequest(resource=resource,) + # Null request, just make one. + request = iam_policy.GetIamPolicyRequest() + + if resource is not None: + request.resource = resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -953,13 +968,14 @@ def get_notification_config( r"""Gets a notification config. Args: - request (:class:`~.securitycenter_service.GetNotificationConfigRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest): The request object. Request message for getting a notification config. - name (:class:`str`): + name (str): Required. Name of the notification config to get. Its format is "organizations/[organization_id]/notificationConfigs/[config_id]". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -971,7 +987,7 @@ def get_notification_config( sent along with the request as metadata. Returns: - ~.notification_config.NotificationConfig: + google.cloud.securitycenter_v1p1beta1.types.NotificationConfig: Security Command Center notification configs. A notification config is a Security @@ -1032,13 +1048,14 @@ def get_organization_settings( r"""Gets the settings for an organization. Args: - request (:class:`~.securitycenter_service.GetOrganizationSettingsRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest): The request object. Request message for getting organization settings. - name (:class:`str`): + name (str): Required. Name of the organization to get organization settings for. Its format is "organizations/[organization_id]/organizationSettings". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1050,7 +1067,7 @@ def get_organization_settings( sent along with the request as metadata. Returns: - ~.organization_settings.OrganizationSettings: + google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings: User specified settings that are attached to the Security Command Center organization. @@ -1111,13 +1128,14 @@ def get_source( r"""Gets a source. Args: - request (:class:`~.securitycenter_service.GetSourceRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest): The request object. Request message for getting a source. - name (:class:`str`): + name (str): Required. Relative resource name of the source. Its format is "organizations/[organization_id]/source/[source_id]". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1129,7 +1147,7 @@ def get_source( sent along with the request as metadata. Returns: - ~.source.Source: + google.cloud.securitycenter_v1p1beta1.types.Source: Security Command Center finding source. A finding source is an entity or a mechanism that can produce a finding. @@ -1189,7 +1207,7 @@ def group_assets( their specified properties. Args: - request (:class:`~.securitycenter_service.GroupAssetsRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest): The request object. Request message for grouping by assets. @@ -1200,7 +1218,7 @@ def group_assets( sent along with the request as metadata. Returns: - ~.pagers.GroupAssetsPager: + google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsPager: Response message for grouping by assets. Iterating over this object will yield @@ -1257,19 +1275,20 @@ def group_findings( /v1p1beta1/organizations/{organization_id}/sources/-/findings Args: - request (:class:`~.securitycenter_service.GroupFindingsRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest): The request object. Request message for grouping by findings. - parent (:class:`str`): + parent (str): Required. Name of the source to groupBy. Its format is "organizations/[organization_id]/sources/[source_id]". To groupBy across all sources provide a source_id of ``-``. For example: organizations/{organization_id}/sources/- + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - group_by (:class:`str`): + group_by (str): Required. Expression that defines what assets fields to use for grouping (including ``state_change``). The string value should follow SQL syntax: comma separated @@ -1280,8 +1299,7 @@ def group_findings( - resource_name - category - state - - parent - + - parent - severity The following fields are supported when compare_duration @@ -1300,7 +1318,7 @@ def group_findings( sent along with the request as metadata. Returns: - ~.pagers.GroupFindingsPager: + google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsPager: Response message for group by findings. Iterating over this object will yield @@ -1367,11 +1385,12 @@ def list_assets( r"""Lists an organization's assets. Args: - request (:class:`~.securitycenter_service.ListAssetsRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest): The request object. Request message for listing assets. - parent (:class:`str`): + parent (str): Required. Name of the organization assets should belong to. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1383,7 +1402,7 @@ def list_assets( sent along with the request as metadata. Returns: - ~.pagers.ListAssetsPager: + google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsPager: Response message for listing assets. Iterating over this object will yield results and resolve additional pages @@ -1451,15 +1470,16 @@ def list_findings( /v1p1beta1/organizations/{organization_id}/sources/-/findings Args: - request (:class:`~.securitycenter_service.ListFindingsRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.ListFindingsRequest): The request object. Request message for listing findings. - parent (:class:`str`): + parent (str): Required. Name of the source the findings belong to. Its format is "organizations/[organization_id]/sources/[source_id]". To list across all sources provide a source_id of ``-``. For example: organizations/{organization_id}/sources/- + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1471,7 +1491,7 @@ def list_findings( sent along with the request as metadata. Returns: - ~.pagers.ListFindingsPager: + google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsPager: Response message for listing findings. Iterating over this object will yield @@ -1536,13 +1556,14 @@ def list_notification_configs( r"""Lists notification configs. Args: - request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest): The request object. Request message for listing notification configs. - parent (:class:`str`): + parent (str): Required. Name of the organization to list notification configs. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1554,7 +1575,7 @@ def list_notification_configs( sent along with the request as metadata. Returns: - ~.pagers.ListNotificationConfigsPager: + google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsPager: Response message for listing notification configs. Iterating over this object will yield @@ -1623,12 +1644,13 @@ def list_sources( r"""Lists all sources belonging to an organization. Args: - request (:class:`~.securitycenter_service.ListSourcesRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest): The request object. Request message for listing sources. - parent (:class:`str`): + parent (str): Required. Resource name of the parent of sources to list. Its format should be "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1640,7 +1662,7 @@ def list_sources( sent along with the request as metadata. Returns: - ~.pagers.ListSourcesPager: + google.cloud.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesPager: Response message for listing sources. Iterating over this object will yield results and resolve additional pages @@ -1709,13 +1731,14 @@ def run_asset_discovery( receive a TOO_MANY_REQUESTS error. Args: - request (:class:`~.securitycenter_service.RunAssetDiscoveryRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest): The request object. Request message for running asset discovery for an organization. - parent (:class:`str`): + parent (str): Required. Name of the organization to run asset discovery for. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1727,11 +1750,11 @@ def run_asset_discovery( sent along with the request as metadata. Returns: - ~.operation.Operation: + google.api_core.operation.Operation: An object representing a long-running operation. The result type for the operation will be - :class:``~.run_asset_discovery_response.RunAssetDiscoveryResponse``: + :class:`google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse` Response of asset discovery run """ @@ -1796,27 +1819,30 @@ def set_finding_state( r"""Updates the state of a finding. Args: - request (:class:`~.securitycenter_service.SetFindingStateRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest): The request object. Request message for updating a finding's state. - name (:class:`str`): + name (str): Required. The relative resource name of the finding. See: https://cloud.google.com/apis/design/resource_names#relative_resource_name Example: "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - state (:class:`~.finding.Finding.State`): + state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): Required. The desired State of the finding. + This corresponds to the ``state`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - start_time (:class:`~.timestamp.Timestamp`): + start_time (google.protobuf.timestamp_pb2.Timestamp): Required. The time at which the updated state takes effect. + This corresponds to the ``start_time`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1828,7 +1854,7 @@ def set_finding_state( sent along with the request as metadata. Returns: - ~.finding.Finding: + google.cloud.securitycenter_v1p1beta1.types.Finding: Security Command Center finding. A finding is a record of assessment data (security, risk, health or privacy) @@ -1896,14 +1922,15 @@ def set_iam_policy( Source. Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): + request (google.iam.v1.iam_policy_pb2.SetIamPolicyRequest): The request object. Request message for `SetIamPolicy` method. - resource (:class:`str`): + resource (str): REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field. + This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1915,72 +1942,62 @@ def set_iam_policy( sent along with the request as metadata. Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. + google.iam.v1.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. It is used to + specify access control policies for Cloud Platform + resources. + + A Policy is a collection of bindings. A binding binds + one or more members to a single role. Members can be + user accounts, service accounts, Google groups, and + domains (such as G Suite). A role is a named list of + permissions (defined by IAM or configured by users). + A binding can optionally specify a condition, which + is a logic expression that further constrains the + role binding based on attributes about the request + and/or target resource. + + **JSON Example** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ] + + } + + **YAML Example** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the + [IAM developer's + guide](\ https://cloud.google.com/iam/docs). """ # Create or coerce a protobuf request object. @@ -1993,13 +2010,16 @@ def set_iam_policy( "the individual field arguments should be set." ) - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. request = iam_policy.SetIamPolicyRequest(**request) - elif not request: - request = iam_policy.SetIamPolicyRequest(resource=resource,) + # Null request, just make one. + request = iam_policy.SetIamPolicyRequest() + + if resource is not None: + request.resource = resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2031,22 +2051,24 @@ def test_iam_permissions( specified source. Args: - request (:class:`~.iam_policy.TestIamPermissionsRequest`): + request (google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest): The request object. Request message for `TestIamPermissions` method. - resource (:class:`str`): + resource (str): REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field. + This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - permissions (:class:`Sequence[str]`): + permissions (Sequence[str]): The set of permissions to check for the ``resource``. Permissions with wildcards (such as '*' or 'storage.*') are not allowed. For more information see `IAM Overview `__. + This corresponds to the ``permissions`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2058,8 +2080,8 @@ def test_iam_permissions( sent along with the request as metadata. Returns: - ~.iam_policy.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have @@ -2071,15 +2093,19 @@ def test_iam_permissions( "the individual field arguments should be set." ) - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. request = iam_policy.TestIamPermissionsRequest(**request) - elif not request: - request = iam_policy.TestIamPermissionsRequest( - resource=resource, permissions=permissions, - ) + # Null request, just make one. + request = iam_policy.TestIamPermissionsRequest() + + if resource is not None: + request.resource = resource + + if permissions: + request.permissions.extend(permissions) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2111,10 +2137,10 @@ def update_finding( source must exist for a finding creation to succeed. Args: - request (:class:`~.securitycenter_service.UpdateFindingRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest): The request object. Request message for updating or creating a finding. - finding (:class:`~.gcs_finding.Finding`): + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): Required. The finding resource to update or create if it does not already exist. parent, security_marks, and update_time will be ignored. @@ -2122,10 +2148,11 @@ def update_finding( In the case of creation, the finding id portion of the name must be alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. + This corresponds to the ``finding`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - update_mask (:class:`~.field_mask.FieldMask`): + update_mask (google.protobuf.field_mask_pb2.FieldMask): The FieldMask to use when updating the finding resource. This field should not be specified when creating a finding. @@ -2135,6 +2162,7 @@ def update_finding( source_properties. Individual source_properties can be added/updated by using "source_properties." in the field mask. + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2146,7 +2174,7 @@ def update_finding( sent along with the request as metadata. Returns: - ~.gcs_finding.Finding: + google.cloud.securitycenter_v1p1beta1.types.Finding: Security Command Center finding. A finding is a record of assessment data (security, risk, health or privacy) @@ -2215,20 +2243,22 @@ def update_notification_config( allowed: description, pubsub_topic, streaming_config.filter Args: - request (:class:`~.securitycenter_service.UpdateNotificationConfigRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest): The request object. Request message for updating a notification config. - notification_config (:class:`~.gcs_notification_config.NotificationConfig`): + notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): Required. The notification config to update. + This corresponds to the ``notification_config`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - update_mask (:class:`~.field_mask.FieldMask`): + update_mask (google.protobuf.field_mask_pb2.FieldMask): The FieldMask to use when updating the notification config. If empty all mutable fields will be updated. + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2240,7 +2270,7 @@ def update_notification_config( sent along with the request as metadata. Returns: - ~.gcs_notification_config.NotificationConfig: + google.cloud.securitycenter_v1p1beta1.types.NotificationConfig: Security Command Center notification configs. A notification config is a Security @@ -2309,12 +2339,13 @@ def update_organization_settings( r"""Updates an organization's settings. Args: - request (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest): The request object. Request message for updating an organization's settings. - organization_settings (:class:`~.gcs_organization_settings.OrganizationSettings`): + organization_settings (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings): Required. The organization settings resource to update. + This corresponds to the ``organization_settings`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2326,7 +2357,7 @@ def update_organization_settings( sent along with the request as metadata. Returns: - ~.gcs_organization_settings.OrganizationSettings: + google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings: User specified settings that are attached to the Security Command Center organization. @@ -2390,20 +2421,22 @@ def update_source( r"""Updates a source. Args: - request (:class:`~.securitycenter_service.UpdateSourceRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest): The request object. Request message for updating a source. - source (:class:`~.gcs_source.Source`): + source (google.cloud.securitycenter_v1p1beta1.types.Source): Required. The source resource to update. + This corresponds to the ``source`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - update_mask (:class:`~.field_mask.FieldMask`): + update_mask (google.protobuf.field_mask_pb2.FieldMask): The FieldMask to use when updating the source resource. If empty all mutable fields will be updated. + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2415,7 +2448,7 @@ def update_source( sent along with the request as metadata. Returns: - ~.gcs_source.Source: + google.cloud.securitycenter_v1p1beta1.types.Source: Security Command Center finding source. A finding source is an entity or a mechanism that can produce a finding. @@ -2480,16 +2513,17 @@ def update_security_marks( r"""Updates security marks. Args: - request (:class:`~.securitycenter_service.UpdateSecurityMarksRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest): The request object. Request message for updating a SecurityMarks resource. - security_marks (:class:`~.gcs_security_marks.SecurityMarks`): + security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): Required. The security marks resource to update. + This corresponds to the ``security_marks`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - update_mask (:class:`~.field_mask.FieldMask`): + update_mask (google.protobuf.field_mask_pb2.FieldMask): The FieldMask to use when updating the security marks resource. @@ -2497,6 +2531,7 @@ def update_security_marks( empty or set to "marks", all marks will be replaced. Individual marks can be updated using "marks.". + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2508,7 +2543,7 @@ def update_security_marks( sent along with the request as metadata. Returns: - ~.gcs_security_marks.SecurityMarks: + google.cloud.securitycenter_v1p1beta1.types.SecurityMarks: User specified security marks that are attached to the parent Security Command Center resource. Security marks diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py index 561db76f..712fa98f 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py @@ -15,7 +15,16 @@ # limitations under the License. # -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple +from typing import ( + Any, + AsyncIterable, + Awaitable, + Callable, + Iterable, + Sequence, + Tuple, + Optional, +) from google.cloud.securitycenter_v1p1beta1.types import notification_config from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service @@ -26,7 +35,7 @@ class GroupAssetsPager: """A pager for iterating through ``group_assets`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.GroupAssetsResponse` object, and + :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` object, and provides an ``__iter__`` method to iterate through its ``group_by_results`` field. @@ -35,7 +44,7 @@ class GroupAssetsPager: through the ``group_by_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.GroupAssetsResponse` + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -53,9 +62,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.GroupAssetsRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest): The initial request object. - response (:class:`~.securitycenter_service.GroupAssetsResponse`): + response (google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -88,7 +97,7 @@ class GroupAssetsAsyncPager: """A pager for iterating through ``group_assets`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.GroupAssetsResponse` object, and + :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` object, and provides an ``__aiter__`` method to iterate through its ``group_by_results`` field. @@ -97,7 +106,7 @@ class GroupAssetsAsyncPager: through the ``group_by_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.GroupAssetsResponse` + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -115,9 +124,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.GroupAssetsRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest): The initial request object. - response (:class:`~.securitycenter_service.GroupAssetsResponse`): + response (google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -154,7 +163,7 @@ class GroupFindingsPager: """A pager for iterating through ``group_findings`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.GroupFindingsResponse` object, and + :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` object, and provides an ``__iter__`` method to iterate through its ``group_by_results`` field. @@ -163,7 +172,7 @@ class GroupFindingsPager: through the ``group_by_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.GroupFindingsResponse` + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -181,9 +190,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.GroupFindingsRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest): The initial request object. - response (:class:`~.securitycenter_service.GroupFindingsResponse`): + response (google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -216,7 +225,7 @@ class GroupFindingsAsyncPager: """A pager for iterating through ``group_findings`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.GroupFindingsResponse` object, and + :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` object, and provides an ``__aiter__`` method to iterate through its ``group_by_results`` field. @@ -225,7 +234,7 @@ class GroupFindingsAsyncPager: through the ``group_by_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.GroupFindingsResponse` + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -243,9 +252,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.GroupFindingsRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest): The initial request object. - response (:class:`~.securitycenter_service.GroupFindingsResponse`): + response (google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -284,7 +293,7 @@ class ListAssetsPager: """A pager for iterating through ``list_assets`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListAssetsResponse` object, and + :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` object, and provides an ``__iter__`` method to iterate through its ``list_assets_results`` field. @@ -293,7 +302,7 @@ class ListAssetsPager: through the ``list_assets_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListAssetsResponse` + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -311,9 +320,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListAssetsRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest): The initial request object. - response (:class:`~.securitycenter_service.ListAssetsResponse`): + response (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -348,7 +357,7 @@ class ListAssetsAsyncPager: """A pager for iterating through ``list_assets`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListAssetsResponse` object, and + :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` object, and provides an ``__aiter__`` method to iterate through its ``list_assets_results`` field. @@ -357,7 +366,7 @@ class ListAssetsAsyncPager: through the ``list_assets_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListAssetsResponse` + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -375,9 +384,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListAssetsRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest): The initial request object. - response (:class:`~.securitycenter_service.ListAssetsResponse`): + response (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -416,7 +425,7 @@ class ListFindingsPager: """A pager for iterating through ``list_findings`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListFindingsResponse` object, and + :class:`google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse` object, and provides an ``__iter__`` method to iterate through its ``list_findings_results`` field. @@ -425,7 +434,7 @@ class ListFindingsPager: through the ``list_findings_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListFindingsResponse` + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -443,9 +452,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListFindingsRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.ListFindingsRequest): The initial request object. - response (:class:`~.securitycenter_service.ListFindingsResponse`): + response (google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -480,7 +489,7 @@ class ListFindingsAsyncPager: """A pager for iterating through ``list_findings`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListFindingsResponse` object, and + :class:`google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse` object, and provides an ``__aiter__`` method to iterate through its ``list_findings_results`` field. @@ -489,7 +498,7 @@ class ListFindingsAsyncPager: through the ``list_findings_results`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListFindingsResponse` + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -507,9 +516,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListFindingsRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.ListFindingsRequest): The initial request object. - response (:class:`~.securitycenter_service.ListFindingsResponse`): + response (google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -548,7 +557,7 @@ class ListNotificationConfigsPager: """A pager for iterating through ``list_notification_configs`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListNotificationConfigsResponse` object, and + :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` object, and provides an ``__iter__`` method to iterate through its ``notification_configs`` field. @@ -557,7 +566,7 @@ class ListNotificationConfigsPager: through the ``notification_configs`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListNotificationConfigsResponse` + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -575,9 +584,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest): The initial request object. - response (:class:`~.securitycenter_service.ListNotificationConfigsResponse`): + response (google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -610,7 +619,7 @@ class ListNotificationConfigsAsyncPager: """A pager for iterating through ``list_notification_configs`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListNotificationConfigsResponse` object, and + :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` object, and provides an ``__aiter__`` method to iterate through its ``notification_configs`` field. @@ -619,7 +628,7 @@ class ListNotificationConfigsAsyncPager: through the ``notification_configs`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListNotificationConfigsResponse` + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -639,9 +648,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest): The initial request object. - response (:class:`~.securitycenter_service.ListNotificationConfigsResponse`): + response (google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -680,7 +689,7 @@ class ListSourcesPager: """A pager for iterating through ``list_sources`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListSourcesResponse` object, and + :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` object, and provides an ``__iter__`` method to iterate through its ``sources`` field. @@ -689,7 +698,7 @@ class ListSourcesPager: through the ``sources`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListSourcesResponse` + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -707,9 +716,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListSourcesRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest): The initial request object. - response (:class:`~.securitycenter_service.ListSourcesResponse`): + response (google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -742,7 +751,7 @@ class ListSourcesAsyncPager: """A pager for iterating through ``list_sources`` requests. This class thinly wraps an initial - :class:`~.securitycenter_service.ListSourcesResponse` object, and + :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` object, and provides an ``__aiter__`` method to iterate through its ``sources`` field. @@ -751,7 +760,7 @@ class ListSourcesAsyncPager: through the ``sources`` field on the corresponding responses. - All the usual :class:`~.securitycenter_service.ListSourcesResponse` + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -769,9 +778,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.securitycenter_service.ListSourcesRequest`): + request (google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest): The initial request object. - response (:class:`~.securitycenter_service.ListSourcesResponse`): + response (google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py index 59b77852..fddc88f5 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py @@ -23,7 +23,6 @@ from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore from google.auth import credentials # type: ignore @@ -90,10 +89,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. @@ -101,6 +100,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: @@ -110,20 +112,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 = { @@ -152,6 +151,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, @@ -165,6 +165,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, @@ -178,6 +179,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, @@ -191,6 +193,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, @@ -204,6 +207,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=client_info, @@ -217,6 +221,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=client_info, @@ -230,6 +235,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=client_info, @@ -243,6 +249,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=480.0, ), default_timeout=480.0, client_info=client_info, @@ -256,6 +263,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, @@ -269,6 +277,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, @@ -291,6 +300,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/securitycenter_v1p1beta1/services/security_center/transports/grpc.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py index d402248c..15182889 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py @@ -77,6 +77,7 @@ def __init__( api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -107,6 +108,10 @@ def __init__( ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -121,72 +126,61 @@ 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] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # 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: - warnings.warn( - "api_mtls_endpoint and client_cert_source are deprecated", - DeprecationWarning, - ) - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials - 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 + 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 + ) - # 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 credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + # 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, - ssl_credentials=ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -194,18 +188,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # 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( @@ -219,7 +203,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/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py index 3269c916..dfb65374 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py @@ -81,7 +81,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 @@ -121,6 +121,7 @@ def __init__( api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -152,12 +153,16 @@ def __init__( ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing + 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: @@ -166,72 +171,61 @@ 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] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # 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: - warnings.warn( - "api_mtls_endpoint and client_cert_source are deprecated", - DeprecationWarning, - ) - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials - 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 + 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 + ) - # 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 credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + # 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, - ssl_credentials=ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -239,18 +233,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 = {} - self._operations_client = None + # 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/securitycenter_v1p1beta1/types/__init__.py b/google/cloud/securitycenter_v1p1beta1/types/__init__.py index 1a1ebb24..0d3cb34a 100644 --- a/google/cloud/securitycenter_v1p1beta1/types/__init__.py +++ b/google/cloud/securitycenter_v1p1beta1/types/__init__.py @@ -15,15 +15,14 @@ # limitations under the License. # -from .security_marks import SecurityMarks from .asset import Asset from .finding import Finding from .notification_config import NotificationConfig -from .resource import Resource from .notification_message import NotificationMessage from .organization_settings import OrganizationSettings +from .resource import Resource from .run_asset_discovery_response import RunAssetDiscoveryResponse -from .source import Source +from .security_marks import SecurityMarks from .securitycenter_service import ( CreateFindingRequest, CreateNotificationConfigRequest, @@ -37,33 +36,33 @@ GroupFindingsRequest, GroupFindingsResponse, GroupResult, - ListNotificationConfigsRequest, - ListNotificationConfigsResponse, - ListSourcesRequest, - ListSourcesResponse, ListAssetsRequest, ListAssetsResponse, ListFindingsRequest, ListFindingsResponse, - SetFindingStateRequest, + ListNotificationConfigsRequest, + ListNotificationConfigsResponse, + ListSourcesRequest, + ListSourcesResponse, RunAssetDiscoveryRequest, + SetFindingStateRequest, UpdateFindingRequest, UpdateNotificationConfigRequest, UpdateOrganizationSettingsRequest, - UpdateSourceRequest, UpdateSecurityMarksRequest, + UpdateSourceRequest, ) +from .source import Source __all__ = ( - "SecurityMarks", "Asset", "Finding", "NotificationConfig", - "Resource", "NotificationMessage", "OrganizationSettings", + "Resource", "RunAssetDiscoveryResponse", - "Source", + "SecurityMarks", "CreateFindingRequest", "CreateNotificationConfigRequest", "CreateSourceRequest", @@ -76,19 +75,20 @@ "GroupFindingsRequest", "GroupFindingsResponse", "GroupResult", - "ListNotificationConfigsRequest", - "ListNotificationConfigsResponse", - "ListSourcesRequest", - "ListSourcesResponse", "ListAssetsRequest", "ListAssetsResponse", "ListFindingsRequest", "ListFindingsResponse", - "SetFindingStateRequest", + "ListNotificationConfigsRequest", + "ListNotificationConfigsResponse", + "ListSourcesRequest", + "ListSourcesResponse", "RunAssetDiscoveryRequest", + "SetFindingStateRequest", "UpdateFindingRequest", "UpdateNotificationConfigRequest", "UpdateOrganizationSettingsRequest", - "UpdateSourceRequest", "UpdateSecurityMarksRequest", + "UpdateSourceRequest", + "Source", ) diff --git a/google/cloud/securitycenter_v1p1beta1/types/asset.py b/google/cloud/securitycenter_v1p1beta1/types/asset.py index 9d7f0742..50406de4 100644 --- a/google/cloud/securitycenter_v1p1beta1/types/asset.py +++ b/google/cloud/securitycenter_v1p1beta1/types/asset.py @@ -46,26 +46,26 @@ class Asset(proto.Message): https://cloud.google.com/apis/design/resource_names#relative_resource_name Example: "organizations/{organization_id}/assets/{asset_id}". - security_center_properties (~.asset.Asset.SecurityCenterProperties): + security_center_properties (google.cloud.securitycenter_v1p1beta1.types.Asset.SecurityCenterProperties): Security Command Center managed properties. These properties are managed by Security Command Center and cannot be modified by the user. - resource_properties (Sequence[~.asset.Asset.ResourcePropertiesEntry]): + resource_properties (Sequence[google.cloud.securitycenter_v1p1beta1.types.Asset.ResourcePropertiesEntry]): Resource managed properties. These properties are managed and defined by the Google Cloud resource and cannot be modified by the user. - security_marks (~.gcs_security_marks.SecurityMarks): + security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): User specified security marks. These marks are entirely managed by the user and come from the SecurityMarks resource that belongs to the asset. - create_time (~.timestamp.Timestamp): + create_time (google.protobuf.timestamp_pb2.Timestamp): The time at which the asset was created in Security Command Center. - update_time (~.timestamp.Timestamp): + update_time (google.protobuf.timestamp_pb2.Timestamp): The time at which the asset was last updated, added, or deleted in Cloud SCC. - iam_policy (~.asset.Asset.IamPolicy): + iam_policy (google.cloud.securitycenter_v1p1beta1.types.Asset.IamPolicy): Cloud IAM Policy information associated with the Google Cloud resource described by the Security Command Center asset. This information diff --git a/google/cloud/securitycenter_v1p1beta1/types/finding.py b/google/cloud/securitycenter_v1p1beta1/types/finding.py index 1d6e12cb..0e667d8c 100644 --- a/google/cloud/securitycenter_v1p1beta1/types/finding.py +++ b/google/cloud/securitycenter_v1p1beta1/types/finding.py @@ -57,7 +57,7 @@ class Finding(proto.Message): When the finding is for a non-Google Cloud resource, the resourceName can be a customer or partner defined string. This field is immutable after creation time. - state (~.finding.Finding.State): + state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): The state of the finding. category (str): The additional taxonomy group within findings from a given @@ -69,18 +69,18 @@ class Finding(proto.Message): additional information about the finding can be found. This field is guaranteed to be either empty or a well formed URL. - source_properties (Sequence[~.finding.Finding.SourcePropertiesEntry]): + source_properties (Sequence[google.cloud.securitycenter_v1p1beta1.types.Finding.SourcePropertiesEntry]): Source specific properties. These properties are managed by the source that writes the finding. The key names in the source_properties map must be between 1 and 255 characters, and must start with a letter and contain alphanumeric characters or underscores only. - security_marks (~.gcs_security_marks.SecurityMarks): + security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): Output only. User specified security marks. These marks are entirely managed by the user and come from the SecurityMarks resource that belongs to the finding. - event_time (~.timestamp.Timestamp): + event_time (google.protobuf.timestamp_pb2.Timestamp): The time at which the event took place, or when an update to the finding occurred. For example, if the finding represents an open @@ -89,10 +89,10 @@ class Finding(proto.Message): is determined by the detector. If the finding were to be resolved afterward, this time would reflect when the finding was resolved. - create_time (~.timestamp.Timestamp): + create_time (google.protobuf.timestamp_pb2.Timestamp): The time at which the finding was created in Security Command Center. - severity (~.finding.Finding.Severity): + severity (google.cloud.securitycenter_v1p1beta1.types.Finding.Severity): The severity of the finding. This field is managed by the source that writes the finding. """ diff --git a/google/cloud/securitycenter_v1p1beta1/types/notification_config.py b/google/cloud/securitycenter_v1p1beta1/types/notification_config.py index 2be493b4..99befd9d 100644 --- a/google/cloud/securitycenter_v1p1beta1/types/notification_config.py +++ b/google/cloud/securitycenter_v1p1beta1/types/notification_config.py @@ -38,7 +38,7 @@ class NotificationConfig(proto.Message): description (str): The description of the notification config (max of 1024 characters). - event_type (~.notification_config.NotificationConfig.EventType): + event_type (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig.EventType): The type of events the config is for, e.g. FINDING. pubsub_topic (str): @@ -48,7 +48,7 @@ class NotificationConfig(proto.Message): Output only. The service account that needs "pubsub.topics.publish" permission to publish to the Pub/Sub topic. - streaming_config (~.notification_config.NotificationConfig.StreamingConfig): + streaming_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig.StreamingConfig): The config for triggering streaming-based notifications. """ diff --git a/google/cloud/securitycenter_v1p1beta1/types/notification_message.py b/google/cloud/securitycenter_v1p1beta1/types/notification_message.py index 700d68eb..215cd555 100644 --- a/google/cloud/securitycenter_v1p1beta1/types/notification_message.py +++ b/google/cloud/securitycenter_v1p1beta1/types/notification_message.py @@ -34,10 +34,10 @@ class NotificationMessage(proto.Message): notification_config_name (str): Name of the notification config that generated current notification. - finding (~.gcs_finding.Finding): + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): If it's a Finding based notification config, this field will be populated. - resource (~.gcs_resource.Resource): + resource (google.cloud.securitycenter_v1p1beta1.types.Resource): The Cloud resource tied to the notification. """ diff --git a/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py b/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py index 70fec686..1cc1caeb 100644 --- a/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py +++ b/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py @@ -38,7 +38,7 @@ class OrganizationSettings(proto.Message): If the flag is set to ``true``, then discovery of assets will occur. If it is set to \`false, all historical assets will remain, but discovery of future assets will not occur. - asset_discovery_config (~.organization_settings.OrganizationSettings.AssetDiscoveryConfig): + asset_discovery_config (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings.AssetDiscoveryConfig): The configuration used for Asset Discovery runs. """ @@ -50,7 +50,7 @@ class AssetDiscoveryConfig(proto.Message): project_ids (Sequence[str]): The project ids to use for filtering asset discovery. - inclusion_mode (~.organization_settings.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): + inclusion_mode (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): The mode to use for filtering asset discovery. """ diff --git a/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py b/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py index 9c474a45..d1201368 100644 --- a/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py +++ b/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py @@ -31,9 +31,9 @@ class RunAssetDiscoveryResponse(proto.Message): r"""Response of asset discovery run Attributes: - state (~.run_asset_discovery_response.RunAssetDiscoveryResponse.State): + state (google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse.State): The state of an asset discovery run. - duration (~.gp_duration.Duration): + duration (google.protobuf.duration_pb2.Duration): The duration between asset discovery run start and end """ diff --git a/google/cloud/securitycenter_v1p1beta1/types/security_marks.py b/google/cloud/securitycenter_v1p1beta1/types/security_marks.py index a7671f48..1d84bd55 100644 --- a/google/cloud/securitycenter_v1p1beta1/types/security_marks.py +++ b/google/cloud/securitycenter_v1p1beta1/types/security_marks.py @@ -37,7 +37,7 @@ class SecurityMarks(proto.Message): Examples: "organizations/{organization_id}/assets/{asset_id}/securityMarks" "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". - marks (Sequence[~.security_marks.SecurityMarks.MarksEntry]): + marks (Sequence[google.cloud.securitycenter_v1p1beta1.types.SecurityMarks.MarksEntry]): Mutable user specified security marks belonging to the parent resource. Constraints are as follows: diff --git a/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py b/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py index bd319164..e608de04 100644 --- a/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py +++ b/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py @@ -81,7 +81,7 @@ class CreateFindingRequest(proto.Message): finding_id (str): Required. Unique identifier provided by the client within the parent scope. - finding (~.gcs_finding.Finding): + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): Required. The Finding being created. The name and security_marks will be ignored as they are both output only fields on this resource. @@ -107,7 +107,7 @@ class CreateNotificationConfigRequest(proto.Message): between 1 and 128 characters, and contains alphanumeric characters, underscores or hyphens only. - notification_config (~.gcs_notification_config.NotificationConfig): + notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): Required. The notification config being created. The name and the service account will be ignored as they are both output only fields @@ -130,7 +130,7 @@ class CreateSourceRequest(proto.Message): parent (str): Required. Resource name of the new source's parent. Its format should be "organizations/[organization_id]". - source (~.gcs_source.Source): + source (google.cloud.securitycenter_v1p1beta1.types.Source): Required. The Source being created, only the display_name and description will be used. All other fields will be ignored. @@ -302,7 +302,7 @@ class GroupAssetsRequest(proto.Message): - security_center_properties.resource_type - security_center_properties.resource_project_display_name - security_center_properties.resource_parent_display_name - compare_duration (~.duration.Duration): + compare_duration (google.protobuf.duration_pb2.Duration): When compare_duration is set, the GroupResult's "state_change" property is updated to indicate whether the asset was added, removed, or remained present during the @@ -334,7 +334,7 @@ class GroupAssetsRequest(proto.Message): If this field is set then ``state_change`` must be a specified field in ``group_by``. - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used as a reference point when filtering assets. The filter is limited to assets existing at the supplied time and their values are those @@ -370,13 +370,13 @@ class GroupAssetsResponse(proto.Message): r"""Response message for grouping by assets. Attributes: - group_by_results (Sequence[~.securitycenter_service.GroupResult]): + group_by_results (Sequence[google.cloud.securitycenter_v1p1beta1.types.GroupResult]): Group results. There exists an element for each existing unique combination of property/values. The element contains a count for the number of times those specific property/values appear. - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used for executing the groupBy request. next_page_token (str): Token to retrieve the next page of results, @@ -492,13 +492,13 @@ class GroupFindingsRequest(proto.Message): set: - state_change - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used as a reference point when filtering findings. The filter is limited to findings existing at the supplied time and their values are those at that specific time. Absence of this field will default to the API's version of NOW. - compare_duration (~.duration.Duration): + compare_duration (google.protobuf.duration_pb2.Duration): When compare_duration is set, the GroupResult's "state_change" attribute is updated to indicate whether the finding had its state changed, the finding's state remained @@ -565,13 +565,13 @@ class GroupFindingsResponse(proto.Message): r"""Response message for group by findings. Attributes: - group_by_results (Sequence[~.securitycenter_service.GroupResult]): + group_by_results (Sequence[google.cloud.securitycenter_v1p1beta1.types.GroupResult]): Group results. There exists an element for each existing unique combination of property/values. The element contains a count for the number of times those specific property/values appear. - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used for executing the groupBy request. next_page_token (str): Token to retrieve the next page of results, @@ -601,7 +601,7 @@ class GroupResult(proto.Message): request. Attributes: - properties (Sequence[~.securitycenter_service.GroupResult.PropertiesEntry]): + properties (Sequence[google.cloud.securitycenter_v1p1beta1.types.GroupResult.PropertiesEntry]): Properties matching the groupBy fields in the request. count (int): @@ -645,7 +645,7 @@ class ListNotificationConfigsResponse(proto.Message): r"""Response message for listing notification configs. Attributes: - notification_configs (Sequence[~.gcs_notification_config.NotificationConfig]): + notification_configs (Sequence[google.cloud.securitycenter_v1p1beta1.types.NotificationConfig]): Notification configs belonging to the requested parent. next_page_token (str): @@ -693,7 +693,7 @@ class ListSourcesResponse(proto.Message): r"""Response message for listing sources. Attributes: - sources (Sequence[~.gcs_source.Source]): + sources (Sequence[google.cloud.securitycenter_v1p1beta1.types.Source]): Sources belonging to the requested parent. next_page_token (str): Token to retrieve the next page of results, @@ -820,13 +820,13 @@ class ListAssetsRequest(proto.Message): security_center_properties.resource_project security_center_properties.resource_project_display_name security_center_properties.resource_type - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used as a reference point when filtering assets. The filter is limited to assets existing at the supplied time and their values are those at that specific time. Absence of this field will default to the API's version of NOW. - compare_duration (~.duration.Duration): + compare_duration (google.protobuf.duration_pb2.Duration): When compare_duration is set, the ListAssetsResult's "state_change" attribute is updated to indicate whether the asset was added, removed, or remained present during the @@ -854,7 +854,7 @@ class ListAssetsRequest(proto.Message): If compare_duration is not specified, then the only possible state_change is "UNUSED", which will be the state_change set for all assets present at read_time. - field_mask (~.gp_field_mask.FieldMask): + field_mask (google.protobuf.field_mask_pb2.FieldMask): A field mask to specify the ListAssetsResult fields to be listed in the response. An empty field mask will list all fields. @@ -890,9 +890,9 @@ class ListAssetsResponse(proto.Message): r"""Response message for listing assets. Attributes: - list_assets_results (Sequence[~.securitycenter_service.ListAssetsResponse.ListAssetsResult]): + list_assets_results (Sequence[google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse.ListAssetsResult]): Assets matching the list request. - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used for executing the list request. next_page_token (str): Token to retrieve the next page of results, @@ -906,9 +906,9 @@ class ListAssetsResult(proto.Message): r"""Result containing the Asset and its State. Attributes: - asset (~.gcs_asset.Asset): + asset (google.cloud.securitycenter_v1p1beta1.types.Asset): Asset matching the search request. - state_change (~.securitycenter_service.ListAssetsResponse.ListAssetsResult.StateChange): + state_change (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse.ListAssetsResult.StateChange): State change of the asset between the points in time. """ @@ -1036,13 +1036,13 @@ class ListFindingsRequest(proto.Message): The following fields are supported: name parent state category resource_name event_time source_properties security_marks.marks - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used as a reference point when filtering findings. The filter is limited to findings existing at the supplied time and their values are those at that specific time. Absence of this field will default to the API's version of NOW. - compare_duration (~.duration.Duration): + compare_duration (google.protobuf.duration_pb2.Duration): When compare_duration is set, the ListFindingsResult's "state_change" attribute is updated to indicate whether the finding had its state changed, the finding's state remained @@ -1076,7 +1076,7 @@ class ListFindingsRequest(proto.Message): If compare_duration is not specified, then the only possible state_change is "UNUSED", which will be the state_change set for all findings present at read_time. - field_mask (~.gp_field_mask.FieldMask): + field_mask (google.protobuf.field_mask_pb2.FieldMask): A field mask to specify the Finding fields to be listed in the response. An empty field mask will list all fields. @@ -1112,9 +1112,9 @@ class ListFindingsResponse(proto.Message): r"""Response message for listing findings. Attributes: - list_findings_results (Sequence[~.securitycenter_service.ListFindingsResponse.ListFindingsResult]): + list_findings_results (Sequence[google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult]): Findings matching the list request. - read_time (~.timestamp.Timestamp): + read_time (google.protobuf.timestamp_pb2.Timestamp): Time used for executing the list request. next_page_token (str): Token to retrieve the next page of results, @@ -1128,12 +1128,12 @@ class ListFindingsResult(proto.Message): r"""Result containing the Finding and its StateChange. Attributes: - finding (~.gcs_finding.Finding): + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): Finding matching the search request. - state_change (~.securitycenter_service.ListFindingsResponse.ListFindingsResult.StateChange): + state_change (google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult.StateChange): State change of the finding between the points in time. - resource (~.securitycenter_service.ListFindingsResponse.ListFindingsResult.Resource): + resource (google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult.Resource): Output only. Resource that is associated with this finding. """ @@ -1222,9 +1222,9 @@ class SetFindingStateRequest(proto.Message): https://cloud.google.com/apis/design/resource_names#relative_resource_name Example: "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - state (~.gcs_finding.Finding.State): + state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): Required. The desired State of the finding. - start_time (~.timestamp.Timestamp): + start_time (google.protobuf.timestamp_pb2.Timestamp): Required. The time at which the updated state takes effect. """ @@ -1253,7 +1253,7 @@ class UpdateFindingRequest(proto.Message): r"""Request message for updating or creating a finding. Attributes: - finding (~.gcs_finding.Finding): + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): Required. The finding resource to update or create if it does not already exist. parent, security_marks, and update_time will be ignored. @@ -1261,7 +1261,7 @@ class UpdateFindingRequest(proto.Message): In the case of creation, the finding id portion of the name must be alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. - update_mask (~.gp_field_mask.FieldMask): + update_mask (google.protobuf.field_mask_pb2.FieldMask): The FieldMask to use when updating the finding resource. This field should not be specified when creating a finding. @@ -1280,9 +1280,9 @@ class UpdateNotificationConfigRequest(proto.Message): r"""Request message for updating a notification config. Attributes: - notification_config (~.gcs_notification_config.NotificationConfig): + notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): Required. The notification config to update. - update_mask (~.gp_field_mask.FieldMask): + update_mask (google.protobuf.field_mask_pb2.FieldMask): The FieldMask to use when updating the notification config. If empty all mutable fields will be updated. @@ -1299,10 +1299,10 @@ class UpdateOrganizationSettingsRequest(proto.Message): r"""Request message for updating an organization's settings. Attributes: - organization_settings (~.gcs_organization_settings.OrganizationSettings): + organization_settings (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings): Required. The organization settings resource to update. - update_mask (~.gp_field_mask.FieldMask): + update_mask (google.protobuf.field_mask_pb2.FieldMask): The FieldMask to use when updating the settings resource. @@ -1320,9 +1320,9 @@ class UpdateSourceRequest(proto.Message): r"""Request message for updating a source. Attributes: - source (~.gcs_source.Source): + source (google.cloud.securitycenter_v1p1beta1.types.Source): Required. The source resource to update. - update_mask (~.gp_field_mask.FieldMask): + update_mask (google.protobuf.field_mask_pb2.FieldMask): The FieldMask to use when updating the source resource. If empty all mutable fields will be updated. @@ -1337,17 +1337,17 @@ class UpdateSecurityMarksRequest(proto.Message): r"""Request message for updating a SecurityMarks resource. Attributes: - security_marks (~.gcs_security_marks.SecurityMarks): + security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): Required. The security marks resource to update. - update_mask (~.gp_field_mask.FieldMask): + update_mask (google.protobuf.field_mask_pb2.FieldMask): The FieldMask to use when updating the security marks resource. The field mask must not contain duplicate fields. If empty or set to "marks", all marks will be replaced. Individual marks can be updated using "marks.". - start_time (~.timestamp.Timestamp): + start_time (google.protobuf.timestamp_pb2.Timestamp): The time at which the updated SecurityMarks take effect. If not set uses current server time. Updates will be applied to the diff --git a/noxfile.py b/noxfile.py index a57e24be..43dd3024 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,22 @@ 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", + "system", + "cover", + "lint", + "lint_setup_py", + "blacken", + "docs", +] + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + @nox.session(python=DEFAULT_PYTHON_VERSION) def lint(session): @@ -70,17 +87,21 @@ 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("-e", ".") + session.install("asyncmock", "pytest-asyncio", "-c", constraints_path) + + session.install("mock", "pytest", "pytest-cov", "-c", constraints_path) + + session.install("-e", ".", "-c", constraints_path) # Run py.test against the unit tests. session.run( "py.test", "--quiet", + f"--junitxml=unit_{session.python}_sponge_log.xml", "--cov=google/cloud", "--cov=tests/unit", "--cov-append", @@ -101,6 +122,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") @@ -110,6 +134,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) @@ -122,16 +149,26 @@ 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: - session.run("py.test", "--quiet", system_test_path, *session.posargs) + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_path, + *session.posargs, + ) if system_test_folder_exists: - session.run("py.test", "--quiet", system_test_folder_path, *session.posargs) + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_folder_path, + *session.posargs, + ) @nox.session(python=DEFAULT_PYTHON_VERSION) @@ -142,7 +179,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=99") + session.run("coverage", "report", "--show-missing", "--fail-under=98") session.run("coverage", "erase") diff --git a/renovate.json b/renovate.json index 4fa94931..f08bc22c 100644 --- a/renovate.json +++ b/renovate.json @@ -1,5 +1,6 @@ { "extends": [ "config:base", ":preserveSemverRanges" - ] + ], + "ignorePaths": [".pre-commit-config.yaml"] } diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py index bca0522e..97bf7da8 100644 --- a/samples/snippets/noxfile.py +++ b/samples/snippets/noxfile.py @@ -85,7 +85,7 @@ def get_pytest_env_vars() -> Dict[str, str]: # DO NOT EDIT - automatically generated. # All versions used to tested samples. -ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8"] +ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8", "3.9"] # Any default versions that should be ignored. IGNORED_VERSIONS = TEST_CONFIG['ignored_versions'] diff --git a/setup.py b/setup.py index 2e201757..c639c9da 100644 --- a/setup.py +++ b/setup.py @@ -24,11 +24,11 @@ version = "1.1.0" release_status = "Development Status :: 3 - Alpha" dependencies = [ - "google-api-core[grpc] >= 1.22.0, < 2.0.0dev", + "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", "grpc-google-iam-v1 >= 0.12.3, < 0.13dev", "proto-plus >= 1.10.0", - "libcst >= 0.2.5", ] +extras = {"libcst": "libcst >= 0.2.5"} package_root = os.path.abspath(os.path.dirname(__file__)) @@ -71,6 +71,7 @@ packages=packages, namespace_packages=namespaces, install_requires=dependencies, + extras_requires=extras, python_requires=">=3.6", scripts=[ "scripts/fixup_securitycenter_v1_keywords.py", diff --git a/synth.metadata b/synth.metadata index cb1fa7e9..5e9ab512 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,30 +3,30 @@ { "git": { "name": ".", - "remote": "https://github.com/googleapis/python-securitycenter.git", - "sha": "8d37bea1658bda9a646277aca90b812ddeee5494" + "remote": "git@github.com:googleapis/python-securitycenter.git", + "sha": "7e7e448e1b4b05aa51b948f7f3463982aa2d302b" } }, { "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "e9135d3cb8a99f77ee2ba3318ebc2c9b807581d0", - "internalRef": "347410691" + "sha": "7c8d16188e68347aac0053a40ab1dc2056a44899", + "internalRef": "365829960" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "41a4e56982620d3edcf110d76f4fcdfdec471ac8" + "sha": "572ef8f70edd9041f5bcfa71511aed6aecfc2098" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "41a4e56982620d3edcf110d76f4fcdfdec471ac8" + "sha": "572ef8f70edd9041f5bcfa71511aed6aecfc2098" } } ], @@ -58,182 +58,5 @@ "generator": "bazel" } } - ], - "generatedFiles": [ - ".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/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/securitycenter_v1/services.rst", - "docs/securitycenter_v1/types.rst", - "docs/securitycenter_v1beta1/services.rst", - "docs/securitycenter_v1beta1/types.rst", - "docs/securitycenter_v1p1beta1/services.rst", - "docs/securitycenter_v1p1beta1/types.rst", - "google/cloud/securitycenter/__init__.py", - "google/cloud/securitycenter/py.typed", - "google/cloud/securitycenter_v1/__init__.py", - "google/cloud/securitycenter_v1/proto/asset.proto", - "google/cloud/securitycenter_v1/proto/finding.proto", - "google/cloud/securitycenter_v1/proto/notification_config.proto", - "google/cloud/securitycenter_v1/proto/notification_message.proto", - "google/cloud/securitycenter_v1/proto/organization_settings.proto", - "google/cloud/securitycenter_v1/proto/resource.proto", - "google/cloud/securitycenter_v1/proto/run_asset_discovery_response.proto", - "google/cloud/securitycenter_v1/proto/security_marks.proto", - "google/cloud/securitycenter_v1/proto/securitycenter_service.proto", - "google/cloud/securitycenter_v1/proto/source.proto", - "google/cloud/securitycenter_v1/py.typed", - "google/cloud/securitycenter_v1/services/__init__.py", - "google/cloud/securitycenter_v1/services/security_center/__init__.py", - "google/cloud/securitycenter_v1/services/security_center/async_client.py", - "google/cloud/securitycenter_v1/services/security_center/client.py", - "google/cloud/securitycenter_v1/services/security_center/pagers.py", - "google/cloud/securitycenter_v1/services/security_center/transports/__init__.py", - "google/cloud/securitycenter_v1/services/security_center/transports/base.py", - "google/cloud/securitycenter_v1/services/security_center/transports/grpc.py", - "google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py", - "google/cloud/securitycenter_v1/types/__init__.py", - "google/cloud/securitycenter_v1/types/asset.py", - "google/cloud/securitycenter_v1/types/finding.py", - "google/cloud/securitycenter_v1/types/notification_config.py", - "google/cloud/securitycenter_v1/types/notification_message.py", - "google/cloud/securitycenter_v1/types/organization_settings.py", - "google/cloud/securitycenter_v1/types/resource.py", - "google/cloud/securitycenter_v1/types/run_asset_discovery_response.py", - "google/cloud/securitycenter_v1/types/security_marks.py", - "google/cloud/securitycenter_v1/types/securitycenter_service.py", - "google/cloud/securitycenter_v1/types/source.py", - "google/cloud/securitycenter_v1beta1/__init__.py", - "google/cloud/securitycenter_v1beta1/proto/asset.proto", - "google/cloud/securitycenter_v1beta1/proto/finding.proto", - "google/cloud/securitycenter_v1beta1/proto/organization_settings.proto", - "google/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response.proto", - "google/cloud/securitycenter_v1beta1/proto/security_marks.proto", - "google/cloud/securitycenter_v1beta1/proto/securitycenter_service.proto", - "google/cloud/securitycenter_v1beta1/proto/source.proto", - "google/cloud/securitycenter_v1beta1/py.typed", - "google/cloud/securitycenter_v1beta1/services/__init__.py", - "google/cloud/securitycenter_v1beta1/services/security_center/__init__.py", - "google/cloud/securitycenter_v1beta1/services/security_center/async_client.py", - "google/cloud/securitycenter_v1beta1/services/security_center/client.py", - "google/cloud/securitycenter_v1beta1/services/security_center/pagers.py", - "google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py", - "google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py", - "google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py", - "google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py", - "google/cloud/securitycenter_v1beta1/types/__init__.py", - "google/cloud/securitycenter_v1beta1/types/asset.py", - "google/cloud/securitycenter_v1beta1/types/finding.py", - "google/cloud/securitycenter_v1beta1/types/organization_settings.py", - "google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py", - "google/cloud/securitycenter_v1beta1/types/security_marks.py", - "google/cloud/securitycenter_v1beta1/types/securitycenter_service.py", - "google/cloud/securitycenter_v1beta1/types/source.py", - "google/cloud/securitycenter_v1p1beta1/__init__.py", - "google/cloud/securitycenter_v1p1beta1/proto/asset.proto", - "google/cloud/securitycenter_v1p1beta1/proto/finding.proto", - "google/cloud/securitycenter_v1p1beta1/proto/notification_config.proto", - "google/cloud/securitycenter_v1p1beta1/proto/notification_message.proto", - "google/cloud/securitycenter_v1p1beta1/proto/organization_settings.proto", - "google/cloud/securitycenter_v1p1beta1/proto/resource.proto", - "google/cloud/securitycenter_v1p1beta1/proto/run_asset_discovery_response.proto", - "google/cloud/securitycenter_v1p1beta1/proto/security_marks.proto", - "google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service.proto", - "google/cloud/securitycenter_v1p1beta1/proto/source.proto", - "google/cloud/securitycenter_v1p1beta1/py.typed", - "google/cloud/securitycenter_v1p1beta1/services/__init__.py", - "google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py", - "google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py", - "google/cloud/securitycenter_v1p1beta1/services/security_center/client.py", - "google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py", - "google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py", - "google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py", - "google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py", - "google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py", - "google/cloud/securitycenter_v1p1beta1/types/__init__.py", - "google/cloud/securitycenter_v1p1beta1/types/asset.py", - "google/cloud/securitycenter_v1p1beta1/types/finding.py", - "google/cloud/securitycenter_v1p1beta1/types/notification_config.py", - "google/cloud/securitycenter_v1p1beta1/types/notification_message.py", - "google/cloud/securitycenter_v1p1beta1/types/organization_settings.py", - "google/cloud/securitycenter_v1p1beta1/types/resource.py", - "google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py", - "google/cloud/securitycenter_v1p1beta1/types/security_marks.py", - "google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py", - "google/cloud/securitycenter_v1p1beta1/types/source.py", - "mypy.ini", - "noxfile.py", - "renovate.json", - "samples/AUTHORING_GUIDE.md", - "samples/CONTRIBUTING.md", - "samples/snippets/noxfile.py", - "scripts/decrypt-secrets.sh", - "scripts/fixup_securitycenter_v1_keywords.py", - "scripts/fixup_securitycenter_v1beta1_keywords.py", - "scripts/fixup_securitycenter_v1p1beta1_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/securitycenter_v1/__init__.py", - "tests/unit/gapic/securitycenter_v1/test_security_center.py", - "tests/unit/gapic/securitycenter_v1beta1/__init__.py", - "tests/unit/gapic/securitycenter_v1beta1/test_security_center.py", - "tests/unit/gapic/securitycenter_v1p1beta1/__init__.py", - "tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py" ] } \ No newline at end of file diff --git a/synth.py b/synth.py index b5771bae..4c9f818d 100644 --- a/synth.py +++ b/synth.py @@ -50,7 +50,7 @@ templated_files = common.py_library( samples=True, microgenerator=True, # set to True only if there are samples - cov_level=99, + cov_level=98, ) s.move( templated_files, excludes=[".coveragerc"] diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index caba91f9..d9594657 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -5,7 +5,7 @@ # # 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.0 +google-api-core==1.22.2 grpc-google-iam-v1==0.12.3 proto-plus==1.10.0 -libcst==0.2.5 \ No newline at end of file +libcst==0.2.5 diff --git a/tests/unit/gapic/securitycenter_v1/__init__.py b/tests/unit/gapic/securitycenter_v1/__init__.py index 8b137891..42ffdf2b 100644 --- a/tests/unit/gapic/securitycenter_v1/__init__.py +++ b/tests/unit/gapic/securitycenter_v1/__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/securitycenter_v1/test_security_center.py b/tests/unit/gapic/securitycenter_v1/test_security_center.py index 0553ce66..ae141baa 100644 --- a/tests/unit/gapic/securitycenter_v1/test_security_center.py +++ b/tests/unit/gapic/securitycenter_v1/test_security_center.py @@ -114,7 +114,24 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize( - "client_class", [SecurityCenterClient, SecurityCenterAsyncClient] + "client_class", [SecurityCenterClient, SecurityCenterAsyncClient,] +) +def test_security_center_client_from_service_account_info(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "securitycenter.googleapis.com:443" + + +@pytest.mark.parametrize( + "client_class", [SecurityCenterClient, SecurityCenterAsyncClient,] ) def test_security_center_client_from_service_account_file(client_class): creds = credentials.AnonymousCredentials() @@ -124,16 +141,21 @@ def test_security_center_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 == "securitycenter.googleapis.com:443" def test_security_center_client_get_transport_class(): transport = SecurityCenterClient.get_transport_class() - assert transport == transports.SecurityCenterGrpcTransport + available_transports = [ + transports.SecurityCenterGrpcTransport, + ] + assert transport in available_transports transport = SecurityCenterClient.get_transport_class("grpc") assert transport == transports.SecurityCenterGrpcTransport @@ -184,7 +206,7 @@ def test_security_center_client_client_options( credentials_file=None, host="squid.clam.whelk", scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -200,7 +222,7 @@ def test_security_center_client_client_options( credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -216,7 +238,7 @@ def test_security_center_client_client_options( credentials_file=None, host=client.DEFAULT_MTLS_ENDPOINT, scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -244,7 +266,7 @@ def test_security_center_client_client_options( credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -295,29 +317,25 @@ def test_security_center_client_mtls_env_auto( client_cert_source=client_cert_source_callback ) with mock.patch.object(transport_class, "__init__") as patched: - ssl_channel_creds = mock.Mock() - with mock.patch( - "grpc.ssl_channel_credentials", return_value=ssl_channel_creds - ): - patched.return_value = None - client = client_class(client_options=options) + patched.return_value = None + client = client_class(client_options=options) - if use_client_cert_env == "false": - expected_ssl_channel_creds = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_ssl_channel_creds = ssl_channel_creds - expected_host = client.DEFAULT_MTLS_ENDPOINT + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - ssl_channel_credentials=expected_ssl_channel_creds, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) # Check the case ADC client cert is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. @@ -326,66 +344,53 @@ def test_security_center_client_mtls_env_auto( ): with mock.patch.object(transport_class, "__init__") as patched: with mock.patch( - "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, ): with mock.patch( - "google.auth.transport.grpc.SslCredentials.is_mtls", - new_callable=mock.PropertyMock, - ) as is_mtls_mock: - with mock.patch( - "google.auth.transport.grpc.SslCredentials.ssl_credentials", - new_callable=mock.PropertyMock, - ) as ssl_credentials_mock: - if use_client_cert_env == "false": - is_mtls_mock.return_value = False - ssl_credentials_mock.return_value = None - expected_host = client.DEFAULT_ENDPOINT - expected_ssl_channel_creds = None - else: - is_mtls_mock.return_value = True - ssl_credentials_mock.return_value = mock.Mock() - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_ssl_channel_creds = ( - ssl_credentials_mock.return_value - ) - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - ssl_channel_credentials=expected_ssl_channel_creds, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.grpc.SslCredentials.__init__", return_value=None - ): - with mock.patch( - "google.auth.transport.grpc.SslCredentials.is_mtls", - new_callable=mock.PropertyMock, - ) as is_mtls_mock: - is_mtls_mock.return_value = False patched.return_value = None client = client_class() patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client.DEFAULT_ENDPOINT, + host=expected_host, scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + @pytest.mark.parametrize( "client_class,transport_class,transport_name", @@ -411,7 +416,7 @@ def test_security_center_client_client_options_scopes( credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=["1", "2"], - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -441,7 +446,7 @@ def test_security_center_client_client_options_credentials_file( credentials_file="credentials.json", host=client.DEFAULT_ENDPOINT, scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -460,7 +465,7 @@ def test_security_center_client_client_options_from_dict(): credentials_file=None, host="squid.clam.whelk", scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -509,6 +514,22 @@ def test_create_source_from_dict(): test_create_source(request_type=dict) +def test_create_source_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 = SecurityCenterClient( + 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_source), "__call__") as call: + client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.CreateSourceRequest() + + @pytest.mark.asyncio async def test_create_source_async( transport: str = "grpc_asyncio", @@ -737,6 +758,22 @@ def test_create_finding_from_dict(): test_create_finding(request_type=dict) +def test_create_finding_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 = SecurityCenterClient( + 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_finding), "__call__") as call: + client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.CreateFindingRequest() + + @pytest.mark.asyncio async def test_create_finding_async( transport: str = "grpc_asyncio", @@ -984,6 +1021,24 @@ def test_create_notification_config_from_dict(): test_create_notification_config(request_type=dict) +def test_create_notification_config_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 = SecurityCenterClient( + 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_notification_config), "__call__" + ) as call: + client.create_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + + @pytest.mark.asyncio async def test_create_notification_config_async( transport: str = "grpc_asyncio", @@ -1235,6 +1290,24 @@ def test_delete_notification_config_from_dict(): test_delete_notification_config(request_type=dict) +def test_delete_notification_config_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 = SecurityCenterClient( + 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_notification_config), "__call__" + ) as call: + client.delete_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + + @pytest.mark.asyncio async def test_delete_notification_config_async( transport: str = "grpc_asyncio", @@ -1431,6 +1504,22 @@ def test_get_iam_policy_from_dict(): test_get_iam_policy(request_type=dict) +def test_get_iam_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 = SecurityCenterClient( + 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_iam_policy), "__call__") as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.GetIamPolicyRequest() + + @pytest.mark.asyncio async def test_get_iam_policy_async( transport: str = "grpc_asyncio", request_type=iam_policy.GetIamPolicyRequest @@ -1653,6 +1742,24 @@ def test_get_notification_config_from_dict(): test_get_notification_config(request_type=dict) +def test_get_notification_config_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 = SecurityCenterClient( + 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_notification_config), "__call__" + ) as call: + client.get_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + + @pytest.mark.asyncio async def test_get_notification_config_async( transport: str = "grpc_asyncio", @@ -1873,6 +1980,24 @@ def test_get_organization_settings_from_dict(): test_get_organization_settings(request_type=dict) +def test_get_organization_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + 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_organization_settings), "__call__" + ) as call: + client.get_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + + @pytest.mark.asyncio async def test_get_organization_settings_async( transport: str = "grpc_asyncio", @@ -2087,6 +2212,22 @@ def test_get_source_from_dict(): test_get_source(request_type=dict) +def test_get_source_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 = SecurityCenterClient( + 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_source), "__call__") as call: + client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.GetSourceRequest() + + @pytest.mark.asyncio async def test_get_source_async( transport: str = "grpc_asyncio", @@ -2287,6 +2428,22 @@ def test_group_assets_from_dict(): test_group_assets(request_type=dict) +def test_group_assets_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 = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.group_assets), "__call__") as call: + client.group_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.GroupAssetsRequest() + + @pytest.mark.asyncio async def test_group_assets_async( transport: str = "grpc_asyncio", @@ -2582,6 +2739,22 @@ def test_group_findings_from_dict(): test_group_findings(request_type=dict) +def test_group_findings_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 = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.group_findings), "__call__") as call: + client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.GroupFindingsRequest() + + @pytest.mark.asyncio async def test_group_findings_async( transport: str = "grpc_asyncio", @@ -2956,6 +3129,22 @@ def test_list_assets_from_dict(): test_list_assets(request_type=dict) +def test_list_assets_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 = SecurityCenterClient( + 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_assets), "__call__") as call: + client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.ListAssetsRequest() + + @pytest.mark.asyncio async def test_list_assets_async( transport: str = "grpc_asyncio", @@ -3265,6 +3454,22 @@ def test_list_findings_from_dict(): test_list_findings(request_type=dict) +def test_list_findings_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 = SecurityCenterClient( + 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_findings), "__call__") as call: + client.list_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.ListFindingsRequest() + + @pytest.mark.asyncio async def test_list_findings_async( transport: str = "grpc_asyncio", @@ -3579,6 +3784,24 @@ def test_list_notification_configs_from_dict(): test_list_notification_configs(request_type=dict) +def test_list_notification_configs_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 = SecurityCenterClient( + 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_notification_configs), "__call__" + ) as call: + client.list_notification_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + + @pytest.mark.asyncio async def test_list_notification_configs_async( transport: str = "grpc_asyncio", @@ -3961,6 +4184,22 @@ def test_list_sources_from_dict(): test_list_sources(request_type=dict) +def test_list_sources_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 = SecurityCenterClient( + 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_sources), "__call__") as call: + client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.ListSourcesRequest() + + @pytest.mark.asyncio async def test_list_sources_async( transport: str = "grpc_asyncio", @@ -4285,6 +4524,24 @@ def test_run_asset_discovery_from_dict(): test_run_asset_discovery(request_type=dict) +def test_run_asset_discovery_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 = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), "__call__" + ) as call: + client.run_asset_discovery() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + + @pytest.mark.asyncio async def test_run_asset_discovery_async( transport: str = "grpc_asyncio", @@ -4507,6 +4764,24 @@ def test_set_finding_state_from_dict(): test_set_finding_state(request_type=dict) +def test_set_finding_state_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 = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), "__call__" + ) as call: + client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.SetFindingStateRequest() + + @pytest.mark.asyncio async def test_set_finding_state_async( transport: str = "grpc_asyncio", @@ -4753,6 +5028,22 @@ def test_set_iam_policy_from_dict(): test_set_iam_policy(request_type=dict) +def test_set_iam_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 = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.SetIamPolicyRequest() + + @pytest.mark.asyncio async def test_set_iam_policy_async( transport: str = "grpc_asyncio", request_type=iam_policy.SetIamPolicyRequest @@ -4962,6 +5253,24 @@ def test_test_iam_permissions_from_dict(): test_test_iam_permissions(request_type=dict) +def test_test_iam_permissions_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 = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.TestIamPermissionsRequest() + + @pytest.mark.asyncio async def test_test_iam_permissions_async( transport: str = "grpc_asyncio", request_type=iam_policy.TestIamPermissionsRequest @@ -5213,6 +5522,22 @@ def test_update_finding_from_dict(): test_update_finding(request_type=dict) +def test_update_finding_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 = SecurityCenterClient( + 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_finding), "__call__") as call: + client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.UpdateFindingRequest() + + @pytest.mark.asyncio async def test_update_finding_async( transport: str = "grpc_asyncio", @@ -5446,6 +5771,24 @@ def test_update_notification_config_from_dict(): test_update_notification_config(request_type=dict) +def test_update_notification_config_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 = SecurityCenterClient( + 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_notification_config), "__call__" + ) as call: + client.update_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + + @pytest.mark.asyncio async def test_update_notification_config_async( transport: str = "grpc_asyncio", @@ -5702,6 +6045,24 @@ def test_update_organization_settings_from_dict(): test_update_organization_settings(request_type=dict) +def test_update_organization_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + 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_organization_settings), "__call__" + ) as call: + client.update_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + + @pytest.mark.asyncio async def test_update_organization_settings_async( transport: str = "grpc_asyncio", @@ -5944,6 +6305,22 @@ def test_update_source_from_dict(): test_update_source(request_type=dict) +def test_update_source_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 = SecurityCenterClient( + 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_source), "__call__") as call: + client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.UpdateSourceRequest() + + @pytest.mark.asyncio async def test_update_source_async( transport: str = "grpc_asyncio", @@ -6147,6 +6524,24 @@ def test_update_security_marks_from_dict(): test_update_security_marks(request_type=dict) +def test_update_security_marks_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 = SecurityCenterClient( + 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_security_marks), "__call__" + ) as call: + client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + @pytest.mark.asyncio async def test_update_security_marks_async( transport: str = "grpc_asyncio", @@ -6516,6 +6911,51 @@ def test_security_center_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +def test_security_center_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + def test_security_center_host_no_port(): client = SecurityCenterClient( credentials=credentials.AnonymousCredentials(), @@ -6537,7 +6977,7 @@ def test_security_center_host_with_port(): def test_security_center_grpc_transport_channel(): - channel = grpc.insecure_channel("http://localhost/") + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.SecurityCenterGrpcTransport( @@ -6549,7 +6989,7 @@ def test_security_center_grpc_transport_channel(): def test_security_center_grpc_asyncio_transport_channel(): - channel = aio.insecure_channel("http://localhost/") + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.SecurityCenterGrpcAsyncIOTransport( @@ -6560,6 +7000,8 @@ def test_security_center_grpc_asyncio_transport_channel(): assert transport._ssl_channel_credentials == None +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( "transport_class", [ @@ -6574,7 +7016,7 @@ def test_security_center_transport_channel_mtls_with_client_cert_source( "grpc.ssl_channel_credentials", autospec=True ) as grpc_ssl_channel_cred: with mock.patch.object( - transport_class, "create_channel", autospec=True + transport_class, "create_channel" ) as grpc_create_channel: mock_ssl_cred = mock.Mock() grpc_ssl_channel_cred.return_value = mock_ssl_cred @@ -6612,6 +7054,8 @@ def test_security_center_transport_channel_mtls_with_client_cert_source( assert transport._ssl_channel_credentials == mock_ssl_cred +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( "transport_class", [ @@ -6627,7 +7071,7 @@ def test_security_center_transport_channel_mtls_with_adc(transport_class): ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), ): with mock.patch.object( - transport_class, "create_channel", autospec=True + transport_class, "create_channel" ) as grpc_create_channel: mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel diff --git a/tests/unit/gapic/securitycenter_v1beta1/__init__.py b/tests/unit/gapic/securitycenter_v1beta1/__init__.py index 8b137891..42ffdf2b 100644 --- a/tests/unit/gapic/securitycenter_v1beta1/__init__.py +++ b/tests/unit/gapic/securitycenter_v1beta1/__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/securitycenter_v1beta1/test_security_center.py b/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py index fc005bf6..bc4bb9a2 100644 --- a/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py +++ b/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py @@ -113,7 +113,24 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize( - "client_class", [SecurityCenterClient, SecurityCenterAsyncClient] + "client_class", [SecurityCenterClient, SecurityCenterAsyncClient,] +) +def test_security_center_client_from_service_account_info(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "securitycenter.googleapis.com:443" + + +@pytest.mark.parametrize( + "client_class", [SecurityCenterClient, SecurityCenterAsyncClient,] ) def test_security_center_client_from_service_account_file(client_class): creds = credentials.AnonymousCredentials() @@ -123,16 +140,21 @@ def test_security_center_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 == "securitycenter.googleapis.com:443" def test_security_center_client_get_transport_class(): transport = SecurityCenterClient.get_transport_class() - assert transport == transports.SecurityCenterGrpcTransport + available_transports = [ + transports.SecurityCenterGrpcTransport, + ] + assert transport in available_transports transport = SecurityCenterClient.get_transport_class("grpc") assert transport == transports.SecurityCenterGrpcTransport @@ -183,7 +205,7 @@ def test_security_center_client_client_options( credentials_file=None, host="squid.clam.whelk", scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -199,7 +221,7 @@ def test_security_center_client_client_options( credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -215,7 +237,7 @@ def test_security_center_client_client_options( credentials_file=None, host=client.DEFAULT_MTLS_ENDPOINT, scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -243,7 +265,7 @@ def test_security_center_client_client_options( credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -294,29 +316,25 @@ def test_security_center_client_mtls_env_auto( client_cert_source=client_cert_source_callback ) with mock.patch.object(transport_class, "__init__") as patched: - ssl_channel_creds = mock.Mock() - with mock.patch( - "grpc.ssl_channel_credentials", return_value=ssl_channel_creds - ): - patched.return_value = None - client = client_class(client_options=options) + patched.return_value = None + client = client_class(client_options=options) - if use_client_cert_env == "false": - expected_ssl_channel_creds = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_ssl_channel_creds = ssl_channel_creds - expected_host = client.DEFAULT_MTLS_ENDPOINT + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - ssl_channel_credentials=expected_ssl_channel_creds, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) # Check the case ADC client cert is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. @@ -325,66 +343,53 @@ def test_security_center_client_mtls_env_auto( ): with mock.patch.object(transport_class, "__init__") as patched: with mock.patch( - "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, ): with mock.patch( - "google.auth.transport.grpc.SslCredentials.is_mtls", - new_callable=mock.PropertyMock, - ) as is_mtls_mock: - with mock.patch( - "google.auth.transport.grpc.SslCredentials.ssl_credentials", - new_callable=mock.PropertyMock, - ) as ssl_credentials_mock: - if use_client_cert_env == "false": - is_mtls_mock.return_value = False - ssl_credentials_mock.return_value = None - expected_host = client.DEFAULT_ENDPOINT - expected_ssl_channel_creds = None - else: - is_mtls_mock.return_value = True - ssl_credentials_mock.return_value = mock.Mock() - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_ssl_channel_creds = ( - ssl_credentials_mock.return_value - ) - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - ssl_channel_credentials=expected_ssl_channel_creds, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.grpc.SslCredentials.__init__", return_value=None - ): - with mock.patch( - "google.auth.transport.grpc.SslCredentials.is_mtls", - new_callable=mock.PropertyMock, - ) as is_mtls_mock: - is_mtls_mock.return_value = False patched.return_value = None client = client_class() patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client.DEFAULT_ENDPOINT, + host=expected_host, scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + @pytest.mark.parametrize( "client_class,transport_class,transport_name", @@ -410,7 +415,7 @@ def test_security_center_client_client_options_scopes( credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=["1", "2"], - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -440,7 +445,7 @@ def test_security_center_client_client_options_credentials_file( credentials_file="credentials.json", host=client.DEFAULT_ENDPOINT, scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -459,7 +464,7 @@ def test_security_center_client_client_options_from_dict(): credentials_file=None, host="squid.clam.whelk", scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -508,6 +513,22 @@ def test_create_source_from_dict(): test_create_source(request_type=dict) +def test_create_source_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 = SecurityCenterClient( + 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_source), "__call__") as call: + client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.CreateSourceRequest() + + @pytest.mark.asyncio async def test_create_source_async( transport: str = "grpc_asyncio", @@ -733,6 +754,22 @@ def test_create_finding_from_dict(): test_create_finding(request_type=dict) +def test_create_finding_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 = SecurityCenterClient( + 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_finding), "__call__") as call: + client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.CreateFindingRequest() + + @pytest.mark.asyncio async def test_create_finding_async( transport: str = "grpc_asyncio", @@ -962,6 +999,22 @@ def test_get_iam_policy_from_dict(): test_get_iam_policy(request_type=dict) +def test_get_iam_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 = SecurityCenterClient( + 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_iam_policy), "__call__") as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.GetIamPolicyRequest() + + @pytest.mark.asyncio async def test_get_iam_policy_async( transport: str = "grpc_asyncio", request_type=iam_policy.GetIamPolicyRequest @@ -1174,6 +1227,24 @@ def test_get_organization_settings_from_dict(): test_get_organization_settings(request_type=dict) +def test_get_organization_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + 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_organization_settings), "__call__" + ) as call: + client.get_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + + @pytest.mark.asyncio async def test_get_organization_settings_async( transport: str = "grpc_asyncio", @@ -1388,6 +1459,22 @@ def test_get_source_from_dict(): test_get_source(request_type=dict) +def test_get_source_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 = SecurityCenterClient( + 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_source), "__call__") as call: + client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.GetSourceRequest() + + @pytest.mark.asyncio async def test_get_source_async( transport: str = "grpc_asyncio", @@ -1586,6 +1673,22 @@ def test_group_assets_from_dict(): test_group_assets(request_type=dict) +def test_group_assets_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 = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.group_assets), "__call__") as call: + client.group_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.GroupAssetsRequest() + + @pytest.mark.asyncio async def test_group_assets_async( transport: str = "grpc_asyncio", @@ -1877,6 +1980,22 @@ def test_group_findings_from_dict(): test_group_findings(request_type=dict) +def test_group_findings_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 = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.group_findings), "__call__") as call: + client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.GroupFindingsRequest() + + @pytest.mark.asyncio async def test_group_findings_async( transport: str = "grpc_asyncio", @@ -2249,6 +2368,22 @@ def test_list_assets_from_dict(): test_list_assets(request_type=dict) +def test_list_assets_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 = SecurityCenterClient( + 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_assets), "__call__") as call: + client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.ListAssetsRequest() + + @pytest.mark.asyncio async def test_list_assets_async( transport: str = "grpc_asyncio", @@ -2558,6 +2693,22 @@ def test_list_findings_from_dict(): test_list_findings(request_type=dict) +def test_list_findings_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 = SecurityCenterClient( + 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_findings), "__call__") as call: + client.list_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.ListFindingsRequest() + + @pytest.mark.asyncio async def test_list_findings_async( transport: str = "grpc_asyncio", @@ -2819,6 +2970,22 @@ def test_list_sources_from_dict(): test_list_sources(request_type=dict) +def test_list_sources_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 = SecurityCenterClient( + 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_sources), "__call__") as call: + client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.ListSourcesRequest() + + @pytest.mark.asyncio async def test_list_sources_async( transport: str = "grpc_asyncio", @@ -3143,6 +3310,24 @@ def test_run_asset_discovery_from_dict(): test_run_asset_discovery(request_type=dict) +def test_run_asset_discovery_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 = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), "__call__" + ) as call: + client.run_asset_discovery() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + + @pytest.mark.asyncio async def test_run_asset_discovery_async( transport: str = "grpc_asyncio", @@ -3362,6 +3547,24 @@ def test_set_finding_state_from_dict(): test_set_finding_state(request_type=dict) +def test_set_finding_state_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 = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), "__call__" + ) as call: + client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.SetFindingStateRequest() + + @pytest.mark.asyncio async def test_set_finding_state_async( transport: str = "grpc_asyncio", @@ -3605,6 +3808,22 @@ def test_set_iam_policy_from_dict(): test_set_iam_policy(request_type=dict) +def test_set_iam_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 = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.SetIamPolicyRequest() + + @pytest.mark.asyncio async def test_set_iam_policy_async( transport: str = "grpc_asyncio", request_type=iam_policy.SetIamPolicyRequest @@ -3814,6 +4033,24 @@ def test_test_iam_permissions_from_dict(): test_test_iam_permissions(request_type=dict) +def test_test_iam_permissions_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 = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.TestIamPermissionsRequest() + + @pytest.mark.asyncio async def test_test_iam_permissions_async( transport: str = "grpc_asyncio", request_type=iam_policy.TestIamPermissionsRequest @@ -4062,6 +4299,22 @@ def test_update_finding_from_dict(): test_update_finding(request_type=dict) +def test_update_finding_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 = SecurityCenterClient( + 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_finding), "__call__") as call: + client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.UpdateFindingRequest() + + @pytest.mark.asyncio async def test_update_finding_async( transport: str = "grpc_asyncio", @@ -4282,6 +4535,24 @@ def test_update_organization_settings_from_dict(): test_update_organization_settings(request_type=dict) +def test_update_organization_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + 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_organization_settings), "__call__" + ) as call: + client.update_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + + @pytest.mark.asyncio async def test_update_organization_settings_async( transport: str = "grpc_asyncio", @@ -4524,6 +4795,22 @@ def test_update_source_from_dict(): test_update_source(request_type=dict) +def test_update_source_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 = SecurityCenterClient( + 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_source), "__call__") as call: + client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.UpdateSourceRequest() + + @pytest.mark.asyncio async def test_update_source_async( transport: str = "grpc_asyncio", @@ -4727,6 +5014,24 @@ def test_update_security_marks_from_dict(): test_update_security_marks(request_type=dict) +def test_update_security_marks_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 = SecurityCenterClient( + 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_security_marks), "__call__" + ) as call: + client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + @pytest.mark.asyncio async def test_update_security_marks_async( transport: str = "grpc_asyncio", @@ -5091,6 +5396,51 @@ def test_security_center_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +def test_security_center_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + def test_security_center_host_no_port(): client = SecurityCenterClient( credentials=credentials.AnonymousCredentials(), @@ -5112,7 +5462,7 @@ def test_security_center_host_with_port(): def test_security_center_grpc_transport_channel(): - channel = grpc.insecure_channel("http://localhost/") + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.SecurityCenterGrpcTransport( @@ -5124,7 +5474,7 @@ def test_security_center_grpc_transport_channel(): def test_security_center_grpc_asyncio_transport_channel(): - channel = aio.insecure_channel("http://localhost/") + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.SecurityCenterGrpcAsyncIOTransport( @@ -5135,6 +5485,8 @@ def test_security_center_grpc_asyncio_transport_channel(): assert transport._ssl_channel_credentials == None +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( "transport_class", [ @@ -5149,7 +5501,7 @@ def test_security_center_transport_channel_mtls_with_client_cert_source( "grpc.ssl_channel_credentials", autospec=True ) as grpc_ssl_channel_cred: with mock.patch.object( - transport_class, "create_channel", autospec=True + transport_class, "create_channel" ) as grpc_create_channel: mock_ssl_cred = mock.Mock() grpc_ssl_channel_cred.return_value = mock_ssl_cred @@ -5187,6 +5539,8 @@ def test_security_center_transport_channel_mtls_with_client_cert_source( assert transport._ssl_channel_credentials == mock_ssl_cred +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( "transport_class", [ @@ -5202,7 +5556,7 @@ def test_security_center_transport_channel_mtls_with_adc(transport_class): ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), ): with mock.patch.object( - transport_class, "create_channel", autospec=True + transport_class, "create_channel" ) as grpc_create_channel: mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel diff --git a/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py b/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py index 8b137891..42ffdf2b 100644 --- a/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py +++ b/tests/unit/gapic/securitycenter_v1p1beta1/__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/securitycenter_v1p1beta1/test_security_center.py b/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py index ecc8ecb0..4e7ebe8b 100644 --- a/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py +++ b/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py @@ -118,7 +118,24 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize( - "client_class", [SecurityCenterClient, SecurityCenterAsyncClient] + "client_class", [SecurityCenterClient, SecurityCenterAsyncClient,] +) +def test_security_center_client_from_service_account_info(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "securitycenter.googleapis.com:443" + + +@pytest.mark.parametrize( + "client_class", [SecurityCenterClient, SecurityCenterAsyncClient,] ) def test_security_center_client_from_service_account_file(client_class): creds = credentials.AnonymousCredentials() @@ -128,16 +145,21 @@ def test_security_center_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 == "securitycenter.googleapis.com:443" def test_security_center_client_get_transport_class(): transport = SecurityCenterClient.get_transport_class() - assert transport == transports.SecurityCenterGrpcTransport + available_transports = [ + transports.SecurityCenterGrpcTransport, + ] + assert transport in available_transports transport = SecurityCenterClient.get_transport_class("grpc") assert transport == transports.SecurityCenterGrpcTransport @@ -188,7 +210,7 @@ def test_security_center_client_client_options( credentials_file=None, host="squid.clam.whelk", scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -204,7 +226,7 @@ def test_security_center_client_client_options( credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -220,7 +242,7 @@ def test_security_center_client_client_options( credentials_file=None, host=client.DEFAULT_MTLS_ENDPOINT, scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -248,7 +270,7 @@ def test_security_center_client_client_options( credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -299,29 +321,25 @@ def test_security_center_client_mtls_env_auto( client_cert_source=client_cert_source_callback ) with mock.patch.object(transport_class, "__init__") as patched: - ssl_channel_creds = mock.Mock() - with mock.patch( - "grpc.ssl_channel_credentials", return_value=ssl_channel_creds - ): - patched.return_value = None - client = client_class(client_options=options) + patched.return_value = None + client = client_class(client_options=options) - if use_client_cert_env == "false": - expected_ssl_channel_creds = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_ssl_channel_creds = ssl_channel_creds - expected_host = client.DEFAULT_MTLS_ENDPOINT + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - ssl_channel_credentials=expected_ssl_channel_creds, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) # Check the case ADC client cert is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. @@ -330,66 +348,53 @@ def test_security_center_client_mtls_env_auto( ): with mock.patch.object(transport_class, "__init__") as patched: with mock.patch( - "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, ): with mock.patch( - "google.auth.transport.grpc.SslCredentials.is_mtls", - new_callable=mock.PropertyMock, - ) as is_mtls_mock: - with mock.patch( - "google.auth.transport.grpc.SslCredentials.ssl_credentials", - new_callable=mock.PropertyMock, - ) as ssl_credentials_mock: - if use_client_cert_env == "false": - is_mtls_mock.return_value = False - ssl_credentials_mock.return_value = None - expected_host = client.DEFAULT_ENDPOINT - expected_ssl_channel_creds = None - else: - is_mtls_mock.return_value = True - ssl_credentials_mock.return_value = mock.Mock() - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_ssl_channel_creds = ( - ssl_credentials_mock.return_value - ) - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - ssl_channel_credentials=expected_ssl_channel_creds, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.grpc.SslCredentials.__init__", return_value=None - ): - with mock.patch( - "google.auth.transport.grpc.SslCredentials.is_mtls", - new_callable=mock.PropertyMock, - ) as is_mtls_mock: - is_mtls_mock.return_value = False patched.return_value = None client = client_class() patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client.DEFAULT_ENDPOINT, + host=expected_host, scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + @pytest.mark.parametrize( "client_class,transport_class,transport_name", @@ -415,7 +420,7 @@ def test_security_center_client_client_options_scopes( credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=["1", "2"], - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -445,7 +450,7 @@ def test_security_center_client_client_options_credentials_file( credentials_file="credentials.json", host=client.DEFAULT_ENDPOINT, scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -464,7 +469,7 @@ def test_security_center_client_client_options_from_dict(): credentials_file=None, host="squid.clam.whelk", scopes=None, - ssl_channel_credentials=None, + client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, ) @@ -513,6 +518,22 @@ def test_create_source_from_dict(): test_create_source(request_type=dict) +def test_create_source_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 = SecurityCenterClient( + 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_source), "__call__") as call: + client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.CreateSourceRequest() + + @pytest.mark.asyncio async def test_create_source_async( transport: str = "grpc_asyncio", @@ -741,6 +762,22 @@ def test_create_finding_from_dict(): test_create_finding(request_type=dict) +def test_create_finding_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 = SecurityCenterClient( + 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_finding), "__call__") as call: + client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.CreateFindingRequest() + + @pytest.mark.asyncio async def test_create_finding_async( transport: str = "grpc_asyncio", @@ -994,6 +1031,24 @@ def test_create_notification_config_from_dict(): test_create_notification_config(request_type=dict) +def test_create_notification_config_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 = SecurityCenterClient( + 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_notification_config), "__call__" + ) as call: + client.create_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + + @pytest.mark.asyncio async def test_create_notification_config_async( transport: str = "grpc_asyncio", @@ -1251,6 +1306,24 @@ def test_delete_notification_config_from_dict(): test_delete_notification_config(request_type=dict) +def test_delete_notification_config_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 = SecurityCenterClient( + 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_notification_config), "__call__" + ) as call: + client.delete_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + + @pytest.mark.asyncio async def test_delete_notification_config_async( transport: str = "grpc_asyncio", @@ -1447,6 +1520,22 @@ def test_get_iam_policy_from_dict(): test_get_iam_policy(request_type=dict) +def test_get_iam_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 = SecurityCenterClient( + 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_iam_policy), "__call__") as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.GetIamPolicyRequest() + + @pytest.mark.asyncio async def test_get_iam_policy_async( transport: str = "grpc_asyncio", request_type=iam_policy.GetIamPolicyRequest @@ -1674,6 +1763,24 @@ def test_get_notification_config_from_dict(): test_get_notification_config(request_type=dict) +def test_get_notification_config_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 = SecurityCenterClient( + 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_notification_config), "__call__" + ) as call: + client.get_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + + @pytest.mark.asyncio async def test_get_notification_config_async( transport: str = "grpc_asyncio", @@ -1899,6 +2006,24 @@ def test_get_organization_settings_from_dict(): test_get_organization_settings(request_type=dict) +def test_get_organization_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + 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_organization_settings), "__call__" + ) as call: + client.get_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + + @pytest.mark.asyncio async def test_get_organization_settings_async( transport: str = "grpc_asyncio", @@ -2113,6 +2238,22 @@ def test_get_source_from_dict(): test_get_source(request_type=dict) +def test_get_source_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 = SecurityCenterClient( + 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_source), "__call__") as call: + client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.GetSourceRequest() + + @pytest.mark.asyncio async def test_get_source_async( transport: str = "grpc_asyncio", @@ -2313,6 +2454,22 @@ def test_group_assets_from_dict(): test_group_assets(request_type=dict) +def test_group_assets_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 = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.group_assets), "__call__") as call: + client.group_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.GroupAssetsRequest() + + @pytest.mark.asyncio async def test_group_assets_async( transport: str = "grpc_asyncio", @@ -2608,6 +2765,22 @@ def test_group_findings_from_dict(): test_group_findings(request_type=dict) +def test_group_findings_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 = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.group_findings), "__call__") as call: + client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.GroupFindingsRequest() + + @pytest.mark.asyncio async def test_group_findings_async( transport: str = "grpc_asyncio", @@ -2982,6 +3155,22 @@ def test_list_assets_from_dict(): test_list_assets(request_type=dict) +def test_list_assets_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 = SecurityCenterClient( + 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_assets), "__call__") as call: + client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.ListAssetsRequest() + + @pytest.mark.asyncio async def test_list_assets_async( transport: str = "grpc_asyncio", @@ -3358,6 +3547,22 @@ def test_list_findings_from_dict(): test_list_findings(request_type=dict) +def test_list_findings_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 = SecurityCenterClient( + 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_findings), "__call__") as call: + client.list_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.ListFindingsRequest() + + @pytest.mark.asyncio async def test_list_findings_async( transport: str = "grpc_asyncio", @@ -3739,6 +3944,24 @@ def test_list_notification_configs_from_dict(): test_list_notification_configs(request_type=dict) +def test_list_notification_configs_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 = SecurityCenterClient( + 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_notification_configs), "__call__" + ) as call: + client.list_notification_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + + @pytest.mark.asyncio async def test_list_notification_configs_async( transport: str = "grpc_asyncio", @@ -4121,6 +4344,22 @@ def test_list_sources_from_dict(): test_list_sources(request_type=dict) +def test_list_sources_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 = SecurityCenterClient( + 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_sources), "__call__") as call: + client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.ListSourcesRequest() + + @pytest.mark.asyncio async def test_list_sources_async( transport: str = "grpc_asyncio", @@ -4445,6 +4684,24 @@ def test_run_asset_discovery_from_dict(): test_run_asset_discovery(request_type=dict) +def test_run_asset_discovery_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 = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), "__call__" + ) as call: + client.run_asset_discovery() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + + @pytest.mark.asyncio async def test_run_asset_discovery_async( transport: str = "grpc_asyncio", @@ -4667,6 +4924,24 @@ def test_set_finding_state_from_dict(): test_set_finding_state(request_type=dict) +def test_set_finding_state_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 = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), "__call__" + ) as call: + client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.SetFindingStateRequest() + + @pytest.mark.asyncio async def test_set_finding_state_async( transport: str = "grpc_asyncio", @@ -4913,6 +5188,22 @@ def test_set_iam_policy_from_dict(): test_set_iam_policy(request_type=dict) +def test_set_iam_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 = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.SetIamPolicyRequest() + + @pytest.mark.asyncio async def test_set_iam_policy_async( transport: str = "grpc_asyncio", request_type=iam_policy.SetIamPolicyRequest @@ -5122,6 +5413,24 @@ def test_test_iam_permissions_from_dict(): test_test_iam_permissions(request_type=dict) +def test_test_iam_permissions_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 = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.TestIamPermissionsRequest() + + @pytest.mark.asyncio async def test_test_iam_permissions_async( transport: str = "grpc_asyncio", request_type=iam_policy.TestIamPermissionsRequest @@ -5373,6 +5682,22 @@ def test_update_finding_from_dict(): test_update_finding(request_type=dict) +def test_update_finding_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 = SecurityCenterClient( + 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_finding), "__call__") as call: + client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.UpdateFindingRequest() + + @pytest.mark.asyncio async def test_update_finding_async( transport: str = "grpc_asyncio", @@ -5622,6 +5947,24 @@ def test_update_notification_config_from_dict(): test_update_notification_config(request_type=dict) +def test_update_notification_config_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 = SecurityCenterClient( + 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_notification_config), "__call__" + ) as call: + client.update_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + + @pytest.mark.asyncio async def test_update_notification_config_async( transport: str = "grpc_asyncio", @@ -5884,6 +6227,24 @@ def test_update_organization_settings_from_dict(): test_update_organization_settings(request_type=dict) +def test_update_organization_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + 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_organization_settings), "__call__" + ) as call: + client.update_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + + @pytest.mark.asyncio async def test_update_organization_settings_async( transport: str = "grpc_asyncio", @@ -6126,6 +6487,22 @@ def test_update_source_from_dict(): test_update_source(request_type=dict) +def test_update_source_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 = SecurityCenterClient( + 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_source), "__call__") as call: + client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.UpdateSourceRequest() + + @pytest.mark.asyncio async def test_update_source_async( transport: str = "grpc_asyncio", @@ -6339,6 +6716,24 @@ def test_update_security_marks_from_dict(): test_update_security_marks(request_type=dict) +def test_update_security_marks_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 = SecurityCenterClient( + 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_security_marks), "__call__" + ) as call: + client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + @pytest.mark.asyncio async def test_update_security_marks_async( transport: str = "grpc_asyncio", @@ -6716,6 +7111,51 @@ def test_security_center_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +def test_security_center_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + def test_security_center_host_no_port(): client = SecurityCenterClient( credentials=credentials.AnonymousCredentials(), @@ -6737,7 +7177,7 @@ def test_security_center_host_with_port(): def test_security_center_grpc_transport_channel(): - channel = grpc.insecure_channel("http://localhost/") + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.SecurityCenterGrpcTransport( @@ -6749,7 +7189,7 @@ def test_security_center_grpc_transport_channel(): def test_security_center_grpc_asyncio_transport_channel(): - channel = aio.insecure_channel("http://localhost/") + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.SecurityCenterGrpcAsyncIOTransport( @@ -6760,6 +7200,8 @@ def test_security_center_grpc_asyncio_transport_channel(): assert transport._ssl_channel_credentials == None +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( "transport_class", [ @@ -6774,7 +7216,7 @@ def test_security_center_transport_channel_mtls_with_client_cert_source( "grpc.ssl_channel_credentials", autospec=True ) as grpc_ssl_channel_cred: with mock.patch.object( - transport_class, "create_channel", autospec=True + transport_class, "create_channel" ) as grpc_create_channel: mock_ssl_cred = mock.Mock() grpc_ssl_channel_cred.return_value = mock_ssl_cred @@ -6812,6 +7254,8 @@ def test_security_center_transport_channel_mtls_with_client_cert_source( assert transport._ssl_channel_credentials == mock_ssl_cred +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. @pytest.mark.parametrize( "transport_class", [ @@ -6827,7 +7271,7 @@ def test_security_center_transport_channel_mtls_with_adc(transport_class): ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), ): with mock.patch.object( - transport_class, "create_channel", autospec=True + transport_class, "create_channel" ) as grpc_create_channel: mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel From 4f5f27563df0b03076353de52e35fe9dd9671b2d Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Wed, 31 Mar 2021 09:27:23 -0700 Subject: [PATCH 16/23] build(python): update docfx job to use new plugin (#118) Source-Author: Dan Lee <71398022+dandhlee@users.noreply.github.com> Source-Date: Tue Mar 30 19:36:37 2021 -0400 Source-Repo: googleapis/synthtool Source-Sha: 4501974ad08b5d693311457e2ea4ce845676e329 Source-Link: https://github.com/googleapis/synthtool/commit/4501974ad08b5d693311457e2ea4ce845676e329 --- noxfile.py | 4 +- synth.metadata | 195 ++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 192 insertions(+), 7 deletions(-) diff --git a/noxfile.py b/noxfile.py index 43dd3024..4d37cd3a 100644 --- a/noxfile.py +++ b/noxfile.py @@ -211,9 +211,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/synth.metadata b/synth.metadata index 5e9ab512..96c39c4c 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,8 +3,8 @@ { "git": { "name": ".", - "remote": "git@github.com:googleapis/python-securitycenter.git", - "sha": "7e7e448e1b4b05aa51b948f7f3463982aa2d302b" + "remote": "https://github.com/googleapis/python-securitycenter.git", + "sha": "15c28e88f5b52a6e4f608198446b0753bf48734e" } }, { @@ -19,14 +19,14 @@ "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "572ef8f70edd9041f5bcfa71511aed6aecfc2098" + "sha": "4501974ad08b5d693311457e2ea4ce845676e329" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "572ef8f70edd9041f5bcfa71511aed6aecfc2098" + "sha": "4501974ad08b5d693311457e2ea4ce845676e329" } } ], @@ -58,5 +58,192 @@ "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/securitycenter_v1/security_center.rst", + "docs/securitycenter_v1/services.rst", + "docs/securitycenter_v1/types.rst", + "docs/securitycenter_v1beta1/security_center.rst", + "docs/securitycenter_v1beta1/services.rst", + "docs/securitycenter_v1beta1/types.rst", + "docs/securitycenter_v1p1beta1/security_center.rst", + "docs/securitycenter_v1p1beta1/services.rst", + "docs/securitycenter_v1p1beta1/types.rst", + "google/cloud/securitycenter/__init__.py", + "google/cloud/securitycenter/py.typed", + "google/cloud/securitycenter_v1/__init__.py", + "google/cloud/securitycenter_v1/proto/asset.proto", + "google/cloud/securitycenter_v1/proto/finding.proto", + "google/cloud/securitycenter_v1/proto/notification_config.proto", + "google/cloud/securitycenter_v1/proto/notification_message.proto", + "google/cloud/securitycenter_v1/proto/organization_settings.proto", + "google/cloud/securitycenter_v1/proto/resource.proto", + "google/cloud/securitycenter_v1/proto/run_asset_discovery_response.proto", + "google/cloud/securitycenter_v1/proto/security_marks.proto", + "google/cloud/securitycenter_v1/proto/securitycenter_service.proto", + "google/cloud/securitycenter_v1/proto/source.proto", + "google/cloud/securitycenter_v1/py.typed", + "google/cloud/securitycenter_v1/services/__init__.py", + "google/cloud/securitycenter_v1/services/security_center/__init__.py", + "google/cloud/securitycenter_v1/services/security_center/async_client.py", + "google/cloud/securitycenter_v1/services/security_center/client.py", + "google/cloud/securitycenter_v1/services/security_center/pagers.py", + "google/cloud/securitycenter_v1/services/security_center/transports/__init__.py", + "google/cloud/securitycenter_v1/services/security_center/transports/base.py", + "google/cloud/securitycenter_v1/services/security_center/transports/grpc.py", + "google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py", + "google/cloud/securitycenter_v1/types/__init__.py", + "google/cloud/securitycenter_v1/types/asset.py", + "google/cloud/securitycenter_v1/types/finding.py", + "google/cloud/securitycenter_v1/types/notification_config.py", + "google/cloud/securitycenter_v1/types/notification_message.py", + "google/cloud/securitycenter_v1/types/organization_settings.py", + "google/cloud/securitycenter_v1/types/resource.py", + "google/cloud/securitycenter_v1/types/run_asset_discovery_response.py", + "google/cloud/securitycenter_v1/types/security_marks.py", + "google/cloud/securitycenter_v1/types/securitycenter_service.py", + "google/cloud/securitycenter_v1/types/source.py", + "google/cloud/securitycenter_v1beta1/__init__.py", + "google/cloud/securitycenter_v1beta1/proto/asset.proto", + "google/cloud/securitycenter_v1beta1/proto/finding.proto", + "google/cloud/securitycenter_v1beta1/proto/organization_settings.proto", + "google/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response.proto", + "google/cloud/securitycenter_v1beta1/proto/security_marks.proto", + "google/cloud/securitycenter_v1beta1/proto/securitycenter_service.proto", + "google/cloud/securitycenter_v1beta1/proto/source.proto", + "google/cloud/securitycenter_v1beta1/py.typed", + "google/cloud/securitycenter_v1beta1/services/__init__.py", + "google/cloud/securitycenter_v1beta1/services/security_center/__init__.py", + "google/cloud/securitycenter_v1beta1/services/security_center/async_client.py", + "google/cloud/securitycenter_v1beta1/services/security_center/client.py", + "google/cloud/securitycenter_v1beta1/services/security_center/pagers.py", + "google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py", + "google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py", + "google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py", + "google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py", + "google/cloud/securitycenter_v1beta1/types/__init__.py", + "google/cloud/securitycenter_v1beta1/types/asset.py", + "google/cloud/securitycenter_v1beta1/types/finding.py", + "google/cloud/securitycenter_v1beta1/types/organization_settings.py", + "google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py", + "google/cloud/securitycenter_v1beta1/types/security_marks.py", + "google/cloud/securitycenter_v1beta1/types/securitycenter_service.py", + "google/cloud/securitycenter_v1beta1/types/source.py", + "google/cloud/securitycenter_v1p1beta1/__init__.py", + "google/cloud/securitycenter_v1p1beta1/proto/asset.proto", + "google/cloud/securitycenter_v1p1beta1/proto/finding.proto", + "google/cloud/securitycenter_v1p1beta1/proto/notification_config.proto", + "google/cloud/securitycenter_v1p1beta1/proto/notification_message.proto", + "google/cloud/securitycenter_v1p1beta1/proto/organization_settings.proto", + "google/cloud/securitycenter_v1p1beta1/proto/resource.proto", + "google/cloud/securitycenter_v1p1beta1/proto/run_asset_discovery_response.proto", + "google/cloud/securitycenter_v1p1beta1/proto/security_marks.proto", + "google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service.proto", + "google/cloud/securitycenter_v1p1beta1/proto/source.proto", + "google/cloud/securitycenter_v1p1beta1/py.typed", + "google/cloud/securitycenter_v1p1beta1/services/__init__.py", + "google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py", + "google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py", + "google/cloud/securitycenter_v1p1beta1/services/security_center/client.py", + "google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py", + "google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py", + "google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py", + "google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py", + "google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py", + "google/cloud/securitycenter_v1p1beta1/types/__init__.py", + "google/cloud/securitycenter_v1p1beta1/types/asset.py", + "google/cloud/securitycenter_v1p1beta1/types/finding.py", + "google/cloud/securitycenter_v1p1beta1/types/notification_config.py", + "google/cloud/securitycenter_v1p1beta1/types/notification_message.py", + "google/cloud/securitycenter_v1p1beta1/types/organization_settings.py", + "google/cloud/securitycenter_v1p1beta1/types/resource.py", + "google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py", + "google/cloud/securitycenter_v1p1beta1/types/security_marks.py", + "google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py", + "google/cloud/securitycenter_v1p1beta1/types/source.py", + "mypy.ini", + "noxfile.py", + "renovate.json", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/noxfile.py", + "scripts/decrypt-secrets.sh", + "scripts/fixup_securitycenter_v1_keywords.py", + "scripts/fixup_securitycenter_v1beta1_keywords.py", + "scripts/fixup_securitycenter_v1p1beta1_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/securitycenter_v1/__init__.py", + "tests/unit/gapic/securitycenter_v1/test_security_center.py", + "tests/unit/gapic/securitycenter_v1beta1/__init__.py", + "tests/unit/gapic/securitycenter_v1beta1/test_security_center.py", + "tests/unit/gapic/securitycenter_v1p1beta1/__init__.py", + "tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py" ] } \ No newline at end of file From 008945b45fbce762e7e878e20b403d3f9ddfe602 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Thu, 1 Apr 2021 01:10:59 +0200 Subject: [PATCH 17/23] chore(deps): update dependency google-cloud-pubsub to v2.4.1 (#119) --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 7a1ca63f..52dd0a4e 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1,2 +1,2 @@ -google-cloud-pubsub==2.4.0 +google-cloud-pubsub==2.4.1 google-cloud-securitycenter==1.1.0 \ No newline at end of file From d22fadd6b343b0e41c9bd32d0a9271211a88152b Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Wed, 7 Apr 2021 08:32:04 -0700 Subject: [PATCH 18/23] chore: Add license headers for python config files (#121) This PR was generated using Autosynth. :rainbow: Synth log will be available here: https://source.cloud.google.com/results/invocations/fda2f952-70ab-4ba7-a453-5cf74dfb8429/targets - [ ] To automatically regenerate this PR, check this box. (May take up to 24 hours.) 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 32302e48..8912e9b5 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 fc36779f..63a2bbd0 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-securitycenter documentation build configuration file # diff --git a/synth.metadata b/synth.metadata index 96c39c4c..e96d9908 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,7 +4,7 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/python-securitycenter.git", - "sha": "15c28e88f5b52a6e4f608198446b0753bf48734e" + "sha": "008945b45fbce762e7e878e20b403d3f9ddfe602" } }, { @@ -19,14 +19,14 @@ "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "4501974ad08b5d693311457e2ea4ce845676e329" + "sha": "5b5bf6d519b2d658d9f2e483d9f6f3d0ba8ee6bc" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "4501974ad08b5d693311457e2ea4ce845676e329" + "sha": "5b5bf6d519b2d658d9f2e483d9f6f3d0ba8ee6bc" } } ], From 4a68acb6e000b7f6f940767aaf3c4565b9b42494 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Tue, 27 Apr 2021 12:14:05 -0400 Subject: [PATCH 19/23] chore: migrate to owlbot (#129) --- .github/.OwlBot.lock.yaml | 4 + .github/.OwlBot.yaml | 26 ++++ .github/header-checker-lint.yml | 2 +- .kokoro/release.sh | 4 +- .kokoro/release/common.cfg | 14 +- docs/_static/custom.css | 13 +- synth.py => owlbot.py | 31 ++-- renovate.json | 5 +- samples/snippets/noxfile.py | 10 +- synth.metadata | 249 -------------------------------- 10 files changed, 69 insertions(+), 289 deletions(-) create mode 100644 .github/.OwlBot.lock.yaml create mode 100644 .github/.OwlBot.yaml rename synth.py => owlbot.py (65%) delete mode 100644 synth.metadata diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml new file mode 100644 index 00000000..29084e8a --- /dev/null +++ b/.github/.OwlBot.lock.yaml @@ -0,0 +1,4 @@ +docker: + digest: sha256:cfc0e802701262c211703c468874d767f65dabe6a1a71d0e07bfc8a3d5175f32 + image: gcr.io/repo-automation-bots/owlbot-python:latest + diff --git a/.github/.OwlBot.yaml b/.github/.OwlBot.yaml new file mode 100644 index 00000000..c0c2d790 --- /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/securitycenter/(v.*)/.*-py/(.*) + dest: /owl-bot-staging/$1/$2 + +begin-after-commit-hash: dfccedc726d558444c665121fb5c1d08a5978e94 + diff --git a/.github/header-checker-lint.yml b/.github/header-checker-lint.yml index fc281c05..6fe78aa7 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/.kokoro/release.sh b/.kokoro/release.sh index 0c137b0f..5ed166d4 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-securitycenter 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 b71fba6a..c9c29a46 100644 --- a/.kokoro/release/common.cfg +++ b/.kokoro/release/common.cfg @@ -23,18 +23,8 @@ env_vars: { value: "github/python-securitycenter/.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/docs/_static/custom.css b/docs/_static/custom.css index bcd37bbd..b0a29546 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/synth.py b/owlbot.py similarity index 65% rename from synth.py rename to owlbot.py index 4c9f818d..aabd7289 100644 --- a/synth.py +++ b/owlbot.py @@ -17,32 +17,21 @@ from synthtool import gcp from synthtool.languages import python -gapic = gcp.GAPICBazel() common = gcp.CommonTemplates() -versions = ["v1p1beta1", "v1beta1", "v1"] -# ---------------------------------------------------------------------------- -# Generate securitycenter GAPIC layer -# ---------------------------------------------------------------------------- -for version in versions: - library = gapic.py_library( - service="securitycenter", - version=version, - bazel_target=f"//google/cloud/securitycenter/{version}:securitycenter-{version}-py", - include_protos=True, +default_version = "v1" + +for library in s.get_staging_dirs(default_version): + # fix bad indentation + s.replace(library / "google/**/*service.py", + r"(\s+)settings resource.\n" + r"\s+If empty all mutable fields will be updated.", + r"\g<1>settings resource.\n" + r"\g<1>If empty all mutable fields will be updated.", ) s.move(library, excludes=["README.rst", "docs/index.rst", "setup.py"]) - - -# fix bad indentation -s.replace( - "google/**/*service.py", - """(\s+)settings resource. -\s+If empty all mutable fields will be updated.""", - """\g<1>settings resource. -\g<1>If empty all mutable fields will be updated.""", -) +s.remove_staging_dirs() # ---------------------------------------------------------------------------- # Add templated files diff --git a/renovate.json b/renovate.json index f08bc22c..c0489556 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/samples/snippets/noxfile.py b/samples/snippets/noxfile.py index 97bf7da8..956cdf4f 100644 --- a/samples/snippets/noxfile.py +++ b/samples/snippets/noxfile.py @@ -172,10 +172,16 @@ def blacken(session: nox.sessions.Session) -> None: def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None: """Runs py.test for a particular project.""" if os.path.exists("requirements.txt"): - session.install("-r", "requirements.txt") + if os.path.exists("constraints.txt"): + session.install("-r", "requirements.txt", "-c", "constraints.txt") + else: + session.install("-r", "requirements.txt") if os.path.exists("requirements-test.txt"): - session.install("-r", "requirements-test.txt") + if os.path.exists("constraints-test.txt"): + session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt") + else: + session.install("-r", "requirements-test.txt") if INSTALL_LIBRARY_FROM_SOURCE: session.install("-e", _get_repo_root()) diff --git a/synth.metadata b/synth.metadata deleted file mode 100644 index e96d9908..00000000 --- a/synth.metadata +++ /dev/null @@ -1,249 +0,0 @@ -{ - "sources": [ - { - "git": { - "name": ".", - "remote": "https://github.com/googleapis/python-securitycenter.git", - "sha": "008945b45fbce762e7e878e20b403d3f9ddfe602" - } - }, - { - "git": { - "name": "googleapis", - "remote": "https://github.com/googleapis/googleapis.git", - "sha": "7c8d16188e68347aac0053a40ab1dc2056a44899", - "internalRef": "365829960" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "5b5bf6d519b2d658d9f2e483d9f6f3d0ba8ee6bc" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "5b5bf6d519b2d658d9f2e483d9f6f3d0ba8ee6bc" - } - } - ], - "destinations": [ - { - "client": { - "source": "googleapis", - "apiName": "securitycenter", - "apiVersion": "v1p1beta1", - "language": "python", - "generator": "bazel" - } - }, - { - "client": { - "source": "googleapis", - "apiName": "securitycenter", - "apiVersion": "v1beta1", - "language": "python", - "generator": "bazel" - } - }, - { - "client": { - "source": "googleapis", - "apiName": "securitycenter", - "apiVersion": "v1", - "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/securitycenter_v1/security_center.rst", - "docs/securitycenter_v1/services.rst", - "docs/securitycenter_v1/types.rst", - "docs/securitycenter_v1beta1/security_center.rst", - "docs/securitycenter_v1beta1/services.rst", - "docs/securitycenter_v1beta1/types.rst", - "docs/securitycenter_v1p1beta1/security_center.rst", - "docs/securitycenter_v1p1beta1/services.rst", - "docs/securitycenter_v1p1beta1/types.rst", - "google/cloud/securitycenter/__init__.py", - "google/cloud/securitycenter/py.typed", - "google/cloud/securitycenter_v1/__init__.py", - "google/cloud/securitycenter_v1/proto/asset.proto", - "google/cloud/securitycenter_v1/proto/finding.proto", - "google/cloud/securitycenter_v1/proto/notification_config.proto", - "google/cloud/securitycenter_v1/proto/notification_message.proto", - "google/cloud/securitycenter_v1/proto/organization_settings.proto", - "google/cloud/securitycenter_v1/proto/resource.proto", - "google/cloud/securitycenter_v1/proto/run_asset_discovery_response.proto", - "google/cloud/securitycenter_v1/proto/security_marks.proto", - "google/cloud/securitycenter_v1/proto/securitycenter_service.proto", - "google/cloud/securitycenter_v1/proto/source.proto", - "google/cloud/securitycenter_v1/py.typed", - "google/cloud/securitycenter_v1/services/__init__.py", - "google/cloud/securitycenter_v1/services/security_center/__init__.py", - "google/cloud/securitycenter_v1/services/security_center/async_client.py", - "google/cloud/securitycenter_v1/services/security_center/client.py", - "google/cloud/securitycenter_v1/services/security_center/pagers.py", - "google/cloud/securitycenter_v1/services/security_center/transports/__init__.py", - "google/cloud/securitycenter_v1/services/security_center/transports/base.py", - "google/cloud/securitycenter_v1/services/security_center/transports/grpc.py", - "google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py", - "google/cloud/securitycenter_v1/types/__init__.py", - "google/cloud/securitycenter_v1/types/asset.py", - "google/cloud/securitycenter_v1/types/finding.py", - "google/cloud/securitycenter_v1/types/notification_config.py", - "google/cloud/securitycenter_v1/types/notification_message.py", - "google/cloud/securitycenter_v1/types/organization_settings.py", - "google/cloud/securitycenter_v1/types/resource.py", - "google/cloud/securitycenter_v1/types/run_asset_discovery_response.py", - "google/cloud/securitycenter_v1/types/security_marks.py", - "google/cloud/securitycenter_v1/types/securitycenter_service.py", - "google/cloud/securitycenter_v1/types/source.py", - "google/cloud/securitycenter_v1beta1/__init__.py", - "google/cloud/securitycenter_v1beta1/proto/asset.proto", - "google/cloud/securitycenter_v1beta1/proto/finding.proto", - "google/cloud/securitycenter_v1beta1/proto/organization_settings.proto", - "google/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response.proto", - "google/cloud/securitycenter_v1beta1/proto/security_marks.proto", - "google/cloud/securitycenter_v1beta1/proto/securitycenter_service.proto", - "google/cloud/securitycenter_v1beta1/proto/source.proto", - "google/cloud/securitycenter_v1beta1/py.typed", - "google/cloud/securitycenter_v1beta1/services/__init__.py", - "google/cloud/securitycenter_v1beta1/services/security_center/__init__.py", - "google/cloud/securitycenter_v1beta1/services/security_center/async_client.py", - "google/cloud/securitycenter_v1beta1/services/security_center/client.py", - "google/cloud/securitycenter_v1beta1/services/security_center/pagers.py", - "google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py", - "google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py", - "google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py", - "google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py", - "google/cloud/securitycenter_v1beta1/types/__init__.py", - "google/cloud/securitycenter_v1beta1/types/asset.py", - "google/cloud/securitycenter_v1beta1/types/finding.py", - "google/cloud/securitycenter_v1beta1/types/organization_settings.py", - "google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py", - "google/cloud/securitycenter_v1beta1/types/security_marks.py", - "google/cloud/securitycenter_v1beta1/types/securitycenter_service.py", - "google/cloud/securitycenter_v1beta1/types/source.py", - "google/cloud/securitycenter_v1p1beta1/__init__.py", - "google/cloud/securitycenter_v1p1beta1/proto/asset.proto", - "google/cloud/securitycenter_v1p1beta1/proto/finding.proto", - "google/cloud/securitycenter_v1p1beta1/proto/notification_config.proto", - "google/cloud/securitycenter_v1p1beta1/proto/notification_message.proto", - "google/cloud/securitycenter_v1p1beta1/proto/organization_settings.proto", - "google/cloud/securitycenter_v1p1beta1/proto/resource.proto", - "google/cloud/securitycenter_v1p1beta1/proto/run_asset_discovery_response.proto", - "google/cloud/securitycenter_v1p1beta1/proto/security_marks.proto", - "google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service.proto", - "google/cloud/securitycenter_v1p1beta1/proto/source.proto", - "google/cloud/securitycenter_v1p1beta1/py.typed", - "google/cloud/securitycenter_v1p1beta1/services/__init__.py", - "google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py", - "google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py", - "google/cloud/securitycenter_v1p1beta1/services/security_center/client.py", - "google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py", - "google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py", - "google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py", - "google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py", - "google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py", - "google/cloud/securitycenter_v1p1beta1/types/__init__.py", - "google/cloud/securitycenter_v1p1beta1/types/asset.py", - "google/cloud/securitycenter_v1p1beta1/types/finding.py", - "google/cloud/securitycenter_v1p1beta1/types/notification_config.py", - "google/cloud/securitycenter_v1p1beta1/types/notification_message.py", - "google/cloud/securitycenter_v1p1beta1/types/organization_settings.py", - "google/cloud/securitycenter_v1p1beta1/types/resource.py", - "google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py", - "google/cloud/securitycenter_v1p1beta1/types/security_marks.py", - "google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py", - "google/cloud/securitycenter_v1p1beta1/types/source.py", - "mypy.ini", - "noxfile.py", - "renovate.json", - "samples/AUTHORING_GUIDE.md", - "samples/CONTRIBUTING.md", - "samples/snippets/noxfile.py", - "scripts/decrypt-secrets.sh", - "scripts/fixup_securitycenter_v1_keywords.py", - "scripts/fixup_securitycenter_v1beta1_keywords.py", - "scripts/fixup_securitycenter_v1p1beta1_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/securitycenter_v1/__init__.py", - "tests/unit/gapic/securitycenter_v1/test_security_center.py", - "tests/unit/gapic/securitycenter_v1beta1/__init__.py", - "tests/unit/gapic/securitycenter_v1beta1/test_security_center.py", - "tests/unit/gapic/securitycenter_v1p1beta1/__init__.py", - "tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py" - ] -} \ No newline at end of file From 5be372b5e0dfb882d999014d3301e992247bf387 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 10 May 2021 15:12:02 +0000 Subject: [PATCH 20/23] chore: new owl bot post processor docker image (#136) gcr.io/repo-automation-bots/owlbot-python:latest@sha256:1f18bfeb1629a6fd4c9301d4174c672cae5ac7ba611a5c8d204d6010e61f6f0d --- .github/.OwlBot.lock.yaml | 5 ++--- .pre-commit-config.yaml | 2 +- CONTRIBUTING.rst | 16 +--------------- noxfile.py | 14 ++------------ 4 files changed, 6 insertions(+), 31 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 29084e8a..bab398e1 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,4 +1,3 @@ docker: - digest: sha256:cfc0e802701262c211703c468874d767f65dabe6a1a71d0e07bfc8a3d5175f32 - image: gcr.io/repo-automation-bots/owlbot-python:latest - + image: gcr.io/repo-automation-bots/owlbot-python:latest + digest: sha256:1f18bfeb1629a6fd4c9301d4174c672cae5ac7ba611a5c8d204d6010e61f6f0d diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8912e9b5..1bbd7878 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 d5b4b7f3..4ef23f50 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/noxfile.py b/noxfile.py index 4d37cd3a..70417e8c 100644 --- a/noxfile.py +++ b/noxfile.py @@ -62,16 +62,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, @@ -131,9 +124,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") From 1fd53d1b673a265e59878ec347e3b7b3e3e19f4a Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 12 May 2021 12:26:05 -0400 Subject: [PATCH 21/23] chore: add library type to .repo-metadata.json (#135) --- .repo-metadata.json | 1 + 1 file changed, 1 insertion(+) diff --git a/.repo-metadata.json b/.repo-metadata.json index e09bbff0..45315ed4 100644 --- a/.repo-metadata.json +++ b/.repo-metadata.json @@ -6,6 +6,7 @@ "issue_tracker": "https://issuetracker.google.com/savedsearches/559748", "release_level": "alpha", "language": "python", + "library_type": "GAPIC_AUTO", "repo": "googleapis/python-securitycenter", "distribution_name": "google-cloud-securitycenter", "api_id": "securitycenter.googleapis.com", From 16a33f4c994b80d9c50537f2e1299282d525171e Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 19 May 2021 16:50:46 -0600 Subject: [PATCH 22/23] chore: upgrade gapic-generator-python to 0.46.3 (#143) feat: add canonical_name and folder fields Assets and findings may be created in organizations, folders or projects, however in the current API version the name field for resources will always be prefixed by "organizations/...", for historical reasons. The "canonical_name" field shows the actual location of the resource, and in requests either the name or "canonical name" can be used for the "name" in the request. The "folder" field contains the folders in the resource's ancestry. PiperOrigin-RevId: 372965035 Source-Link: googleapis/googleapis@0a992df feat: support self-signed JWT flow for service accounts fix: add async client to %name_%version/init.py chore: add autogenerated snippets chore: remove auth, policy, and options from the reserved names list chore: enable GAPIC metadata generation chore: sort subpackages in %namespace/%name/init.py --- docs/securitycenter_v1/security_center.rst | 1 - .../security_center.rst | 1 - .../security_center.rst | 1 - google/cloud/securitycenter/__init__.py | 30 +- google/cloud/securitycenter_v1/__init__.py | 9 +- .../securitycenter_v1/gapic_metadata.json | 253 +++ .../securitycenter_v1/services/__init__.py | 1 - .../services/security_center/__init__.py | 2 - .../services/security_center/async_client.py | 161 +- .../services/security_center/client.py | 207 +-- .../services/security_center/pagers.py | 14 +- .../security_center/transports/__init__.py | 2 - .../security_center/transports/base.py | 265 ++- .../security_center/transports/grpc.py | 61 +- .../transports/grpc_asyncio.py | 64 +- .../cloud/securitycenter_v1/types/__init__.py | 4 +- google/cloud/securitycenter_v1/types/asset.py | 66 +- .../cloud/securitycenter_v1/types/finding.py | 48 +- .../cloud/securitycenter_v1/types/folder.py | 41 + .../types/notification_config.py | 16 +- .../types/notification_message.py | 8 +- .../types/organization_settings.py | 17 +- .../cloud/securitycenter_v1/types/resource.py | 26 +- .../types/run_asset_discovery_response.py | 9 +- .../securitycenter_v1/types/security_marks.py | 16 +- .../types/securitycenter_service.py | 309 ++-- .../cloud/securitycenter_v1/types/source.py | 18 +- .../cloud/securitycenter_v1beta1/__init__.py | 7 +- .../gapic_metadata.json | 203 +++ .../services/__init__.py | 1 - .../services/security_center/__init__.py | 2 - .../services/security_center/async_client.py | 125 +- .../services/security_center/client.py | 164 +- .../services/security_center/pagers.py | 12 +- .../security_center/transports/__init__.py | 2 - .../security_center/transports/base.py | 229 ++- .../security_center/transports/grpc.py | 51 +- .../transports/grpc_asyncio.py | 53 +- .../securitycenter_v1beta1/types/__init__.py | 2 - .../securitycenter_v1beta1/types/asset.py | 36 +- .../securitycenter_v1beta1/types/finding.py | 34 +- .../types/organization_settings.py | 12 +- .../types/run_asset_discovery_response.py | 9 +- .../types/security_marks.py | 7 +- .../types/securitycenter_service.py | 206 +-- .../securitycenter_v1beta1/types/source.py | 10 +- .../securitycenter_v1p1beta1/__init__.py | 9 +- .../gapic_metadata.json | 253 +++ .../services/__init__.py | 1 - .../services/security_center/__init__.py | 2 - .../services/security_center/async_client.py | 181 +- .../services/security_center/client.py | 229 +-- .../services/security_center/pagers.py | 14 +- .../security_center/transports/__init__.py | 2 - .../security_center/transports/base.py | 265 ++- .../security_center/transports/grpc.py | 62 +- .../transports/grpc_asyncio.py | 65 +- .../types/__init__.py | 4 +- .../securitycenter_v1p1beta1/types/asset.py | 66 +- .../securitycenter_v1p1beta1/types/finding.py | 48 +- .../securitycenter_v1p1beta1/types/folder.py | 41 + .../types/notification_config.py | 17 +- .../types/notification_message.py | 8 +- .../types/organization_settings.py | 17 +- .../types/resource.py | 26 +- .../types/run_asset_discovery_response.py | 9 +- .../types/security_marks.py | 16 +- .../types/securitycenter_service.py | 309 ++-- .../securitycenter_v1p1beta1/types/source.py | 18 +- owlbot.py | 8 + scripts/fixup_securitycenter_v1_keywords.py | 51 +- .../fixup_securitycenter_v1beta1_keywords.py | 41 +- ...fixup_securitycenter_v1p1beta1_keywords.py | 51 +- setup.py | 1 + testing/constraints-3.6.txt | 2 + tests/__init__.py | 15 + tests/unit/__init__.py | 15 + tests/unit/gapic/__init__.py | 15 + .../unit/gapic/securitycenter_v1/__init__.py | 1 - .../securitycenter_v1/test_security_center.py | 1499 ++++++++-------- .../gapic/securitycenter_v1beta1/__init__.py | 1 - .../test_security_center.py | 1217 ++++++------- .../securitycenter_v1p1beta1/__init__.py | 1 - .../test_security_center.py | 1579 ++++++++--------- 84 files changed, 4774 insertions(+), 4200 deletions(-) create mode 100644 google/cloud/securitycenter_v1/gapic_metadata.json create mode 100644 google/cloud/securitycenter_v1/types/folder.py create mode 100644 google/cloud/securitycenter_v1beta1/gapic_metadata.json create mode 100644 google/cloud/securitycenter_v1p1beta1/gapic_metadata.json create mode 100644 google/cloud/securitycenter_v1p1beta1/types/folder.py 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/securitycenter_v1/security_center.rst b/docs/securitycenter_v1/security_center.rst index 0d7d0e97..bc6175c8 100644 --- a/docs/securitycenter_v1/security_center.rst +++ b/docs/securitycenter_v1/security_center.rst @@ -5,7 +5,6 @@ SecurityCenter :members: :inherited-members: - .. automodule:: google.cloud.securitycenter_v1.services.security_center.pagers :members: :inherited-members: diff --git a/docs/securitycenter_v1beta1/security_center.rst b/docs/securitycenter_v1beta1/security_center.rst index f7b00994..304849ec 100644 --- a/docs/securitycenter_v1beta1/security_center.rst +++ b/docs/securitycenter_v1beta1/security_center.rst @@ -5,7 +5,6 @@ SecurityCenter :members: :inherited-members: - .. automodule:: google.cloud.securitycenter_v1beta1.services.security_center.pagers :members: :inherited-members: diff --git a/docs/securitycenter_v1p1beta1/security_center.rst b/docs/securitycenter_v1p1beta1/security_center.rst index afda133c..adab7f4a 100644 --- a/docs/securitycenter_v1p1beta1/security_center.rst +++ b/docs/securitycenter_v1p1beta1/security_center.rst @@ -5,7 +5,6 @@ SecurityCenter :members: :inherited-members: - .. automodule:: google.cloud.securitycenter_v1p1beta1.services.security_center.pagers :members: :inherited-members: diff --git a/google/cloud/securitycenter/__init__.py b/google/cloud/securitycenter/__init__.py index 986b34a6..b45dff2c 100644 --- a/google/cloud/securitycenter/__init__.py +++ b/google/cloud/securitycenter/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,14 +14,16 @@ # limitations under the License. # -from google.cloud.securitycenter_v1.services.security_center.async_client import ( - SecurityCenterAsyncClient, -) from google.cloud.securitycenter_v1.services.security_center.client import ( SecurityCenterClient, ) +from google.cloud.securitycenter_v1.services.security_center.async_client import ( + SecurityCenterAsyncClient, +) + from google.cloud.securitycenter_v1.types.asset import Asset from google.cloud.securitycenter_v1.types.finding import Finding +from google.cloud.securitycenter_v1.types.folder import Folder from google.cloud.securitycenter_v1.types.notification_config import NotificationConfig from google.cloud.securitycenter_v1.types.notification_message import ( NotificationMessage, @@ -115,12 +116,21 @@ from google.cloud.securitycenter_v1.types.source import Source __all__ = ( + "SecurityCenterClient", + "SecurityCenterAsyncClient", "Asset", + "Finding", + "Folder", + "NotificationConfig", + "NotificationMessage", + "OrganizationSettings", + "Resource", + "RunAssetDiscoveryResponse", + "SecurityMarks", "CreateFindingRequest", "CreateNotificationConfigRequest", "CreateSourceRequest", "DeleteNotificationConfigRequest", - "Finding", "GetNotificationConfigRequest", "GetOrganizationSettingsRequest", "GetSourceRequest", @@ -137,20 +147,12 @@ "ListNotificationConfigsResponse", "ListSourcesRequest", "ListSourcesResponse", - "NotificationConfig", - "NotificationMessage", - "OrganizationSettings", - "Resource", "RunAssetDiscoveryRequest", - "RunAssetDiscoveryResponse", - "SecurityCenterAsyncClient", - "SecurityCenterClient", - "SecurityMarks", "SetFindingStateRequest", - "Source", "UpdateFindingRequest", "UpdateNotificationConfigRequest", "UpdateOrganizationSettingsRequest", "UpdateSecurityMarksRequest", "UpdateSourceRequest", + "Source", ) diff --git a/google/cloud/securitycenter_v1/__init__.py b/google/cloud/securitycenter_v1/__init__.py index 27c3ed04..9c8fa408 100644 --- a/google/cloud/securitycenter_v1/__init__.py +++ b/google/cloud/securitycenter_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,8 +15,11 @@ # from .services.security_center import SecurityCenterClient +from .services.security_center import SecurityCenterAsyncClient + from .types.asset import Asset from .types.finding import Finding +from .types.folder import Folder from .types.notification_config import NotificationConfig from .types.notification_message import NotificationMessage from .types.organization_settings import OrganizationSettings @@ -53,14 +55,15 @@ from .types.securitycenter_service import UpdateSourceRequest from .types.source import Source - __all__ = ( + "SecurityCenterAsyncClient", "Asset", "CreateFindingRequest", "CreateNotificationConfigRequest", "CreateSourceRequest", "DeleteNotificationConfigRequest", "Finding", + "Folder", "GetNotificationConfigRequest", "GetOrganizationSettingsRequest", "GetSourceRequest", @@ -83,6 +86,7 @@ "Resource", "RunAssetDiscoveryRequest", "RunAssetDiscoveryResponse", + "SecurityCenterClient", "SecurityMarks", "SetFindingStateRequest", "Source", @@ -91,5 +95,4 @@ "UpdateOrganizationSettingsRequest", "UpdateSecurityMarksRequest", "UpdateSourceRequest", - "SecurityCenterClient", ) diff --git a/google/cloud/securitycenter_v1/gapic_metadata.json b/google/cloud/securitycenter_v1/gapic_metadata.json new file mode 100644 index 00000000..e3afaeec --- /dev/null +++ b/google/cloud/securitycenter_v1/gapic_metadata.json @@ -0,0 +1,253 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.securitycenter_v1", + "protoPackage": "google.cloud.securitycenter.v1", + "schema": "1.0", + "services": { + "SecurityCenter": { + "clients": { + "grpc": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecurityCenterAsyncClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/securitycenter_v1/services/__init__.py b/google/cloud/securitycenter_v1/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/securitycenter_v1/services/__init__.py +++ b/google/cloud/securitycenter_v1/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/securitycenter_v1/services/security_center/__init__.py b/google/cloud/securitycenter_v1/services/security_center/__init__.py index 6250349b..b56953c3 100644 --- a/google/cloud/securitycenter_v1/services/security_center/__init__.py +++ b/google/cloud/securitycenter_v1/services/security_center/__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 SecurityCenterClient from .async_client import SecurityCenterAsyncClient diff --git a/google/cloud/securitycenter_v1/services/security_center/async_client.py b/google/cloud/securitycenter_v1/services/security_center/async_client.py index 644bdf4c..1fd7472a 100644 --- a/google/cloud/securitycenter_v1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1/services/security_center/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,10 +20,10 @@ 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.api_core import operation # type: ignore @@ -47,12 +45,11 @@ from google.cloud.securitycenter_v1.types import securitycenter_service from google.cloud.securitycenter_v1.types import source from google.cloud.securitycenter_v1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport from .client import SecurityCenterClient @@ -90,31 +87,26 @@ class SecurityCenterAsyncClient: parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) topic_path = staticmethod(SecurityCenterClient.topic_path) parse_topic_path = staticmethod(SecurityCenterClient.parse_topic_path) - common_billing_account_path = staticmethod( SecurityCenterClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( SecurityCenterClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) parse_common_folder_path = staticmethod( SecurityCenterClient.parse_common_folder_path ) - common_organization_path = staticmethod( SecurityCenterClient.common_organization_path ) parse_common_organization_path = staticmethod( SecurityCenterClient.parse_common_organization_path ) - common_project_path = staticmethod(SecurityCenterClient.common_project_path) parse_common_project_path = staticmethod( SecurityCenterClient.parse_common_project_path ) - common_location_path = staticmethod(SecurityCenterClient.common_location_path) parse_common_location_path = staticmethod( SecurityCenterClient.parse_common_location_path @@ -122,7 +114,8 @@ class SecurityCenterAsyncClient: @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. @@ -137,7 +130,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 @@ -154,7 +147,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SecurityCenterTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: SecurityCenterTransport: The transport used by the client instance. @@ -168,12 +161,12 @@ def transport(self) -> SecurityCenterTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, SecurityCenterTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the security center client. + """Instantiates the security center client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -205,7 +198,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SecurityCenterClient( credentials=credentials, transport=transport, @@ -244,7 +236,6 @@ async def create_source( This corresponds to the ``source`` 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. @@ -275,7 +266,6 @@ async def create_source( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if source is not None: @@ -345,7 +335,6 @@ async def create_finding( This corresponds to the ``finding`` 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. @@ -379,7 +368,6 @@ async def create_finding( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if finding_id is not None: @@ -451,7 +439,6 @@ async def create_notification_config( This corresponds to the ``notification_config`` 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. @@ -482,7 +469,6 @@ async def create_notification_config( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if config_id is not None: @@ -533,7 +519,6 @@ async def delete_notification_config( 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. @@ -554,7 +539,6 @@ async def delete_notification_config( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -579,13 +563,13 @@ async def delete_notification_config( async def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Gets the access control policy on the specified Source. @@ -602,7 +586,6 @@ async def get_iam_policy( This corresponds to the ``resource`` 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. @@ -681,10 +664,9 @@ async def get_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) - + request = iam_policy_pb2.GetIamPolicyRequest(**request) elif not request: - request = iam_policy.GetIamPolicyRequest(resource=resource,) + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -695,7 +677,8 @@ async def get_iam_policy( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -738,7 +721,6 @@ async def get_notification_config( 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. @@ -769,7 +751,6 @@ async def get_notification_config( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -782,7 +763,8 @@ async def get_notification_config( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -825,7 +807,6 @@ async def get_organization_settings( 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. @@ -853,7 +834,6 @@ async def get_organization_settings( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -866,7 +846,8 @@ async def get_organization_settings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -909,7 +890,6 @@ async def get_source( 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. @@ -940,7 +920,6 @@ async def get_source( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -953,7 +932,8 @@ async def get_source( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -988,7 +968,6 @@ async def group_assets( request (:class:`google.cloud.securitycenter_v1.types.GroupAssetsRequest`): The request object. Request message for grouping by assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1005,7 +984,6 @@ async def group_assets( """ # Create or coerce a protobuf request object. - request = securitycenter_service.GroupAssetsRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -1017,7 +995,8 @@ async def group_assets( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -1057,7 +1036,9 @@ async def group_findings( their specified properties. To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings Args: request (:class:`google.cloud.securitycenter_v1.types.GroupFindingsRequest`): @@ -1065,10 +1046,13 @@ async def group_findings( findings. parent (:class:`str`): Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". - To groupBy across all sources provide a source_id of - ``-``. For example: - organizations/{organization_id}/sources/- + "organizations/[organization_id]/sources/[source_id]", + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]. To groupBy + across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/-, or + projects/{project_id}/sources/- This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1095,7 +1079,6 @@ async def group_findings( This corresponds to the ``group_by`` 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. @@ -1125,7 +1108,6 @@ async def group_findings( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if group_by is not None: @@ -1140,7 +1122,8 @@ async def group_findings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -1179,7 +1162,6 @@ async def list_assets( Args: request (:class:`google.cloud.securitycenter_v1.types.ListAssetsRequest`): The request object. Request message for listing assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1195,7 +1177,6 @@ async def list_assets( """ # Create or coerce a protobuf request object. - request = securitycenter_service.ListAssetsRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -1207,7 +1188,8 @@ async def list_assets( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -1250,7 +1232,6 @@ async def list_findings( request (:class:`google.cloud.securitycenter_v1.types.ListFindingsRequest`): The request object. Request message for listing findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1267,7 +1248,6 @@ async def list_findings( """ # Create or coerce a protobuf request object. - request = securitycenter_service.ListFindingsRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -1279,7 +1259,8 @@ async def list_findings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -1328,7 +1309,6 @@ async def list_notification_configs( 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. @@ -1358,7 +1338,6 @@ async def list_notification_configs( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1371,7 +1350,8 @@ async def list_notification_configs( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -1414,12 +1394,12 @@ async def list_sources( parent (:class:`str`): Required. Resource name of the parent of sources to list. Its format should be - "organizations/[organization_id]". + "organizations/[organization_id], folders/[folder_id], + or projects/[project_id]". 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. @@ -1448,7 +1428,6 @@ async def list_sources( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1461,7 +1440,8 @@ async def list_sources( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -1515,7 +1495,6 @@ async def run_asset_discovery( 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. @@ -1545,7 +1524,6 @@ async def run_asset_discovery( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1571,7 +1549,7 @@ async def run_asset_discovery( response, self._client._transport.operations_client, run_asset_discovery_response.RunAssetDiscoveryResponse, - metadata_type=empty.Empty, + metadata_type=empty_pb2.Empty, ) # Done; return the response. @@ -1583,7 +1561,7 @@ async def set_finding_state( *, name: str = None, state: finding.Finding.State = None, - start_time: timestamp.Timestamp = None, + start_time: timestamp_pb2.Timestamp = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -1618,7 +1596,6 @@ async def set_finding_state( This corresponds to the ``start_time`` 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. @@ -1652,7 +1629,6 @@ async def set_finding_state( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if state is not None: @@ -1682,13 +1658,13 @@ async def set_finding_state( async def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the access control policy on the specified Source. @@ -1705,7 +1681,6 @@ async def set_iam_policy( This corresponds to the ``resource`` 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. @@ -1784,10 +1759,9 @@ async def set_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) - + request = iam_policy_pb2.SetIamPolicyRequest(**request) elif not request: - request = iam_policy.SetIamPolicyRequest(resource=resource,) + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1811,14 +1785,14 @@ async def set_iam_policy( async def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, resource: str = None, permissions: Sequence[str] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Returns the permissions that a caller has on the specified source. @@ -1844,7 +1818,6 @@ async def test_iam_permissions( This corresponds to the ``permissions`` 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. @@ -1868,10 +1841,9 @@ async def test_iam_permissions( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) - + request = iam_policy_pb2.TestIamPermissionsRequest(**request) elif not request: - request = iam_policy.TestIamPermissionsRequest( + request = iam_policy_pb2.TestIamPermissionsRequest( resource=resource, permissions=permissions, ) @@ -1884,7 +1856,8 @@ async def test_iam_permissions( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -1932,7 +1905,6 @@ async def update_finding( This corresponds to the ``finding`` 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. @@ -1966,7 +1938,6 @@ async def update_finding( # If we have keyword arguments corresponding to fields on the # request, apply these. - if finding is not None: request.finding = finding @@ -1997,7 +1968,7 @@ async def update_notification_config( request: securitycenter_service.UpdateNotificationConfigRequest = None, *, notification_config: gcs_notification_config.NotificationConfig = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -2025,7 +1996,6 @@ async def update_notification_config( This corresponds to the ``update_mask`` 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. @@ -2056,7 +2026,6 @@ async def update_notification_config( # If we have keyword arguments corresponding to fields on the # request, apply these. - if notification_config is not None: request.notification_config = notification_config if update_mask is not None: @@ -2106,7 +2075,6 @@ async def update_organization_settings( This corresponds to the ``organization_settings`` 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. @@ -2134,7 +2102,6 @@ async def update_organization_settings( # If we have keyword arguments corresponding to fields on the # request, apply these. - if organization_settings is not None: request.organization_settings = organization_settings @@ -2182,7 +2149,6 @@ async def update_source( This corresponds to the ``source`` 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. @@ -2213,7 +2179,6 @@ async def update_source( # If we have keyword arguments corresponding to fields on the # request, apply these. - if source is not None: request.source = source @@ -2261,7 +2226,6 @@ async def update_security_marks( This corresponds to the ``security_marks`` 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. @@ -2294,7 +2258,6 @@ async def update_security_marks( # If we have keyword arguments corresponding to fields on the # request, apply these. - if security_marks is not None: request.security_marks = security_marks diff --git a/google/cloud/securitycenter_v1/services/security_center/client.py b/google/cloud/securitycenter_v1/services/security_center/client.py index 5e85db59..3288415e 100644 --- a/google/cloud/securitycenter_v1/services/security_center/client.py +++ b/google/cloud/securitycenter_v1/services/security_center/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 @@ -51,12 +49,11 @@ from google.cloud.securitycenter_v1.types import securitycenter_service from google.cloud.securitycenter_v1.types import source from google.cloud.securitycenter_v1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SecurityCenterGrpcTransport from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport @@ -77,7 +74,7 @@ class SecurityCenterClientMeta(type): _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[SecurityCenterTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -100,7 +97,8 @@ class SecurityCenterClient(metaclass=SecurityCenterClientMeta): @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: @@ -134,7 +132,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. @@ -151,7 +150,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 @@ -170,23 +169,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SecurityCenterTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SecurityCenterTransport: The transport used by the client instance. + SecurityCenterTransport: The transport used by the client + instance. """ return self._transport @staticmethod def asset_path(organization: str, asset: str,) -> str: - """Return a fully-qualified asset string.""" + """Returns a fully-qualified asset string.""" return "organizations/{organization}/assets/{asset}".format( organization=organization, asset=asset, ) @staticmethod def parse_asset_path(path: str) -> Dict[str, str]: - """Parse a asset path into its component segments.""" + """Parses a asset path into its component segments.""" m = re.match( r"^organizations/(?P.+?)/assets/(?P.+?)$", path ) @@ -194,14 +194,14 @@ def parse_asset_path(path: str) -> Dict[str, str]: @staticmethod def finding_path(organization: str, source: str, finding: str,) -> str: - """Return a fully-qualified finding string.""" + """Returns a fully-qualified finding string.""" return "organizations/{organization}/sources/{source}/findings/{finding}".format( organization=organization, source=source, finding=finding, ) @staticmethod def parse_finding_path(path: str) -> Dict[str, str]: - """Parse a finding path into its component segments.""" + """Parses a finding path into its component segments.""" m = re.match( r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path, @@ -210,14 +210,14 @@ def parse_finding_path(path: str) -> Dict[str, str]: @staticmethod def notification_config_path(organization: str, notification_config: str,) -> str: - """Return a fully-qualified notification_config string.""" + """Returns a fully-qualified notification_config string.""" return "organizations/{organization}/notificationConfigs/{notification_config}".format( organization=organization, notification_config=notification_config, ) @staticmethod def parse_notification_config_path(path: str) -> Dict[str, str]: - """Parse a notification_config path into its component segments.""" + """Parses a notification_config path into its component segments.""" m = re.match( r"^organizations/(?P.+?)/notificationConfigs/(?P.+?)$", path, @@ -226,14 +226,14 @@ def parse_notification_config_path(path: str) -> Dict[str, str]: @staticmethod def organization_settings_path(organization: str,) -> str: - """Return a fully-qualified organization_settings string.""" + """Returns a fully-qualified organization_settings string.""" return "organizations/{organization}/organizationSettings".format( organization=organization, ) @staticmethod def parse_organization_settings_path(path: str) -> Dict[str, str]: - """Parse a organization_settings path into its component segments.""" + """Parses a organization_settings path into its component segments.""" m = re.match( r"^organizations/(?P.+?)/organizationSettings$", path ) @@ -241,14 +241,14 @@ def parse_organization_settings_path(path: str) -> Dict[str, str]: @staticmethod def security_marks_path(organization: str, asset: str,) -> str: - """Return a fully-qualified security_marks string.""" + """Returns a fully-qualified security_marks string.""" return "organizations/{organization}/assets/{asset}/securityMarks".format( organization=organization, asset=asset, ) @staticmethod def parse_security_marks_path(path: str) -> Dict[str, str]: - """Parse a security_marks path into its component segments.""" + """Parses a security_marks path into its component segments.""" m = re.match( r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path, @@ -257,14 +257,14 @@ def parse_security_marks_path(path: str) -> Dict[str, str]: @staticmethod def source_path(organization: str, source: str,) -> str: - """Return a fully-qualified source string.""" + """Returns a fully-qualified source string.""" return "organizations/{organization}/sources/{source}".format( organization=organization, source=source, ) @staticmethod def parse_source_path(path: str) -> Dict[str, str]: - """Parse a source path into its component segments.""" + """Parses a source path into its component segments.""" m = re.match( r"^organizations/(?P.+?)/sources/(?P.+?)$", path ) @@ -272,18 +272,18 @@ def parse_source_path(path: str) -> Dict[str, str]: @staticmethod def topic_path(project: str, topic: str,) -> str: - """Return a fully-qualified topic string.""" + """Returns a fully-qualified topic string.""" return "projects/{project}/topics/{topic}".format(project=project, topic=topic,) @staticmethod def parse_topic_path(path: str) -> Dict[str, str]: - """Parse a topic path into its component segments.""" + """Parses a topic path into its component segments.""" m = re.match(r"^projects/(?P.+?)/topics/(?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, ) @@ -296,7 +296,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 @@ -307,7 +307,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 @@ -318,7 +318,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 @@ -329,7 +329,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, ) @@ -343,12 +343,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, SecurityCenterTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the security center client. + """Instantiates the security center client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -403,9 +403,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: @@ -417,12 +418,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. @@ -437,8 +440,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: @@ -484,7 +487,6 @@ def create_source( This corresponds to the ``source`` 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. @@ -517,10 +519,8 @@ def create_source( # there are no flattened fields. if not isinstance(request, securitycenter_service.CreateSourceRequest): request = securitycenter_service.CreateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if source is not None: @@ -586,7 +586,6 @@ def create_finding( This corresponds to the ``finding`` 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. @@ -622,10 +621,8 @@ def create_finding( # there are no flattened fields. if not isinstance(request, securitycenter_service.CreateFindingRequest): request = securitycenter_service.CreateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if finding_id is not None: @@ -693,7 +690,6 @@ def create_notification_config( This corresponds to the ``notification_config`` 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. @@ -728,10 +724,8 @@ def create_notification_config( request, securitycenter_service.CreateNotificationConfigRequest ): request = securitycenter_service.CreateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if config_id is not None: @@ -780,7 +774,6 @@ def delete_notification_config( 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. @@ -805,10 +798,8 @@ def delete_notification_config( request, securitycenter_service.DeleteNotificationConfigRequest ): request = securitycenter_service.DeleteNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -831,13 +822,13 @@ def delete_notification_config( def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Gets the access control policy on the specified Source. @@ -854,7 +845,6 @@ def get_iam_policy( This corresponds to the ``resource`` 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. @@ -933,11 +923,10 @@ def get_iam_policy( if isinstance(request, dict): # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. - request = iam_policy.GetIamPolicyRequest(**request) + request = iam_policy_pb2.GetIamPolicyRequest(**request) elif not request: # Null request, just make one. - request = iam_policy.GetIamPolicyRequest() - + request = iam_policy_pb2.GetIamPolicyRequest() if resource is not None: request.resource = resource @@ -980,7 +969,6 @@ def get_notification_config( 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. @@ -1013,10 +1001,8 @@ def get_notification_config( # there are no flattened fields. if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): request = securitycenter_service.GetNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1059,7 +1045,6 @@ def get_organization_settings( 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. @@ -1091,10 +1076,8 @@ def get_organization_settings( request, securitycenter_service.GetOrganizationSettingsRequest ): request = securitycenter_service.GetOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1139,7 +1122,6 @@ def get_source( 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. @@ -1172,10 +1154,8 @@ def get_source( # there are no flattened fields. if not isinstance(request, securitycenter_service.GetSourceRequest): request = securitycenter_service.GetSourceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1210,7 +1190,6 @@ def group_assets( request (google.cloud.securitycenter_v1.types.GroupAssetsRequest): The request object. Request message for grouping by assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1227,7 +1206,6 @@ def group_assets( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a securitycenter_service.GroupAssetsRequest. # There's no risk of modifying the input as we've already verified @@ -1271,7 +1249,9 @@ def group_findings( their specified properties. To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings Args: request (google.cloud.securitycenter_v1.types.GroupFindingsRequest): @@ -1279,10 +1259,13 @@ def group_findings( findings. parent (str): Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". - To groupBy across all sources provide a source_id of - ``-``. For example: - organizations/{organization_id}/sources/- + "organizations/[organization_id]/sources/[source_id]", + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]. To groupBy + across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/-, or + projects/{project_id}/sources/- This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1309,7 +1292,6 @@ def group_findings( This corresponds to the ``group_by`` 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. @@ -1341,10 +1323,8 @@ def group_findings( # there are no flattened fields. if not isinstance(request, securitycenter_service.GroupFindingsRequest): request = securitycenter_service.GroupFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if group_by is not None: @@ -1385,7 +1365,6 @@ def list_assets( Args: request (google.cloud.securitycenter_v1.types.ListAssetsRequest): The request object. Request message for listing assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1401,7 +1380,6 @@ def list_assets( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a securitycenter_service.ListAssetsRequest. # There's no risk of modifying the input as we've already verified @@ -1448,7 +1426,6 @@ def list_findings( request (google.cloud.securitycenter_v1.types.ListFindingsRequest): The request object. Request message for listing findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1465,7 +1442,6 @@ def list_findings( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a securitycenter_service.ListFindingsRequest. # There's no risk of modifying the input as we've already verified @@ -1518,7 +1494,6 @@ def list_notification_configs( 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. @@ -1552,10 +1527,8 @@ def list_notification_configs( request, securitycenter_service.ListNotificationConfigsRequest ): request = securitycenter_service.ListNotificationConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1600,12 +1573,12 @@ def list_sources( parent (str): Required. Resource name of the parent of sources to list. Its format should be - "organizations/[organization_id]". + "organizations/[organization_id], folders/[folder_id], + or projects/[project_id]". 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. @@ -1636,10 +1609,8 @@ def list_sources( # there are no flattened fields. if not isinstance(request, securitycenter_service.ListSourcesRequest): request = securitycenter_service.ListSourcesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1693,7 +1664,6 @@ def run_asset_discovery( 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. @@ -1725,10 +1695,8 @@ def run_asset_discovery( # there are no flattened fields. if not isinstance(request, securitycenter_service.RunAssetDiscoveryRequest): request = securitycenter_service.RunAssetDiscoveryRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1750,7 +1718,7 @@ def run_asset_discovery( response, self._transport.operations_client, run_asset_discovery_response.RunAssetDiscoveryResponse, - metadata_type=empty.Empty, + metadata_type=empty_pb2.Empty, ) # Done; return the response. @@ -1762,7 +1730,7 @@ def set_finding_state( *, name: str = None, state: finding.Finding.State = None, - start_time: timestamp.Timestamp = None, + start_time: timestamp_pb2.Timestamp = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -1797,7 +1765,6 @@ def set_finding_state( This corresponds to the ``start_time`` 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. @@ -1833,10 +1800,8 @@ def set_finding_state( # there are no flattened fields. if not isinstance(request, securitycenter_service.SetFindingStateRequest): request = securitycenter_service.SetFindingStateRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if state is not None: @@ -1862,13 +1827,13 @@ def set_finding_state( def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the access control policy on the specified Source. @@ -1885,7 +1850,6 @@ def set_iam_policy( This corresponds to the ``resource`` 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. @@ -1964,11 +1928,10 @@ def set_iam_policy( if isinstance(request, dict): # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. - request = iam_policy.SetIamPolicyRequest(**request) + request = iam_policy_pb2.SetIamPolicyRequest(**request) elif not request: # Null request, just make one. - request = iam_policy.SetIamPolicyRequest() - + request = iam_policy_pb2.SetIamPolicyRequest() if resource is not None: request.resource = resource @@ -1990,14 +1953,14 @@ def set_iam_policy( def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, resource: str = None, permissions: Sequence[str] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Returns the permissions that a caller has on the specified source. @@ -2023,7 +1986,6 @@ def test_iam_permissions( This corresponds to the ``permissions`` 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. @@ -2047,14 +2009,12 @@ def test_iam_permissions( if isinstance(request, dict): # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. - request = iam_policy.TestIamPermissionsRequest(**request) + request = iam_policy_pb2.TestIamPermissionsRequest(**request) elif not request: # Null request, just make one. - request = iam_policy.TestIamPermissionsRequest() - + request = iam_policy_pb2.TestIamPermissionsRequest() if resource is not None: request.resource = resource - if permissions: request.permissions.extend(permissions) @@ -2102,7 +2062,6 @@ def update_finding( This corresponds to the ``finding`` 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. @@ -2138,10 +2097,8 @@ def update_finding( # there are no flattened fields. if not isinstance(request, securitycenter_service.UpdateFindingRequest): request = securitycenter_service.UpdateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if finding is not None: request.finding = finding @@ -2168,7 +2125,7 @@ def update_notification_config( request: securitycenter_service.UpdateNotificationConfigRequest = None, *, notification_config: gcs_notification_config.NotificationConfig = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -2196,7 +2153,6 @@ def update_notification_config( This corresponds to the ``update_mask`` 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. @@ -2231,10 +2187,8 @@ def update_notification_config( request, securitycenter_service.UpdateNotificationConfigRequest ): request = securitycenter_service.UpdateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if notification_config is not None: request.notification_config = notification_config if update_mask is not None: @@ -2282,7 +2236,6 @@ def update_organization_settings( This corresponds to the ``organization_settings`` 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. @@ -2314,10 +2267,8 @@ def update_organization_settings( request, securitycenter_service.UpdateOrganizationSettingsRequest ): request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if organization_settings is not None: request.organization_settings = organization_settings @@ -2363,7 +2314,6 @@ def update_source( This corresponds to the ``source`` 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. @@ -2396,10 +2346,8 @@ def update_source( # there are no flattened fields. if not isinstance(request, securitycenter_service.UpdateSourceRequest): request = securitycenter_service.UpdateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if source is not None: request.source = source @@ -2443,7 +2391,6 @@ def update_security_marks( This corresponds to the ``security_marks`` 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. @@ -2478,10 +2425,8 @@ def update_security_marks( # there are no flattened fields. if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): request = securitycenter_service.UpdateSecurityMarksRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if security_marks is not None: request.security_marks = security_marks diff --git a/google/cloud/securitycenter_v1/services/security_center/pagers.py b/google/cloud/securitycenter_v1/services/security_center/pagers.py index e887de53..318bbb42 100644 --- a/google/cloud/securitycenter_v1/services/security_center/pagers.py +++ b/google/cloud/securitycenter_v1/services/security_center/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, @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -247,7 +245,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -379,7 +377,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -511,7 +509,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -643,7 +641,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -773,7 +771,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/securitycenter_v1/services/security_center/transports/__init__.py b/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py index 45814553..1a2f356a 100644 --- a/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py +++ b/google/cloud/securitycenter_v1/services/security_center/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/securitycenter_v1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1/services/security_center/transports/base.py index 82541447..f200d188 100644 --- a/google/cloud/securitycenter_v1/services/security_center/transports/base.py +++ b/google/cloud/securitycenter_v1/services/security_center/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,17 +13,18 @@ # 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.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.securitycenter_v1.types import finding from google.cloud.securitycenter_v1.types import finding as gcs_finding @@ -40,11 +40,10 @@ from google.cloud.securitycenter_v1.types import securitycenter_service from google.cloud.securitycenter_v1.types import source from google.cloud.securitycenter_v1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -55,27 +54,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 SecurityCenterTransport(abc.ABC): """Abstract transport class for SecurityCenter.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "securitycenter.googleapis.com" + def __init__( self, *, - host: str = "securitycenter.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 @@ -84,7 +97,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): @@ -98,29 +111,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 = { @@ -147,7 +207,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -161,7 +222,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -175,7 +237,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -189,7 +252,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -203,7 +267,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -217,7 +282,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -231,7 +297,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -245,7 +312,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -259,7 +327,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -273,7 +342,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -296,7 +366,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -334,29 +405,29 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def create_source( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.CreateSourceRequest], - typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], + Union[gcs_source.Source, Awaitable[gcs_source.Source]], ]: raise NotImplementedError() @property def create_finding( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.CreateFindingRequest], - typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], + Union[gcs_finding.Finding, Awaitable[gcs_finding.Finding]], ]: raise NotImplementedError() @property def create_notification_config( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.CreateNotificationConfigRequest], - typing.Union[ + Union[ gcs_notification_config.NotificationConfig, - typing.Awaitable[gcs_notification_config.NotificationConfig], + Awaitable[gcs_notification_config.NotificationConfig], ], ]: raise NotImplementedError() @@ -364,29 +435,29 @@ def create_notification_config( @property def delete_notification_config( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.DeleteNotificationConfigRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ - [iam_policy.GetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], ]: raise NotImplementedError() @property def get_notification_config( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.GetNotificationConfigRequest], - typing.Union[ + Union[ notification_config.NotificationConfig, - typing.Awaitable[notification_config.NotificationConfig], + Awaitable[notification_config.NotificationConfig], ], ]: raise NotImplementedError() @@ -394,11 +465,11 @@ def get_notification_config( @property def get_organization_settings( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.GetOrganizationSettingsRequest], - typing.Union[ + Union[ organization_settings.OrganizationSettings, - typing.Awaitable[organization_settings.OrganizationSettings], + Awaitable[organization_settings.OrganizationSettings], ], ]: raise NotImplementedError() @@ -406,20 +477,20 @@ def get_organization_settings( @property def get_source( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.GetSourceRequest], - typing.Union[source.Source, typing.Awaitable[source.Source]], + Union[source.Source, Awaitable[source.Source]], ]: raise NotImplementedError() @property def group_assets( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.GroupAssetsRequest], - typing.Union[ + Union[ securitycenter_service.GroupAssetsResponse, - typing.Awaitable[securitycenter_service.GroupAssetsResponse], + Awaitable[securitycenter_service.GroupAssetsResponse], ], ]: raise NotImplementedError() @@ -427,11 +498,11 @@ def group_assets( @property def group_findings( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.GroupFindingsRequest], - typing.Union[ + Union[ securitycenter_service.GroupFindingsResponse, - typing.Awaitable[securitycenter_service.GroupFindingsResponse], + Awaitable[securitycenter_service.GroupFindingsResponse], ], ]: raise NotImplementedError() @@ -439,11 +510,11 @@ def group_findings( @property def list_assets( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.ListAssetsRequest], - typing.Union[ + Union[ securitycenter_service.ListAssetsResponse, - typing.Awaitable[securitycenter_service.ListAssetsResponse], + Awaitable[securitycenter_service.ListAssetsResponse], ], ]: raise NotImplementedError() @@ -451,11 +522,11 @@ def list_assets( @property def list_findings( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.ListFindingsRequest], - typing.Union[ + Union[ securitycenter_service.ListFindingsResponse, - typing.Awaitable[securitycenter_service.ListFindingsResponse], + Awaitable[securitycenter_service.ListFindingsResponse], ], ]: raise NotImplementedError() @@ -463,11 +534,11 @@ def list_findings( @property def list_notification_configs( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.ListNotificationConfigsRequest], - typing.Union[ + Union[ securitycenter_service.ListNotificationConfigsResponse, - typing.Awaitable[securitycenter_service.ListNotificationConfigsResponse], + Awaitable[securitycenter_service.ListNotificationConfigsResponse], ], ]: raise NotImplementedError() @@ -475,11 +546,11 @@ def list_notification_configs( @property def list_sources( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.ListSourcesRequest], - typing.Union[ + Union[ securitycenter_service.ListSourcesResponse, - typing.Awaitable[securitycenter_service.ListSourcesResponse], + Awaitable[securitycenter_service.ListSourcesResponse], ], ]: raise NotImplementedError() @@ -487,38 +558,38 @@ def list_sources( @property def run_asset_discovery( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.RunAssetDiscoveryRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def set_finding_state( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.SetFindingStateRequest], - typing.Union[finding.Finding, typing.Awaitable[finding.Finding]], + Union[finding.Finding, Awaitable[finding.Finding]], ]: raise NotImplementedError() @property def set_iam_policy( self, - ) -> typing.Callable[ - [iam_policy.SetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ - [iam_policy.TestIamPermissionsRequest], - typing.Union[ - iam_policy.TestIamPermissionsResponse, - typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], ], ]: raise NotImplementedError() @@ -526,20 +597,20 @@ def test_iam_permissions( @property def update_finding( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.UpdateFindingRequest], - typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], + Union[gcs_finding.Finding, Awaitable[gcs_finding.Finding]], ]: raise NotImplementedError() @property def update_notification_config( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.UpdateNotificationConfigRequest], - typing.Union[ + Union[ gcs_notification_config.NotificationConfig, - typing.Awaitable[gcs_notification_config.NotificationConfig], + Awaitable[gcs_notification_config.NotificationConfig], ], ]: raise NotImplementedError() @@ -547,11 +618,11 @@ def update_notification_config( @property def update_organization_settings( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.UpdateOrganizationSettingsRequest], - typing.Union[ + Union[ gcs_organization_settings.OrganizationSettings, - typing.Awaitable[gcs_organization_settings.OrganizationSettings], + Awaitable[gcs_organization_settings.OrganizationSettings], ], ]: raise NotImplementedError() @@ -559,20 +630,20 @@ def update_organization_settings( @property def update_source( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.UpdateSourceRequest], - typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], + Union[gcs_source.Source, Awaitable[gcs_source.Source]], ]: raise NotImplementedError() @property def update_security_marks( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.UpdateSecurityMarksRequest], - typing.Union[ + Union[ gcs_security_marks.SecurityMarks, - typing.Awaitable[gcs_security_marks.SecurityMarks], + Awaitable[gcs_security_marks.SecurityMarks], ], ]: raise NotImplementedError() diff --git a/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py b/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py index 59612c98..4c9b9cf5 100644 --- a/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py +++ b/google/cloud/securitycenter_v1/services/security_center/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,15 +13,14 @@ # 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 operations_v1 # 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 @@ -41,11 +39,10 @@ from google.cloud.securitycenter_v1.types import securitycenter_service from google.cloud.securitycenter_v1.types import source from google.cloud.securitycenter_v1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO @@ -68,7 +65,7 @@ def __init__( self, *, host: str = "securitycenter.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -82,7 +79,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 @@ -193,7 +191,7 @@ def __init__( def create_channel( cls, host: str = "securitycenter.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, @@ -224,13 +222,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, ) @@ -340,7 +340,7 @@ def create_notification_config( def delete_notification_config( self, ) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], empty.Empty + [securitycenter_service.DeleteNotificationConfigRequest], empty_pb2.Empty ]: r"""Return a callable for the delete notification config method over gRPC. @@ -360,14 +360,14 @@ def delete_notification_config( self._stubs["delete_notification_config"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1.SecurityCenter/DeleteNotificationConfig", request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_notification_config"] @property def get_iam_policy( self, - ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: r"""Return a callable for the get iam policy method over gRPC. Gets the access control policy on the specified @@ -386,8 +386,8 @@ def get_iam_policy( if "get_iam_policy" not in self._stubs: self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1.SecurityCenter/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["get_iam_policy"] @@ -518,7 +518,9 @@ def group_findings( their specified properties. To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings Returns: Callable[[~.GroupFindingsRequest], @@ -661,7 +663,7 @@ def list_sources( def run_asset_discovery( self, ) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], operations.Operation + [securitycenter_service.RunAssetDiscoveryRequest], operations_pb2.Operation ]: r"""Return a callable for the run asset discovery method over gRPC. @@ -686,7 +688,7 @@ def run_asset_discovery( self._stubs["run_asset_discovery"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1.SecurityCenter/RunAssetDiscovery", request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["run_asset_discovery"] @@ -719,7 +721,7 @@ def set_finding_state( @property def set_iam_policy( self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: r"""Return a callable for the set iam policy method over gRPC. Sets the access control policy on the specified @@ -738,8 +740,8 @@ def set_iam_policy( if "set_iam_policy" not in self._stubs: self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1.SecurityCenter/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["set_iam_policy"] @@ -747,7 +749,8 @@ def set_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, ]: r"""Return a callable for the test iam permissions method over gRPC. @@ -767,8 +770,8 @@ def test_iam_permissions( if "test_iam_permissions" not in self._stubs: self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1.SecurityCenter/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, ) return self._stubs["test_iam_permissions"] diff --git a/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py b/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py index 8c4e9bef..8c1aa794 100644 --- a/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py +++ b/google/cloud/securitycenter_v1/services/security_center/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,16 +13,15 @@ # 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.api_core import operations_v1 # 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 @@ -42,11 +40,10 @@ from google.cloud.securitycenter_v1.types import securitycenter_service from google.cloud.securitycenter_v1.types import source from google.cloud.securitycenter_v1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO from .grpc import SecurityCenterGrpcTransport @@ -71,7 +68,7 @@ class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): def create_channel( cls, host: str = "securitycenter.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, @@ -98,13 +95,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, ) @@ -112,7 +111,7 @@ def __init__( self, *, host: str = "securitycenter.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, @@ -126,7 +125,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 @@ -185,7 +185,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 @@ -350,7 +349,8 @@ def create_notification_config( def delete_notification_config( self, ) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], Awaitable[empty.Empty] + [securitycenter_service.DeleteNotificationConfigRequest], + Awaitable[empty_pb2.Empty], ]: r"""Return a callable for the delete notification config method over gRPC. @@ -370,14 +370,14 @@ def delete_notification_config( self._stubs["delete_notification_config"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1.SecurityCenter/DeleteNotificationConfig", request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_notification_config"] @property def get_iam_policy( self, - ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: r"""Return a callable for the get iam policy method over gRPC. Gets the access control policy on the specified @@ -396,8 +396,8 @@ def get_iam_policy( if "get_iam_policy" not in self._stubs: self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1.SecurityCenter/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["get_iam_policy"] @@ -528,7 +528,9 @@ def group_findings( their specified properties. To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings Returns: Callable[[~.GroupFindingsRequest], @@ -672,7 +674,7 @@ def run_asset_discovery( self, ) -> Callable[ [securitycenter_service.RunAssetDiscoveryRequest], - Awaitable[operations.Operation], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the run asset discovery method over gRPC. @@ -697,7 +699,7 @@ def run_asset_discovery( self._stubs["run_asset_discovery"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1.SecurityCenter/RunAssetDiscovery", request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["run_asset_discovery"] @@ -732,7 +734,7 @@ def set_finding_state( @property def set_iam_policy( self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: r"""Return a callable for the set iam policy method over gRPC. Sets the access control policy on the specified @@ -751,8 +753,8 @@ def set_iam_policy( if "set_iam_policy" not in self._stubs: self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1.SecurityCenter/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["set_iam_policy"] @@ -760,8 +762,8 @@ def set_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], - Awaitable[iam_policy.TestIamPermissionsResponse], + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], ]: r"""Return a callable for the test iam permissions method over gRPC. @@ -781,8 +783,8 @@ def test_iam_permissions( if "test_iam_permissions" not in self._stubs: self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1.SecurityCenter/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, ) return self._stubs["test_iam_permissions"] diff --git a/google/cloud/securitycenter_v1/types/__init__.py b/google/cloud/securitycenter_v1/types/__init__.py index 0d3cb34a..dc6a8bc3 100644 --- a/google/cloud/securitycenter_v1/types/__init__.py +++ b/google/cloud/securitycenter_v1/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,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .asset import Asset from .finding import Finding +from .folder import Folder from .notification_config import NotificationConfig from .notification_message import NotificationMessage from .organization_settings import OrganizationSettings @@ -57,6 +56,7 @@ __all__ = ( "Asset", "Finding", + "Folder", "NotificationConfig", "NotificationMessage", "OrganizationSettings", diff --git a/google/cloud/securitycenter_v1/types/asset.py b/google/cloud/securitycenter_v1/types/asset.py index 7ec5e67c..2ce564b9 100644 --- a/google/cloud/securitycenter_v1/types/asset.py +++ b/google/cloud/securitycenter_v1/types/asset.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,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - +from google.cloud.securitycenter_v1.types import folder from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -61,14 +59,20 @@ class Asset(proto.Message): The time at which the asset was created in Security Command Center. update_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the asset was last updated, - added, or deleted in Security Command Center. + The time at which the asset was last updated + or added in Cloud SCC. iam_policy (google.cloud.securitycenter_v1.types.Asset.IamPolicy): Cloud IAM Policy information associated with the Google Cloud resource described by the Security Command Center asset. This information is managed and defined by the Google Cloud resource and cannot be modified by the user. + canonical_name (str): + The canonical name of the resource. It's either + "organizations/{organization_id}/assets/{asset_id}", + "folders/{folder_id}/assets/{asset_id}" or + "projects/{project_number}/assets/{asset_id}", depending on + the closest CRM ancestor of the resource. """ class SecurityCenterProperties(proto.Message): @@ -108,23 +112,22 @@ class SecurityCenterProperties(proto.Message): resource_project_display_name (str): The user defined display name for the project of this resource. + folders (Sequence[google.cloud.securitycenter_v1.types.Folder]): + Contains a Folder message for each folder in + the assets ancestry. The first folder is the + deepest nested folder, and the last folder is + the folder directly under the Organization. """ - resource_name = proto.Field(proto.STRING, number=1) - - resource_type = proto.Field(proto.STRING, number=2) - - resource_parent = proto.Field(proto.STRING, number=3) - - resource_project = proto.Field(proto.STRING, number=4) - - resource_owners = proto.RepeatedField(proto.STRING, number=5) - - resource_display_name = proto.Field(proto.STRING, number=6) - - resource_parent_display_name = proto.Field(proto.STRING, number=7) - - resource_project_display_name = proto.Field(proto.STRING, number=8) + resource_name = proto.Field(proto.STRING, number=1,) + resource_type = proto.Field(proto.STRING, number=2,) + resource_parent = proto.Field(proto.STRING, number=3,) + resource_project = proto.Field(proto.STRING, number=4,) + resource_owners = proto.RepeatedField(proto.STRING, number=5,) + resource_display_name = proto.Field(proto.STRING, number=6,) + resource_parent_display_name = proto.Field(proto.STRING, number=7,) + resource_project_display_name = proto.Field(proto.STRING, number=8,) + folders = proto.RepeatedField(proto.MESSAGE, number=10, message=folder.Folder,) class IamPolicy(proto.Message): r"""Cloud IAM Policy information associated with the Google Cloud @@ -140,27 +143,24 @@ class IamPolicy(proto.Message): for format details. """ - policy_blob = proto.Field(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=1) + policy_blob = proto.Field(proto.STRING, number=1,) + name = proto.Field(proto.STRING, number=1,) security_center_properties = proto.Field( proto.MESSAGE, number=2, message=SecurityCenterProperties, ) - resource_properties = proto.MapField( - proto.STRING, proto.MESSAGE, number=7, message=struct.Value, + proto.STRING, proto.MESSAGE, number=7, message=struct_pb2.Value, ) - security_marks = proto.Field( proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, ) - - create_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) - - update_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) - + create_time = proto.Field(proto.MESSAGE, number=9, message=timestamp_pb2.Timestamp,) + update_time = proto.Field( + proto.MESSAGE, number=10, message=timestamp_pb2.Timestamp, + ) iam_policy = proto.Field(proto.MESSAGE, number=11, message=IamPolicy,) + canonical_name = proto.Field(proto.STRING, number=13,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/finding.py b/google/cloud/securitycenter_v1/types/finding.py index 7fb6a109..40cbb2a2 100644 --- a/google/cloud/securitycenter_v1/types/finding.py +++ b/google/cloud/securitycenter_v1/types/finding.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.securitycenter_v1.types import security_marks as gcs_security_marks -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -86,13 +83,23 @@ class Finding(proto.Message): believes the firewall became open. The accuracy is determined by the detector. If the finding were to be resolved afterward, this time would - reflect when the finding was resolved. + reflect when the finding was resolved. Must not + be set to a value greater than the current + timestamp. create_time (google.protobuf.timestamp_pb2.Timestamp): The time at which the finding was created in Security Command Center. severity (google.cloud.securitycenter_v1.types.Finding.Severity): The severity of the finding. This field is managed by the source that writes the finding. + canonical_name (str): + The canonical name of the finding. It's either + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}", + "folders/{folder_id}/sources/{source_id}/findings/{finding_id}" + or + "projects/{project_number}/sources/{source_id}/findings/{finding_id}", + depending on the closest CRM ancestor of the resource + associated with the finding. """ class State(proto.Enum): @@ -109,31 +116,24 @@ class Severity(proto.Enum): MEDIUM = 3 LOW = 4 - name = proto.Field(proto.STRING, number=1) - - parent = proto.Field(proto.STRING, number=2) - - resource_name = proto.Field(proto.STRING, number=3) - + name = proto.Field(proto.STRING, number=1,) + parent = proto.Field(proto.STRING, number=2,) + resource_name = proto.Field(proto.STRING, number=3,) state = proto.Field(proto.ENUM, number=4, enum=State,) - - category = proto.Field(proto.STRING, number=5) - - external_uri = proto.Field(proto.STRING, number=6) - + category = proto.Field(proto.STRING, number=5,) + external_uri = proto.Field(proto.STRING, number=6,) source_properties = proto.MapField( - proto.STRING, proto.MESSAGE, number=7, message=struct.Value, + proto.STRING, proto.MESSAGE, number=7, message=struct_pb2.Value, ) - security_marks = proto.Field( proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, ) - - event_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) - - create_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) - + event_time = proto.Field(proto.MESSAGE, number=9, message=timestamp_pb2.Timestamp,) + create_time = proto.Field( + proto.MESSAGE, number=10, message=timestamp_pb2.Timestamp, + ) severity = proto.Field(proto.ENUM, number=12, enum=Severity,) + canonical_name = proto.Field(proto.STRING, number=14,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/folder.py b/google/cloud/securitycenter_v1/types/folder.py new file mode 100644 index 00000000..896ee9ad --- /dev/null +++ b/google/cloud/securitycenter_v1/types/folder.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1", manifest={"Folder",}, +) + + +class Folder(proto.Message): + r"""Message that contains the resource name and display name of a + folder resource. + + Attributes: + resource_folder (str): + Full resource name of this folder. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_folder_display_name (str): + The user defined display name for this + folder. + """ + + resource_folder = proto.Field(proto.STRING, number=1,) + resource_folder_display_name = proto.Field(proto.STRING, number=2,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/notification_config.py b/google/cloud/securitycenter_v1/types/notification_config.py index d6876046..921a6854 100644 --- a/google/cloud/securitycenter_v1/types/notification_config.py +++ b/google/cloud/securitycenter_v1/types/notification_config.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 @@ -82,16 +80,12 @@ class StreamingConfig(proto.Message): - boolean literals ``true`` and ``false`` without quotes. """ - filter = proto.Field(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=1) - - description = proto.Field(proto.STRING, number=2) - - pubsub_topic = proto.Field(proto.STRING, number=3) - - service_account = proto.Field(proto.STRING, number=4) + filter = proto.Field(proto.STRING, number=1,) + name = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) + pubsub_topic = proto.Field(proto.STRING, number=3,) + service_account = proto.Field(proto.STRING, number=4,) streaming_config = proto.Field( proto.MESSAGE, number=5, oneof="notify_config", message=StreamingConfig, ) diff --git a/google/cloud/securitycenter_v1/types/notification_message.py b/google/cloud/securitycenter_v1/types/notification_message.py index c3a6436f..49dfce88 100644 --- a/google/cloud/securitycenter_v1/types/notification_message.py +++ b/google/cloud/securitycenter_v1/types/notification_message.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.securitycenter_v1.types import finding as gcs_finding from google.cloud.securitycenter_v1.types import resource as gcs_resource @@ -29,7 +26,6 @@ class NotificationMessage(proto.Message): r"""Cloud SCC's Notification - Attributes: notification_config_name (str): Name of the notification config that @@ -42,12 +38,10 @@ class NotificationMessage(proto.Message): notification's Finding. """ - notification_config_name = proto.Field(proto.STRING, number=1) - + notification_config_name = proto.Field(proto.STRING, number=1,) finding = proto.Field( proto.MESSAGE, number=2, oneof="event", message=gcs_finding.Finding, ) - resource = proto.Field(proto.MESSAGE, number=3, message=gcs_resource.Resource,) diff --git a/google/cloud/securitycenter_v1/types/organization_settings.py b/google/cloud/securitycenter_v1/types/organization_settings.py index a1135a8d..8462c7e7 100644 --- a/google/cloud/securitycenter_v1/types/organization_settings.py +++ b/google/cloud/securitycenter_v1/types/organization_settings.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 @@ -45,7 +43,6 @@ class OrganizationSettings(proto.Message): class AssetDiscoveryConfig(proto.Message): r"""The configuration used for Asset Discovery runs. - Attributes: project_ids (Sequence[str]): The project ids to use for filtering asset @@ -53,6 +50,10 @@ class AssetDiscoveryConfig(proto.Message): inclusion_mode (google.cloud.securitycenter_v1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): The mode to use for filtering asset discovery. + folder_ids (Sequence[str]): + The folder ids to use for filtering asset + discovery. It consists of only digits, e.g., + 756619654966. """ class InclusionMode(proto.Enum): @@ -69,18 +70,16 @@ class InclusionMode(proto.Enum): INCLUDE_ONLY = 1 EXCLUDE = 2 - project_ids = proto.RepeatedField(proto.STRING, number=1) - + project_ids = proto.RepeatedField(proto.STRING, number=1,) inclusion_mode = proto.Field( proto.ENUM, number=2, enum="OrganizationSettings.AssetDiscoveryConfig.InclusionMode", ) + folder_ids = proto.RepeatedField(proto.STRING, number=3,) - name = proto.Field(proto.STRING, number=1) - - enable_asset_discovery = proto.Field(proto.BOOL, number=2) - + name = proto.Field(proto.STRING, number=1,) + enable_asset_discovery = proto.Field(proto.BOOL, number=2,) asset_discovery_config = proto.Field( proto.MESSAGE, number=3, message=AssetDiscoveryConfig, ) diff --git a/google/cloud/securitycenter_v1/types/resource.py b/google/cloud/securitycenter_v1/types/resource.py index 49c709fa..d3101244 100644 --- a/google/cloud/securitycenter_v1/types/resource.py +++ b/google/cloud/securitycenter_v1/types/resource.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,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore +from google.cloud.securitycenter_v1.types import folder + __protobuf__ = proto.module( package="google.cloud.securitycenter.v1", manifest={"Resource",}, @@ -25,7 +25,6 @@ class Resource(proto.Message): r"""Information related to the Google Cloud resource. - Attributes: name (str): The full resource name of the resource. See: @@ -40,17 +39,20 @@ class Resource(proto.Message): The full resource name of resource's parent. parent_display_name (str): The human readable name of resource's parent. + folders (Sequence[google.cloud.securitycenter_v1.types.Folder]): + Output only. Contains a Folder message for + each folder in the assets ancestry. The first + folder is the deepest nested folder, and the + last folder is the folder directly under the + Organization. """ - name = proto.Field(proto.STRING, number=1) - - project = proto.Field(proto.STRING, number=2) - - project_display_name = proto.Field(proto.STRING, number=3) - - parent = proto.Field(proto.STRING, number=4) - - parent_display_name = proto.Field(proto.STRING, number=5) + name = proto.Field(proto.STRING, number=1,) + project = proto.Field(proto.STRING, number=2,) + project_display_name = proto.Field(proto.STRING, number=3,) + parent = proto.Field(proto.STRING, number=4,) + parent_display_name = proto.Field(proto.STRING, number=5,) + folders = proto.RepeatedField(proto.MESSAGE, number=7, message=folder.Folder,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py b/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py index 845adafd..aabbe200 100644 --- a/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py +++ b/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import duration_pb2 as gp_duration # type: ignore +from google.protobuf import duration_pb2 # type: ignore __protobuf__ = proto.module( @@ -28,7 +25,6 @@ class RunAssetDiscoveryResponse(proto.Message): r"""Response of asset discovery run - Attributes: state (google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse.State): The state of an asset discovery run. @@ -45,8 +41,7 @@ class State(proto.Enum): TERMINATED = 3 state = proto.Field(proto.ENUM, number=1, enum=State,) - - duration = proto.Field(proto.MESSAGE, number=2, message=gp_duration.Duration,) + duration = proto.Field(proto.MESSAGE, number=2, message=duration_pb2.Duration,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/security_marks.py b/google/cloud/securitycenter_v1/types/security_marks.py index 181d1d74..02c8bc30 100644 --- a/google/cloud/securitycenter_v1/types/security_marks.py +++ b/google/cloud/securitycenter_v1/types/security_marks.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 @@ -47,11 +45,19 @@ class SecurityMarks(proto.Message): - Values have leading and trailing whitespace trimmed, remaining characters must be between 1 - 4096 characters (inclusive) + canonical_name (str): + The canonical name of the marks. Examples: + "organizations/{organization_id}/assets/{asset_id}/securityMarks" + "folders/{folder_id}/assets/{asset_id}/securityMarks" + "projects/{project_number}/assets/{asset_id}/securityMarks" + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks" + "folders/{folder_id}/sources/{source_id}/findings/{finding_id}/securityMarks" + "projects/{project_number}/sources/{source_id}/findings/{finding_id}/securityMarks". """ - name = proto.Field(proto.STRING, number=1) - - marks = proto.MapField(proto.STRING, proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + marks = proto.MapField(proto.STRING, proto.STRING, number=2,) + canonical_name = proto.Field(proto.STRING, number=3,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/securitycenter_service.py b/google/cloud/securitycenter_v1/types/securitycenter_service.py index 9b80e842..2d5227a4 100644 --- a/google/cloud/securitycenter_v1/types/securitycenter_service.py +++ b/google/cloud/securitycenter_v1/types/securitycenter_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.securitycenter_v1.types import asset as gcs_asset from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import folder from google.cloud.securitycenter_v1.types import ( notification_config as gcs_notification_config, ) @@ -28,10 +26,10 @@ ) from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks from google.cloud.securitycenter_v1.types import source as gcs_source -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as gp_field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -70,7 +68,6 @@ class CreateFindingRequest(proto.Message): r"""Request message for creating a finding. - Attributes: parent (str): Required. Resource name of the new finding's parent. Its @@ -88,16 +85,13 @@ class CreateFindingRequest(proto.Message): fields on this resource. """ - parent = proto.Field(proto.STRING, number=1) - - finding_id = proto.Field(proto.STRING, number=2) - + parent = proto.Field(proto.STRING, number=1,) + finding_id = proto.Field(proto.STRING, number=2,) finding = proto.Field(proto.MESSAGE, number=3, message=gcs_finding.Finding,) class CreateNotificationConfigRequest(proto.Message): r"""Request message for creating a notification config. - Attributes: parent (str): Required. Resource name of the new notification config's @@ -115,10 +109,8 @@ class CreateNotificationConfigRequest(proto.Message): on this resource. """ - parent = proto.Field(proto.STRING, number=1) - - config_id = proto.Field(proto.STRING, number=2) - + parent = proto.Field(proto.STRING, number=1,) + config_id = proto.Field(proto.STRING, number=2,) notification_config = proto.Field( proto.MESSAGE, number=3, message=gcs_notification_config.NotificationConfig, ) @@ -126,7 +118,6 @@ class CreateNotificationConfigRequest(proto.Message): class CreateSourceRequest(proto.Message): r"""Request message for creating a source. - Attributes: parent (str): Required. Resource name of the new source's parent. Its @@ -137,14 +128,12 @@ class CreateSourceRequest(proto.Message): ignored. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) source = proto.Field(proto.MESSAGE, number=2, message=gcs_source.Source,) class DeleteNotificationConfigRequest(proto.Message): r"""Request message for deleting a notification config. - Attributes: name (str): Required. Name of the notification config to delete. Its @@ -152,12 +141,11 @@ class DeleteNotificationConfigRequest(proto.Message): "organizations/[organization_id]/notificationConfigs/[config_id]". """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class GetNotificationConfigRequest(proto.Message): r"""Request message for getting a notification config. - Attributes: name (str): Required. Name of the notification config to get. Its format @@ -165,12 +153,11 @@ class GetNotificationConfigRequest(proto.Message): "organizations/[organization_id]/notificationConfigs/[config_id]". """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class GetOrganizationSettingsRequest(proto.Message): r"""Request message for getting organization settings. - Attributes: name (str): Required. Name of the organization to get organization @@ -178,28 +165,27 @@ class GetOrganizationSettingsRequest(proto.Message): "organizations/[organization_id]/organizationSettings". """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class GetSourceRequest(proto.Message): r"""Request message for getting a source. - Attributes: name (str): Required. Relative resource name of the source. Its format is "organizations/[organization_id]/source/[source_id]". """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class GroupAssetsRequest(proto.Message): r"""Request message for grouping by assets. - Attributes: parent (str): Required. Name of the organization to groupBy. Its format is - "organizations/[organization_id]". + "organizations/[organization_id], folders/[folder_id], or + projects/[project_id]". filter (str): Expression that defines the filter to apply across assets. The expression is a list of zero or more restrictions @@ -352,24 +338,19 @@ class GroupAssetsRequest(proto.Message): maximum is 1000. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - group_by = proto.Field(proto.STRING, number=3) - - compare_duration = proto.Field(proto.MESSAGE, number=4, message=duration.Duration,) - - read_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - - page_token = proto.Field(proto.STRING, number=7) - - page_size = proto.Field(proto.INT32, number=8) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + group_by = proto.Field(proto.STRING, number=3,) + compare_duration = proto.Field( + proto.MESSAGE, number=4, message=duration_pb2.Duration, + ) + read_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + page_token = proto.Field(proto.STRING, number=7,) + page_size = proto.Field(proto.INT32, number=8,) class GroupAssetsResponse(proto.Message): r"""Response message for grouping by assets. - Attributes: group_by_results (Sequence[google.cloud.securitycenter_v1.types.GroupResult]): Group results. There exists an element for @@ -394,23 +375,23 @@ def raw_page(self): group_by_results = proto.RepeatedField( proto.MESSAGE, number=1, message="GroupResult", ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - total_size = proto.Field(proto.INT32, number=4) + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + next_page_token = proto.Field(proto.STRING, number=3,) + total_size = proto.Field(proto.INT32, number=4,) class GroupFindingsRequest(proto.Message): r"""Request message for grouping by findings. - Attributes: parent (str): Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". To - groupBy across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/- + "organizations/[organization_id]/sources/[source_id]", + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]. To groupBy across + all sources provide a source_id of ``-``. For example: + organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/-, or + projects/{project_id}/sources/- filter (str): Expression that defines the filter to apply across findings. The expression is a list of one or more restrictions @@ -547,24 +528,19 @@ class GroupFindingsRequest(proto.Message): maximum is 1000. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - group_by = proto.Field(proto.STRING, number=3) - - read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) - - page_token = proto.Field(proto.STRING, number=7) - - page_size = proto.Field(proto.INT32, number=8) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + group_by = proto.Field(proto.STRING, number=3,) + read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + compare_duration = proto.Field( + proto.MESSAGE, number=5, message=duration_pb2.Duration, + ) + page_token = proto.Field(proto.STRING, number=7,) + page_size = proto.Field(proto.INT32, number=8,) class GroupFindingsResponse(proto.Message): r"""Response message for group by findings. - Attributes: group_by_results (Sequence[google.cloud.securitycenter_v1.types.GroupResult]): Group results. There exists an element for @@ -589,12 +565,9 @@ def raw_page(self): group_by_results = proto.RepeatedField( proto.MESSAGE, number=1, message="GroupResult", ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - total_size = proto.Field(proto.INT32, number=4) + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + next_page_token = proto.Field(proto.STRING, number=3,) + total_size = proto.Field(proto.INT32, number=4,) class GroupResult(proto.Message): @@ -611,15 +584,13 @@ class GroupResult(proto.Message): """ properties = proto.MapField( - proto.STRING, proto.MESSAGE, number=1, message=struct.Value, + proto.STRING, proto.MESSAGE, number=1, message=struct_pb2.Value, ) - - count = proto.Field(proto.INT64, number=2) + count = proto.Field(proto.INT64, number=2,) class ListNotificationConfigsRequest(proto.Message): r"""Request message for listing notification configs. - Attributes: parent (str): Required. Name of the organization to list notification @@ -635,16 +606,13 @@ class ListNotificationConfigsRequest(proto.Message): maximum is 1000. """ - parent = proto.Field(proto.STRING, number=1) - - page_token = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_token = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) class ListNotificationConfigsResponse(proto.Message): r"""Response message for listing notification configs. - Attributes: notification_configs (Sequence[google.cloud.securitycenter_v1.types.NotificationConfig]): Notification configs belonging to the @@ -661,17 +629,16 @@ def raw_page(self): notification_configs = proto.RepeatedField( proto.MESSAGE, number=1, message=gcs_notification_config.NotificationConfig, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class ListSourcesRequest(proto.Message): r"""Request message for listing sources. - Attributes: parent (str): Required. Resource name of the parent of sources to list. - Its format should be "organizations/[organization_id]". + Its format should be "organizations/[organization_id], + folders/[folder_id], or projects/[project_id]". page_token (str): The value returned by the last ``ListSourcesResponse``; indicates that this is a continuation of a prior @@ -683,16 +650,13 @@ class ListSourcesRequest(proto.Message): maximum is 1000. """ - parent = proto.Field(proto.STRING, number=1) - - page_token = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=7) + parent = proto.Field(proto.STRING, number=1,) + page_token = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=7,) class ListSourcesResponse(proto.Message): r"""Response message for listing sources. - Attributes: sources (Sequence[google.cloud.securitycenter_v1.types.Source]): Sources belonging to the requested parent. @@ -706,17 +670,16 @@ def raw_page(self): return self sources = proto.RepeatedField(proto.MESSAGE, number=1, message=gcs_source.Source,) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class ListAssetsRequest(proto.Message): r"""Request message for listing assets. - Attributes: parent (str): Required. Name of the organization assets should belong to. - Its format is "organizations/[organization_id]". + Its format is "organizations/[organization_id], + folders/[folder_id], or projects/[project_id]". filter (str): Expression that defines the filter to apply across assets. The expression is a list of zero or more restrictions @@ -870,26 +833,20 @@ class ListAssetsRequest(proto.Message): maximum is 1000. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - order_by = proto.Field(proto.STRING, number=3) - - read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) - - field_mask = proto.Field(proto.MESSAGE, number=7, message=gp_field_mask.FieldMask,) - - page_token = proto.Field(proto.STRING, number=8) - - page_size = proto.Field(proto.INT32, number=9) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + order_by = proto.Field(proto.STRING, number=3,) + read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + compare_duration = proto.Field( + proto.MESSAGE, number=5, message=duration_pb2.Duration, + ) + field_mask = proto.Field(proto.MESSAGE, number=7, message=field_mask_pb2.FieldMask,) + page_token = proto.Field(proto.STRING, number=8,) + page_size = proto.Field(proto.INT32, number=9,) class ListAssetsResponse(proto.Message): r"""Response message for listing assets. - Attributes: list_assets_results (Sequence[google.cloud.securitycenter_v1.types.ListAssetsResponse.ListAssetsResult]): Assets matching the list request. @@ -905,7 +862,6 @@ class ListAssetsResponse(proto.Message): class ListAssetsResult(proto.Message): r"""Result containing the Asset and its State. - Attributes: asset (google.cloud.securitycenter_v1.types.Asset): Asset matching the search request. @@ -928,7 +884,6 @@ class StateChange(proto.Enum): ACTIVE = 3 asset = proto.Field(proto.MESSAGE, number=1, message=gcs_asset.Asset,) - state_change = proto.Field( proto.ENUM, number=2, @@ -942,24 +897,24 @@ def raw_page(self): list_assets_results = proto.RepeatedField( proto.MESSAGE, number=1, message=ListAssetsResult, ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - total_size = proto.Field(proto.INT32, number=4) + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + next_page_token = proto.Field(proto.STRING, number=3,) + total_size = proto.Field(proto.INT32, number=4,) class ListFindingsRequest(proto.Message): r"""Request message for listing findings. - Attributes: parent (str): Required. Name of the source the findings belong to. Its format is - "organizations/[organization_id]/sources/[source_id]". To - list across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/- + "organizations/[organization_id]/sources/[source_id], + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]". To list across + all sources provide a source_id of ``-``. For example: + organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/- or + projects/{projects_id}/sources/- filter (str): Expression that defines the filter to apply across findings. The expression is a list of one or more restrictions @@ -1092,26 +1047,20 @@ class ListFindingsRequest(proto.Message): maximum is 1000. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - order_by = proto.Field(proto.STRING, number=3) - - read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) - - field_mask = proto.Field(proto.MESSAGE, number=7, message=gp_field_mask.FieldMask,) - - page_token = proto.Field(proto.STRING, number=8) - - page_size = proto.Field(proto.INT32, number=9) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + order_by = proto.Field(proto.STRING, number=3,) + read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + compare_duration = proto.Field( + proto.MESSAGE, number=5, message=duration_pb2.Duration, + ) + field_mask = proto.Field(proto.MESSAGE, number=7, message=field_mask_pb2.FieldMask,) + page_token = proto.Field(proto.STRING, number=8,) + page_size = proto.Field(proto.INT32, number=9,) class ListFindingsResponse(proto.Message): r"""Response message for listing findings. - Attributes: list_findings_results (Sequence[google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult]): Findings matching the list request. @@ -1127,7 +1076,6 @@ class ListFindingsResponse(proto.Message): class ListFindingsResult(proto.Message): r"""Result containing the Finding and its StateChange. - Attributes: finding (google.cloud.securitycenter_v1.types.Finding): Finding matching the search request. @@ -1173,26 +1121,28 @@ class Resource(proto.Message): The full resource name of resource's parent. parent_display_name (str): The human readable name of resource's parent. + folders (Sequence[google.cloud.securitycenter_v1.types.Folder]): + Contains a Folder message for each folder in + the assets ancestry. The first folder is the + deepest nested folder, and the last folder is + the folder directly under the Organization. """ - name = proto.Field(proto.STRING, number=1) - - project_name = proto.Field(proto.STRING, number=2) - - project_display_name = proto.Field(proto.STRING, number=3) - - parent_name = proto.Field(proto.STRING, number=4) - - parent_display_name = proto.Field(proto.STRING, number=5) + name = proto.Field(proto.STRING, number=1,) + project_name = proto.Field(proto.STRING, number=2,) + project_display_name = proto.Field(proto.STRING, number=3,) + parent_name = proto.Field(proto.STRING, number=4,) + parent_display_name = proto.Field(proto.STRING, number=5,) + folders = proto.RepeatedField( + proto.MESSAGE, number=7, message=folder.Folder, + ) finding = proto.Field(proto.MESSAGE, number=1, message=gcs_finding.Finding,) - state_change = proto.Field( proto.ENUM, number=2, enum="ListFindingsResponse.ListFindingsResult.StateChange", ) - resource = proto.Field( proto.MESSAGE, number=3, @@ -1206,17 +1156,13 @@ def raw_page(self): list_findings_results = proto.RepeatedField( proto.MESSAGE, number=1, message=ListFindingsResult, ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - total_size = proto.Field(proto.INT32, number=4) + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + next_page_token = proto.Field(proto.STRING, number=3,) + total_size = proto.Field(proto.INT32, number=4,) class SetFindingStateRequest(proto.Message): r"""Request message for updating a finding's state. - Attributes: name (str): Required. The relative resource name of the finding. See: @@ -1230,11 +1176,9 @@ class SetFindingStateRequest(proto.Message): takes effect. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) state = proto.Field(proto.ENUM, number=2, enum=gcs_finding.Finding.State,) - - start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) class RunAssetDiscoveryRequest(proto.Message): @@ -1247,12 +1191,11 @@ class RunAssetDiscoveryRequest(proto.Message): for. Its format is "organizations/[organization_id]". """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) class UpdateFindingRequest(proto.Message): r"""Request message for updating or creating a finding. - Attributes: finding (google.cloud.securitycenter_v1.types.Finding): Required. The finding resource to update or create if it @@ -1273,13 +1216,13 @@ class UpdateFindingRequest(proto.Message): """ finding = proto.Field(proto.MESSAGE, number=1, message=gcs_finding.Finding,) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class UpdateNotificationConfigRequest(proto.Message): r"""Request message for updating a notification config. - Attributes: notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): Required. The notification config to update. @@ -1292,13 +1235,13 @@ class UpdateNotificationConfigRequest(proto.Message): notification_config = proto.Field( proto.MESSAGE, number=1, message=gcs_notification_config.NotificationConfig, ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class UpdateOrganizationSettingsRequest(proto.Message): r"""Request message for updating an organization's settings. - Attributes: organization_settings (google.cloud.securitycenter_v1.types.OrganizationSettings): Required. The organization settings resource @@ -1313,13 +1256,13 @@ class UpdateOrganizationSettingsRequest(proto.Message): organization_settings = proto.Field( proto.MESSAGE, number=1, message=gcs_organization_settings.OrganizationSettings, ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class UpdateSourceRequest(proto.Message): r"""Request message for updating a source. - Attributes: source (google.cloud.securitycenter_v1.types.Source): Required. The source resource to update. @@ -1330,13 +1273,13 @@ class UpdateSourceRequest(proto.Message): """ source = proto.Field(proto.MESSAGE, number=1, message=gcs_source.Source,) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class UpdateSecurityMarksRequest(proto.Message): r"""Request message for updating a SecurityMarks resource. - Attributes: security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): Required. The security marks resource to @@ -1359,10 +1302,10 @@ class UpdateSecurityMarksRequest(proto.Message): security_marks = proto.Field( proto.MESSAGE, number=1, message=gcs_security_marks.SecurityMarks, ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) - - start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) + start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/source.py b/google/cloud/securitycenter_v1/types/source.py index ce412d1c..9fb3ec48 100644 --- a/google/cloud/securitycenter_v1/types/source.py +++ b/google/cloud/securitycenter_v1/types/source.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 @@ -52,13 +50,19 @@ class Source(proto.Message): cross-site-scripting (XSS), Flash injection, mixed content (HTTP in HTTPS), and outdated or insecure libraries.". + canonical_name (str): + The canonical name of the finding. It's either + "organizations/{organization_id}/sources/{source_id}", + "folders/{folder_id}/sources/{source_id}" or + "projects/{project_number}/sources/{source_id}", depending + on the closest CRM ancestor of the resource associated with + the finding. """ - 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,) + canonical_name = proto.Field(proto.STRING, number=14,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/__init__.py b/google/cloud/securitycenter_v1beta1/__init__.py index 55c3ce49..fae8e1ee 100644 --- a/google/cloud/securitycenter_v1beta1/__init__.py +++ b/google/cloud/securitycenter_v1beta1/__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.security_center import SecurityCenterClient +from .services.security_center import SecurityCenterAsyncClient + from .types.asset import Asset from .types.finding import Finding from .types.organization_settings import OrganizationSettings @@ -44,8 +45,8 @@ from .types.securitycenter_service import UpdateSourceRequest from .types.source import Source - __all__ = ( + "SecurityCenterAsyncClient", "Asset", "CreateFindingRequest", "CreateSourceRequest", @@ -66,6 +67,7 @@ "OrganizationSettings", "RunAssetDiscoveryRequest", "RunAssetDiscoveryResponse", + "SecurityCenterClient", "SecurityMarks", "SetFindingStateRequest", "Source", @@ -73,5 +75,4 @@ "UpdateOrganizationSettingsRequest", "UpdateSecurityMarksRequest", "UpdateSourceRequest", - "SecurityCenterClient", ) diff --git a/google/cloud/securitycenter_v1beta1/gapic_metadata.json b/google/cloud/securitycenter_v1beta1/gapic_metadata.json new file mode 100644 index 00000000..56b17ccf --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/gapic_metadata.json @@ -0,0 +1,203 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.securitycenter_v1beta1", + "protoPackage": "google.cloud.securitycenter.v1beta1", + "schema": "1.0", + "services": { + "SecurityCenter": { + "clients": { + "grpc": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecurityCenterAsyncClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/securitycenter_v1beta1/services/__init__.py b/google/cloud/securitycenter_v1beta1/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/securitycenter_v1beta1/services/__init__.py +++ b/google/cloud/securitycenter_v1beta1/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/securitycenter_v1beta1/services/security_center/__init__.py b/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py index 6250349b..b56953c3 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/__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 SecurityCenterClient from .async_client import SecurityCenterAsyncClient diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py index 14c5d94f..7723dc7e 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/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,10 +20,10 @@ 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.api_core import operation # type: ignore @@ -44,11 +42,10 @@ from google.cloud.securitycenter_v1beta1.types import securitycenter_service from google.cloud.securitycenter_v1beta1.types import source from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport from .client import SecurityCenterClient @@ -78,31 +75,26 @@ class SecurityCenterAsyncClient: ) source_path = staticmethod(SecurityCenterClient.source_path) parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) - common_billing_account_path = staticmethod( SecurityCenterClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( SecurityCenterClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) parse_common_folder_path = staticmethod( SecurityCenterClient.parse_common_folder_path ) - common_organization_path = staticmethod( SecurityCenterClient.common_organization_path ) parse_common_organization_path = staticmethod( SecurityCenterClient.parse_common_organization_path ) - common_project_path = staticmethod(SecurityCenterClient.common_project_path) parse_common_project_path = staticmethod( SecurityCenterClient.parse_common_project_path ) - common_location_path = staticmethod(SecurityCenterClient.common_location_path) parse_common_location_path = staticmethod( SecurityCenterClient.parse_common_location_path @@ -110,7 +102,8 @@ class SecurityCenterAsyncClient: @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. @@ -125,7 +118,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 @@ -142,7 +135,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SecurityCenterTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: SecurityCenterTransport: The transport used by the client instance. @@ -156,12 +149,12 @@ def transport(self) -> SecurityCenterTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, SecurityCenterTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the security center client. + """Instantiates the security center client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -193,7 +186,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SecurityCenterClient( credentials=credentials, transport=transport, @@ -232,7 +224,6 @@ async def create_source( This corresponds to the ``source`` 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. @@ -263,7 +254,6 @@ async def create_source( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if source is not None: @@ -333,7 +323,6 @@ async def create_finding( This corresponds to the ``finding`` 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. @@ -367,7 +356,6 @@ async def create_finding( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if finding_id is not None: @@ -397,13 +385,13 @@ async def create_finding( async def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Gets the access control policy on the specified Source. @@ -420,7 +408,6 @@ async def get_iam_policy( This corresponds to the ``resource`` 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. @@ -499,10 +486,9 @@ async def get_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) - + request = iam_policy_pb2.GetIamPolicyRequest(**request) elif not request: - request = iam_policy.GetIamPolicyRequest(resource=resource,) + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -513,7 +499,8 @@ async def get_iam_policy( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -556,7 +543,6 @@ async def get_organization_settings( 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. @@ -584,7 +570,6 @@ async def get_organization_settings( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -597,7 +582,8 @@ async def get_organization_settings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -640,7 +626,6 @@ async def get_source( 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. @@ -671,7 +656,6 @@ async def get_source( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -684,7 +668,8 @@ async def get_source( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -719,7 +704,6 @@ async def group_assets( request (:class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest`): The request object. Request message for grouping by assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -736,7 +720,6 @@ async def group_assets( """ # Create or coerce a protobuf request object. - request = securitycenter_service.GroupAssetsRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -748,7 +731,8 @@ async def group_assets( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -821,7 +805,6 @@ async def group_findings( This corresponds to the ``group_by`` 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. @@ -851,7 +834,6 @@ async def group_findings( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if group_by is not None: @@ -866,7 +848,8 @@ async def group_findings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -905,7 +888,6 @@ async def list_assets( Args: request (:class:`google.cloud.securitycenter_v1beta1.types.ListAssetsRequest`): The request object. Request message for listing assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -921,7 +903,6 @@ async def list_assets( """ # Create or coerce a protobuf request object. - request = securitycenter_service.ListAssetsRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -933,7 +914,8 @@ async def list_assets( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -977,7 +959,6 @@ async def list_findings( request (:class:`google.cloud.securitycenter_v1beta1.types.ListFindingsRequest`): The request object. Request message for listing findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -994,7 +975,6 @@ async def list_findings( """ # Create or coerce a protobuf request object. - request = securitycenter_service.ListFindingsRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -1006,7 +986,8 @@ async def list_findings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -1054,7 +1035,6 @@ async def list_sources( 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. @@ -1083,7 +1063,6 @@ async def list_sources( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1096,7 +1075,8 @@ async def list_sources( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -1150,7 +1130,6 @@ async def run_asset_discovery( 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. @@ -1190,7 +1169,6 @@ async def run_asset_discovery( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1215,8 +1193,8 @@ async def run_asset_discovery( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=empty.Empty, + empty_pb2.Empty, + metadata_type=empty_pb2.Empty, ) # Done; return the response. @@ -1228,7 +1206,7 @@ async def set_finding_state( *, name: str = None, state: finding.Finding.State = None, - start_time: timestamp.Timestamp = None, + start_time: timestamp_pb2.Timestamp = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -1263,7 +1241,6 @@ async def set_finding_state( This corresponds to the ``start_time`` 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. @@ -1297,7 +1274,6 @@ async def set_finding_state( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if state is not None: @@ -1327,13 +1303,13 @@ async def set_finding_state( async def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the access control policy on the specified Source. @@ -1350,7 +1326,6 @@ async def set_iam_policy( This corresponds to the ``resource`` 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. @@ -1429,10 +1404,9 @@ async def set_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) - + request = iam_policy_pb2.SetIamPolicyRequest(**request) elif not request: - request = iam_policy.SetIamPolicyRequest(resource=resource,) + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1456,14 +1430,14 @@ async def set_iam_policy( async def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, resource: str = None, permissions: Sequence[str] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Returns the permissions that a caller has on the specified source. @@ -1489,7 +1463,6 @@ async def test_iam_permissions( This corresponds to the ``permissions`` 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. @@ -1513,10 +1486,9 @@ async def test_iam_permissions( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) - + request = iam_policy_pb2.TestIamPermissionsRequest(**request) elif not request: - request = iam_policy.TestIamPermissionsRequest( + request = iam_policy_pb2.TestIamPermissionsRequest( resource=resource, permissions=permissions, ) @@ -1529,7 +1501,8 @@ async def test_iam_permissions( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -1577,7 +1550,6 @@ async def update_finding( This corresponds to the ``finding`` 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. @@ -1611,7 +1583,6 @@ async def update_finding( # If we have keyword arguments corresponding to fields on the # request, apply these. - if finding is not None: request.finding = finding @@ -1659,7 +1630,6 @@ async def update_organization_settings( This corresponds to the ``organization_settings`` 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. @@ -1687,7 +1657,6 @@ async def update_organization_settings( # If we have keyword arguments corresponding to fields on the # request, apply these. - if organization_settings is not None: request.organization_settings = organization_settings @@ -1735,7 +1704,6 @@ async def update_source( This corresponds to the ``source`` 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. @@ -1766,7 +1734,6 @@ async def update_source( # If we have keyword arguments corresponding to fields on the # request, apply these. - if source is not None: request.source = source @@ -1814,7 +1781,6 @@ async def update_security_marks( This corresponds to the ``security_marks`` 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. @@ -1847,7 +1813,6 @@ async def update_security_marks( # If we have keyword arguments corresponding to fields on the # request, apply these. - if security_marks is not None: request.security_marks = security_marks diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/client.py b/google/cloud/securitycenter_v1beta1/services/security_center/client.py index 73dd2f2a..2dca887d 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/client.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/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 @@ -48,11 +46,10 @@ from google.cloud.securitycenter_v1beta1.types import securitycenter_service from google.cloud.securitycenter_v1beta1.types import source from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SecurityCenterGrpcTransport from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport @@ -73,7 +70,7 @@ class SecurityCenterClientMeta(type): _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[SecurityCenterTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -96,7 +93,8 @@ class SecurityCenterClient(metaclass=SecurityCenterClientMeta): @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: @@ -130,7 +128,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. @@ -147,7 +146,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 @@ -166,23 +165,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SecurityCenterTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SecurityCenterTransport: The transport used by the client instance. + SecurityCenterTransport: The transport used by the client + instance. """ return self._transport @staticmethod def asset_path(organization: str, asset: str,) -> str: - """Return a fully-qualified asset string.""" + """Returns a fully-qualified asset string.""" return "organizations/{organization}/assets/{asset}".format( organization=organization, asset=asset, ) @staticmethod def parse_asset_path(path: str) -> Dict[str, str]: - """Parse a asset path into its component segments.""" + """Parses a asset path into its component segments.""" m = re.match( r"^organizations/(?P.+?)/assets/(?P.+?)$", path ) @@ -190,14 +190,14 @@ def parse_asset_path(path: str) -> Dict[str, str]: @staticmethod def finding_path(organization: str, source: str, finding: str,) -> str: - """Return a fully-qualified finding string.""" + """Returns a fully-qualified finding string.""" return "organizations/{organization}/sources/{source}/findings/{finding}".format( organization=organization, source=source, finding=finding, ) @staticmethod def parse_finding_path(path: str) -> Dict[str, str]: - """Parse a finding path into its component segments.""" + """Parses a finding path into its component segments.""" m = re.match( r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path, @@ -206,14 +206,14 @@ def parse_finding_path(path: str) -> Dict[str, str]: @staticmethod def organization_settings_path(organization: str,) -> str: - """Return a fully-qualified organization_settings string.""" + """Returns a fully-qualified organization_settings string.""" return "organizations/{organization}/organizationSettings".format( organization=organization, ) @staticmethod def parse_organization_settings_path(path: str) -> Dict[str, str]: - """Parse a organization_settings path into its component segments.""" + """Parses a organization_settings path into its component segments.""" m = re.match( r"^organizations/(?P.+?)/organizationSettings$", path ) @@ -221,14 +221,14 @@ def parse_organization_settings_path(path: str) -> Dict[str, str]: @staticmethod def security_marks_path(organization: str, asset: str,) -> str: - """Return a fully-qualified security_marks string.""" + """Returns a fully-qualified security_marks string.""" return "organizations/{organization}/assets/{asset}/securityMarks".format( organization=organization, asset=asset, ) @staticmethod def parse_security_marks_path(path: str) -> Dict[str, str]: - """Parse a security_marks path into its component segments.""" + """Parses a security_marks path into its component segments.""" m = re.match( r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path, @@ -237,14 +237,14 @@ def parse_security_marks_path(path: str) -> Dict[str, str]: @staticmethod def source_path(organization: str, source: str,) -> str: - """Return a fully-qualified source string.""" + """Returns a fully-qualified source string.""" return "organizations/{organization}/sources/{source}".format( organization=organization, source=source, ) @staticmethod def parse_source_path(path: str) -> Dict[str, str]: - """Parse a source path into its component segments.""" + """Parses a source path into its component segments.""" m = re.match( r"^organizations/(?P.+?)/sources/(?P.+?)$", path ) @@ -252,7 +252,7 @@ def parse_source_path(path: str) -> Dict[str, str]: @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, ) @@ -265,7 +265,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 @@ -276,7 +276,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 @@ -287,7 +287,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 @@ -298,7 +298,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, ) @@ -312,12 +312,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, SecurityCenterTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the security center client. + """Instantiates the security center client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -372,9 +372,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: @@ -386,12 +387,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. @@ -406,8 +409,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: @@ -453,7 +456,6 @@ def create_source( This corresponds to the ``source`` 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. @@ -486,10 +488,8 @@ def create_source( # there are no flattened fields. if not isinstance(request, securitycenter_service.CreateSourceRequest): request = securitycenter_service.CreateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if source is not None: @@ -555,7 +555,6 @@ def create_finding( This corresponds to the ``finding`` 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. @@ -591,10 +590,8 @@ def create_finding( # there are no flattened fields. if not isinstance(request, securitycenter_service.CreateFindingRequest): request = securitycenter_service.CreateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if finding_id is not None: @@ -620,13 +617,13 @@ def create_finding( def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Gets the access control policy on the specified Source. @@ -643,7 +640,6 @@ def get_iam_policy( This corresponds to the ``resource`` 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. @@ -722,11 +718,10 @@ def get_iam_policy( if isinstance(request, dict): # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. - request = iam_policy.GetIamPolicyRequest(**request) + request = iam_policy_pb2.GetIamPolicyRequest(**request) elif not request: # Null request, just make one. - request = iam_policy.GetIamPolicyRequest() - + request = iam_policy_pb2.GetIamPolicyRequest() if resource is not None: request.resource = resource @@ -769,7 +764,6 @@ def get_organization_settings( 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. @@ -801,10 +795,8 @@ def get_organization_settings( request, securitycenter_service.GetOrganizationSettingsRequest ): request = securitycenter_service.GetOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -849,7 +841,6 @@ def get_source( 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. @@ -882,10 +873,8 @@ def get_source( # there are no flattened fields. if not isinstance(request, securitycenter_service.GetSourceRequest): request = securitycenter_service.GetSourceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -920,7 +909,6 @@ def group_assets( request (google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest): The request object. Request message for grouping by assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -937,7 +925,6 @@ def group_assets( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a securitycenter_service.GroupAssetsRequest. # There's no risk of modifying the input as we've already verified @@ -1014,7 +1001,6 @@ def group_findings( This corresponds to the ``group_by`` 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. @@ -1046,10 +1032,8 @@ def group_findings( # there are no flattened fields. if not isinstance(request, securitycenter_service.GroupFindingsRequest): request = securitycenter_service.GroupFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if group_by is not None: @@ -1090,7 +1074,6 @@ def list_assets( Args: request (google.cloud.securitycenter_v1beta1.types.ListAssetsRequest): The request object. Request message for listing assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1106,7 +1089,6 @@ def list_assets( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a securitycenter_service.ListAssetsRequest. # There's no risk of modifying the input as we've already verified @@ -1154,7 +1136,6 @@ def list_findings( request (google.cloud.securitycenter_v1beta1.types.ListFindingsRequest): The request object. Request message for listing findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1171,7 +1152,6 @@ def list_findings( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a securitycenter_service.ListFindingsRequest. # There's no risk of modifying the input as we've already verified @@ -1223,7 +1203,6 @@ def list_sources( 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. @@ -1254,10 +1233,8 @@ def list_sources( # there are no flattened fields. if not isinstance(request, securitycenter_service.ListSourcesRequest): request = securitycenter_service.ListSourcesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1311,7 +1288,6 @@ def run_asset_discovery( 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. @@ -1353,10 +1329,8 @@ def run_asset_discovery( # there are no flattened fields. if not isinstance(request, securitycenter_service.RunAssetDiscoveryRequest): request = securitycenter_service.RunAssetDiscoveryRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1377,8 +1351,8 @@ def run_asset_discovery( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=empty.Empty, + empty_pb2.Empty, + metadata_type=empty_pb2.Empty, ) # Done; return the response. @@ -1390,7 +1364,7 @@ def set_finding_state( *, name: str = None, state: finding.Finding.State = None, - start_time: timestamp.Timestamp = None, + start_time: timestamp_pb2.Timestamp = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -1425,7 +1399,6 @@ def set_finding_state( This corresponds to the ``start_time`` 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. @@ -1461,10 +1434,8 @@ def set_finding_state( # there are no flattened fields. if not isinstance(request, securitycenter_service.SetFindingStateRequest): request = securitycenter_service.SetFindingStateRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if state is not None: @@ -1490,13 +1461,13 @@ def set_finding_state( def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the access control policy on the specified Source. @@ -1513,7 +1484,6 @@ def set_iam_policy( This corresponds to the ``resource`` 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. @@ -1592,11 +1562,10 @@ def set_iam_policy( if isinstance(request, dict): # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. - request = iam_policy.SetIamPolicyRequest(**request) + request = iam_policy_pb2.SetIamPolicyRequest(**request) elif not request: # Null request, just make one. - request = iam_policy.SetIamPolicyRequest() - + request = iam_policy_pb2.SetIamPolicyRequest() if resource is not None: request.resource = resource @@ -1618,14 +1587,14 @@ def set_iam_policy( def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, resource: str = None, permissions: Sequence[str] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Returns the permissions that a caller has on the specified source. @@ -1651,7 +1620,6 @@ def test_iam_permissions( This corresponds to the ``permissions`` 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. @@ -1675,14 +1643,12 @@ def test_iam_permissions( if isinstance(request, dict): # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. - request = iam_policy.TestIamPermissionsRequest(**request) + request = iam_policy_pb2.TestIamPermissionsRequest(**request) elif not request: # Null request, just make one. - request = iam_policy.TestIamPermissionsRequest() - + request = iam_policy_pb2.TestIamPermissionsRequest() if resource is not None: request.resource = resource - if permissions: request.permissions.extend(permissions) @@ -1730,7 +1696,6 @@ def update_finding( This corresponds to the ``finding`` 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. @@ -1766,10 +1731,8 @@ def update_finding( # there are no flattened fields. if not isinstance(request, securitycenter_service.UpdateFindingRequest): request = securitycenter_service.UpdateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if finding is not None: request.finding = finding @@ -1813,7 +1776,6 @@ def update_organization_settings( This corresponds to the ``organization_settings`` 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. @@ -1845,10 +1807,8 @@ def update_organization_settings( request, securitycenter_service.UpdateOrganizationSettingsRequest ): request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if organization_settings is not None: request.organization_settings = organization_settings @@ -1894,7 +1854,6 @@ def update_source( This corresponds to the ``source`` 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. @@ -1927,10 +1886,8 @@ def update_source( # there are no flattened fields. if not isinstance(request, securitycenter_service.UpdateSourceRequest): request = securitycenter_service.UpdateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if source is not None: request.source = source @@ -1974,7 +1931,6 @@ def update_security_marks( This corresponds to the ``security_marks`` 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. @@ -2009,10 +1965,8 @@ def update_security_marks( # there are no flattened fields. if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): request = securitycenter_service.UpdateSecurityMarksRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if security_marks is not None: request.security_marks = security_marks diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py b/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py index a3a18cc4..dc560fb3 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/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, @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -247,7 +245,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -379,7 +377,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -509,7 +507,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -637,7 +635,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/securitycenter_v1beta1/services/security_center/transports/__init__.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py index 45814553..1a2f356a 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/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/securitycenter_v1beta1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py index 3a22dfc9..9578ef76 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/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,17 +13,18 @@ # 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.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.securitycenter_v1beta1.types import finding from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding @@ -38,10 +38,9 @@ from google.cloud.securitycenter_v1beta1.types import securitycenter_service from google.cloud.securitycenter_v1beta1.types import source from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -52,27 +51,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 SecurityCenterTransport(abc.ABC): """Abstract transport class for SecurityCenter.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "securitycenter.googleapis.com" + def __init__( self, *, - host: str = "securitycenter.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 @@ -81,7 +94,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): @@ -95,29 +108,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 = { @@ -134,7 +194,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -148,7 +209,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -162,7 +224,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -176,7 +239,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -190,7 +254,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -204,7 +269,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -218,7 +284,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -232,7 +299,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -255,7 +323,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -288,38 +357,38 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def create_source( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.CreateSourceRequest], - typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], + Union[gcs_source.Source, Awaitable[gcs_source.Source]], ]: raise NotImplementedError() @property def create_finding( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.CreateFindingRequest], - typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], + Union[gcs_finding.Finding, Awaitable[gcs_finding.Finding]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ - [iam_policy.GetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], ]: raise NotImplementedError() @property def get_organization_settings( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.GetOrganizationSettingsRequest], - typing.Union[ + Union[ organization_settings.OrganizationSettings, - typing.Awaitable[organization_settings.OrganizationSettings], + Awaitable[organization_settings.OrganizationSettings], ], ]: raise NotImplementedError() @@ -327,20 +396,20 @@ def get_organization_settings( @property def get_source( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.GetSourceRequest], - typing.Union[source.Source, typing.Awaitable[source.Source]], + Union[source.Source, Awaitable[source.Source]], ]: raise NotImplementedError() @property def group_assets( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.GroupAssetsRequest], - typing.Union[ + Union[ securitycenter_service.GroupAssetsResponse, - typing.Awaitable[securitycenter_service.GroupAssetsResponse], + Awaitable[securitycenter_service.GroupAssetsResponse], ], ]: raise NotImplementedError() @@ -348,11 +417,11 @@ def group_assets( @property def group_findings( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.GroupFindingsRequest], - typing.Union[ + Union[ securitycenter_service.GroupFindingsResponse, - typing.Awaitable[securitycenter_service.GroupFindingsResponse], + Awaitable[securitycenter_service.GroupFindingsResponse], ], ]: raise NotImplementedError() @@ -360,11 +429,11 @@ def group_findings( @property def list_assets( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.ListAssetsRequest], - typing.Union[ + Union[ securitycenter_service.ListAssetsResponse, - typing.Awaitable[securitycenter_service.ListAssetsResponse], + Awaitable[securitycenter_service.ListAssetsResponse], ], ]: raise NotImplementedError() @@ -372,11 +441,11 @@ def list_assets( @property def list_findings( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.ListFindingsRequest], - typing.Union[ + Union[ securitycenter_service.ListFindingsResponse, - typing.Awaitable[securitycenter_service.ListFindingsResponse], + Awaitable[securitycenter_service.ListFindingsResponse], ], ]: raise NotImplementedError() @@ -384,11 +453,11 @@ def list_findings( @property def list_sources( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.ListSourcesRequest], - typing.Union[ + Union[ securitycenter_service.ListSourcesResponse, - typing.Awaitable[securitycenter_service.ListSourcesResponse], + Awaitable[securitycenter_service.ListSourcesResponse], ], ]: raise NotImplementedError() @@ -396,38 +465,38 @@ def list_sources( @property def run_asset_discovery( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.RunAssetDiscoveryRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def set_finding_state( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.SetFindingStateRequest], - typing.Union[finding.Finding, typing.Awaitable[finding.Finding]], + Union[finding.Finding, Awaitable[finding.Finding]], ]: raise NotImplementedError() @property def set_iam_policy( self, - ) -> typing.Callable[ - [iam_policy.SetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ - [iam_policy.TestIamPermissionsRequest], - typing.Union[ - iam_policy.TestIamPermissionsResponse, - typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], ], ]: raise NotImplementedError() @@ -435,20 +504,20 @@ def test_iam_permissions( @property def update_finding( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.UpdateFindingRequest], - typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], + Union[gcs_finding.Finding, Awaitable[gcs_finding.Finding]], ]: raise NotImplementedError() @property def update_organization_settings( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.UpdateOrganizationSettingsRequest], - typing.Union[ + Union[ gcs_organization_settings.OrganizationSettings, - typing.Awaitable[gcs_organization_settings.OrganizationSettings], + Awaitable[gcs_organization_settings.OrganizationSettings], ], ]: raise NotImplementedError() @@ -456,20 +525,20 @@ def update_organization_settings( @property def update_source( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.UpdateSourceRequest], - typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], + Union[gcs_source.Source, Awaitable[gcs_source.Source]], ]: raise NotImplementedError() @property def update_security_marks( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.UpdateSecurityMarksRequest], - typing.Union[ + Union[ gcs_security_marks.SecurityMarks, - typing.Awaitable[gcs_security_marks.SecurityMarks], + Awaitable[gcs_security_marks.SecurityMarks], ], ]: raise NotImplementedError() diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py index 2bcfb198..045f36a6 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/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,15 +13,14 @@ # 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 operations_v1 # 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 @@ -39,10 +37,9 @@ from google.cloud.securitycenter_v1beta1.types import securitycenter_service from google.cloud.securitycenter_v1beta1.types import source from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO @@ -65,7 +62,7 @@ def __init__( self, *, host: str = "securitycenter.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -79,7 +76,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 @@ -190,7 +188,7 @@ def __init__( def create_channel( cls, host: str = "securitycenter.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, @@ -221,13 +219,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, ) @@ -307,7 +307,7 @@ def create_finding( @property def get_iam_policy( self, - ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: r"""Return a callable for the get iam policy method over gRPC. Gets the access control policy on the specified @@ -326,8 +326,8 @@ def get_iam_policy( if "get_iam_policy" not in self._stubs: self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1beta1.SecurityCenter/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["get_iam_policy"] @@ -545,7 +545,7 @@ def list_sources( def run_asset_discovery( self, ) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], operations.Operation + [securitycenter_service.RunAssetDiscoveryRequest], operations_pb2.Operation ]: r"""Return a callable for the run asset discovery method over gRPC. @@ -570,7 +570,7 @@ def run_asset_discovery( self._stubs["run_asset_discovery"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1beta1.SecurityCenter/RunAssetDiscovery", request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["run_asset_discovery"] @@ -603,7 +603,7 @@ def set_finding_state( @property def set_iam_policy( self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: r"""Return a callable for the set iam policy method over gRPC. Sets the access control policy on the specified @@ -622,8 +622,8 @@ def set_iam_policy( if "set_iam_policy" not in self._stubs: self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1beta1.SecurityCenter/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["set_iam_policy"] @@ -631,7 +631,8 @@ def set_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, ]: r"""Return a callable for the test iam permissions method over gRPC. @@ -651,8 +652,8 @@ def test_iam_permissions( if "test_iam_permissions" not in self._stubs: self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1beta1.SecurityCenter/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, ) return self._stubs["test_iam_permissions"] diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py index f401d887..642115a5 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/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,16 +13,15 @@ # 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.api_core import operations_v1 # 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 @@ -40,10 +38,9 @@ from google.cloud.securitycenter_v1beta1.types import securitycenter_service from google.cloud.securitycenter_v1beta1.types import source from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO from .grpc import SecurityCenterGrpcTransport @@ -68,7 +65,7 @@ class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): def create_channel( cls, host: str = "securitycenter.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, @@ -95,13 +92,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, ) @@ -109,7 +108,7 @@ def __init__( self, *, host: str = "securitycenter.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, @@ -123,7 +122,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 @@ -182,7 +182,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 @@ -317,7 +316,7 @@ def create_finding( @property def get_iam_policy( self, - ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: r"""Return a callable for the get iam policy method over gRPC. Gets the access control policy on the specified @@ -336,8 +335,8 @@ def get_iam_policy( if "get_iam_policy" not in self._stubs: self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1beta1.SecurityCenter/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["get_iam_policy"] @@ -556,7 +555,7 @@ def run_asset_discovery( self, ) -> Callable[ [securitycenter_service.RunAssetDiscoveryRequest], - Awaitable[operations.Operation], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the run asset discovery method over gRPC. @@ -581,7 +580,7 @@ def run_asset_discovery( self._stubs["run_asset_discovery"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1beta1.SecurityCenter/RunAssetDiscovery", request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["run_asset_discovery"] @@ -616,7 +615,7 @@ def set_finding_state( @property def set_iam_policy( self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: r"""Return a callable for the set iam policy method over gRPC. Sets the access control policy on the specified @@ -635,8 +634,8 @@ def set_iam_policy( if "set_iam_policy" not in self._stubs: self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1beta1.SecurityCenter/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["set_iam_policy"] @@ -644,8 +643,8 @@ def set_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], - Awaitable[iam_policy.TestIamPermissionsResponse], + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], ]: r"""Return a callable for the test iam permissions method over gRPC. @@ -665,8 +664,8 @@ def test_iam_permissions( if "test_iam_permissions" not in self._stubs: self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1beta1.SecurityCenter/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, ) return self._stubs["test_iam_permissions"] diff --git a/google/cloud/securitycenter_v1beta1/types/__init__.py b/google/cloud/securitycenter_v1beta1/types/__init__.py index 1f373080..3ae3b744 100644 --- a/google/cloud/securitycenter_v1beta1/types/__init__.py +++ b/google/cloud/securitycenter_v1beta1/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 .asset import Asset from .finding import Finding from .organization_settings import OrganizationSettings diff --git a/google/cloud/securitycenter_v1beta1/types/asset.py b/google/cloud/securitycenter_v1beta1/types/asset.py index 75d676b8..91215e46 100644 --- a/google/cloud/securitycenter_v1beta1/types/asset.py +++ b/google/cloud/securitycenter_v1beta1/types/asset.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.securitycenter_v1beta1.types import ( security_marks as gcs_security_marks, ) -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -97,33 +94,26 @@ class SecurityCenterProperties(proto.Message): Owners of the Google Cloud resource. """ - resource_name = proto.Field(proto.STRING, number=1) - - resource_type = proto.Field(proto.STRING, number=2) - - resource_parent = proto.Field(proto.STRING, number=3) - - resource_project = proto.Field(proto.STRING, number=4) - - resource_owners = proto.RepeatedField(proto.STRING, number=5) - - name = proto.Field(proto.STRING, number=1) + resource_name = proto.Field(proto.STRING, number=1,) + resource_type = proto.Field(proto.STRING, number=2,) + resource_parent = proto.Field(proto.STRING, number=3,) + resource_project = proto.Field(proto.STRING, number=4,) + resource_owners = proto.RepeatedField(proto.STRING, number=5,) + name = proto.Field(proto.STRING, number=1,) security_center_properties = proto.Field( proto.MESSAGE, number=2, message=SecurityCenterProperties, ) - resource_properties = proto.MapField( - proto.STRING, proto.MESSAGE, number=7, message=struct.Value, + proto.STRING, proto.MESSAGE, number=7, message=struct_pb2.Value, ) - security_marks = proto.Field( proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, ) - - create_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) - - update_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) + create_time = proto.Field(proto.MESSAGE, number=9, message=timestamp_pb2.Timestamp,) + update_time = proto.Field( + proto.MESSAGE, number=10, message=timestamp_pb2.Timestamp, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/finding.py b/google/cloud/securitycenter_v1beta1/types/finding.py index 6b48d620..1fc2b420 100644 --- a/google/cloud/securitycenter_v1beta1/types/finding.py +++ b/google/cloud/securitycenter_v1beta1/types/finding.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.securitycenter_v1beta1.types import ( security_marks as gcs_security_marks, ) -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -100,29 +97,22 @@ class State(proto.Enum): ACTIVE = 1 INACTIVE = 2 - name = proto.Field(proto.STRING, number=1) - - parent = proto.Field(proto.STRING, number=2) - - resource_name = proto.Field(proto.STRING, number=3) - + name = proto.Field(proto.STRING, number=1,) + parent = proto.Field(proto.STRING, number=2,) + resource_name = proto.Field(proto.STRING, number=3,) state = proto.Field(proto.ENUM, number=4, enum=State,) - - category = proto.Field(proto.STRING, number=5) - - external_uri = proto.Field(proto.STRING, number=6) - + category = proto.Field(proto.STRING, number=5,) + external_uri = proto.Field(proto.STRING, number=6,) source_properties = proto.MapField( - proto.STRING, proto.MESSAGE, number=7, message=struct.Value, + proto.STRING, proto.MESSAGE, number=7, message=struct_pb2.Value, ) - security_marks = proto.Field( proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, ) - - event_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) - - create_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) + event_time = proto.Field(proto.MESSAGE, number=9, message=timestamp_pb2.Timestamp,) + create_time = proto.Field( + proto.MESSAGE, number=10, message=timestamp_pb2.Timestamp, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/organization_settings.py b/google/cloud/securitycenter_v1beta1/types/organization_settings.py index f8a2a563..d76fe161 100644 --- a/google/cloud/securitycenter_v1beta1/types/organization_settings.py +++ b/google/cloud/securitycenter_v1beta1/types/organization_settings.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 @@ -45,7 +43,6 @@ class OrganizationSettings(proto.Message): class AssetDiscoveryConfig(proto.Message): r"""The configuration used for Asset Discovery runs. - Attributes: project_ids (Sequence[str]): The project ids to use for filtering asset @@ -69,18 +66,15 @@ class InclusionMode(proto.Enum): INCLUDE_ONLY = 1 EXCLUDE = 2 - project_ids = proto.RepeatedField(proto.STRING, number=1) - + project_ids = proto.RepeatedField(proto.STRING, number=1,) inclusion_mode = proto.Field( proto.ENUM, number=2, enum="OrganizationSettings.AssetDiscoveryConfig.InclusionMode", ) - name = proto.Field(proto.STRING, number=1) - - enable_asset_discovery = proto.Field(proto.BOOL, number=2) - + name = proto.Field(proto.STRING, number=1,) + enable_asset_discovery = proto.Field(proto.BOOL, number=2,) asset_discovery_config = proto.Field( proto.MESSAGE, number=3, message=AssetDiscoveryConfig, ) diff --git a/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py b/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py index 5d444d6b..3e78a7ad 100644 --- a/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py +++ b/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import duration_pb2 as gp_duration # type: ignore +from google.protobuf import duration_pb2 # type: ignore __protobuf__ = proto.module( @@ -29,7 +26,6 @@ class RunAssetDiscoveryResponse(proto.Message): r"""Response of asset discovery run - Attributes: state (google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryResponse.State): The state of an asset discovery run. @@ -46,8 +42,7 @@ class State(proto.Enum): TERMINATED = 3 state = proto.Field(proto.ENUM, number=1, enum=State,) - - duration = proto.Field(proto.MESSAGE, number=2, message=gp_duration.Duration,) + duration = proto.Field(proto.MESSAGE, number=2, message=duration_pb2.Duration,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/security_marks.py b/google/cloud/securitycenter_v1beta1/types/security_marks.py index fa5b1795..f0ebfb01 100644 --- a/google/cloud/securitycenter_v1beta1/types/security_marks.py +++ b/google/cloud/securitycenter_v1beta1/types/security_marks.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 @@ -49,9 +47,8 @@ class SecurityMarks(proto.Message): (inclusive) """ - name = proto.Field(proto.STRING, number=1) - - marks = proto.MapField(proto.STRING, proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + marks = proto.MapField(proto.STRING, proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py b/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py index dec898c5..d942e4bc 100644 --- a/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py +++ b/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.securitycenter_v1beta1.types import asset as gcs_asset from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding from google.cloud.securitycenter_v1beta1.types import ( @@ -27,10 +24,10 @@ security_marks as gcs_security_marks, ) from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as gp_field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -63,7 +60,6 @@ class CreateFindingRequest(proto.Message): r"""Request message for creating a finding. - Attributes: parent (str): Required. Resource name of the new finding's parent. Its @@ -81,16 +77,13 @@ class CreateFindingRequest(proto.Message): fields on this resource. """ - parent = proto.Field(proto.STRING, number=1) - - finding_id = proto.Field(proto.STRING, number=2) - + parent = proto.Field(proto.STRING, number=1,) + finding_id = proto.Field(proto.STRING, number=2,) finding = proto.Field(proto.MESSAGE, number=3, message=gcs_finding.Finding,) class CreateSourceRequest(proto.Message): r"""Request message for creating a source. - Attributes: parent (str): Required. Resource name of the new source's parent. Its @@ -101,14 +94,12 @@ class CreateSourceRequest(proto.Message): ignored. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) source = proto.Field(proto.MESSAGE, number=2, message=gcs_source.Source,) class GetOrganizationSettingsRequest(proto.Message): r"""Request message for getting organization settings. - Attributes: name (str): Required. Name of the organization to get organization @@ -116,24 +107,22 @@ class GetOrganizationSettingsRequest(proto.Message): "organizations/[organization_id]/organizationSettings". """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class GetSourceRequest(proto.Message): r"""Request message for getting a source. - Attributes: name (str): Required. Relative resource name of the source. Its format is "organizations/[organization_id]/source/[source_id]". """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class GroupAssetsRequest(proto.Message): r"""Request message for grouping by assets. - Attributes: parent (str): Required. Name of the organization to groupBy. Its format is @@ -229,24 +218,19 @@ class GroupAssetsRequest(proto.Message): maximum is 1000. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - group_by = proto.Field(proto.STRING, number=3) - - compare_duration = proto.Field(proto.MESSAGE, number=4, message=duration.Duration,) - - read_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - - page_token = proto.Field(proto.STRING, number=7) - - page_size = proto.Field(proto.INT32, number=8) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + group_by = proto.Field(proto.STRING, number=3,) + compare_duration = proto.Field( + proto.MESSAGE, number=4, message=duration_pb2.Duration, + ) + read_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + page_token = proto.Field(proto.STRING, number=7,) + page_size = proto.Field(proto.INT32, number=8,) class GroupAssetsResponse(proto.Message): r"""Response message for grouping by assets. - Attributes: group_by_results (Sequence[google.cloud.securitycenter_v1beta1.types.GroupResult]): Group results. There exists an element for @@ -268,15 +252,12 @@ def raw_page(self): group_by_results = proto.RepeatedField( proto.MESSAGE, number=1, message="GroupResult", ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + next_page_token = proto.Field(proto.STRING, number=3,) class GroupFindingsRequest(proto.Message): r"""Request message for grouping by findings. - Attributes: parent (str): Required. Name of the source to groupBy. Its format is @@ -341,22 +322,16 @@ class GroupFindingsRequest(proto.Message): maximum is 1000. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - group_by = proto.Field(proto.STRING, number=3) - - read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - page_token = proto.Field(proto.STRING, number=5) - - page_size = proto.Field(proto.INT32, number=6) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + group_by = proto.Field(proto.STRING, number=3,) + read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + page_token = proto.Field(proto.STRING, number=5,) + page_size = proto.Field(proto.INT32, number=6,) class GroupFindingsResponse(proto.Message): r"""Response message for group by findings. - Attributes: group_by_results (Sequence[google.cloud.securitycenter_v1beta1.types.GroupResult]): Group results. There exists an element for @@ -378,10 +353,8 @@ def raw_page(self): group_by_results = proto.RepeatedField( proto.MESSAGE, number=1, message="GroupResult", ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + next_page_token = proto.Field(proto.STRING, number=3,) class GroupResult(proto.Message): @@ -398,15 +371,13 @@ class GroupResult(proto.Message): """ properties = proto.MapField( - proto.STRING, proto.MESSAGE, number=1, message=struct.Value, + proto.STRING, proto.MESSAGE, number=1, message=struct_pb2.Value, ) - - count = proto.Field(proto.INT64, number=2) + count = proto.Field(proto.INT64, number=2,) class ListSourcesRequest(proto.Message): r"""Request message for listing sources. - Attributes: parent (str): Required. Resource name of the parent of sources to list. @@ -422,16 +393,13 @@ class ListSourcesRequest(proto.Message): maximum is 1000. """ - parent = proto.Field(proto.STRING, number=1) - - page_token = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=7) + parent = proto.Field(proto.STRING, number=1,) + page_token = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=7,) class ListSourcesResponse(proto.Message): r"""Response message for listing sources. - Attributes: sources (Sequence[google.cloud.securitycenter_v1beta1.types.Source]): Sources belonging to the requested parent. @@ -445,13 +413,11 @@ def raw_page(self): return self sources = proto.RepeatedField(proto.MESSAGE, number=1, message=gcs_source.Source,) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class ListAssetsRequest(proto.Message): r"""Request message for listing assets. - Attributes: parent (str): Required. Name of the organization assets should belong to. @@ -547,26 +513,20 @@ class ListAssetsRequest(proto.Message): maximum is 1000. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - order_by = proto.Field(proto.STRING, number=3) - - read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) - - field_mask = proto.Field(proto.MESSAGE, number=7, message=gp_field_mask.FieldMask,) - - page_token = proto.Field(proto.STRING, number=8) - - page_size = proto.Field(proto.INT32, number=9) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + order_by = proto.Field(proto.STRING, number=3,) + read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + compare_duration = proto.Field( + proto.MESSAGE, number=5, message=duration_pb2.Duration, + ) + field_mask = proto.Field(proto.MESSAGE, number=7, message=field_mask_pb2.FieldMask,) + page_token = proto.Field(proto.STRING, number=8,) + page_size = proto.Field(proto.INT32, number=9,) class ListAssetsResponse(proto.Message): r"""Response message for listing assets. - Attributes: list_assets_results (Sequence[google.cloud.securitycenter_v1beta1.types.ListAssetsResponse.ListAssetsResult]): Assets matching the list request. @@ -582,7 +542,6 @@ class ListAssetsResponse(proto.Message): class ListAssetsResult(proto.Message): r"""Result containing the Asset and its State. - Attributes: asset (google.cloud.securitycenter_v1beta1.types.Asset): Asset matching the search request. @@ -604,7 +563,6 @@ class State(proto.Enum): ACTIVE = 4 asset = proto.Field(proto.MESSAGE, number=1, message=gcs_asset.Asset,) - state = proto.Field( proto.ENUM, number=2, enum="ListAssetsResponse.ListAssetsResult.State", ) @@ -616,17 +574,13 @@ def raw_page(self): list_assets_results = proto.RepeatedField( proto.MESSAGE, number=1, message=ListAssetsResult, ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - total_size = proto.Field(proto.INT32, number=4) + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + next_page_token = proto.Field(proto.STRING, number=3,) + total_size = proto.Field(proto.INT32, number=4,) class ListFindingsRequest(proto.Message): r"""Request message for listing findings. - Attributes: parent (str): Required. Name of the source the findings belong to. Its @@ -695,24 +649,17 @@ class ListFindingsRequest(proto.Message): maximum is 1000. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - order_by = proto.Field(proto.STRING, number=3) - - read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - field_mask = proto.Field(proto.MESSAGE, number=5, message=gp_field_mask.FieldMask,) - - page_token = proto.Field(proto.STRING, number=6) - - page_size = proto.Field(proto.INT32, number=7) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + order_by = proto.Field(proto.STRING, number=3,) + read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + field_mask = proto.Field(proto.MESSAGE, number=5, message=field_mask_pb2.FieldMask,) + page_token = proto.Field(proto.STRING, number=6,) + page_size = proto.Field(proto.INT32, number=7,) class ListFindingsResponse(proto.Message): r"""Response message for listing findings. - Attributes: findings (Sequence[google.cloud.securitycenter_v1beta1.types.Finding]): Findings matching the list request. @@ -733,17 +680,13 @@ def raw_page(self): findings = proto.RepeatedField( proto.MESSAGE, number=1, message=gcs_finding.Finding, ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - total_size = proto.Field(proto.INT32, number=4) + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + next_page_token = proto.Field(proto.STRING, number=3,) + total_size = proto.Field(proto.INT32, number=4,) class SetFindingStateRequest(proto.Message): r"""Request message for updating a finding's state. - Attributes: name (str): Required. The relative resource name of the finding. See: @@ -757,11 +700,9 @@ class SetFindingStateRequest(proto.Message): takes effect. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) state = proto.Field(proto.ENUM, number=2, enum=gcs_finding.Finding.State,) - - start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) class RunAssetDiscoveryRequest(proto.Message): @@ -774,12 +715,11 @@ class RunAssetDiscoveryRequest(proto.Message): for. Its format is "organizations/[organization_id]". """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) class UpdateFindingRequest(proto.Message): r"""Request message for updating or creating a finding. - Attributes: finding (google.cloud.securitycenter_v1beta1.types.Finding): Required. The finding resource to update or create if it @@ -796,13 +736,13 @@ class UpdateFindingRequest(proto.Message): """ finding = proto.Field(proto.MESSAGE, number=1, message=gcs_finding.Finding,) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class UpdateOrganizationSettingsRequest(proto.Message): r"""Request message for updating an organization's settings. - Attributes: organization_settings (google.cloud.securitycenter_v1beta1.types.OrganizationSettings): Required. The organization settings resource @@ -815,13 +755,13 @@ class UpdateOrganizationSettingsRequest(proto.Message): organization_settings = proto.Field( proto.MESSAGE, number=1, message=gcs_organization_settings.OrganizationSettings, ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class UpdateSourceRequest(proto.Message): r"""Request message for updating a source. - Attributes: source (google.cloud.securitycenter_v1beta1.types.Source): Required. The source resource to update. @@ -831,13 +771,13 @@ class UpdateSourceRequest(proto.Message): """ source = proto.Field(proto.MESSAGE, number=1, message=gcs_source.Source,) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class UpdateSecurityMarksRequest(proto.Message): r"""Request message for updating a SecurityMarks resource. - Attributes: security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): Required. The security marks resource to @@ -853,10 +793,10 @@ class UpdateSecurityMarksRequest(proto.Message): security_marks = proto.Field( proto.MESSAGE, number=1, message=gcs_security_marks.SecurityMarks, ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) - - start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) + start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/source.py b/google/cloud/securitycenter_v1beta1/types/source.py index 2546454f..89eb17a4 100644 --- a/google/cloud/securitycenter_v1beta1/types/source.py +++ b/google/cloud/securitycenter_v1beta1/types/source.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 @@ -54,11 +52,9 @@ class Source(proto.Message): outdated/insecure libraries.". """ - 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,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/__init__.py b/google/cloud/securitycenter_v1p1beta1/__init__.py index 27c3ed04..9c8fa408 100644 --- a/google/cloud/securitycenter_v1p1beta1/__init__.py +++ b/google/cloud/securitycenter_v1p1beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,8 +15,11 @@ # from .services.security_center import SecurityCenterClient +from .services.security_center import SecurityCenterAsyncClient + from .types.asset import Asset from .types.finding import Finding +from .types.folder import Folder from .types.notification_config import NotificationConfig from .types.notification_message import NotificationMessage from .types.organization_settings import OrganizationSettings @@ -53,14 +55,15 @@ from .types.securitycenter_service import UpdateSourceRequest from .types.source import Source - __all__ = ( + "SecurityCenterAsyncClient", "Asset", "CreateFindingRequest", "CreateNotificationConfigRequest", "CreateSourceRequest", "DeleteNotificationConfigRequest", "Finding", + "Folder", "GetNotificationConfigRequest", "GetOrganizationSettingsRequest", "GetSourceRequest", @@ -83,6 +86,7 @@ "Resource", "RunAssetDiscoveryRequest", "RunAssetDiscoveryResponse", + "SecurityCenterClient", "SecurityMarks", "SetFindingStateRequest", "Source", @@ -91,5 +95,4 @@ "UpdateOrganizationSettingsRequest", "UpdateSecurityMarksRequest", "UpdateSourceRequest", - "SecurityCenterClient", ) diff --git a/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json b/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json new file mode 100644 index 00000000..734457b5 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json @@ -0,0 +1,253 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.securitycenter_v1p1beta1", + "protoPackage": "google.cloud.securitycenter.v1p1beta1", + "schema": "1.0", + "services": { + "SecurityCenter": { + "clients": { + "grpc": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecurityCenterAsyncClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/securitycenter_v1p1beta1/services/__init__.py b/google/cloud/securitycenter_v1p1beta1/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/__init__.py +++ b/google/cloud/securitycenter_v1p1beta1/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/securitycenter_v1p1beta1/services/security_center/__init__.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py index 6250349b..b56953c3 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/__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 SecurityCenterClient from .async_client import SecurityCenterAsyncClient diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py index ac8719ec..6aa30766 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/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,10 +20,10 @@ 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.api_core import operation # type: ignore @@ -49,12 +47,11 @@ from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service from google.cloud.securitycenter_v1p1beta1.types import source from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport from .client import SecurityCenterClient @@ -92,31 +89,26 @@ class SecurityCenterAsyncClient: parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) topic_path = staticmethod(SecurityCenterClient.topic_path) parse_topic_path = staticmethod(SecurityCenterClient.parse_topic_path) - common_billing_account_path = staticmethod( SecurityCenterClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( SecurityCenterClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) parse_common_folder_path = staticmethod( SecurityCenterClient.parse_common_folder_path ) - common_organization_path = staticmethod( SecurityCenterClient.common_organization_path ) parse_common_organization_path = staticmethod( SecurityCenterClient.parse_common_organization_path ) - common_project_path = staticmethod(SecurityCenterClient.common_project_path) parse_common_project_path = staticmethod( SecurityCenterClient.parse_common_project_path ) - common_location_path = staticmethod(SecurityCenterClient.common_location_path) parse_common_location_path = staticmethod( SecurityCenterClient.parse_common_location_path @@ -124,7 +116,8 @@ class SecurityCenterAsyncClient: @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. @@ -139,7 +132,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 @@ -156,7 +149,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SecurityCenterTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: SecurityCenterTransport: The transport used by the client instance. @@ -170,12 +163,12 @@ def transport(self) -> SecurityCenterTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, SecurityCenterTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the security center client. + """Instantiates the security center client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -207,7 +200,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SecurityCenterClient( credentials=credentials, transport=transport, @@ -246,7 +238,6 @@ async def create_source( This corresponds to the ``source`` 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. @@ -277,7 +268,6 @@ async def create_source( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if source is not None: @@ -344,7 +334,6 @@ async def create_finding( This corresponds to the ``finding`` 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. @@ -378,7 +367,6 @@ async def create_finding( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if finding_id is not None: @@ -449,7 +437,6 @@ async def create_notification_config( This corresponds to the ``notification_config`` 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. @@ -481,7 +468,6 @@ async def create_notification_config( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if config_id is not None: @@ -532,7 +518,6 @@ async def delete_notification_config( 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. @@ -553,7 +538,6 @@ async def delete_notification_config( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -578,13 +562,13 @@ async def delete_notification_config( async def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Gets the access control policy on the specified Source. @@ -601,7 +585,6 @@ async def get_iam_policy( This corresponds to the ``resource`` 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. @@ -680,10 +663,9 @@ async def get_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) - + request = iam_policy_pb2.GetIamPolicyRequest(**request) elif not request: - request = iam_policy.GetIamPolicyRequest(resource=resource,) + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -694,7 +676,8 @@ async def get_iam_policy( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -737,7 +720,6 @@ async def get_notification_config( 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. @@ -769,7 +751,6 @@ async def get_notification_config( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -782,7 +763,8 @@ async def get_notification_config( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -825,7 +807,6 @@ async def get_organization_settings( 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. @@ -853,7 +834,6 @@ async def get_organization_settings( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -866,7 +846,8 @@ async def get_organization_settings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -909,7 +890,6 @@ async def get_source( 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. @@ -940,7 +920,6 @@ async def get_source( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -953,7 +932,8 @@ async def get_source( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -988,7 +968,6 @@ async def group_assets( request (:class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest`): The request object. Request message for grouping by assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1005,7 +984,6 @@ async def group_assets( """ # Create or coerce a protobuf request object. - request = securitycenter_service.GroupAssetsRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -1017,7 +995,8 @@ async def group_assets( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -1057,8 +1036,9 @@ async def group_findings( their specified properties. To group across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings Args: request (:class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest`): @@ -1066,10 +1046,13 @@ async def group_findings( findings. parent (:class:`str`): Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". - To groupBy across all sources provide a source_id of - ``-``. For example: - organizations/{organization_id}/sources/- + "organizations/[organization_id]/sources/[source_id]", + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]. To groupBy + across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/-, or + projects/{project_id}/sources/- This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1096,7 +1079,6 @@ async def group_findings( This corresponds to the ``group_by`` 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. @@ -1126,7 +1108,6 @@ async def group_findings( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if group_by is not None: @@ -1141,7 +1122,8 @@ async def group_findings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -1183,12 +1165,12 @@ async def list_assets( The request object. Request message for listing assets. parent (:class:`str`): Required. Name of the organization assets should belong - to. Its format is "organizations/[organization_id]". + to. Its format is "organizations/[organization_id], + folders/[folder_id], or projects/[project_id]". 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. @@ -1217,7 +1199,6 @@ async def list_assets( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1230,7 +1211,8 @@ async def list_assets( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -1278,14 +1260,17 @@ async def list_findings( parent (:class:`str`): Required. Name of the source the findings belong to. Its format is - "organizations/[organization_id]/sources/[source_id]". - To list across all sources provide a source_id of ``-``. - For example: organizations/{organization_id}/sources/- + "organizations/[organization_id]/sources/[source_id], + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]". To list + across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/- or + projects/{projects_id}/sources/- 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. @@ -1315,7 +1300,6 @@ async def list_findings( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1328,7 +1312,8 @@ async def list_findings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -1377,7 +1362,6 @@ async def list_notification_configs( 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. @@ -1407,7 +1391,6 @@ async def list_notification_configs( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1420,7 +1403,8 @@ async def list_notification_configs( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -1463,12 +1447,12 @@ async def list_sources( parent (:class:`str`): Required. Resource name of the parent of sources to list. Its format should be - "organizations/[organization_id]". + "organizations/[organization_id], folders/[folder_id], + or projects/[project_id]". 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. @@ -1497,7 +1481,6 @@ async def list_sources( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1510,7 +1493,8 @@ async def list_sources( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -1564,7 +1548,6 @@ async def run_asset_discovery( 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. @@ -1594,7 +1577,6 @@ async def run_asset_discovery( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1620,7 +1602,7 @@ async def run_asset_discovery( response, self._client._transport.operations_client, run_asset_discovery_response.RunAssetDiscoveryResponse, - metadata_type=empty.Empty, + metadata_type=empty_pb2.Empty, ) # Done; return the response. @@ -1632,7 +1614,7 @@ async def set_finding_state( *, name: str = None, state: finding.Finding.State = None, - start_time: timestamp.Timestamp = None, + start_time: timestamp_pb2.Timestamp = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -1667,7 +1649,6 @@ async def set_finding_state( This corresponds to the ``start_time`` 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. @@ -1701,7 +1682,6 @@ async def set_finding_state( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if state is not None: @@ -1731,13 +1711,13 @@ async def set_finding_state( async def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the access control policy on the specified Source. @@ -1754,7 +1734,6 @@ async def set_iam_policy( This corresponds to the ``resource`` 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. @@ -1833,10 +1812,9 @@ async def set_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) - + request = iam_policy_pb2.SetIamPolicyRequest(**request) elif not request: - request = iam_policy.SetIamPolicyRequest(resource=resource,) + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1860,14 +1838,14 @@ async def set_iam_policy( async def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, resource: str = None, permissions: Sequence[str] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Returns the permissions that a caller has on the specified source. @@ -1893,7 +1871,6 @@ async def test_iam_permissions( This corresponds to the ``permissions`` 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. @@ -1917,10 +1894,9 @@ async def test_iam_permissions( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) - + request = iam_policy_pb2.TestIamPermissionsRequest(**request) elif not request: - request = iam_policy.TestIamPermissionsRequest( + request = iam_policy_pb2.TestIamPermissionsRequest( resource=resource, permissions=permissions, ) @@ -1933,7 +1909,8 @@ async def test_iam_permissions( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -1958,7 +1935,7 @@ async def update_finding( request: securitycenter_service.UpdateFindingRequest = None, *, finding: gcs_finding.Finding = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -1996,7 +1973,6 @@ async def update_finding( This corresponds to the ``update_mask`` 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. @@ -2030,7 +2006,6 @@ async def update_finding( # If we have keyword arguments corresponding to fields on the # request, apply these. - if finding is not None: request.finding = finding if update_mask is not None: @@ -2063,7 +2038,7 @@ async def update_notification_config( request: securitycenter_service.UpdateNotificationConfigRequest = None, *, notification_config: gcs_notification_config.NotificationConfig = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -2091,7 +2066,6 @@ async def update_notification_config( This corresponds to the ``update_mask`` 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. @@ -2123,7 +2097,6 @@ async def update_notification_config( # If we have keyword arguments corresponding to fields on the # request, apply these. - if notification_config is not None: request.notification_config = notification_config if update_mask is not None: @@ -2173,7 +2146,6 @@ async def update_organization_settings( This corresponds to the ``organization_settings`` 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. @@ -2201,7 +2173,6 @@ async def update_organization_settings( # If we have keyword arguments corresponding to fields on the # request, apply these. - if organization_settings is not None: request.organization_settings = organization_settings @@ -2232,7 +2203,7 @@ async def update_source( request: securitycenter_service.UpdateSourceRequest = None, *, source: gcs_source.Source = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -2259,7 +2230,6 @@ async def update_source( This corresponds to the ``update_mask`` 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. @@ -2290,7 +2260,6 @@ async def update_source( # If we have keyword arguments corresponding to fields on the # request, apply these. - if source is not None: request.source = source if update_mask is not None: @@ -2323,7 +2292,7 @@ async def update_security_marks( request: securitycenter_service.UpdateSecurityMarksRequest = None, *, security_marks: gcs_security_marks.SecurityMarks = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -2353,7 +2322,6 @@ async def update_security_marks( This corresponds to the ``update_mask`` 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. @@ -2386,7 +2354,6 @@ async def update_security_marks( # If we have keyword arguments corresponding to fields on the # request, apply these. - if security_marks is not None: request.security_marks = security_marks if update_mask is not None: diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py index bbee6898..9604557d 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/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 @@ -53,12 +51,11 @@ from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service from google.cloud.securitycenter_v1p1beta1.types import source from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SecurityCenterGrpcTransport from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport @@ -79,7 +76,7 @@ class SecurityCenterClientMeta(type): _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[SecurityCenterTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -102,7 +99,8 @@ class SecurityCenterClient(metaclass=SecurityCenterClientMeta): @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: @@ -136,7 +134,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. @@ -153,7 +152,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 @@ -172,23 +171,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SecurityCenterTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SecurityCenterTransport: The transport used by the client instance. + SecurityCenterTransport: The transport used by the client + instance. """ return self._transport @staticmethod def asset_path(organization: str, asset: str,) -> str: - """Return a fully-qualified asset string.""" + """Returns a fully-qualified asset string.""" return "organizations/{organization}/assets/{asset}".format( organization=organization, asset=asset, ) @staticmethod def parse_asset_path(path: str) -> Dict[str, str]: - """Parse a asset path into its component segments.""" + """Parses a asset path into its component segments.""" m = re.match( r"^organizations/(?P.+?)/assets/(?P.+?)$", path ) @@ -196,14 +196,14 @@ def parse_asset_path(path: str) -> Dict[str, str]: @staticmethod def finding_path(organization: str, source: str, finding: str,) -> str: - """Return a fully-qualified finding string.""" + """Returns a fully-qualified finding string.""" return "organizations/{organization}/sources/{source}/findings/{finding}".format( organization=organization, source=source, finding=finding, ) @staticmethod def parse_finding_path(path: str) -> Dict[str, str]: - """Parse a finding path into its component segments.""" + """Parses a finding path into its component segments.""" m = re.match( r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path, @@ -212,14 +212,14 @@ def parse_finding_path(path: str) -> Dict[str, str]: @staticmethod def notification_config_path(organization: str, notification_config: str,) -> str: - """Return a fully-qualified notification_config string.""" + """Returns a fully-qualified notification_config string.""" return "organizations/{organization}/notificationConfigs/{notification_config}".format( organization=organization, notification_config=notification_config, ) @staticmethod def parse_notification_config_path(path: str) -> Dict[str, str]: - """Parse a notification_config path into its component segments.""" + """Parses a notification_config path into its component segments.""" m = re.match( r"^organizations/(?P.+?)/notificationConfigs/(?P.+?)$", path, @@ -228,14 +228,14 @@ def parse_notification_config_path(path: str) -> Dict[str, str]: @staticmethod def organization_settings_path(organization: str,) -> str: - """Return a fully-qualified organization_settings string.""" + """Returns a fully-qualified organization_settings string.""" return "organizations/{organization}/organizationSettings".format( organization=organization, ) @staticmethod def parse_organization_settings_path(path: str) -> Dict[str, str]: - """Parse a organization_settings path into its component segments.""" + """Parses a organization_settings path into its component segments.""" m = re.match( r"^organizations/(?P.+?)/organizationSettings$", path ) @@ -243,14 +243,14 @@ def parse_organization_settings_path(path: str) -> Dict[str, str]: @staticmethod def security_marks_path(organization: str, asset: str,) -> str: - """Return a fully-qualified security_marks string.""" + """Returns a fully-qualified security_marks string.""" return "organizations/{organization}/assets/{asset}/securityMarks".format( organization=organization, asset=asset, ) @staticmethod def parse_security_marks_path(path: str) -> Dict[str, str]: - """Parse a security_marks path into its component segments.""" + """Parses a security_marks path into its component segments.""" m = re.match( r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path, @@ -259,14 +259,14 @@ def parse_security_marks_path(path: str) -> Dict[str, str]: @staticmethod def source_path(organization: str, source: str,) -> str: - """Return a fully-qualified source string.""" + """Returns a fully-qualified source string.""" return "organizations/{organization}/sources/{source}".format( organization=organization, source=source, ) @staticmethod def parse_source_path(path: str) -> Dict[str, str]: - """Parse a source path into its component segments.""" + """Parses a source path into its component segments.""" m = re.match( r"^organizations/(?P.+?)/sources/(?P.+?)$", path ) @@ -274,18 +274,18 @@ def parse_source_path(path: str) -> Dict[str, str]: @staticmethod def topic_path(project: str, topic: str,) -> str: - """Return a fully-qualified topic string.""" + """Returns a fully-qualified topic string.""" return "projects/{project}/topics/{topic}".format(project=project, topic=topic,) @staticmethod def parse_topic_path(path: str) -> Dict[str, str]: - """Parse a topic path into its component segments.""" + """Parses a topic path into its component segments.""" m = re.match(r"^projects/(?P.+?)/topics/(?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, ) @@ -298,7 +298,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 @@ -309,7 +309,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 @@ -320,7 +320,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 @@ -331,7 +331,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, ) @@ -345,12 +345,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, SecurityCenterTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the security center client. + """Instantiates the security center client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -405,9 +405,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: @@ -419,12 +420,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. @@ -439,8 +442,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: @@ -486,7 +489,6 @@ def create_source( This corresponds to the ``source`` 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. @@ -519,10 +521,8 @@ def create_source( # there are no flattened fields. if not isinstance(request, securitycenter_service.CreateSourceRequest): request = securitycenter_service.CreateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if source is not None: @@ -585,7 +585,6 @@ def create_finding( This corresponds to the ``finding`` 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. @@ -621,10 +620,8 @@ def create_finding( # there are no flattened fields. if not isinstance(request, securitycenter_service.CreateFindingRequest): request = securitycenter_service.CreateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if finding_id is not None: @@ -691,7 +688,6 @@ def create_notification_config( This corresponds to the ``notification_config`` 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. @@ -727,10 +723,8 @@ def create_notification_config( request, securitycenter_service.CreateNotificationConfigRequest ): request = securitycenter_service.CreateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if config_id is not None: @@ -779,7 +773,6 @@ def delete_notification_config( 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. @@ -804,10 +797,8 @@ def delete_notification_config( request, securitycenter_service.DeleteNotificationConfigRequest ): request = securitycenter_service.DeleteNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -830,13 +821,13 @@ def delete_notification_config( def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Gets the access control policy on the specified Source. @@ -853,7 +844,6 @@ def get_iam_policy( This corresponds to the ``resource`` 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. @@ -932,11 +922,10 @@ def get_iam_policy( if isinstance(request, dict): # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. - request = iam_policy.GetIamPolicyRequest(**request) + request = iam_policy_pb2.GetIamPolicyRequest(**request) elif not request: # Null request, just make one. - request = iam_policy.GetIamPolicyRequest() - + request = iam_policy_pb2.GetIamPolicyRequest() if resource is not None: request.resource = resource @@ -979,7 +968,6 @@ def get_notification_config( 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. @@ -1013,10 +1001,8 @@ def get_notification_config( # there are no flattened fields. if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): request = securitycenter_service.GetNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1059,7 +1045,6 @@ def get_organization_settings( 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. @@ -1091,10 +1076,8 @@ def get_organization_settings( request, securitycenter_service.GetOrganizationSettingsRequest ): request = securitycenter_service.GetOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1139,7 +1122,6 @@ def get_source( 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. @@ -1172,10 +1154,8 @@ def get_source( # there are no flattened fields. if not isinstance(request, securitycenter_service.GetSourceRequest): request = securitycenter_service.GetSourceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1210,7 +1190,6 @@ def group_assets( request (google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest): The request object. Request message for grouping by assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1227,7 +1206,6 @@ def group_assets( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a securitycenter_service.GroupAssetsRequest. # There's no risk of modifying the input as we've already verified @@ -1271,8 +1249,9 @@ def group_findings( their specified properties. To group across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings Args: request (google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest): @@ -1280,10 +1259,13 @@ def group_findings( findings. parent (str): Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". - To groupBy across all sources provide a source_id of - ``-``. For example: - organizations/{organization_id}/sources/- + "organizations/[organization_id]/sources/[source_id]", + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]. To groupBy + across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/-, or + projects/{project_id}/sources/- This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1310,7 +1292,6 @@ def group_findings( This corresponds to the ``group_by`` 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. @@ -1342,10 +1323,8 @@ def group_findings( # there are no flattened fields. if not isinstance(request, securitycenter_service.GroupFindingsRequest): request = securitycenter_service.GroupFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if group_by is not None: @@ -1389,12 +1368,12 @@ def list_assets( The request object. Request message for listing assets. parent (str): Required. Name of the organization assets should belong - to. Its format is "organizations/[organization_id]". + to. Its format is "organizations/[organization_id], + folders/[folder_id], or projects/[project_id]". 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. @@ -1425,10 +1404,8 @@ def list_assets( # there are no flattened fields. if not isinstance(request, securitycenter_service.ListAssetsRequest): request = securitycenter_service.ListAssetsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1476,14 +1453,17 @@ def list_findings( parent (str): Required. Name of the source the findings belong to. Its format is - "organizations/[organization_id]/sources/[source_id]". - To list across all sources provide a source_id of ``-``. - For example: organizations/{organization_id}/sources/- + "organizations/[organization_id]/sources/[source_id], + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]". To list + across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/- or + projects/{projects_id}/sources/- 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. @@ -1515,10 +1495,8 @@ def list_findings( # there are no flattened fields. if not isinstance(request, securitycenter_service.ListFindingsRequest): request = securitycenter_service.ListFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1567,7 +1545,6 @@ def list_notification_configs( 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. @@ -1601,10 +1578,8 @@ def list_notification_configs( request, securitycenter_service.ListNotificationConfigsRequest ): request = securitycenter_service.ListNotificationConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1649,12 +1624,12 @@ def list_sources( parent (str): Required. Resource name of the parent of sources to list. Its format should be - "organizations/[organization_id]". + "organizations/[organization_id], folders/[folder_id], + or projects/[project_id]". 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. @@ -1685,10 +1660,8 @@ def list_sources( # there are no flattened fields. if not isinstance(request, securitycenter_service.ListSourcesRequest): request = securitycenter_service.ListSourcesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1742,7 +1715,6 @@ def run_asset_discovery( 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. @@ -1774,10 +1746,8 @@ def run_asset_discovery( # there are no flattened fields. if not isinstance(request, securitycenter_service.RunAssetDiscoveryRequest): request = securitycenter_service.RunAssetDiscoveryRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1799,7 +1769,7 @@ def run_asset_discovery( response, self._transport.operations_client, run_asset_discovery_response.RunAssetDiscoveryResponse, - metadata_type=empty.Empty, + metadata_type=empty_pb2.Empty, ) # Done; return the response. @@ -1811,7 +1781,7 @@ def set_finding_state( *, name: str = None, state: finding.Finding.State = None, - start_time: timestamp.Timestamp = None, + start_time: timestamp_pb2.Timestamp = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -1846,7 +1816,6 @@ def set_finding_state( This corresponds to the ``start_time`` 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. @@ -1882,10 +1851,8 @@ def set_finding_state( # there are no flattened fields. if not isinstance(request, securitycenter_service.SetFindingStateRequest): request = securitycenter_service.SetFindingStateRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if state is not None: @@ -1911,13 +1878,13 @@ def set_finding_state( def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the access control policy on the specified Source. @@ -1934,7 +1901,6 @@ def set_iam_policy( This corresponds to the ``resource`` 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. @@ -2013,11 +1979,10 @@ def set_iam_policy( if isinstance(request, dict): # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. - request = iam_policy.SetIamPolicyRequest(**request) + request = iam_policy_pb2.SetIamPolicyRequest(**request) elif not request: # Null request, just make one. - request = iam_policy.SetIamPolicyRequest() - + request = iam_policy_pb2.SetIamPolicyRequest() if resource is not None: request.resource = resource @@ -2039,14 +2004,14 @@ def set_iam_policy( def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, resource: str = None, permissions: Sequence[str] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Returns the permissions that a caller has on the specified source. @@ -2072,7 +2037,6 @@ def test_iam_permissions( This corresponds to the ``permissions`` 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. @@ -2096,14 +2060,12 @@ def test_iam_permissions( if isinstance(request, dict): # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. - request = iam_policy.TestIamPermissionsRequest(**request) + request = iam_policy_pb2.TestIamPermissionsRequest(**request) elif not request: # Null request, just make one. - request = iam_policy.TestIamPermissionsRequest() - + request = iam_policy_pb2.TestIamPermissionsRequest() if resource is not None: request.resource = resource - if permissions: request.permissions.extend(permissions) @@ -2128,7 +2090,7 @@ def update_finding( request: securitycenter_service.UpdateFindingRequest = None, *, finding: gcs_finding.Finding = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -2166,7 +2128,6 @@ def update_finding( This corresponds to the ``update_mask`` 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. @@ -2202,10 +2163,8 @@ def update_finding( # there are no flattened fields. if not isinstance(request, securitycenter_service.UpdateFindingRequest): request = securitycenter_service.UpdateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if finding is not None: request.finding = finding if update_mask is not None: @@ -2234,7 +2193,7 @@ def update_notification_config( request: securitycenter_service.UpdateNotificationConfigRequest = None, *, notification_config: gcs_notification_config.NotificationConfig = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -2262,7 +2221,6 @@ def update_notification_config( This corresponds to the ``update_mask`` 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. @@ -2298,10 +2256,8 @@ def update_notification_config( request, securitycenter_service.UpdateNotificationConfigRequest ): request = securitycenter_service.UpdateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if notification_config is not None: request.notification_config = notification_config if update_mask is not None: @@ -2349,7 +2305,6 @@ def update_organization_settings( This corresponds to the ``organization_settings`` 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. @@ -2381,10 +2336,8 @@ def update_organization_settings( request, securitycenter_service.UpdateOrganizationSettingsRequest ): request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if organization_settings is not None: request.organization_settings = organization_settings @@ -2413,7 +2366,7 @@ def update_source( request: securitycenter_service.UpdateSourceRequest = None, *, source: gcs_source.Source = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -2440,7 +2393,6 @@ def update_source( This corresponds to the ``update_mask`` 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. @@ -2473,10 +2425,8 @@ def update_source( # there are no flattened fields. if not isinstance(request, securitycenter_service.UpdateSourceRequest): request = securitycenter_service.UpdateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if source is not None: request.source = source if update_mask is not None: @@ -2505,7 +2455,7 @@ def update_security_marks( request: securitycenter_service.UpdateSecurityMarksRequest = None, *, security_marks: gcs_security_marks.SecurityMarks = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -2535,7 +2485,6 @@ def update_security_marks( This corresponds to the ``update_mask`` 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. @@ -2570,10 +2519,8 @@ def update_security_marks( # there are no flattened fields. if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): request = securitycenter_service.UpdateSecurityMarksRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if security_marks is not None: request.security_marks = security_marks if update_mask is not None: diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py index 712fa98f..4290274a 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/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, @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -247,7 +245,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -379,7 +377,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -511,7 +509,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -643,7 +641,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -773,7 +771,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/securitycenter_v1p1beta1/services/security_center/transports/__init__.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py index 45814553..1a2f356a 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/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/securitycenter_v1p1beta1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py index fddc88f5..0ca71d2c 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/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,17 +13,18 @@ # 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.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.securitycenter_v1p1beta1.types import finding from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding @@ -42,11 +42,10 @@ from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service from google.cloud.securitycenter_v1p1beta1.types import source from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -57,27 +56,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 SecurityCenterTransport(abc.ABC): """Abstract transport class for SecurityCenter.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "securitycenter.googleapis.com" + def __init__( self, *, - host: str = "securitycenter.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 @@ -86,7 +99,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): @@ -100,29 +113,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 = { @@ -149,7 +209,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -163,7 +224,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -177,7 +239,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -191,7 +254,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -205,7 +269,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -219,7 +284,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -233,7 +299,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -247,7 +314,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=480.0, ), @@ -261,7 +329,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -275,7 +344,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -298,7 +368,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -336,29 +407,29 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def create_source( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.CreateSourceRequest], - typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], + Union[gcs_source.Source, Awaitable[gcs_source.Source]], ]: raise NotImplementedError() @property def create_finding( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.CreateFindingRequest], - typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], + Union[gcs_finding.Finding, Awaitable[gcs_finding.Finding]], ]: raise NotImplementedError() @property def create_notification_config( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.CreateNotificationConfigRequest], - typing.Union[ + Union[ gcs_notification_config.NotificationConfig, - typing.Awaitable[gcs_notification_config.NotificationConfig], + Awaitable[gcs_notification_config.NotificationConfig], ], ]: raise NotImplementedError() @@ -366,29 +437,29 @@ def create_notification_config( @property def delete_notification_config( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.DeleteNotificationConfigRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def get_iam_policy( self, - ) -> typing.Callable[ - [iam_policy.GetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], ]: raise NotImplementedError() @property def get_notification_config( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.GetNotificationConfigRequest], - typing.Union[ + Union[ notification_config.NotificationConfig, - typing.Awaitable[notification_config.NotificationConfig], + Awaitable[notification_config.NotificationConfig], ], ]: raise NotImplementedError() @@ -396,11 +467,11 @@ def get_notification_config( @property def get_organization_settings( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.GetOrganizationSettingsRequest], - typing.Union[ + Union[ organization_settings.OrganizationSettings, - typing.Awaitable[organization_settings.OrganizationSettings], + Awaitable[organization_settings.OrganizationSettings], ], ]: raise NotImplementedError() @@ -408,20 +479,20 @@ def get_organization_settings( @property def get_source( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.GetSourceRequest], - typing.Union[source.Source, typing.Awaitable[source.Source]], + Union[source.Source, Awaitable[source.Source]], ]: raise NotImplementedError() @property def group_assets( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.GroupAssetsRequest], - typing.Union[ + Union[ securitycenter_service.GroupAssetsResponse, - typing.Awaitable[securitycenter_service.GroupAssetsResponse], + Awaitable[securitycenter_service.GroupAssetsResponse], ], ]: raise NotImplementedError() @@ -429,11 +500,11 @@ def group_assets( @property def group_findings( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.GroupFindingsRequest], - typing.Union[ + Union[ securitycenter_service.GroupFindingsResponse, - typing.Awaitable[securitycenter_service.GroupFindingsResponse], + Awaitable[securitycenter_service.GroupFindingsResponse], ], ]: raise NotImplementedError() @@ -441,11 +512,11 @@ def group_findings( @property def list_assets( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.ListAssetsRequest], - typing.Union[ + Union[ securitycenter_service.ListAssetsResponse, - typing.Awaitable[securitycenter_service.ListAssetsResponse], + Awaitable[securitycenter_service.ListAssetsResponse], ], ]: raise NotImplementedError() @@ -453,11 +524,11 @@ def list_assets( @property def list_findings( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.ListFindingsRequest], - typing.Union[ + Union[ securitycenter_service.ListFindingsResponse, - typing.Awaitable[securitycenter_service.ListFindingsResponse], + Awaitable[securitycenter_service.ListFindingsResponse], ], ]: raise NotImplementedError() @@ -465,11 +536,11 @@ def list_findings( @property def list_notification_configs( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.ListNotificationConfigsRequest], - typing.Union[ + Union[ securitycenter_service.ListNotificationConfigsResponse, - typing.Awaitable[securitycenter_service.ListNotificationConfigsResponse], + Awaitable[securitycenter_service.ListNotificationConfigsResponse], ], ]: raise NotImplementedError() @@ -477,11 +548,11 @@ def list_notification_configs( @property def list_sources( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.ListSourcesRequest], - typing.Union[ + Union[ securitycenter_service.ListSourcesResponse, - typing.Awaitable[securitycenter_service.ListSourcesResponse], + Awaitable[securitycenter_service.ListSourcesResponse], ], ]: raise NotImplementedError() @@ -489,38 +560,38 @@ def list_sources( @property def run_asset_discovery( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.RunAssetDiscoveryRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def set_finding_state( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.SetFindingStateRequest], - typing.Union[finding.Finding, typing.Awaitable[finding.Finding]], + Union[finding.Finding, Awaitable[finding.Finding]], ]: raise NotImplementedError() @property def set_iam_policy( self, - ) -> typing.Callable[ - [iam_policy.SetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ - [iam_policy.TestIamPermissionsRequest], - typing.Union[ - iam_policy.TestIamPermissionsResponse, - typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], ], ]: raise NotImplementedError() @@ -528,20 +599,20 @@ def test_iam_permissions( @property def update_finding( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.UpdateFindingRequest], - typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], + Union[gcs_finding.Finding, Awaitable[gcs_finding.Finding]], ]: raise NotImplementedError() @property def update_notification_config( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.UpdateNotificationConfigRequest], - typing.Union[ + Union[ gcs_notification_config.NotificationConfig, - typing.Awaitable[gcs_notification_config.NotificationConfig], + Awaitable[gcs_notification_config.NotificationConfig], ], ]: raise NotImplementedError() @@ -549,11 +620,11 @@ def update_notification_config( @property def update_organization_settings( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.UpdateOrganizationSettingsRequest], - typing.Union[ + Union[ gcs_organization_settings.OrganizationSettings, - typing.Awaitable[gcs_organization_settings.OrganizationSettings], + Awaitable[gcs_organization_settings.OrganizationSettings], ], ]: raise NotImplementedError() @@ -561,20 +632,20 @@ def update_organization_settings( @property def update_source( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.UpdateSourceRequest], - typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], + Union[gcs_source.Source, Awaitable[gcs_source.Source]], ]: raise NotImplementedError() @property def update_security_marks( self, - ) -> typing.Callable[ + ) -> Callable[ [securitycenter_service.UpdateSecurityMarksRequest], - typing.Union[ + Union[ gcs_security_marks.SecurityMarks, - typing.Awaitable[gcs_security_marks.SecurityMarks], + Awaitable[gcs_security_marks.SecurityMarks], ], ]: raise NotImplementedError() diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py index 15182889..1e7365b0 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/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,15 +13,14 @@ # 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 operations_v1 # 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 @@ -43,11 +41,10 @@ from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service from google.cloud.securitycenter_v1p1beta1.types import source from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO @@ -70,7 +67,7 @@ def __init__( self, *, host: str = "securitycenter.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -84,7 +81,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 @@ -195,7 +193,7 @@ def __init__( def create_channel( cls, host: str = "securitycenter.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, @@ -226,13 +224,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, ) @@ -342,7 +342,7 @@ def create_notification_config( def delete_notification_config( self, ) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], empty.Empty + [securitycenter_service.DeleteNotificationConfigRequest], empty_pb2.Empty ]: r"""Return a callable for the delete notification config method over gRPC. @@ -362,14 +362,14 @@ def delete_notification_config( self._stubs["delete_notification_config"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/DeleteNotificationConfig", request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_notification_config"] @property def get_iam_policy( self, - ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: r"""Return a callable for the get iam policy method over gRPC. Gets the access control policy on the specified @@ -388,8 +388,8 @@ def get_iam_policy( if "get_iam_policy" not in self._stubs: self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["get_iam_policy"] @@ -520,8 +520,9 @@ def group_findings( their specified properties. To group across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings Returns: Callable[[~.GroupFindingsRequest], @@ -665,7 +666,7 @@ def list_sources( def run_asset_discovery( self, ) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], operations.Operation + [securitycenter_service.RunAssetDiscoveryRequest], operations_pb2.Operation ]: r"""Return a callable for the run asset discovery method over gRPC. @@ -690,7 +691,7 @@ def run_asset_discovery( self._stubs["run_asset_discovery"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/RunAssetDiscovery", request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["run_asset_discovery"] @@ -723,7 +724,7 @@ def set_finding_state( @property def set_iam_policy( self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: r"""Return a callable for the set iam policy method over gRPC. Sets the access control policy on the specified @@ -742,8 +743,8 @@ def set_iam_policy( if "set_iam_policy" not in self._stubs: self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["set_iam_policy"] @@ -751,7 +752,8 @@ def set_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, ]: r"""Return a callable for the test iam permissions method over gRPC. @@ -771,8 +773,8 @@ def test_iam_permissions( if "test_iam_permissions" not in self._stubs: self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, ) return self._stubs["test_iam_permissions"] diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py index dfb65374..5126ab1c 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/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,16 +13,15 @@ # 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.api_core import operations_v1 # 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 @@ -44,11 +42,10 @@ from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service from google.cloud.securitycenter_v1p1beta1.types import source from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO from .grpc import SecurityCenterGrpcTransport @@ -73,7 +70,7 @@ class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): def create_channel( cls, host: str = "securitycenter.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, @@ -100,13 +97,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, ) @@ -114,7 +113,7 @@ def __init__( self, *, host: str = "securitycenter.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, @@ -128,7 +127,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 @@ -187,7 +187,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 @@ -352,7 +351,8 @@ def create_notification_config( def delete_notification_config( self, ) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], Awaitable[empty.Empty] + [securitycenter_service.DeleteNotificationConfigRequest], + Awaitable[empty_pb2.Empty], ]: r"""Return a callable for the delete notification config method over gRPC. @@ -372,14 +372,14 @@ def delete_notification_config( self._stubs["delete_notification_config"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/DeleteNotificationConfig", request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_notification_config"] @property def get_iam_policy( self, - ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: r"""Return a callable for the get iam policy method over gRPC. Gets the access control policy on the specified @@ -398,8 +398,8 @@ def get_iam_policy( if "get_iam_policy" not in self._stubs: self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["get_iam_policy"] @@ -530,8 +530,9 @@ def group_findings( their specified properties. To group across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings Returns: Callable[[~.GroupFindingsRequest], @@ -676,7 +677,7 @@ def run_asset_discovery( self, ) -> Callable[ [securitycenter_service.RunAssetDiscoveryRequest], - Awaitable[operations.Operation], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the run asset discovery method over gRPC. @@ -701,7 +702,7 @@ def run_asset_discovery( self._stubs["run_asset_discovery"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/RunAssetDiscovery", request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["run_asset_discovery"] @@ -736,7 +737,7 @@ def set_finding_state( @property def set_iam_policy( self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: r"""Return a callable for the set iam policy method over gRPC. Sets the access control policy on the specified @@ -755,8 +756,8 @@ def set_iam_policy( if "set_iam_policy" not in self._stubs: self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["set_iam_policy"] @@ -764,8 +765,8 @@ def set_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], - Awaitable[iam_policy.TestIamPermissionsResponse], + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], ]: r"""Return a callable for the test iam permissions method over gRPC. @@ -785,8 +786,8 @@ def test_iam_permissions( if "test_iam_permissions" not in self._stubs: self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, ) return self._stubs["test_iam_permissions"] diff --git a/google/cloud/securitycenter_v1p1beta1/types/__init__.py b/google/cloud/securitycenter_v1p1beta1/types/__init__.py index 0d3cb34a..dc6a8bc3 100644 --- a/google/cloud/securitycenter_v1p1beta1/types/__init__.py +++ b/google/cloud/securitycenter_v1p1beta1/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,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .asset import Asset from .finding import Finding +from .folder import Folder from .notification_config import NotificationConfig from .notification_message import NotificationMessage from .organization_settings import OrganizationSettings @@ -57,6 +56,7 @@ __all__ = ( "Asset", "Finding", + "Folder", "NotificationConfig", "NotificationMessage", "OrganizationSettings", diff --git a/google/cloud/securitycenter_v1p1beta1/types/asset.py b/google/cloud/securitycenter_v1p1beta1/types/asset.py index 50406de4..9869d497 100644 --- a/google/cloud/securitycenter_v1p1beta1/types/asset.py +++ b/google/cloud/securitycenter_v1p1beta1/types/asset.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - +from google.cloud.securitycenter_v1p1beta1.types import folder from google.cloud.securitycenter_v1p1beta1.types import ( security_marks as gcs_security_marks, ) -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -63,14 +61,20 @@ class Asset(proto.Message): The time at which the asset was created in Security Command Center. update_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the asset was last updated, - added, or deleted in Cloud SCC. + The time at which the asset was last updated + or added in Cloud SCC. iam_policy (google.cloud.securitycenter_v1p1beta1.types.Asset.IamPolicy): Cloud IAM Policy information associated with the Google Cloud resource described by the Security Command Center asset. This information is managed and defined by the Google Cloud resource and cannot be modified by the user. + canonical_name (str): + The canonical name of the resource. It's either + "organizations/{organization_id}/assets/{asset_id}", + "folders/{folder_id}/assets/{asset_id}" or + "projects/{project_number}/assets/{asset_id}", depending on + the closest CRM ancestor of the resource. """ class SecurityCenterProperties(proto.Message): @@ -110,23 +114,22 @@ class SecurityCenterProperties(proto.Message): resource_project_display_name (str): The user defined display name for the project of this resource. + folders (Sequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): + Contains a Folder message for each folder in + the assets ancestry. The first folder is the + deepest nested folder, and the last folder is + the folder directly under the Organization. """ - resource_name = proto.Field(proto.STRING, number=1) - - resource_type = proto.Field(proto.STRING, number=2) - - resource_parent = proto.Field(proto.STRING, number=3) - - resource_project = proto.Field(proto.STRING, number=4) - - resource_owners = proto.RepeatedField(proto.STRING, number=5) - - resource_display_name = proto.Field(proto.STRING, number=6) - - resource_parent_display_name = proto.Field(proto.STRING, number=7) - - resource_project_display_name = proto.Field(proto.STRING, number=8) + resource_name = proto.Field(proto.STRING, number=1,) + resource_type = proto.Field(proto.STRING, number=2,) + resource_parent = proto.Field(proto.STRING, number=3,) + resource_project = proto.Field(proto.STRING, number=4,) + resource_owners = proto.RepeatedField(proto.STRING, number=5,) + resource_display_name = proto.Field(proto.STRING, number=6,) + resource_parent_display_name = proto.Field(proto.STRING, number=7,) + resource_project_display_name = proto.Field(proto.STRING, number=8,) + folders = proto.RepeatedField(proto.MESSAGE, number=10, message=folder.Folder,) class IamPolicy(proto.Message): r"""Cloud IAM Policy information associated with the Google Cloud @@ -142,27 +145,24 @@ class IamPolicy(proto.Message): for format details. """ - policy_blob = proto.Field(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=1) + policy_blob = proto.Field(proto.STRING, number=1,) + name = proto.Field(proto.STRING, number=1,) security_center_properties = proto.Field( proto.MESSAGE, number=2, message=SecurityCenterProperties, ) - resource_properties = proto.MapField( - proto.STRING, proto.MESSAGE, number=7, message=struct.Value, + proto.STRING, proto.MESSAGE, number=7, message=struct_pb2.Value, ) - security_marks = proto.Field( proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, ) - - create_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) - - update_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) - + create_time = proto.Field(proto.MESSAGE, number=9, message=timestamp_pb2.Timestamp,) + update_time = proto.Field( + proto.MESSAGE, number=10, message=timestamp_pb2.Timestamp, + ) iam_policy = proto.Field(proto.MESSAGE, number=11, message=IamPolicy,) + canonical_name = proto.Field(proto.STRING, number=13,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/finding.py b/google/cloud/securitycenter_v1p1beta1/types/finding.py index 0e667d8c..2c122a4b 100644 --- a/google/cloud/securitycenter_v1p1beta1/types/finding.py +++ b/google/cloud/securitycenter_v1p1beta1/types/finding.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.securitycenter_v1p1beta1.types import ( security_marks as gcs_security_marks, ) -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -88,13 +85,23 @@ class Finding(proto.Message): believes the firewall became open. The accuracy is determined by the detector. If the finding were to be resolved afterward, this time would - reflect when the finding was resolved. + reflect when the finding was resolved. Must not + be set to a value greater than the current + timestamp. create_time (google.protobuf.timestamp_pb2.Timestamp): The time at which the finding was created in Security Command Center. severity (google.cloud.securitycenter_v1p1beta1.types.Finding.Severity): The severity of the finding. This field is managed by the source that writes the finding. + canonical_name (str): + The canonical name of the finding. It's either + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}", + "folders/{folder_id}/sources/{source_id}/findings/{finding_id}" + or + "projects/{project_number}/sources/{source_id}/findings/{finding_id}", + depending on the closest CRM ancestor of the resource + associated with the finding. """ class State(proto.Enum): @@ -113,31 +120,24 @@ class Severity(proto.Enum): MEDIUM = 3 LOW = 4 - name = proto.Field(proto.STRING, number=1) - - parent = proto.Field(proto.STRING, number=2) - - resource_name = proto.Field(proto.STRING, number=3) - + name = proto.Field(proto.STRING, number=1,) + parent = proto.Field(proto.STRING, number=2,) + resource_name = proto.Field(proto.STRING, number=3,) state = proto.Field(proto.ENUM, number=4, enum=State,) - - category = proto.Field(proto.STRING, number=5) - - external_uri = proto.Field(proto.STRING, number=6) - + category = proto.Field(proto.STRING, number=5,) + external_uri = proto.Field(proto.STRING, number=6,) source_properties = proto.MapField( - proto.STRING, proto.MESSAGE, number=7, message=struct.Value, + proto.STRING, proto.MESSAGE, number=7, message=struct_pb2.Value, ) - security_marks = proto.Field( proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, ) - - event_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) - - create_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) - + event_time = proto.Field(proto.MESSAGE, number=9, message=timestamp_pb2.Timestamp,) + create_time = proto.Field( + proto.MESSAGE, number=10, message=timestamp_pb2.Timestamp, + ) severity = proto.Field(proto.ENUM, number=13, enum=Severity,) + canonical_name = proto.Field(proto.STRING, number=14,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/folder.py b/google/cloud/securitycenter_v1p1beta1/types/folder.py new file mode 100644 index 00000000..407f9183 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/folder.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1p1beta1", manifest={"Folder",}, +) + + +class Folder(proto.Message): + r"""Message that contains the resource name and display name of a + folder resource. + + Attributes: + resource_folder (str): + Full resource name of this folder. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_folder_display_name (str): + The user defined display name for this + folder. + """ + + resource_folder = proto.Field(proto.STRING, number=1,) + resource_folder_display_name = proto.Field(proto.STRING, number=2,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/notification_config.py b/google/cloud/securitycenter_v1p1beta1/types/notification_config.py index 99befd9d..f9f720a8 100644 --- a/google/cloud/securitycenter_v1p1beta1/types/notification_config.py +++ b/google/cloud/securitycenter_v1p1beta1/types/notification_config.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 @@ -89,18 +87,13 @@ class StreamingConfig(proto.Message): - boolean literals ``true`` and ``false`` without quotes. """ - filter = proto.Field(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=1) - - description = proto.Field(proto.STRING, number=2) + filter = proto.Field(proto.STRING, number=1,) + name = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) event_type = proto.Field(proto.ENUM, number=3, enum=EventType,) - - pubsub_topic = proto.Field(proto.STRING, number=4) - - service_account = proto.Field(proto.STRING, number=5) - + pubsub_topic = proto.Field(proto.STRING, number=4,) + service_account = proto.Field(proto.STRING, number=5,) streaming_config = proto.Field( proto.MESSAGE, number=6, oneof="notify_config", message=StreamingConfig, ) diff --git a/google/cloud/securitycenter_v1p1beta1/types/notification_message.py b/google/cloud/securitycenter_v1p1beta1/types/notification_message.py index 215cd555..484cd101 100644 --- a/google/cloud/securitycenter_v1p1beta1/types/notification_message.py +++ b/google/cloud/securitycenter_v1p1beta1/types/notification_message.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding from google.cloud.securitycenter_v1p1beta1.types import resource as gcs_resource @@ -29,7 +26,6 @@ class NotificationMessage(proto.Message): r"""Security Command Center's Notification - Attributes: notification_config_name (str): Name of the notification config that @@ -41,12 +37,10 @@ class NotificationMessage(proto.Message): The Cloud resource tied to the notification. """ - notification_config_name = proto.Field(proto.STRING, number=1) - + notification_config_name = proto.Field(proto.STRING, number=1,) finding = proto.Field( proto.MESSAGE, number=2, oneof="event", message=gcs_finding.Finding, ) - resource = proto.Field(proto.MESSAGE, number=3, message=gcs_resource.Resource,) diff --git a/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py b/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py index 1cc1caeb..604b9c09 100644 --- a/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py +++ b/google/cloud/securitycenter_v1p1beta1/types/organization_settings.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 @@ -45,7 +43,6 @@ class OrganizationSettings(proto.Message): class AssetDiscoveryConfig(proto.Message): r"""The configuration used for Asset Discovery runs. - Attributes: project_ids (Sequence[str]): The project ids to use for filtering asset @@ -53,6 +50,10 @@ class AssetDiscoveryConfig(proto.Message): inclusion_mode (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): The mode to use for filtering asset discovery. + folder_ids (Sequence[str]): + The folder ids to use for filtering asset + discovery. It consists of only digits, e.g., + 756619654966. """ class InclusionMode(proto.Enum): @@ -69,18 +70,16 @@ class InclusionMode(proto.Enum): INCLUDE_ONLY = 1 EXCLUDE = 2 - project_ids = proto.RepeatedField(proto.STRING, number=1) - + project_ids = proto.RepeatedField(proto.STRING, number=1,) inclusion_mode = proto.Field( proto.ENUM, number=2, enum="OrganizationSettings.AssetDiscoveryConfig.InclusionMode", ) + folder_ids = proto.RepeatedField(proto.STRING, number=3,) - name = proto.Field(proto.STRING, number=1) - - enable_asset_discovery = proto.Field(proto.BOOL, number=2) - + name = proto.Field(proto.STRING, number=1,) + enable_asset_discovery = proto.Field(proto.BOOL, number=2,) asset_discovery_config = proto.Field( proto.MESSAGE, number=3, message=AssetDiscoveryConfig, ) diff --git a/google/cloud/securitycenter_v1p1beta1/types/resource.py b/google/cloud/securitycenter_v1p1beta1/types/resource.py index b29684ef..ab3ea8fa 100644 --- a/google/cloud/securitycenter_v1p1beta1/types/resource.py +++ b/google/cloud/securitycenter_v1p1beta1/types/resource.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,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore +from google.cloud.securitycenter_v1p1beta1.types import folder + __protobuf__ = proto.module( package="google.cloud.securitycenter.v1p1beta1", manifest={"Resource",}, @@ -25,7 +25,6 @@ class Resource(proto.Message): r"""Information related to the Google Cloud resource. - Attributes: name (str): The full resource name of the resource. See: @@ -40,17 +39,20 @@ class Resource(proto.Message): The full resource name of resource's parent. parent_display_name (str): The human readable name of resource's parent. + folders (Sequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): + Output only. Contains a Folder message for + each folder in the assets ancestry. The first + folder is the deepest nested folder, and the + last folder is the folder directly under the + Organization. """ - name = proto.Field(proto.STRING, number=1) - - project = proto.Field(proto.STRING, number=2) - - project_display_name = proto.Field(proto.STRING, number=3) - - parent = proto.Field(proto.STRING, number=4) - - parent_display_name = proto.Field(proto.STRING, number=5) + name = proto.Field(proto.STRING, number=1,) + project = proto.Field(proto.STRING, number=2,) + project_display_name = proto.Field(proto.STRING, number=3,) + parent = proto.Field(proto.STRING, number=4,) + parent_display_name = proto.Field(proto.STRING, number=5,) + folders = proto.RepeatedField(proto.MESSAGE, number=7, message=folder.Folder,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py b/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py index d1201368..8fb57687 100644 --- a/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py +++ b/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import duration_pb2 as gp_duration # type: ignore +from google.protobuf import duration_pb2 # type: ignore __protobuf__ = proto.module( @@ -29,7 +26,6 @@ class RunAssetDiscoveryResponse(proto.Message): r"""Response of asset discovery run - Attributes: state (google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse.State): The state of an asset discovery run. @@ -46,8 +42,7 @@ class State(proto.Enum): TERMINATED = 3 state = proto.Field(proto.ENUM, number=1, enum=State,) - - duration = proto.Field(proto.MESSAGE, number=2, message=gp_duration.Duration,) + duration = proto.Field(proto.MESSAGE, number=2, message=duration_pb2.Duration,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/security_marks.py b/google/cloud/securitycenter_v1p1beta1/types/security_marks.py index 1d84bd55..d00e98b9 100644 --- a/google/cloud/securitycenter_v1p1beta1/types/security_marks.py +++ b/google/cloud/securitycenter_v1p1beta1/types/security_marks.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 @@ -47,11 +45,19 @@ class SecurityMarks(proto.Message): - Values have leading and trailing whitespace trimmed, remaining characters must be between 1 - 4096 characters (inclusive) + canonical_name (str): + The canonical name of the marks. Examples: + "organizations/{organization_id}/assets/{asset_id}/securityMarks" + "folders/{folder_id}/assets/{asset_id}/securityMarks" + "projects/{project_number}/assets/{asset_id}/securityMarks" + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks" + "folders/{folder_id}/sources/{source_id}/findings/{finding_id}/securityMarks" + "projects/{project_number}/sources/{source_id}/findings/{finding_id}/securityMarks". """ - name = proto.Field(proto.STRING, number=1) - - marks = proto.MapField(proto.STRING, proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + marks = proto.MapField(proto.STRING, proto.STRING, number=2,) + canonical_name = proto.Field(proto.STRING, number=3,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py b/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py index e608de04..12533a09 100644 --- a/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py +++ b/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.securitycenter_v1p1beta1.types import asset as gcs_asset from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import folder from google.cloud.securitycenter_v1p1beta1.types import ( notification_config as gcs_notification_config, ) @@ -30,10 +28,10 @@ security_marks as gcs_security_marks, ) from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as gp_field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -72,7 +70,6 @@ class CreateFindingRequest(proto.Message): r"""Request message for creating a finding. - Attributes: parent (str): Required. Resource name of the new finding's parent. Its @@ -87,16 +84,13 @@ class CreateFindingRequest(proto.Message): fields on this resource. """ - parent = proto.Field(proto.STRING, number=1) - - finding_id = proto.Field(proto.STRING, number=2) - + parent = proto.Field(proto.STRING, number=1,) + finding_id = proto.Field(proto.STRING, number=2,) finding = proto.Field(proto.MESSAGE, number=3, message=gcs_finding.Finding,) class CreateNotificationConfigRequest(proto.Message): r"""Request message for creating a notification config. - Attributes: parent (str): Required. Resource name of the new notification config's @@ -114,10 +108,8 @@ class CreateNotificationConfigRequest(proto.Message): on this resource. """ - parent = proto.Field(proto.STRING, number=1) - - config_id = proto.Field(proto.STRING, number=2) - + parent = proto.Field(proto.STRING, number=1,) + config_id = proto.Field(proto.STRING, number=2,) notification_config = proto.Field( proto.MESSAGE, number=3, message=gcs_notification_config.NotificationConfig, ) @@ -125,7 +117,6 @@ class CreateNotificationConfigRequest(proto.Message): class CreateSourceRequest(proto.Message): r"""Request message for creating a source. - Attributes: parent (str): Required. Resource name of the new source's parent. Its @@ -136,14 +127,12 @@ class CreateSourceRequest(proto.Message): ignored. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) source = proto.Field(proto.MESSAGE, number=2, message=gcs_source.Source,) class DeleteNotificationConfigRequest(proto.Message): r"""Request message for deleting a notification config. - Attributes: name (str): Required. Name of the notification config to delete. Its @@ -151,12 +140,11 @@ class DeleteNotificationConfigRequest(proto.Message): "organizations/[organization_id]/notificationConfigs/[config_id]". """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class GetNotificationConfigRequest(proto.Message): r"""Request message for getting a notification config. - Attributes: name (str): Required. Name of the notification config to get. Its format @@ -164,12 +152,11 @@ class GetNotificationConfigRequest(proto.Message): "organizations/[organization_id]/notificationConfigs/[config_id]". """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class GetOrganizationSettingsRequest(proto.Message): r"""Request message for getting organization settings. - Attributes: name (str): Required. Name of the organization to get organization @@ -177,28 +164,27 @@ class GetOrganizationSettingsRequest(proto.Message): "organizations/[organization_id]/organizationSettings". """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class GetSourceRequest(proto.Message): r"""Request message for getting a source. - Attributes: name (str): Required. Relative resource name of the source. Its format is "organizations/[organization_id]/source/[source_id]". """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class GroupAssetsRequest(proto.Message): r"""Request message for grouping by assets. - Attributes: parent (str): Required. Name of the organization to groupBy. Its format is - "organizations/[organization_id]". + "organizations/[organization_id], folders/[folder_id], or + projects/[project_id]". filter (str): Expression that defines the filter to apply across assets. The expression is a list of zero or more restrictions @@ -351,24 +337,19 @@ class GroupAssetsRequest(proto.Message): maximum is 1000. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - group_by = proto.Field(proto.STRING, number=3) - - compare_duration = proto.Field(proto.MESSAGE, number=4, message=duration.Duration,) - - read_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - - page_token = proto.Field(proto.STRING, number=7) - - page_size = proto.Field(proto.INT32, number=8) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + group_by = proto.Field(proto.STRING, number=3,) + compare_duration = proto.Field( + proto.MESSAGE, number=4, message=duration_pb2.Duration, + ) + read_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + page_token = proto.Field(proto.STRING, number=7,) + page_size = proto.Field(proto.INT32, number=8,) class GroupAssetsResponse(proto.Message): r"""Response message for grouping by assets. - Attributes: group_by_results (Sequence[google.cloud.securitycenter_v1p1beta1.types.GroupResult]): Group results. There exists an element for @@ -393,23 +374,23 @@ def raw_page(self): group_by_results = proto.RepeatedField( proto.MESSAGE, number=1, message="GroupResult", ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - total_size = proto.Field(proto.INT32, number=4) + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + next_page_token = proto.Field(proto.STRING, number=3,) + total_size = proto.Field(proto.INT32, number=4,) class GroupFindingsRequest(proto.Message): r"""Request message for grouping by findings. - Attributes: parent (str): Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". To - groupBy across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/- + "organizations/[organization_id]/sources/[source_id]", + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]. To groupBy across + all sources provide a source_id of ``-``. For example: + organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/-, or + projects/{project_id}/sources/- filter (str): Expression that defines the filter to apply across findings. The expression is a list of one or more restrictions @@ -546,24 +527,19 @@ class GroupFindingsRequest(proto.Message): maximum is 1000. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - group_by = proto.Field(proto.STRING, number=3) - - read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) - - page_token = proto.Field(proto.STRING, number=7) - - page_size = proto.Field(proto.INT32, number=8) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + group_by = proto.Field(proto.STRING, number=3,) + read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + compare_duration = proto.Field( + proto.MESSAGE, number=5, message=duration_pb2.Duration, + ) + page_token = proto.Field(proto.STRING, number=7,) + page_size = proto.Field(proto.INT32, number=8,) class GroupFindingsResponse(proto.Message): r"""Response message for group by findings. - Attributes: group_by_results (Sequence[google.cloud.securitycenter_v1p1beta1.types.GroupResult]): Group results. There exists an element for @@ -588,12 +564,9 @@ def raw_page(self): group_by_results = proto.RepeatedField( proto.MESSAGE, number=1, message="GroupResult", ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - total_size = proto.Field(proto.INT32, number=4) + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + next_page_token = proto.Field(proto.STRING, number=3,) + total_size = proto.Field(proto.INT32, number=4,) class GroupResult(proto.Message): @@ -610,15 +583,13 @@ class GroupResult(proto.Message): """ properties = proto.MapField( - proto.STRING, proto.MESSAGE, number=1, message=struct.Value, + proto.STRING, proto.MESSAGE, number=1, message=struct_pb2.Value, ) - - count = proto.Field(proto.INT64, number=2) + count = proto.Field(proto.INT64, number=2,) class ListNotificationConfigsRequest(proto.Message): r"""Request message for listing notification configs. - Attributes: parent (str): Required. Name of the organization to list notification @@ -634,16 +605,13 @@ class ListNotificationConfigsRequest(proto.Message): maximum is 1000. """ - parent = proto.Field(proto.STRING, number=1) - - page_token = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_token = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) class ListNotificationConfigsResponse(proto.Message): r"""Response message for listing notification configs. - Attributes: notification_configs (Sequence[google.cloud.securitycenter_v1p1beta1.types.NotificationConfig]): Notification configs belonging to the @@ -660,17 +628,16 @@ def raw_page(self): notification_configs = proto.RepeatedField( proto.MESSAGE, number=1, message=gcs_notification_config.NotificationConfig, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class ListSourcesRequest(proto.Message): r"""Request message for listing sources. - Attributes: parent (str): Required. Resource name of the parent of sources to list. - Its format should be "organizations/[organization_id]". + Its format should be "organizations/[organization_id], + folders/[folder_id], or projects/[project_id]". page_token (str): The value returned by the last ``ListSourcesResponse``; indicates that this is a continuation of a prior @@ -682,16 +649,13 @@ class ListSourcesRequest(proto.Message): maximum is 1000. """ - parent = proto.Field(proto.STRING, number=1) - - page_token = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=7) + parent = proto.Field(proto.STRING, number=1,) + page_token = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=7,) class ListSourcesResponse(proto.Message): r"""Response message for listing sources. - Attributes: sources (Sequence[google.cloud.securitycenter_v1p1beta1.types.Source]): Sources belonging to the requested parent. @@ -705,17 +669,16 @@ def raw_page(self): return self sources = proto.RepeatedField(proto.MESSAGE, number=1, message=gcs_source.Source,) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class ListAssetsRequest(proto.Message): r"""Request message for listing assets. - Attributes: parent (str): Required. Name of the organization assets should belong to. - Its format is "organizations/[organization_id]". + Its format is "organizations/[organization_id], + folders/[folder_id], or projects/[project_id]". filter (str): Expression that defines the filter to apply across assets. The expression is a list of zero or more restrictions @@ -869,26 +832,20 @@ class ListAssetsRequest(proto.Message): maximum is 1000. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - order_by = proto.Field(proto.STRING, number=3) - - read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) - - field_mask = proto.Field(proto.MESSAGE, number=7, message=gp_field_mask.FieldMask,) - - page_token = proto.Field(proto.STRING, number=8) - - page_size = proto.Field(proto.INT32, number=9) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + order_by = proto.Field(proto.STRING, number=3,) + read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + compare_duration = proto.Field( + proto.MESSAGE, number=5, message=duration_pb2.Duration, + ) + field_mask = proto.Field(proto.MESSAGE, number=7, message=field_mask_pb2.FieldMask,) + page_token = proto.Field(proto.STRING, number=8,) + page_size = proto.Field(proto.INT32, number=9,) class ListAssetsResponse(proto.Message): r"""Response message for listing assets. - Attributes: list_assets_results (Sequence[google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse.ListAssetsResult]): Assets matching the list request. @@ -904,7 +861,6 @@ class ListAssetsResponse(proto.Message): class ListAssetsResult(proto.Message): r"""Result containing the Asset and its State. - Attributes: asset (google.cloud.securitycenter_v1p1beta1.types.Asset): Asset matching the search request. @@ -927,7 +883,6 @@ class StateChange(proto.Enum): ACTIVE = 3 asset = proto.Field(proto.MESSAGE, number=1, message=gcs_asset.Asset,) - state_change = proto.Field( proto.ENUM, number=2, @@ -941,24 +896,24 @@ def raw_page(self): list_assets_results = proto.RepeatedField( proto.MESSAGE, number=1, message=ListAssetsResult, ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - total_size = proto.Field(proto.INT32, number=4) + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + next_page_token = proto.Field(proto.STRING, number=3,) + total_size = proto.Field(proto.INT32, number=4,) class ListFindingsRequest(proto.Message): r"""Request message for listing findings. - Attributes: parent (str): Required. Name of the source the findings belong to. Its format is - "organizations/[organization_id]/sources/[source_id]". To - list across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/- + "organizations/[organization_id]/sources/[source_id], + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]". To list across + all sources provide a source_id of ``-``. For example: + organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/- or + projects/{projects_id}/sources/- filter (str): Expression that defines the filter to apply across findings. The expression is a list of one or more restrictions @@ -1091,26 +1046,20 @@ class ListFindingsRequest(proto.Message): maximum is 1000. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - order_by = proto.Field(proto.STRING, number=3) - - read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) - - field_mask = proto.Field(proto.MESSAGE, number=7, message=gp_field_mask.FieldMask,) - - page_token = proto.Field(proto.STRING, number=8) - - page_size = proto.Field(proto.INT32, number=9) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + order_by = proto.Field(proto.STRING, number=3,) + read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + compare_duration = proto.Field( + proto.MESSAGE, number=5, message=duration_pb2.Duration, + ) + field_mask = proto.Field(proto.MESSAGE, number=7, message=field_mask_pb2.FieldMask,) + page_token = proto.Field(proto.STRING, number=8,) + page_size = proto.Field(proto.INT32, number=9,) class ListFindingsResponse(proto.Message): r"""Response message for listing findings. - Attributes: list_findings_results (Sequence[google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult]): Findings matching the list request. @@ -1126,7 +1075,6 @@ class ListFindingsResponse(proto.Message): class ListFindingsResult(proto.Message): r"""Result containing the Finding and its StateChange. - Attributes: finding (google.cloud.securitycenter_v1p1beta1.types.Finding): Finding matching the search request. @@ -1172,26 +1120,28 @@ class Resource(proto.Message): The full resource name of resource's parent. parent_display_name (str): The human readable name of resource's parent. + folders (Sequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): + Contains a Folder message for each folder in + the assets ancestry. The first folder is the + deepest nested folder, and the last folder is + the folder directly under the Organization. """ - name = proto.Field(proto.STRING, number=1) - - project_name = proto.Field(proto.STRING, number=2) - - project_display_name = proto.Field(proto.STRING, number=3) - - parent_name = proto.Field(proto.STRING, number=4) - - parent_display_name = proto.Field(proto.STRING, number=5) + name = proto.Field(proto.STRING, number=1,) + project_name = proto.Field(proto.STRING, number=2,) + project_display_name = proto.Field(proto.STRING, number=3,) + parent_name = proto.Field(proto.STRING, number=4,) + parent_display_name = proto.Field(proto.STRING, number=5,) + folders = proto.RepeatedField( + proto.MESSAGE, number=10, message=folder.Folder, + ) finding = proto.Field(proto.MESSAGE, number=1, message=gcs_finding.Finding,) - state_change = proto.Field( proto.ENUM, number=2, enum="ListFindingsResponse.ListFindingsResult.StateChange", ) - resource = proto.Field( proto.MESSAGE, number=3, @@ -1205,17 +1155,13 @@ def raw_page(self): list_findings_results = proto.RepeatedField( proto.MESSAGE, number=1, message=ListFindingsResult, ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - total_size = proto.Field(proto.INT32, number=4) + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + next_page_token = proto.Field(proto.STRING, number=3,) + total_size = proto.Field(proto.INT32, number=4,) class SetFindingStateRequest(proto.Message): r"""Request message for updating a finding's state. - Attributes: name (str): Required. The relative resource name of the finding. See: @@ -1229,11 +1175,9 @@ class SetFindingStateRequest(proto.Message): takes effect. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) state = proto.Field(proto.ENUM, number=2, enum=gcs_finding.Finding.State,) - - start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) class RunAssetDiscoveryRequest(proto.Message): @@ -1246,12 +1190,11 @@ class RunAssetDiscoveryRequest(proto.Message): for. Its format is "organizations/[organization_id]". """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) class UpdateFindingRequest(proto.Message): r"""Request message for updating or creating a finding. - Attributes: finding (google.cloud.securitycenter_v1p1beta1.types.Finding): Required. The finding resource to update or create if it @@ -1272,13 +1215,13 @@ class UpdateFindingRequest(proto.Message): """ finding = proto.Field(proto.MESSAGE, number=1, message=gcs_finding.Finding,) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class UpdateNotificationConfigRequest(proto.Message): r"""Request message for updating a notification config. - Attributes: notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): Required. The notification config to update. @@ -1291,13 +1234,13 @@ class UpdateNotificationConfigRequest(proto.Message): notification_config = proto.Field( proto.MESSAGE, number=1, message=gcs_notification_config.NotificationConfig, ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class UpdateOrganizationSettingsRequest(proto.Message): r"""Request message for updating an organization's settings. - Attributes: organization_settings (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings): Required. The organization settings resource @@ -1312,13 +1255,13 @@ class UpdateOrganizationSettingsRequest(proto.Message): organization_settings = proto.Field( proto.MESSAGE, number=1, message=gcs_organization_settings.OrganizationSettings, ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class UpdateSourceRequest(proto.Message): r"""Request message for updating a source. - Attributes: source (google.cloud.securitycenter_v1p1beta1.types.Source): Required. The source resource to update. @@ -1329,13 +1272,13 @@ class UpdateSourceRequest(proto.Message): """ source = proto.Field(proto.MESSAGE, number=1, message=gcs_source.Source,) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class UpdateSecurityMarksRequest(proto.Message): r"""Request message for updating a SecurityMarks resource. - Attributes: security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): Required. The security marks resource to @@ -1358,10 +1301,10 @@ class UpdateSecurityMarksRequest(proto.Message): security_marks = proto.Field( proto.MESSAGE, number=1, message=gcs_security_marks.SecurityMarks, ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) - - start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) + start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/source.py b/google/cloud/securitycenter_v1p1beta1/types/source.py index 90a4ad7d..5fd35e81 100644 --- a/google/cloud/securitycenter_v1p1beta1/types/source.py +++ b/google/cloud/securitycenter_v1p1beta1/types/source.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 @@ -52,13 +50,19 @@ class Source(proto.Message): cross-site-scripting (XSS), Flash injection, mixed content (HTTP in HTTPS), and outdated/insecure libraries.". + canonical_name (str): + The canonical name of the finding. It's either + "organizations/{organization_id}/sources/{source_id}", + "folders/{folder_id}/sources/{source_id}" or + "projects/{project_number}/sources/{source_id}", depending + on the closest CRM ancestor of the resource associated with + the finding. """ - 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,) + canonical_name = proto.Field(proto.STRING, number=14,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owlbot.py b/owlbot.py index aabd7289..e3f81fc4 100644 --- a/owlbot.py +++ b/owlbot.py @@ -33,6 +33,14 @@ s.remove_staging_dirs() +# Comment out broken assertion in unit test +# https://github.com/googleapis/gapic-generator-python/issues/897 +s.replace( + "tests/**/*.py", + "assert args\[0\]\.start_time == timestamp_pb2\.Timestamp\(seconds=751\)", + "# assert args[0].start_time == timestamp_pb2.Timestamp(seconds=751)" +) + # ---------------------------------------------------------------------------- # Add templated files # ---------------------------------------------------------------------------- diff --git a/scripts/fixup_securitycenter_v1_keywords.py b/scripts/fixup_securitycenter_v1_keywords.py index 6afbe367..43acd75e 100644 --- a/scripts/fixup_securitycenter_v1_keywords.py +++ b/scripts/fixup_securitycenter_v1_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,30 +39,29 @@ def partition( class securitycenterCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_finding': ('parent', 'finding_id', 'finding', ), - 'create_notification_config': ('parent', 'config_id', 'notification_config', ), - 'create_source': ('parent', 'source', ), - 'delete_notification_config': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_notification_config': ('name', ), - 'get_organization_settings': ('name', ), - 'get_source': ('name', ), - 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), - 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'compare_duration', 'page_token', 'page_size', ), - 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), - 'list_notification_configs': ('parent', 'page_token', 'page_size', ), - 'list_sources': ('parent', 'page_token', 'page_size', ), - 'run_asset_discovery': ('parent', ), - 'set_finding_state': ('name', 'state', 'start_time', ), - 'set_iam_policy': ('resource', 'policy', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_finding': ('finding', 'update_mask', ), - 'update_notification_config': ('notification_config', 'update_mask', ), - 'update_organization_settings': ('organization_settings', 'update_mask', ), - 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), - 'update_source': ('source', 'update_mask', ), - + 'create_finding': ('parent', 'finding_id', 'finding', ), + 'create_notification_config': ('parent', 'config_id', 'notification_config', ), + 'create_source': ('parent', 'source', ), + 'delete_notification_config': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_notification_config': ('name', ), + 'get_organization_settings': ('name', ), + 'get_source': ('name', ), + 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), + 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'compare_duration', 'page_token', 'page_size', ), + 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), + 'list_notification_configs': ('parent', 'page_token', 'page_size', ), + 'list_sources': ('parent', 'page_token', 'page_size', ), + 'run_asset_discovery': ('parent', ), + 'set_finding_state': ('name', 'state', 'start_time', ), + 'set_iam_policy': ('resource', 'policy', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_finding': ('finding', 'update_mask', ), + 'update_notification_config': ('notification_config', 'update_mask', ), + 'update_organization_settings': ('organization_settings', 'update_mask', ), + 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), + 'update_source': ('source', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -95,7 +92,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/scripts/fixup_securitycenter_v1beta1_keywords.py b/scripts/fixup_securitycenter_v1beta1_keywords.py index c2bdd2db..c85a7b83 100644 --- a/scripts/fixup_securitycenter_v1beta1_keywords.py +++ b/scripts/fixup_securitycenter_v1beta1_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,25 +39,24 @@ def partition( class securitycenterCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_finding': ('parent', 'finding_id', 'finding', ), - 'create_source': ('parent', 'source', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_organization_settings': ('name', ), - 'get_source': ('name', ), - 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), - 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'page_token', 'page_size', ), - 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'field_mask', 'page_token', 'page_size', ), - 'list_sources': ('parent', 'page_token', 'page_size', ), - 'run_asset_discovery': ('parent', ), - 'set_finding_state': ('name', 'state', 'start_time', ), - 'set_iam_policy': ('resource', 'policy', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_finding': ('finding', 'update_mask', ), - 'update_organization_settings': ('organization_settings', 'update_mask', ), - 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), - 'update_source': ('source', 'update_mask', ), - + 'create_finding': ('parent', 'finding_id', 'finding', ), + 'create_source': ('parent', 'source', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_organization_settings': ('name', ), + 'get_source': ('name', ), + 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), + 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'page_token', 'page_size', ), + 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'field_mask', 'page_token', 'page_size', ), + 'list_sources': ('parent', 'page_token', 'page_size', ), + 'run_asset_discovery': ('parent', ), + 'set_finding_state': ('name', 'state', 'start_time', ), + 'set_iam_policy': ('resource', 'policy', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_finding': ('finding', 'update_mask', ), + 'update_organization_settings': ('organization_settings', 'update_mask', ), + 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), + 'update_source': ('source', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -90,7 +87,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/scripts/fixup_securitycenter_v1p1beta1_keywords.py b/scripts/fixup_securitycenter_v1p1beta1_keywords.py index 6afbe367..43acd75e 100644 --- a/scripts/fixup_securitycenter_v1p1beta1_keywords.py +++ b/scripts/fixup_securitycenter_v1p1beta1_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,30 +39,29 @@ def partition( class securitycenterCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_finding': ('parent', 'finding_id', 'finding', ), - 'create_notification_config': ('parent', 'config_id', 'notification_config', ), - 'create_source': ('parent', 'source', ), - 'delete_notification_config': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_notification_config': ('name', ), - 'get_organization_settings': ('name', ), - 'get_source': ('name', ), - 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), - 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'compare_duration', 'page_token', 'page_size', ), - 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), - 'list_notification_configs': ('parent', 'page_token', 'page_size', ), - 'list_sources': ('parent', 'page_token', 'page_size', ), - 'run_asset_discovery': ('parent', ), - 'set_finding_state': ('name', 'state', 'start_time', ), - 'set_iam_policy': ('resource', 'policy', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_finding': ('finding', 'update_mask', ), - 'update_notification_config': ('notification_config', 'update_mask', ), - 'update_organization_settings': ('organization_settings', 'update_mask', ), - 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), - 'update_source': ('source', 'update_mask', ), - + 'create_finding': ('parent', 'finding_id', 'finding', ), + 'create_notification_config': ('parent', 'config_id', 'notification_config', ), + 'create_source': ('parent', 'source', ), + 'delete_notification_config': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_notification_config': ('name', ), + 'get_organization_settings': ('name', ), + 'get_source': ('name', ), + 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), + 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'compare_duration', 'page_token', 'page_size', ), + 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), + 'list_notification_configs': ('parent', 'page_token', 'page_size', ), + 'list_sources': ('parent', 'page_token', 'page_size', ), + 'run_asset_discovery': ('parent', ), + 'set_finding_state': ('name', 'state', 'start_time', ), + 'set_iam_policy': ('resource', 'policy', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_finding': ('finding', 'update_mask', ), + 'update_notification_config': ('notification_config', 'update_mask', ), + 'update_organization_settings': ('organization_settings', 'update_mask', ), + 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), + 'update_source': ('source', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -95,7 +92,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/setup.py b/setup.py index c639c9da..0f264290 100644 --- a/setup.py +++ b/setup.py @@ -27,6 +27,7 @@ "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", "grpc-google-iam-v1 >= 0.12.3, < 0.13dev", "proto-plus >= 1.10.0", + "packaging >= 14.3", ] extras = {"libcst": "libcst >= 0.2.5"} diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index d9594657..f74cd45d 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -9,3 +9,5 @@ google-api-core==1.22.2 grpc-google-iam-v1==0.12.3 proto-plus==1.10.0 libcst==0.2.5 +packaging==14.3 +google-auth==1.24.0 # TODO: Remove when google-auth >= 1.25.0 is transitively required through google-api-core diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 00000000..4de65971 --- /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 00000000..4de65971 --- /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 00000000..4de65971 --- /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/securitycenter_v1/__init__.py b/tests/unit/gapic/securitycenter_v1/__init__.py index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/securitycenter_v1/__init__.py +++ b/tests/unit/gapic/securitycenter_v1/__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/securitycenter_v1/test_security_center.py b/tests/unit/gapic/securitycenter_v1/test_security_center.py index ae141baa..9d0a6e4e 100644 --- a/tests/unit/gapic/securitycenter_v1/test_security_center.py +++ b/tests/unit/gapic/securitycenter_v1/test_security_center.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,16 +23,16 @@ 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 future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.securitycenter_v1.services.security_center import ( SecurityCenterAsyncClient, @@ -41,6 +40,12 @@ from google.cloud.securitycenter_v1.services.security_center import SecurityCenterClient from google.cloud.securitycenter_v1.services.security_center import pagers from google.cloud.securitycenter_v1.services.security_center import transports +from google.cloud.securitycenter_v1.services.security_center.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.securitycenter_v1.services.security_center.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.securitycenter_v1.types import finding from google.cloud.securitycenter_v1.types import finding as gcs_finding from google.cloud.securitycenter_v1.types import notification_config @@ -57,16 +62,40 @@ from google.cloud.securitycenter_v1.types import securitycenter_service from google.cloud.securitycenter_v1.types import source from google.cloud.securitycenter_v1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import options_pb2 as options # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.type import expr_pb2 as expr # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # 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(): @@ -117,7 +146,7 @@ def test__get_default_mtls_endpoint(): "client_class", [SecurityCenterClient, SecurityCenterAsyncClient,] ) def test_security_center_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: @@ -134,7 +163,7 @@ def test_security_center_client_from_service_account_info(client_class): "client_class", [SecurityCenterClient, SecurityCenterAsyncClient,] ) def test_security_center_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: @@ -187,7 +216,7 @@ def test_security_center_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(SecurityCenterClient, "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() @@ -475,7 +504,7 @@ def test_create_source( transport: str = "grpc", request_type=securitycenter_service.CreateSourceRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -489,25 +518,21 @@ def test_create_source( name="name_value", display_name="display_name_value", description="description_value", + canonical_name="canonical_name_value", ) - response = client.create_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" def test_create_source_from_dict(): @@ -518,7 +543,7 @@ def test_create_source_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -526,7 +551,6 @@ def test_create_source_empty_call(): client.create_source() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() @@ -536,7 +560,7 @@ async def test_create_source_async( request_type=securitycenter_service.CreateSourceRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -551,25 +575,22 @@ async def test_create_source_async( name="name_value", display_name="display_name_value", description="description_value", + canonical_name="canonical_name_value", ) ) - response = await client.create_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_source.Source) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" @pytest.mark.asyncio @@ -578,17 +599,17 @@ async def test_create_source_async_from_dict(): def test_create_source_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.CreateSourceRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_source), "__call__") as call: call.return_value = gcs_source.Source() - client.create_source(request) # Establish that the underlying gRPC stub method was called. @@ -603,17 +624,19 @@ def test_create_source_field_headers(): @pytest.mark.asyncio async def test_create_source_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.CreateSourceRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_source), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.create_source(request) # Establish that the underlying gRPC stub method was called. @@ -627,13 +650,12 @@ async def test_create_source_field_headers_async(): def test_create_source_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_source), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_source( @@ -644,14 +666,12 @@ def test_create_source_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].source == gcs_source.Source(name="name_value") def test_create_source_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -665,7 +685,9 @@ def test_create_source_flattened_error(): @pytest.mark.asyncio async def test_create_source_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_source), "__call__") as call: @@ -683,15 +705,15 @@ async def test_create_source_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].source == gcs_source.Source(name="name_value") @pytest.mark.asyncio async def test_create_source_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -707,7 +729,7 @@ def test_create_finding( transport: str = "grpc", request_type=securitycenter_service.CreateFindingRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -725,33 +747,25 @@ def test_create_finding( category="category_value", external_uri="external_uri_value", severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name="canonical_name_value", ) - response = client.create_finding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.resource_name == "resource_name_value" - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == "category_value" - assert response.external_uri == "external_uri_value" - assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == "canonical_name_value" def test_create_finding_from_dict(): @@ -762,7 +776,7 @@ def test_create_finding_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -770,7 +784,6 @@ def test_create_finding_empty_call(): client.create_finding() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() @@ -780,7 +793,7 @@ async def test_create_finding_async( request_type=securitycenter_service.CreateFindingRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -799,33 +812,26 @@ async def test_create_finding_async( category="category_value", external_uri="external_uri_value", severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name="canonical_name_value", ) ) - response = await client.create_finding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_finding.Finding) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.resource_name == "resource_name_value" - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == "category_value" - assert response.external_uri == "external_uri_value" - assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == "canonical_name_value" @pytest.mark.asyncio @@ -834,17 +840,17 @@ async def test_create_finding_async_from_dict(): def test_create_finding_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.CreateFindingRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_finding), "__call__") as call: call.return_value = gcs_finding.Finding() - client.create_finding(request) # Establish that the underlying gRPC stub method was called. @@ -859,17 +865,19 @@ def test_create_finding_field_headers(): @pytest.mark.asyncio async def test_create_finding_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.CreateFindingRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_finding), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.create_finding(request) # Establish that the underlying gRPC stub method was called. @@ -883,13 +891,12 @@ async def test_create_finding_field_headers_async(): def test_create_finding_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_finding), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_finding( @@ -902,16 +909,13 @@ def test_create_finding_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].finding_id == "finding_id_value" - assert args[0].finding == gcs_finding.Finding(name="name_value") def test_create_finding_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -926,7 +930,9 @@ def test_create_finding_flattened_error(): @pytest.mark.asyncio async def test_create_finding_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_finding), "__call__") as call: @@ -946,17 +952,16 @@ async def test_create_finding_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].finding_id == "finding_id_value" - assert args[0].finding == gcs_finding.Finding(name="name_value") @pytest.mark.asyncio async def test_create_finding_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -974,7 +979,7 @@ def test_create_notification_config( request_type=securitycenter_service.CreateNotificationConfigRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -995,25 +1000,18 @@ def test_create_notification_config( filter="filter_value" ), ) - response = client.create_notification_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.pubsub_topic == "pubsub_topic_value" - assert response.service_account == "service_account_value" @@ -1025,7 +1023,7 @@ def test_create_notification_config_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1035,7 +1033,6 @@ def test_create_notification_config_empty_call(): client.create_notification_config() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() @@ -1045,7 +1042,7 @@ async def test_create_notification_config_async( request_type=securitycenter_service.CreateNotificationConfigRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1065,24 +1062,18 @@ async def test_create_notification_config_async( service_account="service_account_value", ) ) - response = await client.create_notification_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.pubsub_topic == "pubsub_topic_value" - assert response.service_account == "service_account_value" @@ -1092,11 +1083,12 @@ async def test_create_notification_config_async_from_dict(): def test_create_notification_config_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.CreateNotificationConfigRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1104,7 +1096,6 @@ def test_create_notification_config_field_headers(): type(client.transport.create_notification_config), "__call__" ) as call: call.return_value = gcs_notification_config.NotificationConfig() - client.create_notification_config(request) # Establish that the underlying gRPC stub method was called. @@ -1119,11 +1110,14 @@ def test_create_notification_config_field_headers(): @pytest.mark.asyncio async def test_create_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.CreateNotificationConfigRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1133,7 +1127,6 @@ async def test_create_notification_config_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcs_notification_config.NotificationConfig() ) - await client.create_notification_config(request) # Establish that the underlying gRPC stub method was called. @@ -1147,7 +1140,7 @@ async def test_create_notification_config_field_headers_async(): def test_create_notification_config_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1155,7 +1148,6 @@ def test_create_notification_config_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcs_notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_notification_config( @@ -1170,11 +1162,8 @@ def test_create_notification_config_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].config_id == "config_id_value" - assert args[ 0 ].notification_config == gcs_notification_config.NotificationConfig( @@ -1183,7 +1172,7 @@ def test_create_notification_config_flattened(): def test_create_notification_config_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1200,7 +1189,9 @@ def test_create_notification_config_flattened_error(): @pytest.mark.asyncio async def test_create_notification_config_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1226,11 +1217,8 @@ async def test_create_notification_config_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].config_id == "config_id_value" - assert args[ 0 ].notification_config == gcs_notification_config.NotificationConfig( @@ -1240,7 +1228,9 @@ async def test_create_notification_config_flattened_async(): @pytest.mark.asyncio async def test_create_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1260,7 +1250,7 @@ def test_delete_notification_config( request_type=securitycenter_service.DeleteNotificationConfigRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1273,13 +1263,11 @@ def test_delete_notification_config( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_notification_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() # Establish that the response is the type that we expect. @@ -1294,7 +1282,7 @@ def test_delete_notification_config_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1304,7 +1292,6 @@ def test_delete_notification_config_empty_call(): client.delete_notification_config() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() @@ -1314,7 +1301,7 @@ async def test_delete_notification_config_async( request_type=securitycenter_service.DeleteNotificationConfigRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1327,13 +1314,11 @@ async def test_delete_notification_config_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_notification_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() # Establish that the response is the type that we expect. @@ -1346,11 +1331,12 @@ async def test_delete_notification_config_async_from_dict(): def test_delete_notification_config_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.DeleteNotificationConfigRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1358,7 +1344,6 @@ def test_delete_notification_config_field_headers(): type(client.transport.delete_notification_config), "__call__" ) as call: call.return_value = None - client.delete_notification_config(request) # Establish that the underlying gRPC stub method was called. @@ -1373,11 +1358,14 @@ def test_delete_notification_config_field_headers(): @pytest.mark.asyncio async def test_delete_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.DeleteNotificationConfigRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1385,7 +1373,6 @@ async def test_delete_notification_config_field_headers_async(): type(client.transport.delete_notification_config), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_notification_config(request) # Establish that the underlying gRPC stub method was called. @@ -1399,7 +1386,7 @@ async def test_delete_notification_config_field_headers_async(): def test_delete_notification_config_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1407,7 +1394,6 @@ def test_delete_notification_config_flattened(): ) 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_notification_config(name="name_value",) @@ -1416,12 +1402,11 @@ def test_delete_notification_config_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_notification_config_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1433,7 +1418,9 @@ def test_delete_notification_config_flattened_error(): @pytest.mark.asyncio async def test_delete_notification_config_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1451,13 +1438,14 @@ async def test_delete_notification_config_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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1468,10 +1456,10 @@ async def test_delete_notification_config_flattened_error_async(): def test_get_iam_policy( - transport: str = "grpc", request_type=iam_policy.GetIamPolicyRequest + transport: str = "grpc", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1481,22 +1469,17 @@ def test_get_iam_policy( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy(version=774, etag=b"etag_blob",) - + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) response = client.get_iam_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] == iam_policy.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -1508,7 +1491,7 @@ def test_get_iam_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1516,16 +1499,15 @@ def test_get_iam_policy_empty_call(): client.get_iam_policy() call.assert_called() _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() @pytest.mark.asyncio async def test_get_iam_policy_async( - transport: str = "grpc_asyncio", request_type=iam_policy.GetIamPolicyRequest + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1536,22 +1518,18 @@ async def test_get_iam_policy_async( with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy.Policy(version=774, etag=b"etag_blob",) + policy_pb2.Policy(version=774, etag=b"etag_blob",) ) - response = await client.get_iam_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -1561,17 +1539,17 @@ async def test_get_iam_policy_async_from_dict(): def test_get_iam_policy_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = iam_policy.GetIamPolicyRequest() + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() client.get_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1586,17 +1564,19 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = iam_policy.GetIamPolicyRequest() + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) - + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) await client.get_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1610,29 +1590,27 @@ async def test_get_iam_policy_field_headers_async(): def test_get_iam_policy_from_dict_foreign(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() response = client.get_iam_policy( request={ "resource": "resource_value", - "options": options.GetPolicyOptions(requested_policy_version=2598), + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), } ) call.assert_called() def test_get_iam_policy_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_iam_policy(resource="resource_value",) @@ -1641,31 +1619,32 @@ def test_get_iam_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" def test_get_iam_policy_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.get_iam_policy( - iam_policy.GetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.GetIamPolicyRequest(), resource="resource_value", ) @pytest.mark.asyncio async def test_get_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() + call.return_value = policy_pb2.Policy() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_iam_policy(resource="resource_value",) @@ -1674,19 +1653,20 @@ async def test_get_iam_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" @pytest.mark.asyncio async def test_get_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.get_iam_policy( - iam_policy.GetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.GetIamPolicyRequest(), resource="resource_value", ) @@ -1695,7 +1675,7 @@ def test_get_notification_config( request_type=securitycenter_service.GetNotificationConfigRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1716,25 +1696,18 @@ def test_get_notification_config( filter="filter_value" ), ) - response = client.get_notification_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.pubsub_topic == "pubsub_topic_value" - assert response.service_account == "service_account_value" @@ -1746,7 +1719,7 @@ def test_get_notification_config_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1756,7 +1729,6 @@ def test_get_notification_config_empty_call(): client.get_notification_config() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() @@ -1766,7 +1738,7 @@ async def test_get_notification_config_async( request_type=securitycenter_service.GetNotificationConfigRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1786,24 +1758,18 @@ async def test_get_notification_config_async( service_account="service_account_value", ) ) - response = await client.get_notification_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() # Establish that the response is the type that we expect. assert isinstance(response, notification_config.NotificationConfig) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.pubsub_topic == "pubsub_topic_value" - assert response.service_account == "service_account_value" @@ -1813,11 +1779,12 @@ async def test_get_notification_config_async_from_dict(): def test_get_notification_config_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.GetNotificationConfigRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1825,7 +1792,6 @@ def test_get_notification_config_field_headers(): type(client.transport.get_notification_config), "__call__" ) as call: call.return_value = notification_config.NotificationConfig() - client.get_notification_config(request) # Establish that the underlying gRPC stub method was called. @@ -1840,11 +1806,14 @@ def test_get_notification_config_field_headers(): @pytest.mark.asyncio async def test_get_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GetNotificationConfigRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1854,7 +1823,6 @@ async def test_get_notification_config_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( notification_config.NotificationConfig() ) - await client.get_notification_config(request) # Establish that the underlying gRPC stub method was called. @@ -1868,7 +1836,7 @@ async def test_get_notification_config_field_headers_async(): def test_get_notification_config_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1876,7 +1844,6 @@ def test_get_notification_config_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_notification_config(name="name_value",) @@ -1885,12 +1852,11 @@ def test_get_notification_config_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_notification_config_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1902,7 +1868,9 @@ def test_get_notification_config_flattened_error(): @pytest.mark.asyncio async def test_get_notification_config_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1922,13 +1890,14 @@ async def test_get_notification_config_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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1943,7 +1912,7 @@ def test_get_organization_settings( request_type=securitycenter_service.GetOrganizationSettingsRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1958,21 +1927,16 @@ def test_get_organization_settings( call.return_value = organization_settings.OrganizationSettings( name="name_value", enable_asset_discovery=True, ) - response = client.get_organization_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == "name_value" - assert response.enable_asset_discovery is True @@ -1984,7 +1948,7 @@ def test_get_organization_settings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1994,7 +1958,6 @@ def test_get_organization_settings_empty_call(): client.get_organization_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() @@ -2004,7 +1967,7 @@ async def test_get_organization_settings_async( request_type=securitycenter_service.GetOrganizationSettingsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2021,20 +1984,16 @@ async def test_get_organization_settings_async( name="name_value", enable_asset_discovery=True, ) ) - response = await client.get_organization_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == "name_value" - assert response.enable_asset_discovery is True @@ -2044,11 +2003,12 @@ async def test_get_organization_settings_async_from_dict(): def test_get_organization_settings_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.GetOrganizationSettingsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2056,7 +2016,6 @@ def test_get_organization_settings_field_headers(): type(client.transport.get_organization_settings), "__call__" ) as call: call.return_value = organization_settings.OrganizationSettings() - client.get_organization_settings(request) # Establish that the underlying gRPC stub method was called. @@ -2071,11 +2030,14 @@ def test_get_organization_settings_field_headers(): @pytest.mark.asyncio async def test_get_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GetOrganizationSettingsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2085,7 +2047,6 @@ async def test_get_organization_settings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( organization_settings.OrganizationSettings() ) - await client.get_organization_settings(request) # Establish that the underlying gRPC stub method was called. @@ -2099,7 +2060,7 @@ async def test_get_organization_settings_field_headers_async(): def test_get_organization_settings_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2107,7 +2068,6 @@ def test_get_organization_settings_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_organization_settings(name="name_value",) @@ -2116,12 +2076,11 @@ def test_get_organization_settings_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_organization_settings_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2133,7 +2092,9 @@ def test_get_organization_settings_flattened_error(): @pytest.mark.asyncio async def test_get_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2153,13 +2114,14 @@ async def test_get_organization_settings_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_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2173,7 +2135,7 @@ def test_get_source( transport: str = "grpc", request_type=securitycenter_service.GetSourceRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2187,25 +2149,21 @@ def test_get_source( name="name_value", display_name="display_name_value", description="description_value", + canonical_name="canonical_name_value", ) - response = client.get_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" def test_get_source_from_dict(): @@ -2216,7 +2174,7 @@ def test_get_source_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2224,7 +2182,6 @@ def test_get_source_empty_call(): client.get_source() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() @@ -2234,7 +2191,7 @@ async def test_get_source_async( request_type=securitycenter_service.GetSourceRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2249,25 +2206,22 @@ async def test_get_source_async( name="name_value", display_name="display_name_value", description="description_value", + canonical_name="canonical_name_value", ) ) - response = await client.get_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() # Establish that the response is the type that we expect. assert isinstance(response, source.Source) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" @pytest.mark.asyncio @@ -2276,17 +2230,17 @@ async def test_get_source_async_from_dict(): def test_get_source_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.GetSourceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_source), "__call__") as call: call.return_value = source.Source() - client.get_source(request) # Establish that the underlying gRPC stub method was called. @@ -2301,17 +2255,19 @@ def test_get_source_field_headers(): @pytest.mark.asyncio async def test_get_source_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GetSourceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_source), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - await client.get_source(request) # Establish that the underlying gRPC stub method was called. @@ -2325,13 +2281,12 @@ async def test_get_source_field_headers_async(): def test_get_source_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_source), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = source.Source() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_source(name="name_value",) @@ -2340,12 +2295,11 @@ def test_get_source_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_source_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2357,7 +2311,9 @@ def test_get_source_flattened_error(): @pytest.mark.asyncio async def test_get_source_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_source), "__call__") as call: @@ -2373,13 +2329,14 @@ async def test_get_source_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_source_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2393,7 +2350,7 @@ def test_group_assets( transport: str = "grpc", request_type=securitycenter_service.GroupAssetsRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2406,21 +2363,16 @@ def test_group_assets( call.return_value = securitycenter_service.GroupAssetsResponse( next_page_token="next_page_token_value", total_size=1086, ) - response = client.group_assets(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -2432,7 +2384,7 @@ def test_group_assets_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2440,7 +2392,6 @@ def test_group_assets_empty_call(): client.group_assets() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() @@ -2450,7 +2401,7 @@ async def test_group_assets_async( request_type=securitycenter_service.GroupAssetsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2465,20 +2416,16 @@ async def test_group_assets_async( next_page_token="next_page_token_value", total_size=1086, ) ) - response = await client.group_assets(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.GroupAssetsAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -2488,17 +2435,17 @@ async def test_group_assets_async_from_dict(): def test_group_assets_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.GroupAssetsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_assets), "__call__") as call: call.return_value = securitycenter_service.GroupAssetsResponse() - client.group_assets(request) # Establish that the underlying gRPC stub method was called. @@ -2513,11 +2460,14 @@ def test_group_assets_field_headers(): @pytest.mark.asyncio async def test_group_assets_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GroupAssetsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2525,7 +2475,6 @@ async def test_group_assets_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( securitycenter_service.GroupAssetsResponse() ) - await client.group_assets(request) # Establish that the underlying gRPC stub method was called. @@ -2539,7 +2488,7 @@ async def test_group_assets_field_headers_async(): def test_group_assets_pager(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_assets), "__call__") as call: @@ -2583,7 +2532,7 @@ def test_group_assets_pager(): def test_group_assets_pages(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_assets), "__call__") as call: @@ -2619,7 +2568,7 @@ def test_group_assets_pages(): @pytest.mark.asyncio async def test_group_assets_async_pager(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2662,7 +2611,7 @@ async def test_group_assets_async_pager(): @pytest.mark.asyncio async def test_group_assets_async_pages(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2704,7 +2653,7 @@ def test_group_findings( transport: str = "grpc", request_type=securitycenter_service.GroupFindingsRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2717,21 +2666,16 @@ def test_group_findings( call.return_value = securitycenter_service.GroupFindingsResponse( next_page_token="next_page_token_value", total_size=1086, ) - response = client.group_findings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -2743,7 +2687,7 @@ def test_group_findings_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2751,7 +2695,6 @@ def test_group_findings_empty_call(): client.group_findings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() @@ -2761,7 +2704,7 @@ async def test_group_findings_async( request_type=securitycenter_service.GroupFindingsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2776,20 +2719,16 @@ async def test_group_findings_async( next_page_token="next_page_token_value", total_size=1086, ) ) - response = await client.group_findings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.GroupFindingsAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -2799,17 +2738,17 @@ async def test_group_findings_async_from_dict(): def test_group_findings_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.GroupFindingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_findings), "__call__") as call: call.return_value = securitycenter_service.GroupFindingsResponse() - client.group_findings(request) # Establish that the underlying gRPC stub method was called. @@ -2824,11 +2763,14 @@ def test_group_findings_field_headers(): @pytest.mark.asyncio async def test_group_findings_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GroupFindingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2836,7 +2778,6 @@ async def test_group_findings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( securitycenter_service.GroupFindingsResponse() ) - await client.group_findings(request) # Establish that the underlying gRPC stub method was called. @@ -2850,13 +2791,12 @@ async def test_group_findings_field_headers_async(): def test_group_findings_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_findings), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = securitycenter_service.GroupFindingsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.group_findings( @@ -2867,14 +2807,12 @@ def test_group_findings_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].group_by == "group_by_value" def test_group_findings_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2888,7 +2826,9 @@ def test_group_findings_flattened_error(): @pytest.mark.asyncio async def test_group_findings_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_findings), "__call__") as call: @@ -2908,15 +2848,15 @@ async def test_group_findings_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].group_by == "group_by_value" @pytest.mark.asyncio async def test_group_findings_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2929,7 +2869,7 @@ async def test_group_findings_flattened_error_async(): def test_group_findings_pager(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_findings), "__call__") as call: @@ -2973,7 +2913,7 @@ def test_group_findings_pager(): def test_group_findings_pages(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_findings), "__call__") as call: @@ -3009,7 +2949,7 @@ def test_group_findings_pages(): @pytest.mark.asyncio async def test_group_findings_async_pager(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3052,7 +2992,7 @@ async def test_group_findings_async_pager(): @pytest.mark.asyncio async def test_group_findings_async_pages(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3094,7 +3034,7 @@ def test_list_assets( transport: str = "grpc", request_type=securitycenter_service.ListAssetsRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3107,21 +3047,16 @@ def test_list_assets( call.return_value = securitycenter_service.ListAssetsResponse( next_page_token="next_page_token_value", total_size=1086, ) - response = client.list_assets(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -3133,7 +3068,7 @@ def test_list_assets_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3141,7 +3076,6 @@ def test_list_assets_empty_call(): client.list_assets() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() @@ -3151,7 +3085,7 @@ async def test_list_assets_async( request_type=securitycenter_service.ListAssetsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3166,20 +3100,16 @@ async def test_list_assets_async( next_page_token="next_page_token_value", total_size=1086, ) ) - response = await client.list_assets(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAssetsAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -3189,17 +3119,17 @@ async def test_list_assets_async_from_dict(): def test_list_assets_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.ListAssetsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_assets), "__call__") as call: call.return_value = securitycenter_service.ListAssetsResponse() - client.list_assets(request) # Establish that the underlying gRPC stub method was called. @@ -3214,11 +3144,14 @@ def test_list_assets_field_headers(): @pytest.mark.asyncio async def test_list_assets_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListAssetsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3226,7 +3159,6 @@ async def test_list_assets_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( securitycenter_service.ListAssetsResponse() ) - await client.list_assets(request) # Establish that the underlying gRPC stub method was called. @@ -3240,7 +3172,7 @@ async def test_list_assets_field_headers_async(): def test_list_assets_pager(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_assets), "__call__") as call: @@ -3289,7 +3221,7 @@ def test_list_assets_pager(): def test_list_assets_pages(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_assets), "__call__") as call: @@ -3327,7 +3259,7 @@ def test_list_assets_pages(): @pytest.mark.asyncio async def test_list_assets_async_pager(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3375,7 +3307,7 @@ async def test_list_assets_async_pager(): @pytest.mark.asyncio async def test_list_assets_async_pages(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3419,7 +3351,7 @@ def test_list_findings( transport: str = "grpc", request_type=securitycenter_service.ListFindingsRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3432,21 +3364,16 @@ def test_list_findings( call.return_value = securitycenter_service.ListFindingsResponse( next_page_token="next_page_token_value", total_size=1086, ) - response = client.list_findings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -3458,7 +3385,7 @@ def test_list_findings_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3466,7 +3393,6 @@ def test_list_findings_empty_call(): client.list_findings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() @@ -3476,7 +3402,7 @@ async def test_list_findings_async( request_type=securitycenter_service.ListFindingsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3491,20 +3417,16 @@ async def test_list_findings_async( next_page_token="next_page_token_value", total_size=1086, ) ) - response = await client.list_findings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListFindingsAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -3514,17 +3436,17 @@ async def test_list_findings_async_from_dict(): def test_list_findings_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.ListFindingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_findings), "__call__") as call: call.return_value = securitycenter_service.ListFindingsResponse() - client.list_findings(request) # Establish that the underlying gRPC stub method was called. @@ -3539,11 +3461,14 @@ def test_list_findings_field_headers(): @pytest.mark.asyncio async def test_list_findings_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListFindingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3551,7 +3476,6 @@ async def test_list_findings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( securitycenter_service.ListFindingsResponse() ) - await client.list_findings(request) # Establish that the underlying gRPC stub method was called. @@ -3565,7 +3489,7 @@ async def test_list_findings_field_headers_async(): def test_list_findings_pager(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_findings), "__call__") as call: @@ -3616,7 +3540,7 @@ def test_list_findings_pager(): def test_list_findings_pages(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_findings), "__call__") as call: @@ -3654,7 +3578,7 @@ def test_list_findings_pages(): @pytest.mark.asyncio async def test_list_findings_async_pager(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3704,7 +3628,7 @@ async def test_list_findings_async_pager(): @pytest.mark.asyncio async def test_list_findings_async_pages(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3749,7 +3673,7 @@ def test_list_notification_configs( request_type=securitycenter_service.ListNotificationConfigsRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3764,19 +3688,15 @@ def test_list_notification_configs( call.return_value = securitycenter_service.ListNotificationConfigsResponse( next_page_token="next_page_token_value", ) - response = client.list_notification_configs(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsPager) - assert response.next_page_token == "next_page_token_value" @@ -3788,7 +3708,7 @@ def test_list_notification_configs_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3798,7 +3718,6 @@ def test_list_notification_configs_empty_call(): client.list_notification_configs() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() @@ -3808,7 +3727,7 @@ async def test_list_notification_configs_async( request_type=securitycenter_service.ListNotificationConfigsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3825,18 +3744,15 @@ async def test_list_notification_configs_async( next_page_token="next_page_token_value", ) ) - response = await client.list_notification_configs(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -3846,11 +3762,12 @@ async def test_list_notification_configs_async_from_dict(): def test_list_notification_configs_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.ListNotificationConfigsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3858,7 +3775,6 @@ def test_list_notification_configs_field_headers(): type(client.transport.list_notification_configs), "__call__" ) as call: call.return_value = securitycenter_service.ListNotificationConfigsResponse() - client.list_notification_configs(request) # Establish that the underlying gRPC stub method was called. @@ -3873,11 +3789,14 @@ def test_list_notification_configs_field_headers(): @pytest.mark.asyncio async def test_list_notification_configs_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListNotificationConfigsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3887,7 +3806,6 @@ async def test_list_notification_configs_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( securitycenter_service.ListNotificationConfigsResponse() ) - await client.list_notification_configs(request) # Establish that the underlying gRPC stub method was called. @@ -3901,7 +3819,7 @@ async def test_list_notification_configs_field_headers_async(): def test_list_notification_configs_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3909,7 +3827,6 @@ def test_list_notification_configs_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = securitycenter_service.ListNotificationConfigsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_notification_configs(parent="parent_value",) @@ -3918,12 +3835,11 @@ def test_list_notification_configs_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_notification_configs_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3936,7 +3852,9 @@ def test_list_notification_configs_flattened_error(): @pytest.mark.asyncio async def test_list_notification_configs_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3956,13 +3874,14 @@ async def test_list_notification_configs_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_notification_configs_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3974,7 +3893,7 @@ async def test_list_notification_configs_flattened_error_async(): def test_list_notification_configs_pager(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4022,7 +3941,7 @@ def test_list_notification_configs_pager(): def test_list_notification_configs_pages(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4060,7 +3979,7 @@ def test_list_notification_configs_pages(): @pytest.mark.asyncio async def test_list_notification_configs_async_pager(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4107,7 +4026,7 @@ async def test_list_notification_configs_async_pager(): @pytest.mark.asyncio async def test_list_notification_configs_async_pages(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4151,7 +4070,7 @@ def test_list_sources( transport: str = "grpc", request_type=securitycenter_service.ListSourcesRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4164,19 +4083,15 @@ def test_list_sources( call.return_value = securitycenter_service.ListSourcesResponse( next_page_token="next_page_token_value", ) - response = client.list_sources(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == "next_page_token_value" @@ -4188,7 +4103,7 @@ def test_list_sources_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4196,7 +4111,6 @@ def test_list_sources_empty_call(): client.list_sources() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() @@ -4206,7 +4120,7 @@ async def test_list_sources_async( request_type=securitycenter_service.ListSourcesRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4221,18 +4135,15 @@ async def test_list_sources_async( next_page_token="next_page_token_value", ) ) - response = await client.list_sources(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListSourcesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -4242,17 +4153,17 @@ async def test_list_sources_async_from_dict(): def test_list_sources_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.ListSourcesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_sources), "__call__") as call: call.return_value = securitycenter_service.ListSourcesResponse() - client.list_sources(request) # Establish that the underlying gRPC stub method was called. @@ -4267,11 +4178,14 @@ def test_list_sources_field_headers(): @pytest.mark.asyncio async def test_list_sources_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListSourcesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -4279,7 +4193,6 @@ async def test_list_sources_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( securitycenter_service.ListSourcesResponse() ) - await client.list_sources(request) # Establish that the underlying gRPC stub method was called. @@ -4293,13 +4206,12 @@ async def test_list_sources_field_headers_async(): def test_list_sources_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_sources), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = securitycenter_service.ListSourcesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_sources(parent="parent_value",) @@ -4308,12 +4220,11 @@ def test_list_sources_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_sources_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4325,7 +4236,9 @@ def test_list_sources_flattened_error(): @pytest.mark.asyncio async def test_list_sources_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_sources), "__call__") as call: @@ -4343,13 +4256,14 @@ async def test_list_sources_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_sources_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4360,7 +4274,7 @@ async def test_list_sources_flattened_error_async(): def test_list_sources_pager(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_sources), "__call__") as call: @@ -4396,7 +4310,7 @@ def test_list_sources_pager(): def test_list_sources_pages(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_sources), "__call__") as call: @@ -4424,7 +4338,7 @@ def test_list_sources_pages(): @pytest.mark.asyncio async def test_list_sources_async_pager(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4459,7 +4373,7 @@ async def test_list_sources_async_pager(): @pytest.mark.asyncio async def test_list_sources_async_pages(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4494,7 +4408,7 @@ def test_run_asset_discovery( request_type=securitycenter_service.RunAssetDiscoveryRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4507,13 +4421,11 @@ def test_run_asset_discovery( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.run_asset_discovery(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() # Establish that the response is the type that we expect. @@ -4528,7 +4440,7 @@ def test_run_asset_discovery_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4538,7 +4450,6 @@ def test_run_asset_discovery_empty_call(): client.run_asset_discovery() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() @@ -4548,7 +4459,7 @@ async def test_run_asset_discovery_async( request_type=securitycenter_service.RunAssetDiscoveryRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4563,13 +4474,11 @@ async def test_run_asset_discovery_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.run_asset_discovery(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() # Establish that the response is the type that we expect. @@ -4582,11 +4491,12 @@ async def test_run_asset_discovery_async_from_dict(): def test_run_asset_discovery_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.RunAssetDiscoveryRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -4594,7 +4504,6 @@ def test_run_asset_discovery_field_headers(): type(client.transport.run_asset_discovery), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.run_asset_discovery(request) # Establish that the underlying gRPC stub method was called. @@ -4609,11 +4518,14 @@ def test_run_asset_discovery_field_headers(): @pytest.mark.asyncio async def test_run_asset_discovery_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.RunAssetDiscoveryRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -4623,7 +4535,6 @@ async def test_run_asset_discovery_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.run_asset_discovery(request) # Establish that the underlying gRPC stub method was called. @@ -4637,7 +4548,7 @@ async def test_run_asset_discovery_field_headers_async(): def test_run_asset_discovery_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4645,7 +4556,6 @@ def test_run_asset_discovery_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.run_asset_discovery(parent="parent_value",) @@ -4654,12 +4564,11 @@ def test_run_asset_discovery_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_run_asset_discovery_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4671,7 +4580,9 @@ def test_run_asset_discovery_flattened_error(): @pytest.mark.asyncio async def test_run_asset_discovery_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4691,13 +4602,14 @@ async def test_run_asset_discovery_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_run_asset_discovery_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4711,7 +4623,7 @@ def test_set_finding_state( transport: str = "grpc", request_type=securitycenter_service.SetFindingStateRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4731,33 +4643,25 @@ def test_set_finding_state( category="category_value", external_uri="external_uri_value", severity=finding.Finding.Severity.CRITICAL, + canonical_name="canonical_name_value", ) - response = client.set_finding_state(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.resource_name == "resource_name_value" - assert response.state == finding.Finding.State.ACTIVE - assert response.category == "category_value" - assert response.external_uri == "external_uri_value" - assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == "canonical_name_value" def test_set_finding_state_from_dict(): @@ -4768,7 +4672,7 @@ def test_set_finding_state_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4778,7 +4682,6 @@ def test_set_finding_state_empty_call(): client.set_finding_state() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() @@ -4788,7 +4691,7 @@ async def test_set_finding_state_async( request_type=securitycenter_service.SetFindingStateRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4809,33 +4712,26 @@ async def test_set_finding_state_async( category="category_value", external_uri="external_uri_value", severity=finding.Finding.Severity.CRITICAL, + canonical_name="canonical_name_value", ) ) - response = await client.set_finding_state(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() # Establish that the response is the type that we expect. assert isinstance(response, finding.Finding) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.resource_name == "resource_name_value" - assert response.state == finding.Finding.State.ACTIVE - assert response.category == "category_value" - assert response.external_uri == "external_uri_value" - assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == "canonical_name_value" @pytest.mark.asyncio @@ -4844,11 +4740,12 @@ async def test_set_finding_state_async_from_dict(): def test_set_finding_state_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.SetFindingStateRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -4856,7 +4753,6 @@ def test_set_finding_state_field_headers(): type(client.transport.set_finding_state), "__call__" ) as call: call.return_value = finding.Finding() - client.set_finding_state(request) # Establish that the underlying gRPC stub method was called. @@ -4871,11 +4767,14 @@ def test_set_finding_state_field_headers(): @pytest.mark.asyncio async def test_set_finding_state_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.SetFindingStateRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -4883,7 +4782,6 @@ async def test_set_finding_state_field_headers_async(): type(client.transport.set_finding_state), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.set_finding_state(request) # Establish that the underlying gRPC stub method was called. @@ -4897,7 +4795,7 @@ async def test_set_finding_state_field_headers_async(): def test_set_finding_state_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4905,31 +4803,25 @@ def test_set_finding_state_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = finding.Finding() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.set_finding_state( name="name_value", state=finding.Finding.State.ACTIVE, - start_time=timestamp.Timestamp(seconds=751), + start_time=timestamp_pb2.Timestamp(seconds=751), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].state == finding.Finding.State.ACTIVE - - assert TimestampRule().to_proto(args[0].start_time) == timestamp.Timestamp( - seconds=751 - ) + # # # # assert args[0].start_time == timestamp_pb2.Timestamp(seconds=751) def test_set_finding_state_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4938,13 +4830,15 @@ def test_set_finding_state_flattened_error(): securitycenter_service.SetFindingStateRequest(), name="name_value", state=finding.Finding.State.ACTIVE, - start_time=timestamp.Timestamp(seconds=751), + start_time=timestamp_pb2.Timestamp(seconds=751), ) @pytest.mark.asyncio async def test_set_finding_state_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4959,26 +4853,23 @@ async def test_set_finding_state_flattened_async(): response = await client.set_finding_state( name="name_value", state=finding.Finding.State.ACTIVE, - start_time=timestamp.Timestamp(seconds=751), + start_time=timestamp_pb2.Timestamp(seconds=751), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].state == finding.Finding.State.ACTIVE - - assert TimestampRule().to_proto(args[0].start_time) == timestamp.Timestamp( - seconds=751 - ) + # # # # assert args[0].start_time == timestamp_pb2.Timestamp(seconds=751) @pytest.mark.asyncio async def test_set_finding_state_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4987,15 +4878,15 @@ async def test_set_finding_state_flattened_error_async(): securitycenter_service.SetFindingStateRequest(), name="name_value", state=finding.Finding.State.ACTIVE, - start_time=timestamp.Timestamp(seconds=751), + start_time=timestamp_pb2.Timestamp(seconds=751), ) def test_set_iam_policy( - transport: str = "grpc", request_type=iam_policy.SetIamPolicyRequest + transport: str = "grpc", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5005,22 +4896,17 @@ def test_set_iam_policy( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy(version=774, etag=b"etag_blob",) - + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) response = client.set_iam_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] == iam_policy.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -5032,7 +4918,7 @@ def test_set_iam_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5040,16 +4926,15 @@ def test_set_iam_policy_empty_call(): client.set_iam_policy() call.assert_called() _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() @pytest.mark.asyncio async def test_set_iam_policy_async( - transport: str = "grpc_asyncio", request_type=iam_policy.SetIamPolicyRequest + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5060,22 +4945,18 @@ async def test_set_iam_policy_async( with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy.Policy(version=774, etag=b"etag_blob",) + policy_pb2.Policy(version=774, etag=b"etag_blob",) ) - response = await client.set_iam_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -5085,17 +4966,17 @@ async def test_set_iam_policy_async_from_dict(): def test_set_iam_policy_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = iam_policy.SetIamPolicyRequest() + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() client.set_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -5110,17 +4991,19 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = iam_policy.SetIamPolicyRequest() + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) - + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) await client.set_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -5134,29 +5017,27 @@ async def test_set_iam_policy_field_headers_async(): def test_set_iam_policy_from_dict_foreign(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() response = client.set_iam_policy( request={ "resource": "resource_value", - "policy": policy.Policy(version=774), + "policy": policy_pb2.Policy(version=774), } ) call.assert_called() def test_set_iam_policy_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.set_iam_policy(resource="resource_value",) @@ -5165,31 +5046,32 @@ def test_set_iam_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" def test_set_iam_policy_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.set_iam_policy( - iam_policy.SetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.SetIamPolicyRequest(), resource="resource_value", ) @pytest.mark.asyncio async def test_set_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() + call.return_value = policy_pb2.Policy() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.set_iam_policy(resource="resource_value",) @@ -5198,27 +5080,28 @@ async def test_set_iam_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" @pytest.mark.asyncio async def test_set_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.set_iam_policy( - iam_policy.SetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.SetIamPolicyRequest(), resource="resource_value", ) def test_test_iam_permissions( - transport: str = "grpc", request_type=iam_policy.TestIamPermissionsRequest + transport: str = "grpc", request_type=iam_policy_pb2.TestIamPermissionsRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5230,22 +5113,18 @@ def test_test_iam_permissions( type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = iam_policy.TestIamPermissionsResponse( + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( permissions=["permissions_value"], ) - response = client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, iam_policy.TestIamPermissionsResponse) - + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] @@ -5257,7 +5136,7 @@ def test_test_iam_permissions_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5267,16 +5146,16 @@ def test_test_iam_permissions_empty_call(): client.test_iam_permissions() call.assert_called() _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() @pytest.mark.asyncio async def test_test_iam_permissions_async( - transport: str = "grpc_asyncio", request_type=iam_policy.TestIamPermissionsRequest + transport: str = "grpc_asyncio", + request_type=iam_policy_pb2.TestIamPermissionsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5289,20 +5168,19 @@ async def test_test_iam_permissions_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse(permissions=["permissions_value"],) + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) ) - response = await client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy.TestIamPermissionsResponse) - + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] @@ -5312,19 +5190,19 @@ async def test_test_iam_permissions_async_from_dict(): def test_test_iam_permissions_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = iam_policy.TestIamPermissionsRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.test_iam_permissions), "__call__" ) as call: - call.return_value = iam_policy.TestIamPermissionsResponse() - + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. @@ -5339,11 +5217,14 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = iam_policy.TestIamPermissionsRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -5351,9 +5232,8 @@ async def test_test_iam_permissions_field_headers_async(): type(client.transport.test_iam_permissions), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) - await client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. @@ -5367,14 +5247,13 @@ async def test_test_iam_permissions_field_headers_async(): def test_test_iam_permissions_from_dict_foreign(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = iam_policy.TestIamPermissionsResponse() - + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() response = client.test_iam_permissions( request={ "resource": "resource_value", @@ -5385,15 +5264,14 @@ def test_test_iam_permissions_from_dict_foreign(): def test_test_iam_permissions_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = iam_policy.TestIamPermissionsResponse() - + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.test_iam_permissions( @@ -5404,20 +5282,18 @@ def test_test_iam_permissions_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" - assert args[0].permissions == ["permissions_value"] def test_test_iam_permissions_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.test_iam_permissions( - iam_policy.TestIamPermissionsRequest(), + iam_policy_pb2.TestIamPermissionsRequest(), resource="resource_value", permissions=["permissions_value"], ) @@ -5425,17 +5301,19 @@ def test_test_iam_permissions_flattened_error(): @pytest.mark.asyncio async def test_test_iam_permissions_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = iam_policy.TestIamPermissionsResponse() + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. @@ -5447,21 +5325,21 @@ async def test_test_iam_permissions_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" - assert args[0].permissions == ["permissions_value"] @pytest.mark.asyncio async def test_test_iam_permissions_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.test_iam_permissions( - iam_policy.TestIamPermissionsRequest(), + iam_policy_pb2.TestIamPermissionsRequest(), resource="resource_value", permissions=["permissions_value"], ) @@ -5471,7 +5349,7 @@ def test_update_finding( transport: str = "grpc", request_type=securitycenter_service.UpdateFindingRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5489,33 +5367,25 @@ def test_update_finding( category="category_value", external_uri="external_uri_value", severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name="canonical_name_value", ) - response = client.update_finding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.resource_name == "resource_name_value" - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == "category_value" - assert response.external_uri == "external_uri_value" - assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == "canonical_name_value" def test_update_finding_from_dict(): @@ -5526,7 +5396,7 @@ def test_update_finding_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5534,7 +5404,6 @@ def test_update_finding_empty_call(): client.update_finding() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() @@ -5544,7 +5413,7 @@ async def test_update_finding_async( request_type=securitycenter_service.UpdateFindingRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5563,33 +5432,26 @@ async def test_update_finding_async( category="category_value", external_uri="external_uri_value", severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name="canonical_name_value", ) ) - response = await client.update_finding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_finding.Finding) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.resource_name == "resource_name_value" - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == "category_value" - assert response.external_uri == "external_uri_value" - assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == "canonical_name_value" @pytest.mark.asyncio @@ -5598,17 +5460,17 @@ async def test_update_finding_async_from_dict(): def test_update_finding_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.UpdateFindingRequest() + request.finding.name = "finding.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_finding), "__call__") as call: call.return_value = gcs_finding.Finding() - client.update_finding(request) # Establish that the underlying gRPC stub method was called. @@ -5625,17 +5487,19 @@ def test_update_finding_field_headers(): @pytest.mark.asyncio async def test_update_finding_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateFindingRequest() + request.finding.name = "finding.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_finding), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.update_finding(request) # Establish that the underlying gRPC stub method was called. @@ -5651,13 +5515,12 @@ async def test_update_finding_field_headers_async(): def test_update_finding_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_finding), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_finding(finding=gcs_finding.Finding(name="name_value"),) @@ -5666,12 +5529,11 @@ def test_update_finding_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].finding == gcs_finding.Finding(name="name_value") def test_update_finding_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5684,7 +5546,9 @@ def test_update_finding_flattened_error(): @pytest.mark.asyncio async def test_update_finding_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_finding), "__call__") as call: @@ -5702,13 +5566,14 @@ async def test_update_finding_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].finding == gcs_finding.Finding(name="name_value") @pytest.mark.asyncio async def test_update_finding_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5724,7 +5589,7 @@ def test_update_notification_config( request_type=securitycenter_service.UpdateNotificationConfigRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5745,25 +5610,18 @@ def test_update_notification_config( filter="filter_value" ), ) - response = client.update_notification_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.pubsub_topic == "pubsub_topic_value" - assert response.service_account == "service_account_value" @@ -5775,7 +5633,7 @@ def test_update_notification_config_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5785,7 +5643,6 @@ def test_update_notification_config_empty_call(): client.update_notification_config() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() @@ -5795,7 +5652,7 @@ async def test_update_notification_config_async( request_type=securitycenter_service.UpdateNotificationConfigRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5815,24 +5672,18 @@ async def test_update_notification_config_async( service_account="service_account_value", ) ) - response = await client.update_notification_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.pubsub_topic == "pubsub_topic_value" - assert response.service_account == "service_account_value" @@ -5842,11 +5693,12 @@ async def test_update_notification_config_async_from_dict(): def test_update_notification_config_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.UpdateNotificationConfigRequest() + request.notification_config.name = "notification_config.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -5854,7 +5706,6 @@ def test_update_notification_config_field_headers(): type(client.transport.update_notification_config), "__call__" ) as call: call.return_value = gcs_notification_config.NotificationConfig() - client.update_notification_config(request) # Establish that the underlying gRPC stub method was called. @@ -5872,11 +5723,14 @@ def test_update_notification_config_field_headers(): @pytest.mark.asyncio async def test_update_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateNotificationConfigRequest() + request.notification_config.name = "notification_config.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -5886,7 +5740,6 @@ async def test_update_notification_config_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcs_notification_config.NotificationConfig() ) - await client.update_notification_config(request) # Establish that the underlying gRPC stub method was called. @@ -5903,7 +5756,7 @@ async def test_update_notification_config_field_headers_async(): def test_update_notification_config_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -5911,32 +5764,29 @@ def test_update_notification_config_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcs_notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_notification_config( notification_config=gcs_notification_config.NotificationConfig( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[ 0 ].notification_config == gcs_notification_config.NotificationConfig( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_notification_config_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5946,13 +5796,15 @@ def test_update_notification_config_flattened_error(): notification_config=gcs_notification_config.NotificationConfig( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_notification_config_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -5970,26 +5822,26 @@ async def test_update_notification_config_flattened_async(): notification_config=gcs_notification_config.NotificationConfig( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[ 0 ].notification_config == gcs_notification_config.NotificationConfig( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5999,7 +5851,7 @@ async def test_update_notification_config_flattened_error_async(): notification_config=gcs_notification_config.NotificationConfig( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -6008,7 +5860,7 @@ def test_update_organization_settings( request_type=securitycenter_service.UpdateOrganizationSettingsRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -6023,21 +5875,16 @@ def test_update_organization_settings( call.return_value = gcs_organization_settings.OrganizationSettings( name="name_value", enable_asset_discovery=True, ) - response = client.update_organization_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == "name_value" - assert response.enable_asset_discovery is True @@ -6049,7 +5896,7 @@ def test_update_organization_settings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6059,7 +5906,6 @@ def test_update_organization_settings_empty_call(): client.update_organization_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() @@ -6069,7 +5915,7 @@ async def test_update_organization_settings_async( request_type=securitycenter_service.UpdateOrganizationSettingsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -6086,20 +5932,16 @@ async def test_update_organization_settings_async( name="name_value", enable_asset_discovery=True, ) ) - response = await client.update_organization_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == "name_value" - assert response.enable_asset_discovery is True @@ -6109,11 +5951,12 @@ async def test_update_organization_settings_async_from_dict(): def test_update_organization_settings_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.UpdateOrganizationSettingsRequest() + request.organization_settings.name = "organization_settings.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -6121,7 +5964,6 @@ def test_update_organization_settings_field_headers(): type(client.transport.update_organization_settings), "__call__" ) as call: call.return_value = gcs_organization_settings.OrganizationSettings() - client.update_organization_settings(request) # Establish that the underlying gRPC stub method was called. @@ -6139,11 +5981,14 @@ def test_update_organization_settings_field_headers(): @pytest.mark.asyncio async def test_update_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateOrganizationSettingsRequest() + request.organization_settings.name = "organization_settings.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -6153,7 +5998,6 @@ async def test_update_organization_settings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcs_organization_settings.OrganizationSettings() ) - await client.update_organization_settings(request) # Establish that the underlying gRPC stub method was called. @@ -6170,7 +6014,7 @@ async def test_update_organization_settings_field_headers_async(): def test_update_organization_settings_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -6178,7 +6022,6 @@ def test_update_organization_settings_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcs_organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_organization_settings( @@ -6191,7 +6034,6 @@ def test_update_organization_settings_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[ 0 ].organization_settings == gcs_organization_settings.OrganizationSettings( @@ -6200,7 +6042,7 @@ def test_update_organization_settings_flattened(): def test_update_organization_settings_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -6215,7 +6057,9 @@ def test_update_organization_settings_flattened_error(): @pytest.mark.asyncio async def test_update_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -6239,7 +6083,6 @@ async def test_update_organization_settings_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[ 0 ].organization_settings == gcs_organization_settings.OrganizationSettings( @@ -6249,7 +6092,9 @@ async def test_update_organization_settings_flattened_async(): @pytest.mark.asyncio async def test_update_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -6266,7 +6111,7 @@ def test_update_source( transport: str = "grpc", request_type=securitycenter_service.UpdateSourceRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -6280,25 +6125,21 @@ def test_update_source( name="name_value", display_name="display_name_value", description="description_value", + canonical_name="canonical_name_value", ) - response = client.update_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" def test_update_source_from_dict(): @@ -6309,7 +6150,7 @@ def test_update_source_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6317,7 +6158,6 @@ def test_update_source_empty_call(): client.update_source() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() @@ -6327,7 +6167,7 @@ async def test_update_source_async( request_type=securitycenter_service.UpdateSourceRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -6342,25 +6182,22 @@ async def test_update_source_async( name="name_value", display_name="display_name_value", description="description_value", + canonical_name="canonical_name_value", ) ) - response = await client.update_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_source.Source) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" @pytest.mark.asyncio @@ -6369,17 +6206,17 @@ async def test_update_source_async_from_dict(): def test_update_source_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.UpdateSourceRequest() + request.source.name = "source.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_source), "__call__") as call: call.return_value = gcs_source.Source() - client.update_source(request) # Establish that the underlying gRPC stub method was called. @@ -6394,17 +6231,19 @@ def test_update_source_field_headers(): @pytest.mark.asyncio async def test_update_source_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateSourceRequest() + request.source.name = "source.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_source), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.update_source(request) # Establish that the underlying gRPC stub method was called. @@ -6418,13 +6257,12 @@ async def test_update_source_field_headers_async(): def test_update_source_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_source), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_source(source=gcs_source.Source(name="name_value"),) @@ -6433,12 +6271,11 @@ def test_update_source_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].source == gcs_source.Source(name="name_value") def test_update_source_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -6451,7 +6288,9 @@ def test_update_source_flattened_error(): @pytest.mark.asyncio async def test_update_source_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_source), "__call__") as call: @@ -6469,13 +6308,14 @@ async def test_update_source_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].source == gcs_source.Source(name="name_value") @pytest.mark.asyncio async def test_update_source_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -6491,7 +6331,7 @@ def test_update_security_marks( request_type=securitycenter_service.UpdateSecurityMarksRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -6503,21 +6343,20 @@ def test_update_security_marks( type(client.transport.update_security_marks), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks(name="name_value",) - + call.return_value = gcs_security_marks.SecurityMarks( + name="name_value", canonical_name="canonical_name_value", + ) response = client.update_security_marks(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == "name_value" + assert response.canonical_name == "canonical_name_value" def test_update_security_marks_from_dict(): @@ -6528,7 +6367,7 @@ def test_update_security_marks_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6538,7 +6377,6 @@ def test_update_security_marks_empty_call(): client.update_security_marks() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() @@ -6548,7 +6386,7 @@ async def test_update_security_marks_async( request_type=securitycenter_service.UpdateSecurityMarksRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -6561,21 +6399,21 @@ async def test_update_security_marks_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcs_security_marks.SecurityMarks(name="name_value",) + gcs_security_marks.SecurityMarks( + name="name_value", canonical_name="canonical_name_value", + ) ) - response = await client.update_security_marks(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == "name_value" + assert response.canonical_name == "canonical_name_value" @pytest.mark.asyncio @@ -6584,11 +6422,12 @@ async def test_update_security_marks_async_from_dict(): def test_update_security_marks_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.UpdateSecurityMarksRequest() + request.security_marks.name = "security_marks.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -6596,7 +6435,6 @@ def test_update_security_marks_field_headers(): type(client.transport.update_security_marks), "__call__" ) as call: call.return_value = gcs_security_marks.SecurityMarks() - client.update_security_marks(request) # Establish that the underlying gRPC stub method was called. @@ -6614,11 +6452,14 @@ def test_update_security_marks_field_headers(): @pytest.mark.asyncio async def test_update_security_marks_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateSecurityMarksRequest() + request.security_marks.name = "security_marks.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -6628,7 +6469,6 @@ async def test_update_security_marks_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcs_security_marks.SecurityMarks() ) - await client.update_security_marks(request) # Establish that the underlying gRPC stub method was called. @@ -6645,7 +6485,7 @@ async def test_update_security_marks_field_headers_async(): def test_update_security_marks_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -6653,7 +6493,6 @@ def test_update_security_marks_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcs_security_marks.SecurityMarks() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_security_marks( @@ -6664,14 +6503,13 @@ def test_update_security_marks_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].security_marks == gcs_security_marks.SecurityMarks( name="name_value" ) def test_update_security_marks_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -6684,7 +6522,9 @@ def test_update_security_marks_flattened_error(): @pytest.mark.asyncio async def test_update_security_marks_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -6706,7 +6546,6 @@ async def test_update_security_marks_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].security_marks == gcs_security_marks.SecurityMarks( name="name_value" ) @@ -6714,7 +6553,9 @@ async def test_update_security_marks_flattened_async(): @pytest.mark.asyncio async def test_update_security_marks_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -6728,16 +6569,16 @@ async def test_update_security_marks_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SecurityCenterGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecurityCenterClient( - 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.SecurityCenterGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecurityCenterClient( @@ -6747,7 +6588,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SecurityCenterGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecurityCenterClient( @@ -6758,7 +6599,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SecurityCenterGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SecurityCenterClient(transport=transport) assert client.transport is transport @@ -6767,13 +6608,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.SecurityCenterGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.SecurityCenterGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -6788,23 +6629,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 = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.SecurityCenterGrpcTransport,) def test_security_center_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.SecurityCenterTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -6816,7 +6657,7 @@ def test_security_center_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SecurityCenterTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -6856,15 +6697,37 @@ def test_security_center_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_security_center_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.securitycenter_v1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport( + 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_security_center_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.securitycenter_v1.services.security_center.transports.SecurityCenterTransport._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.SecurityCenterTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -6877,19 +6740,33 @@ def test_security_center_base_transport_with_credentials_file(): def test_security_center_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.securitycenter_v1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SecurityCenterTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_security_center_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) + SecurityCenterClient() + 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_security_center_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) SecurityCenterClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -6897,20 +6774,156 @@ def test_security_center_auth_adc(): ) -def test_security_center_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_security_center_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.SecurityCenterGrpcTransport( - 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.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_security_center_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.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_security_center_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( + "securitycenter.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="securitycenter.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.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_security_center_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( + "securitycenter.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.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_security_center_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( + "securitycenter.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", [ @@ -6919,7 +6932,7 @@ def test_security_center_transport_auth_adc(): ], ) def test_security_center_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: @@ -6958,7 +6971,7 @@ def test_security_center_grpc_transport_client_cert_source_for_mtls(transport_cl def test_security_center_host_no_port(): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="securitycenter.googleapis.com" ), @@ -6968,7 +6981,7 @@ def test_security_center_host_no_port(): def test_security_center_host_with_port(): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="securitycenter.googleapis.com:8000" ), @@ -7024,9 +7037,9 @@ def test_security_center_transport_channel_mtls_with_client_cert_source( 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", @@ -7102,7 +7115,7 @@ def test_security_center_transport_channel_mtls_with_adc(transport_class): def test_security_center_grpc_lro_client(): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -7115,7 +7128,7 @@ def test_security_center_grpc_lro_client(): def test_security_center_grpc_lro_async_client(): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -7129,7 +7142,6 @@ def test_security_center_grpc_lro_async_client(): def test_asset_path(): organization = "squid" asset = "clam" - expected = "organizations/{organization}/assets/{asset}".format( organization=organization, asset=asset, ) @@ -7153,7 +7165,6 @@ def test_finding_path(): organization = "oyster" source = "nudibranch" finding = "cuttlefish" - expected = "organizations/{organization}/sources/{source}/findings/{finding}".format( organization=organization, source=source, finding=finding, ) @@ -7177,7 +7188,6 @@ def test_parse_finding_path(): def test_notification_config_path(): organization = "scallop" notification_config = "abalone" - expected = "organizations/{organization}/notificationConfigs/{notification_config}".format( organization=organization, notification_config=notification_config, ) @@ -7201,7 +7211,6 @@ def test_parse_notification_config_path(): def test_organization_settings_path(): organization = "whelk" - expected = "organizations/{organization}/organizationSettings".format( organization=organization, ) @@ -7223,7 +7232,6 @@ def test_parse_organization_settings_path(): def test_security_marks_path(): organization = "oyster" asset = "nudibranch" - expected = "organizations/{organization}/assets/{asset}/securityMarks".format( organization=organization, asset=asset, ) @@ -7246,7 +7254,6 @@ def test_parse_security_marks_path(): def test_source_path(): organization = "winkle" source = "nautilus" - expected = "organizations/{organization}/sources/{source}".format( organization=organization, source=source, ) @@ -7269,7 +7276,6 @@ def test_parse_source_path(): def test_topic_path(): project = "squid" topic = "clam" - expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic,) actual = SecurityCenterClient.topic_path(project, topic) assert expected == actual @@ -7289,7 +7295,6 @@ def test_parse_topic_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -7310,7 +7315,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = SecurityCenterClient.common_folder_path(folder) assert expected == actual @@ -7329,7 +7333,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = SecurityCenterClient.common_organization_path(organization) assert expected == actual @@ -7348,7 +7351,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = SecurityCenterClient.common_project_path(project) assert expected == actual @@ -7368,7 +7370,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -7395,7 +7396,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SecurityCenterTransport, "_prep_wrapped_messages" ) as prep: client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -7404,6 +7405,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SecurityCenterClient.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) diff --git a/tests/unit/gapic/securitycenter_v1beta1/__init__.py b/tests/unit/gapic/securitycenter_v1beta1/__init__.py index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/securitycenter_v1beta1/__init__.py +++ b/tests/unit/gapic/securitycenter_v1beta1/__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/securitycenter_v1beta1/test_security_center.py b/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py index bc4bb9a2..7a968277 100644 --- a/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py +++ b/tests/unit/gapic/securitycenter_v1beta1/test_security_center.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,16 +23,16 @@ 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 future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.securitycenter_v1beta1.services.security_center import ( SecurityCenterAsyncClient, @@ -43,6 +42,12 @@ ) from google.cloud.securitycenter_v1beta1.services.security_center import pagers from google.cloud.securitycenter_v1beta1.services.security_center import transports +from google.cloud.securitycenter_v1beta1.services.security_center.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.securitycenter_v1beta1.services.security_center.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.securitycenter_v1beta1.types import finding from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding from google.cloud.securitycenter_v1beta1.types import organization_settings @@ -56,16 +61,40 @@ from google.cloud.securitycenter_v1beta1.types import securitycenter_service from google.cloud.securitycenter_v1beta1.types import source from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import options_pb2 as options # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.type import expr_pb2 as expr # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # 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(): @@ -116,7 +145,7 @@ def test__get_default_mtls_endpoint(): "client_class", [SecurityCenterClient, SecurityCenterAsyncClient,] ) def test_security_center_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: @@ -133,7 +162,7 @@ def test_security_center_client_from_service_account_info(client_class): "client_class", [SecurityCenterClient, SecurityCenterAsyncClient,] ) def test_security_center_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: @@ -186,7 +215,7 @@ def test_security_center_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(SecurityCenterClient, "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() @@ -474,7 +503,7 @@ def test_create_source( transport: str = "grpc", request_type=securitycenter_service.CreateSourceRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -489,23 +518,17 @@ def test_create_source( display_name="display_name_value", description="description_value", ) - response = client.create_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" @@ -517,7 +540,7 @@ def test_create_source_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -525,7 +548,6 @@ def test_create_source_empty_call(): client.create_source() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() @@ -535,7 +557,7 @@ async def test_create_source_async( request_type=securitycenter_service.CreateSourceRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -552,22 +574,17 @@ async def test_create_source_async( description="description_value", ) ) - response = await client.create_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_source.Source) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" @@ -577,17 +594,17 @@ async def test_create_source_async_from_dict(): def test_create_source_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.CreateSourceRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_source), "__call__") as call: call.return_value = gcs_source.Source() - client.create_source(request) # Establish that the underlying gRPC stub method was called. @@ -602,17 +619,19 @@ def test_create_source_field_headers(): @pytest.mark.asyncio async def test_create_source_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.CreateSourceRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_source), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.create_source(request) # Establish that the underlying gRPC stub method was called. @@ -626,13 +645,12 @@ async def test_create_source_field_headers_async(): def test_create_source_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_source), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_source( @@ -643,14 +661,12 @@ def test_create_source_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].source == gcs_source.Source(name="name_value") def test_create_source_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -664,7 +680,9 @@ def test_create_source_flattened_error(): @pytest.mark.asyncio async def test_create_source_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_source), "__call__") as call: @@ -682,15 +700,15 @@ async def test_create_source_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].source == gcs_source.Source(name="name_value") @pytest.mark.asyncio async def test_create_source_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -706,7 +724,7 @@ def test_create_finding( transport: str = "grpc", request_type=securitycenter_service.CreateFindingRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -724,29 +742,20 @@ def test_create_finding( category="category_value", external_uri="external_uri_value", ) - response = client.create_finding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.resource_name == "resource_name_value" - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == "category_value" - assert response.external_uri == "external_uri_value" @@ -758,7 +767,7 @@ def test_create_finding_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -766,7 +775,6 @@ def test_create_finding_empty_call(): client.create_finding() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() @@ -776,7 +784,7 @@ async def test_create_finding_async( request_type=securitycenter_service.CreateFindingRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -796,28 +804,20 @@ async def test_create_finding_async( external_uri="external_uri_value", ) ) - response = await client.create_finding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_finding.Finding) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.resource_name == "resource_name_value" - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == "category_value" - assert response.external_uri == "external_uri_value" @@ -827,17 +827,17 @@ async def test_create_finding_async_from_dict(): def test_create_finding_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.CreateFindingRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_finding), "__call__") as call: call.return_value = gcs_finding.Finding() - client.create_finding(request) # Establish that the underlying gRPC stub method was called. @@ -852,17 +852,19 @@ def test_create_finding_field_headers(): @pytest.mark.asyncio async def test_create_finding_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.CreateFindingRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_finding), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.create_finding(request) # Establish that the underlying gRPC stub method was called. @@ -876,13 +878,12 @@ async def test_create_finding_field_headers_async(): def test_create_finding_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_finding), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_finding( @@ -895,16 +896,13 @@ def test_create_finding_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].finding_id == "finding_id_value" - assert args[0].finding == gcs_finding.Finding(name="name_value") def test_create_finding_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -919,7 +917,9 @@ def test_create_finding_flattened_error(): @pytest.mark.asyncio async def test_create_finding_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_finding), "__call__") as call: @@ -939,17 +939,16 @@ async def test_create_finding_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].finding_id == "finding_id_value" - assert args[0].finding == gcs_finding.Finding(name="name_value") @pytest.mark.asyncio async def test_create_finding_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -963,10 +962,10 @@ async def test_create_finding_flattened_error_async(): def test_get_iam_policy( - transport: str = "grpc", request_type=iam_policy.GetIamPolicyRequest + transport: str = "grpc", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -976,22 +975,17 @@ def test_get_iam_policy( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy(version=774, etag=b"etag_blob",) - + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) response = client.get_iam_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] == iam_policy.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -1003,7 +997,7 @@ def test_get_iam_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1011,16 +1005,15 @@ def test_get_iam_policy_empty_call(): client.get_iam_policy() call.assert_called() _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() @pytest.mark.asyncio async def test_get_iam_policy_async( - transport: str = "grpc_asyncio", request_type=iam_policy.GetIamPolicyRequest + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1031,22 +1024,18 @@ async def test_get_iam_policy_async( with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy.Policy(version=774, etag=b"etag_blob",) + policy_pb2.Policy(version=774, etag=b"etag_blob",) ) - response = await client.get_iam_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -1056,17 +1045,17 @@ async def test_get_iam_policy_async_from_dict(): def test_get_iam_policy_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = iam_policy.GetIamPolicyRequest() + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() client.get_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1081,17 +1070,19 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = iam_policy.GetIamPolicyRequest() + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) - + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) await client.get_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1105,29 +1096,27 @@ async def test_get_iam_policy_field_headers_async(): def test_get_iam_policy_from_dict_foreign(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() response = client.get_iam_policy( request={ "resource": "resource_value", - "options": options.GetPolicyOptions(requested_policy_version=2598), + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), } ) call.assert_called() def test_get_iam_policy_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_iam_policy(resource="resource_value",) @@ -1136,31 +1125,32 @@ def test_get_iam_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" def test_get_iam_policy_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.get_iam_policy( - iam_policy.GetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.GetIamPolicyRequest(), resource="resource_value", ) @pytest.mark.asyncio async def test_get_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() + call.return_value = policy_pb2.Policy() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_iam_policy(resource="resource_value",) @@ -1169,19 +1159,20 @@ async def test_get_iam_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" @pytest.mark.asyncio async def test_get_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.get_iam_policy( - iam_policy.GetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.GetIamPolicyRequest(), resource="resource_value", ) @@ -1190,7 +1181,7 @@ def test_get_organization_settings( request_type=securitycenter_service.GetOrganizationSettingsRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1205,21 +1196,16 @@ def test_get_organization_settings( call.return_value = organization_settings.OrganizationSettings( name="name_value", enable_asset_discovery=True, ) - response = client.get_organization_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == "name_value" - assert response.enable_asset_discovery is True @@ -1231,7 +1217,7 @@ def test_get_organization_settings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1241,7 +1227,6 @@ def test_get_organization_settings_empty_call(): client.get_organization_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() @@ -1251,7 +1236,7 @@ async def test_get_organization_settings_async( request_type=securitycenter_service.GetOrganizationSettingsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1268,20 +1253,16 @@ async def test_get_organization_settings_async( name="name_value", enable_asset_discovery=True, ) ) - response = await client.get_organization_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == "name_value" - assert response.enable_asset_discovery is True @@ -1291,11 +1272,12 @@ async def test_get_organization_settings_async_from_dict(): def test_get_organization_settings_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.GetOrganizationSettingsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1303,7 +1285,6 @@ def test_get_organization_settings_field_headers(): type(client.transport.get_organization_settings), "__call__" ) as call: call.return_value = organization_settings.OrganizationSettings() - client.get_organization_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1318,11 +1299,14 @@ def test_get_organization_settings_field_headers(): @pytest.mark.asyncio async def test_get_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GetOrganizationSettingsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1332,7 +1316,6 @@ async def test_get_organization_settings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( organization_settings.OrganizationSettings() ) - await client.get_organization_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1346,7 +1329,7 @@ async def test_get_organization_settings_field_headers_async(): def test_get_organization_settings_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1354,7 +1337,6 @@ def test_get_organization_settings_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_organization_settings(name="name_value",) @@ -1363,12 +1345,11 @@ def test_get_organization_settings_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_organization_settings_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1380,7 +1361,9 @@ def test_get_organization_settings_flattened_error(): @pytest.mark.asyncio async def test_get_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1400,13 +1383,14 @@ async def test_get_organization_settings_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_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1420,7 +1404,7 @@ def test_get_source( transport: str = "grpc", request_type=securitycenter_service.GetSourceRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1435,23 +1419,17 @@ def test_get_source( display_name="display_name_value", description="description_value", ) - response = client.get_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" @@ -1463,7 +1441,7 @@ def test_get_source_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1471,7 +1449,6 @@ def test_get_source_empty_call(): client.get_source() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() @@ -1481,7 +1458,7 @@ async def test_get_source_async( request_type=securitycenter_service.GetSourceRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1498,22 +1475,17 @@ async def test_get_source_async( description="description_value", ) ) - response = await client.get_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() # Establish that the response is the type that we expect. assert isinstance(response, source.Source) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" @@ -1523,17 +1495,17 @@ async def test_get_source_async_from_dict(): def test_get_source_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.GetSourceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_source), "__call__") as call: call.return_value = source.Source() - client.get_source(request) # Establish that the underlying gRPC stub method was called. @@ -1548,17 +1520,19 @@ def test_get_source_field_headers(): @pytest.mark.asyncio async def test_get_source_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GetSourceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_source), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - await client.get_source(request) # Establish that the underlying gRPC stub method was called. @@ -1572,13 +1546,12 @@ async def test_get_source_field_headers_async(): def test_get_source_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_source), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = source.Source() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_source(name="name_value",) @@ -1587,12 +1560,11 @@ def test_get_source_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_source_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1604,7 +1576,9 @@ def test_get_source_flattened_error(): @pytest.mark.asyncio async def test_get_source_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_source), "__call__") as call: @@ -1620,13 +1594,14 @@ async def test_get_source_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_source_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1640,7 +1615,7 @@ def test_group_assets( transport: str = "grpc", request_type=securitycenter_service.GroupAssetsRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1653,19 +1628,15 @@ def test_group_assets( call.return_value = securitycenter_service.GroupAssetsResponse( next_page_token="next_page_token_value", ) - response = client.group_assets(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsPager) - assert response.next_page_token == "next_page_token_value" @@ -1677,7 +1648,7 @@ def test_group_assets_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1685,7 +1656,6 @@ def test_group_assets_empty_call(): client.group_assets() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() @@ -1695,7 +1665,7 @@ async def test_group_assets_async( request_type=securitycenter_service.GroupAssetsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1710,18 +1680,15 @@ async def test_group_assets_async( next_page_token="next_page_token_value", ) ) - response = await client.group_assets(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.GroupAssetsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1731,17 +1698,17 @@ async def test_group_assets_async_from_dict(): def test_group_assets_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.GroupAssetsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_assets), "__call__") as call: call.return_value = securitycenter_service.GroupAssetsResponse() - client.group_assets(request) # Establish that the underlying gRPC stub method was called. @@ -1756,11 +1723,14 @@ def test_group_assets_field_headers(): @pytest.mark.asyncio async def test_group_assets_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GroupAssetsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1768,7 +1738,6 @@ async def test_group_assets_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( securitycenter_service.GroupAssetsResponse() ) - await client.group_assets(request) # Establish that the underlying gRPC stub method was called. @@ -1782,7 +1751,7 @@ async def test_group_assets_field_headers_async(): def test_group_assets_pager(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_assets), "__call__") as call: @@ -1826,7 +1795,7 @@ def test_group_assets_pager(): def test_group_assets_pages(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_assets), "__call__") as call: @@ -1862,7 +1831,7 @@ def test_group_assets_pages(): @pytest.mark.asyncio async def test_group_assets_async_pager(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1905,7 +1874,7 @@ async def test_group_assets_async_pager(): @pytest.mark.asyncio async def test_group_assets_async_pages(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1947,7 +1916,7 @@ def test_group_findings( transport: str = "grpc", request_type=securitycenter_service.GroupFindingsRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1960,19 +1929,15 @@ def test_group_findings( call.return_value = securitycenter_service.GroupFindingsResponse( next_page_token="next_page_token_value", ) - response = client.group_findings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == "next_page_token_value" @@ -1984,7 +1949,7 @@ def test_group_findings_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1992,7 +1957,6 @@ def test_group_findings_empty_call(): client.group_findings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() @@ -2002,7 +1966,7 @@ async def test_group_findings_async( request_type=securitycenter_service.GroupFindingsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2017,18 +1981,15 @@ async def test_group_findings_async( next_page_token="next_page_token_value", ) ) - response = await client.group_findings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.GroupFindingsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -2038,17 +1999,17 @@ async def test_group_findings_async_from_dict(): def test_group_findings_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.GroupFindingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_findings), "__call__") as call: call.return_value = securitycenter_service.GroupFindingsResponse() - client.group_findings(request) # Establish that the underlying gRPC stub method was called. @@ -2063,11 +2024,14 @@ def test_group_findings_field_headers(): @pytest.mark.asyncio async def test_group_findings_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GroupFindingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2075,7 +2039,6 @@ async def test_group_findings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( securitycenter_service.GroupFindingsResponse() ) - await client.group_findings(request) # Establish that the underlying gRPC stub method was called. @@ -2089,13 +2052,12 @@ async def test_group_findings_field_headers_async(): def test_group_findings_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_findings), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = securitycenter_service.GroupFindingsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.group_findings( @@ -2106,14 +2068,12 @@ def test_group_findings_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].group_by == "group_by_value" def test_group_findings_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2127,7 +2087,9 @@ def test_group_findings_flattened_error(): @pytest.mark.asyncio async def test_group_findings_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_findings), "__call__") as call: @@ -2147,15 +2109,15 @@ async def test_group_findings_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].group_by == "group_by_value" @pytest.mark.asyncio async def test_group_findings_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2168,7 +2130,7 @@ async def test_group_findings_flattened_error_async(): def test_group_findings_pager(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_findings), "__call__") as call: @@ -2212,7 +2174,7 @@ def test_group_findings_pager(): def test_group_findings_pages(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_findings), "__call__") as call: @@ -2248,7 +2210,7 @@ def test_group_findings_pages(): @pytest.mark.asyncio async def test_group_findings_async_pager(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2291,7 +2253,7 @@ async def test_group_findings_async_pager(): @pytest.mark.asyncio async def test_group_findings_async_pages(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2333,7 +2295,7 @@ def test_list_assets( transport: str = "grpc", request_type=securitycenter_service.ListAssetsRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2346,21 +2308,16 @@ def test_list_assets( call.return_value = securitycenter_service.ListAssetsResponse( next_page_token="next_page_token_value", total_size=1086, ) - response = client.list_assets(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -2372,7 +2329,7 @@ def test_list_assets_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2380,7 +2337,6 @@ def test_list_assets_empty_call(): client.list_assets() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() @@ -2390,7 +2346,7 @@ async def test_list_assets_async( request_type=securitycenter_service.ListAssetsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2405,20 +2361,16 @@ async def test_list_assets_async( next_page_token="next_page_token_value", total_size=1086, ) ) - response = await client.list_assets(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAssetsAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -2428,17 +2380,17 @@ async def test_list_assets_async_from_dict(): def test_list_assets_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.ListAssetsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_assets), "__call__") as call: call.return_value = securitycenter_service.ListAssetsResponse() - client.list_assets(request) # Establish that the underlying gRPC stub method was called. @@ -2453,11 +2405,14 @@ def test_list_assets_field_headers(): @pytest.mark.asyncio async def test_list_assets_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListAssetsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2465,7 +2420,6 @@ async def test_list_assets_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( securitycenter_service.ListAssetsResponse() ) - await client.list_assets(request) # Establish that the underlying gRPC stub method was called. @@ -2479,7 +2433,7 @@ async def test_list_assets_field_headers_async(): def test_list_assets_pager(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_assets), "__call__") as call: @@ -2528,7 +2482,7 @@ def test_list_assets_pager(): def test_list_assets_pages(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_assets), "__call__") as call: @@ -2566,7 +2520,7 @@ def test_list_assets_pages(): @pytest.mark.asyncio async def test_list_assets_async_pager(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2614,7 +2568,7 @@ async def test_list_assets_async_pager(): @pytest.mark.asyncio async def test_list_assets_async_pages(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2658,7 +2612,7 @@ def test_list_findings( transport: str = "grpc", request_type=securitycenter_service.ListFindingsRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2671,21 +2625,16 @@ def test_list_findings( call.return_value = securitycenter_service.ListFindingsResponse( next_page_token="next_page_token_value", total_size=1086, ) - response = client.list_findings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -2697,7 +2646,7 @@ def test_list_findings_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2705,7 +2654,6 @@ def test_list_findings_empty_call(): client.list_findings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() @@ -2715,7 +2663,7 @@ async def test_list_findings_async( request_type=securitycenter_service.ListFindingsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2730,20 +2678,16 @@ async def test_list_findings_async( next_page_token="next_page_token_value", total_size=1086, ) ) - response = await client.list_findings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListFindingsAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -2753,17 +2697,17 @@ async def test_list_findings_async_from_dict(): def test_list_findings_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.ListFindingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_findings), "__call__") as call: call.return_value = securitycenter_service.ListFindingsResponse() - client.list_findings(request) # Establish that the underlying gRPC stub method was called. @@ -2778,11 +2722,14 @@ def test_list_findings_field_headers(): @pytest.mark.asyncio async def test_list_findings_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListFindingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2790,7 +2737,6 @@ async def test_list_findings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( securitycenter_service.ListFindingsResponse() ) - await client.list_findings(request) # Establish that the underlying gRPC stub method was called. @@ -2804,7 +2750,7 @@ async def test_list_findings_field_headers_async(): def test_list_findings_pager(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_findings), "__call__") as call: @@ -2840,7 +2786,7 @@ def test_list_findings_pager(): def test_list_findings_pages(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_findings), "__call__") as call: @@ -2868,7 +2814,7 @@ def test_list_findings_pages(): @pytest.mark.asyncio async def test_list_findings_async_pager(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2903,7 +2849,7 @@ async def test_list_findings_async_pager(): @pytest.mark.asyncio async def test_list_findings_async_pages(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2937,7 +2883,7 @@ def test_list_sources( transport: str = "grpc", request_type=securitycenter_service.ListSourcesRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2950,19 +2896,15 @@ def test_list_sources( call.return_value = securitycenter_service.ListSourcesResponse( next_page_token="next_page_token_value", ) - response = client.list_sources(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == "next_page_token_value" @@ -2974,7 +2916,7 @@ def test_list_sources_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2982,7 +2924,6 @@ def test_list_sources_empty_call(): client.list_sources() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() @@ -2992,7 +2933,7 @@ async def test_list_sources_async( request_type=securitycenter_service.ListSourcesRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3007,18 +2948,15 @@ async def test_list_sources_async( next_page_token="next_page_token_value", ) ) - response = await client.list_sources(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListSourcesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -3028,17 +2966,17 @@ async def test_list_sources_async_from_dict(): def test_list_sources_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.ListSourcesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_sources), "__call__") as call: call.return_value = securitycenter_service.ListSourcesResponse() - client.list_sources(request) # Establish that the underlying gRPC stub method was called. @@ -3053,11 +2991,14 @@ def test_list_sources_field_headers(): @pytest.mark.asyncio async def test_list_sources_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListSourcesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3065,7 +3006,6 @@ async def test_list_sources_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( securitycenter_service.ListSourcesResponse() ) - await client.list_sources(request) # Establish that the underlying gRPC stub method was called. @@ -3079,13 +3019,12 @@ async def test_list_sources_field_headers_async(): def test_list_sources_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_sources), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = securitycenter_service.ListSourcesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_sources(parent="parent_value",) @@ -3094,12 +3033,11 @@ def test_list_sources_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_sources_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3111,7 +3049,9 @@ def test_list_sources_flattened_error(): @pytest.mark.asyncio async def test_list_sources_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_sources), "__call__") as call: @@ -3129,13 +3069,14 @@ async def test_list_sources_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_sources_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3146,7 +3087,7 @@ async def test_list_sources_flattened_error_async(): def test_list_sources_pager(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_sources), "__call__") as call: @@ -3182,7 +3123,7 @@ def test_list_sources_pager(): def test_list_sources_pages(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_sources), "__call__") as call: @@ -3210,7 +3151,7 @@ def test_list_sources_pages(): @pytest.mark.asyncio async def test_list_sources_async_pager(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3245,7 +3186,7 @@ async def test_list_sources_async_pager(): @pytest.mark.asyncio async def test_list_sources_async_pages(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3280,7 +3221,7 @@ def test_run_asset_discovery( request_type=securitycenter_service.RunAssetDiscoveryRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3293,13 +3234,11 @@ def test_run_asset_discovery( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.run_asset_discovery(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() # Establish that the response is the type that we expect. @@ -3314,7 +3253,7 @@ def test_run_asset_discovery_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3324,7 +3263,6 @@ def test_run_asset_discovery_empty_call(): client.run_asset_discovery() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() @@ -3334,7 +3272,7 @@ async def test_run_asset_discovery_async( request_type=securitycenter_service.RunAssetDiscoveryRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3349,13 +3287,11 @@ async def test_run_asset_discovery_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.run_asset_discovery(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() # Establish that the response is the type that we expect. @@ -3368,11 +3304,12 @@ async def test_run_asset_discovery_async_from_dict(): def test_run_asset_discovery_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.RunAssetDiscoveryRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3380,7 +3317,6 @@ def test_run_asset_discovery_field_headers(): type(client.transport.run_asset_discovery), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.run_asset_discovery(request) # Establish that the underlying gRPC stub method was called. @@ -3395,11 +3331,14 @@ def test_run_asset_discovery_field_headers(): @pytest.mark.asyncio async def test_run_asset_discovery_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.RunAssetDiscoveryRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3409,7 +3348,6 @@ async def test_run_asset_discovery_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.run_asset_discovery(request) # Establish that the underlying gRPC stub method was called. @@ -3423,7 +3361,7 @@ async def test_run_asset_discovery_field_headers_async(): def test_run_asset_discovery_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3431,7 +3369,6 @@ def test_run_asset_discovery_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.run_asset_discovery(parent="parent_value",) @@ -3440,12 +3377,11 @@ def test_run_asset_discovery_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_run_asset_discovery_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3457,7 +3393,9 @@ def test_run_asset_discovery_flattened_error(): @pytest.mark.asyncio async def test_run_asset_discovery_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3477,13 +3415,14 @@ async def test_run_asset_discovery_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_run_asset_discovery_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3497,7 +3436,7 @@ def test_set_finding_state( transport: str = "grpc", request_type=securitycenter_service.SetFindingStateRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3517,29 +3456,20 @@ def test_set_finding_state( category="category_value", external_uri="external_uri_value", ) - response = client.set_finding_state(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.resource_name == "resource_name_value" - assert response.state == finding.Finding.State.ACTIVE - assert response.category == "category_value" - assert response.external_uri == "external_uri_value" @@ -3551,7 +3481,7 @@ def test_set_finding_state_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3561,7 +3491,6 @@ def test_set_finding_state_empty_call(): client.set_finding_state() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() @@ -3571,7 +3500,7 @@ async def test_set_finding_state_async( request_type=securitycenter_service.SetFindingStateRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3593,28 +3522,20 @@ async def test_set_finding_state_async( external_uri="external_uri_value", ) ) - response = await client.set_finding_state(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() # Establish that the response is the type that we expect. assert isinstance(response, finding.Finding) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.resource_name == "resource_name_value" - assert response.state == finding.Finding.State.ACTIVE - assert response.category == "category_value" - assert response.external_uri == "external_uri_value" @@ -3624,11 +3545,12 @@ async def test_set_finding_state_async_from_dict(): def test_set_finding_state_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.SetFindingStateRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3636,7 +3558,6 @@ def test_set_finding_state_field_headers(): type(client.transport.set_finding_state), "__call__" ) as call: call.return_value = finding.Finding() - client.set_finding_state(request) # Establish that the underlying gRPC stub method was called. @@ -3651,11 +3572,14 @@ def test_set_finding_state_field_headers(): @pytest.mark.asyncio async def test_set_finding_state_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.SetFindingStateRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3663,7 +3587,6 @@ async def test_set_finding_state_field_headers_async(): type(client.transport.set_finding_state), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.set_finding_state(request) # Establish that the underlying gRPC stub method was called. @@ -3677,7 +3600,7 @@ async def test_set_finding_state_field_headers_async(): def test_set_finding_state_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3685,31 +3608,25 @@ def test_set_finding_state_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = finding.Finding() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.set_finding_state( name="name_value", state=finding.Finding.State.ACTIVE, - start_time=timestamp.Timestamp(seconds=751), + start_time=timestamp_pb2.Timestamp(seconds=751), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].state == finding.Finding.State.ACTIVE - - assert TimestampRule().to_proto(args[0].start_time) == timestamp.Timestamp( - seconds=751 - ) + # # # # assert args[0].start_time == timestamp_pb2.Timestamp(seconds=751) def test_set_finding_state_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3718,13 +3635,15 @@ def test_set_finding_state_flattened_error(): securitycenter_service.SetFindingStateRequest(), name="name_value", state=finding.Finding.State.ACTIVE, - start_time=timestamp.Timestamp(seconds=751), + start_time=timestamp_pb2.Timestamp(seconds=751), ) @pytest.mark.asyncio async def test_set_finding_state_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3739,26 +3658,23 @@ async def test_set_finding_state_flattened_async(): response = await client.set_finding_state( name="name_value", state=finding.Finding.State.ACTIVE, - start_time=timestamp.Timestamp(seconds=751), + start_time=timestamp_pb2.Timestamp(seconds=751), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].state == finding.Finding.State.ACTIVE - - assert TimestampRule().to_proto(args[0].start_time) == timestamp.Timestamp( - seconds=751 - ) + # # # # assert args[0].start_time == timestamp_pb2.Timestamp(seconds=751) @pytest.mark.asyncio async def test_set_finding_state_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3767,15 +3683,15 @@ async def test_set_finding_state_flattened_error_async(): securitycenter_service.SetFindingStateRequest(), name="name_value", state=finding.Finding.State.ACTIVE, - start_time=timestamp.Timestamp(seconds=751), + start_time=timestamp_pb2.Timestamp(seconds=751), ) def test_set_iam_policy( - transport: str = "grpc", request_type=iam_policy.SetIamPolicyRequest + transport: str = "grpc", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3785,22 +3701,17 @@ def test_set_iam_policy( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy(version=774, etag=b"etag_blob",) - + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) response = client.set_iam_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] == iam_policy.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -3812,7 +3723,7 @@ def test_set_iam_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3820,16 +3731,15 @@ def test_set_iam_policy_empty_call(): client.set_iam_policy() call.assert_called() _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() @pytest.mark.asyncio async def test_set_iam_policy_async( - transport: str = "grpc_asyncio", request_type=iam_policy.SetIamPolicyRequest + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3840,22 +3750,18 @@ async def test_set_iam_policy_async( with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy.Policy(version=774, etag=b"etag_blob",) + policy_pb2.Policy(version=774, etag=b"etag_blob",) ) - response = await client.set_iam_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -3865,17 +3771,17 @@ async def test_set_iam_policy_async_from_dict(): def test_set_iam_policy_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = iam_policy.SetIamPolicyRequest() + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() client.set_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -3890,17 +3796,19 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = iam_policy.SetIamPolicyRequest() + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) - + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) await client.set_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -3914,29 +3822,27 @@ async def test_set_iam_policy_field_headers_async(): def test_set_iam_policy_from_dict_foreign(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() response = client.set_iam_policy( request={ "resource": "resource_value", - "policy": policy.Policy(version=774), + "policy": policy_pb2.Policy(version=774), } ) call.assert_called() def test_set_iam_policy_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.set_iam_policy(resource="resource_value",) @@ -3945,31 +3851,32 @@ def test_set_iam_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" def test_set_iam_policy_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.set_iam_policy( - iam_policy.SetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.SetIamPolicyRequest(), resource="resource_value", ) @pytest.mark.asyncio async def test_set_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() + call.return_value = policy_pb2.Policy() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.set_iam_policy(resource="resource_value",) @@ -3978,27 +3885,28 @@ async def test_set_iam_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" @pytest.mark.asyncio async def test_set_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.set_iam_policy( - iam_policy.SetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.SetIamPolicyRequest(), resource="resource_value", ) def test_test_iam_permissions( - transport: str = "grpc", request_type=iam_policy.TestIamPermissionsRequest + transport: str = "grpc", request_type=iam_policy_pb2.TestIamPermissionsRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4010,22 +3918,18 @@ def test_test_iam_permissions( type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = iam_policy.TestIamPermissionsResponse( + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( permissions=["permissions_value"], ) - response = client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, iam_policy.TestIamPermissionsResponse) - + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] @@ -4037,7 +3941,7 @@ def test_test_iam_permissions_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4047,16 +3951,16 @@ def test_test_iam_permissions_empty_call(): client.test_iam_permissions() call.assert_called() _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() @pytest.mark.asyncio async def test_test_iam_permissions_async( - transport: str = "grpc_asyncio", request_type=iam_policy.TestIamPermissionsRequest + transport: str = "grpc_asyncio", + request_type=iam_policy_pb2.TestIamPermissionsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4069,20 +3973,19 @@ async def test_test_iam_permissions_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse(permissions=["permissions_value"],) + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) ) - response = await client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy.TestIamPermissionsResponse) - + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] @@ -4092,19 +3995,19 @@ async def test_test_iam_permissions_async_from_dict(): def test_test_iam_permissions_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = iam_policy.TestIamPermissionsRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.test_iam_permissions), "__call__" ) as call: - call.return_value = iam_policy.TestIamPermissionsResponse() - + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. @@ -4119,11 +4022,14 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = iam_policy.TestIamPermissionsRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -4131,9 +4037,8 @@ async def test_test_iam_permissions_field_headers_async(): type(client.transport.test_iam_permissions), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) - await client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. @@ -4147,14 +4052,13 @@ async def test_test_iam_permissions_field_headers_async(): def test_test_iam_permissions_from_dict_foreign(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = iam_policy.TestIamPermissionsResponse() - + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() response = client.test_iam_permissions( request={ "resource": "resource_value", @@ -4165,15 +4069,14 @@ def test_test_iam_permissions_from_dict_foreign(): def test_test_iam_permissions_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = iam_policy.TestIamPermissionsResponse() - + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.test_iam_permissions( @@ -4184,20 +4087,18 @@ def test_test_iam_permissions_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" - assert args[0].permissions == ["permissions_value"] def test_test_iam_permissions_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.test_iam_permissions( - iam_policy.TestIamPermissionsRequest(), + iam_policy_pb2.TestIamPermissionsRequest(), resource="resource_value", permissions=["permissions_value"], ) @@ -4205,17 +4106,19 @@ def test_test_iam_permissions_flattened_error(): @pytest.mark.asyncio async def test_test_iam_permissions_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = iam_policy.TestIamPermissionsResponse() + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. @@ -4227,21 +4130,21 @@ async def test_test_iam_permissions_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" - assert args[0].permissions == ["permissions_value"] @pytest.mark.asyncio async def test_test_iam_permissions_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.test_iam_permissions( - iam_policy.TestIamPermissionsRequest(), + iam_policy_pb2.TestIamPermissionsRequest(), resource="resource_value", permissions=["permissions_value"], ) @@ -4251,7 +4154,7 @@ def test_update_finding( transport: str = "grpc", request_type=securitycenter_service.UpdateFindingRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4269,29 +4172,20 @@ def test_update_finding( category="category_value", external_uri="external_uri_value", ) - response = client.update_finding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.resource_name == "resource_name_value" - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == "category_value" - assert response.external_uri == "external_uri_value" @@ -4303,7 +4197,7 @@ def test_update_finding_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4311,7 +4205,6 @@ def test_update_finding_empty_call(): client.update_finding() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() @@ -4321,7 +4214,7 @@ async def test_update_finding_async( request_type=securitycenter_service.UpdateFindingRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4341,28 +4234,20 @@ async def test_update_finding_async( external_uri="external_uri_value", ) ) - response = await client.update_finding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_finding.Finding) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.resource_name == "resource_name_value" - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == "category_value" - assert response.external_uri == "external_uri_value" @@ -4372,17 +4257,17 @@ async def test_update_finding_async_from_dict(): def test_update_finding_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.UpdateFindingRequest() + request.finding.name = "finding.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_finding), "__call__") as call: call.return_value = gcs_finding.Finding() - client.update_finding(request) # Establish that the underlying gRPC stub method was called. @@ -4399,17 +4284,19 @@ def test_update_finding_field_headers(): @pytest.mark.asyncio async def test_update_finding_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateFindingRequest() + request.finding.name = "finding.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_finding), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.update_finding(request) # Establish that the underlying gRPC stub method was called. @@ -4425,13 +4312,12 @@ async def test_update_finding_field_headers_async(): def test_update_finding_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_finding), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_finding(finding=gcs_finding.Finding(name="name_value"),) @@ -4440,12 +4326,11 @@ def test_update_finding_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].finding == gcs_finding.Finding(name="name_value") def test_update_finding_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4458,7 +4343,9 @@ def test_update_finding_flattened_error(): @pytest.mark.asyncio async def test_update_finding_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_finding), "__call__") as call: @@ -4476,13 +4363,14 @@ async def test_update_finding_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].finding == gcs_finding.Finding(name="name_value") @pytest.mark.asyncio async def test_update_finding_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4498,7 +4386,7 @@ def test_update_organization_settings( request_type=securitycenter_service.UpdateOrganizationSettingsRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4513,21 +4401,16 @@ def test_update_organization_settings( call.return_value = gcs_organization_settings.OrganizationSettings( name="name_value", enable_asset_discovery=True, ) - response = client.update_organization_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == "name_value" - assert response.enable_asset_discovery is True @@ -4539,7 +4422,7 @@ def test_update_organization_settings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4549,7 +4432,6 @@ def test_update_organization_settings_empty_call(): client.update_organization_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() @@ -4559,7 +4441,7 @@ async def test_update_organization_settings_async( request_type=securitycenter_service.UpdateOrganizationSettingsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4576,20 +4458,16 @@ async def test_update_organization_settings_async( name="name_value", enable_asset_discovery=True, ) ) - response = await client.update_organization_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == "name_value" - assert response.enable_asset_discovery is True @@ -4599,11 +4477,12 @@ async def test_update_organization_settings_async_from_dict(): def test_update_organization_settings_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.UpdateOrganizationSettingsRequest() + request.organization_settings.name = "organization_settings.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -4611,7 +4490,6 @@ def test_update_organization_settings_field_headers(): type(client.transport.update_organization_settings), "__call__" ) as call: call.return_value = gcs_organization_settings.OrganizationSettings() - client.update_organization_settings(request) # Establish that the underlying gRPC stub method was called. @@ -4629,11 +4507,14 @@ def test_update_organization_settings_field_headers(): @pytest.mark.asyncio async def test_update_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateOrganizationSettingsRequest() + request.organization_settings.name = "organization_settings.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -4643,7 +4524,6 @@ async def test_update_organization_settings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcs_organization_settings.OrganizationSettings() ) - await client.update_organization_settings(request) # Establish that the underlying gRPC stub method was called. @@ -4660,7 +4540,7 @@ async def test_update_organization_settings_field_headers_async(): def test_update_organization_settings_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4668,7 +4548,6 @@ def test_update_organization_settings_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcs_organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_organization_settings( @@ -4681,7 +4560,6 @@ def test_update_organization_settings_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[ 0 ].organization_settings == gcs_organization_settings.OrganizationSettings( @@ -4690,7 +4568,7 @@ def test_update_organization_settings_flattened(): def test_update_organization_settings_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4705,7 +4583,9 @@ def test_update_organization_settings_flattened_error(): @pytest.mark.asyncio async def test_update_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4729,7 +4609,6 @@ async def test_update_organization_settings_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[ 0 ].organization_settings == gcs_organization_settings.OrganizationSettings( @@ -4739,7 +4618,9 @@ async def test_update_organization_settings_flattened_async(): @pytest.mark.asyncio async def test_update_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4756,7 +4637,7 @@ def test_update_source( transport: str = "grpc", request_type=securitycenter_service.UpdateSourceRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4771,23 +4652,17 @@ def test_update_source( display_name="display_name_value", description="description_value", ) - response = client.update_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" @@ -4799,7 +4674,7 @@ def test_update_source_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4807,7 +4682,6 @@ def test_update_source_empty_call(): client.update_source() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() @@ -4817,7 +4691,7 @@ async def test_update_source_async( request_type=securitycenter_service.UpdateSourceRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4834,22 +4708,17 @@ async def test_update_source_async( description="description_value", ) ) - response = await client.update_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_source.Source) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" @@ -4859,17 +4728,17 @@ async def test_update_source_async_from_dict(): def test_update_source_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.UpdateSourceRequest() + request.source.name = "source.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_source), "__call__") as call: call.return_value = gcs_source.Source() - client.update_source(request) # Establish that the underlying gRPC stub method was called. @@ -4884,17 +4753,19 @@ def test_update_source_field_headers(): @pytest.mark.asyncio async def test_update_source_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateSourceRequest() + request.source.name = "source.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_source), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.update_source(request) # Establish that the underlying gRPC stub method was called. @@ -4908,13 +4779,12 @@ async def test_update_source_field_headers_async(): def test_update_source_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_source), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_source(source=gcs_source.Source(name="name_value"),) @@ -4923,12 +4793,11 @@ def test_update_source_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].source == gcs_source.Source(name="name_value") def test_update_source_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4941,7 +4810,9 @@ def test_update_source_flattened_error(): @pytest.mark.asyncio async def test_update_source_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_source), "__call__") as call: @@ -4959,13 +4830,14 @@ async def test_update_source_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].source == gcs_source.Source(name="name_value") @pytest.mark.asyncio async def test_update_source_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4981,7 +4853,7 @@ def test_update_security_marks( request_type=securitycenter_service.UpdateSecurityMarksRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4994,19 +4866,15 @@ def test_update_security_marks( ) as call: # Designate an appropriate return value for the call. call.return_value = gcs_security_marks.SecurityMarks(name="name_value",) - response = client.update_security_marks(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == "name_value" @@ -5018,7 +4886,7 @@ def test_update_security_marks_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5028,7 +4896,6 @@ def test_update_security_marks_empty_call(): client.update_security_marks() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() @@ -5038,7 +4905,7 @@ async def test_update_security_marks_async( request_type=securitycenter_service.UpdateSecurityMarksRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5053,18 +4920,15 @@ async def test_update_security_marks_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcs_security_marks.SecurityMarks(name="name_value",) ) - response = await client.update_security_marks(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == "name_value" @@ -5074,11 +4938,12 @@ async def test_update_security_marks_async_from_dict(): def test_update_security_marks_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.UpdateSecurityMarksRequest() + request.security_marks.name = "security_marks.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -5086,7 +4951,6 @@ def test_update_security_marks_field_headers(): type(client.transport.update_security_marks), "__call__" ) as call: call.return_value = gcs_security_marks.SecurityMarks() - client.update_security_marks(request) # Establish that the underlying gRPC stub method was called. @@ -5104,11 +4968,14 @@ def test_update_security_marks_field_headers(): @pytest.mark.asyncio async def test_update_security_marks_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateSecurityMarksRequest() + request.security_marks.name = "security_marks.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -5118,7 +4985,6 @@ async def test_update_security_marks_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcs_security_marks.SecurityMarks() ) - await client.update_security_marks(request) # Establish that the underlying gRPC stub method was called. @@ -5135,7 +5001,7 @@ async def test_update_security_marks_field_headers_async(): def test_update_security_marks_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -5143,7 +5009,6 @@ def test_update_security_marks_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcs_security_marks.SecurityMarks() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_security_marks( @@ -5154,14 +5019,13 @@ def test_update_security_marks_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].security_marks == gcs_security_marks.SecurityMarks( name="name_value" ) def test_update_security_marks_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5174,7 +5038,9 @@ def test_update_security_marks_flattened_error(): @pytest.mark.asyncio async def test_update_security_marks_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -5196,7 +5062,6 @@ async def test_update_security_marks_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].security_marks == gcs_security_marks.SecurityMarks( name="name_value" ) @@ -5204,7 +5069,9 @@ async def test_update_security_marks_flattened_async(): @pytest.mark.asyncio async def test_update_security_marks_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5218,16 +5085,16 @@ async def test_update_security_marks_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SecurityCenterGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecurityCenterClient( - 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.SecurityCenterGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecurityCenterClient( @@ -5237,7 +5104,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SecurityCenterGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecurityCenterClient( @@ -5248,7 +5115,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SecurityCenterGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SecurityCenterClient(transport=transport) assert client.transport is transport @@ -5257,13 +5124,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.SecurityCenterGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.SecurityCenterGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -5278,23 +5145,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 = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.SecurityCenterGrpcTransport,) def test_security_center_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.SecurityCenterTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -5306,7 +5173,7 @@ def test_security_center_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SecurityCenterTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -5341,15 +5208,37 @@ def test_security_center_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_security_center_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.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport( + 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_security_center_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.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport._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.SecurityCenterTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -5362,19 +5251,33 @@ def test_security_center_base_transport_with_credentials_file(): def test_security_center_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.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SecurityCenterTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_security_center_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) + SecurityCenterClient() + 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_security_center_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) SecurityCenterClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -5382,20 +5285,156 @@ def test_security_center_auth_adc(): ) -def test_security_center_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_security_center_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.SecurityCenterGrpcTransport( - 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.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_security_center_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.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_security_center_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( + "securitycenter.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="securitycenter.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.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_security_center_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( + "securitycenter.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.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_security_center_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( + "securitycenter.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", [ @@ -5404,7 +5443,7 @@ def test_security_center_transport_auth_adc(): ], ) def test_security_center_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: @@ -5443,7 +5482,7 @@ def test_security_center_grpc_transport_client_cert_source_for_mtls(transport_cl def test_security_center_host_no_port(): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="securitycenter.googleapis.com" ), @@ -5453,7 +5492,7 @@ def test_security_center_host_no_port(): def test_security_center_host_with_port(): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="securitycenter.googleapis.com:8000" ), @@ -5509,9 +5548,9 @@ def test_security_center_transport_channel_mtls_with_client_cert_source( 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", @@ -5587,7 +5626,7 @@ def test_security_center_transport_channel_mtls_with_adc(transport_class): def test_security_center_grpc_lro_client(): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -5600,7 +5639,7 @@ def test_security_center_grpc_lro_client(): def test_security_center_grpc_lro_async_client(): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -5614,7 +5653,6 @@ def test_security_center_grpc_lro_async_client(): def test_asset_path(): organization = "squid" asset = "clam" - expected = "organizations/{organization}/assets/{asset}".format( organization=organization, asset=asset, ) @@ -5638,7 +5676,6 @@ def test_finding_path(): organization = "oyster" source = "nudibranch" finding = "cuttlefish" - expected = "organizations/{organization}/sources/{source}/findings/{finding}".format( organization=organization, source=source, finding=finding, ) @@ -5661,7 +5698,6 @@ def test_parse_finding_path(): def test_organization_settings_path(): organization = "scallop" - expected = "organizations/{organization}/organizationSettings".format( organization=organization, ) @@ -5683,7 +5719,6 @@ def test_parse_organization_settings_path(): def test_security_marks_path(): organization = "squid" asset = "clam" - expected = "organizations/{organization}/assets/{asset}/securityMarks".format( organization=organization, asset=asset, ) @@ -5706,7 +5741,6 @@ def test_parse_security_marks_path(): def test_source_path(): organization = "oyster" source = "nudibranch" - expected = "organizations/{organization}/sources/{source}".format( organization=organization, source=source, ) @@ -5728,7 +5762,6 @@ def test_parse_source_path(): def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -5749,7 +5782,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format(folder=folder,) actual = SecurityCenterClient.common_folder_path(folder) assert expected == actual @@ -5768,7 +5800,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format(organization=organization,) actual = SecurityCenterClient.common_organization_path(organization) assert expected == actual @@ -5787,7 +5818,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format(project=project,) actual = SecurityCenterClient.common_project_path(project) assert expected == actual @@ -5807,7 +5837,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, ) @@ -5834,7 +5863,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SecurityCenterTransport, "_prep_wrapped_messages" ) as prep: client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -5843,6 +5872,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SecurityCenterClient.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) diff --git a/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py b/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py +++ b/tests/unit/gapic/securitycenter_v1p1beta1/__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/securitycenter_v1p1beta1/test_security_center.py b/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py index 4e7ebe8b..4051107d 100644 --- a/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py +++ b/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.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,16 +23,16 @@ 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 future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.securitycenter_v1p1beta1.services.security_center import ( SecurityCenterAsyncClient, @@ -43,6 +42,12 @@ ) from google.cloud.securitycenter_v1p1beta1.services.security_center import pagers from google.cloud.securitycenter_v1p1beta1.services.security_center import transports +from google.cloud.securitycenter_v1p1beta1.services.security_center.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.securitycenter_v1p1beta1.services.security_center.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.securitycenter_v1p1beta1.types import finding from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding from google.cloud.securitycenter_v1p1beta1.types import notification_config @@ -61,16 +66,40 @@ from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service from google.cloud.securitycenter_v1p1beta1.types import source from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import options_pb2 as options # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.type import expr_pb2 as expr # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # 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(): @@ -121,7 +150,7 @@ def test__get_default_mtls_endpoint(): "client_class", [SecurityCenterClient, SecurityCenterAsyncClient,] ) def test_security_center_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: @@ -138,7 +167,7 @@ def test_security_center_client_from_service_account_info(client_class): "client_class", [SecurityCenterClient, SecurityCenterAsyncClient,] ) def test_security_center_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: @@ -191,7 +220,7 @@ def test_security_center_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(SecurityCenterClient, "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() @@ -479,7 +508,7 @@ def test_create_source( transport: str = "grpc", request_type=securitycenter_service.CreateSourceRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -493,25 +522,21 @@ def test_create_source( name="name_value", display_name="display_name_value", description="description_value", + canonical_name="canonical_name_value", ) - response = client.create_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" def test_create_source_from_dict(): @@ -522,7 +547,7 @@ def test_create_source_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -530,7 +555,6 @@ def test_create_source_empty_call(): client.create_source() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() @@ -540,7 +564,7 @@ async def test_create_source_async( request_type=securitycenter_service.CreateSourceRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -555,25 +579,22 @@ async def test_create_source_async( name="name_value", display_name="display_name_value", description="description_value", + canonical_name="canonical_name_value", ) ) - response = await client.create_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_source.Source) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" @pytest.mark.asyncio @@ -582,17 +603,17 @@ async def test_create_source_async_from_dict(): def test_create_source_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.CreateSourceRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_source), "__call__") as call: call.return_value = gcs_source.Source() - client.create_source(request) # Establish that the underlying gRPC stub method was called. @@ -607,17 +628,19 @@ def test_create_source_field_headers(): @pytest.mark.asyncio async def test_create_source_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.CreateSourceRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_source), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.create_source(request) # Establish that the underlying gRPC stub method was called. @@ -631,13 +654,12 @@ async def test_create_source_field_headers_async(): def test_create_source_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_source), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_source( @@ -648,14 +670,12 @@ def test_create_source_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].source == gcs_source.Source(name="name_value") def test_create_source_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -669,7 +689,9 @@ def test_create_source_flattened_error(): @pytest.mark.asyncio async def test_create_source_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_source), "__call__") as call: @@ -687,15 +709,15 @@ async def test_create_source_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].source == gcs_source.Source(name="name_value") @pytest.mark.asyncio async def test_create_source_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -711,7 +733,7 @@ def test_create_finding( transport: str = "grpc", request_type=securitycenter_service.CreateFindingRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -729,33 +751,25 @@ def test_create_finding( category="category_value", external_uri="external_uri_value", severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name="canonical_name_value", ) - response = client.create_finding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.resource_name == "resource_name_value" - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == "category_value" - assert response.external_uri == "external_uri_value" - assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == "canonical_name_value" def test_create_finding_from_dict(): @@ -766,7 +780,7 @@ def test_create_finding_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -774,7 +788,6 @@ def test_create_finding_empty_call(): client.create_finding() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() @@ -784,7 +797,7 @@ async def test_create_finding_async( request_type=securitycenter_service.CreateFindingRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -803,33 +816,26 @@ async def test_create_finding_async( category="category_value", external_uri="external_uri_value", severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name="canonical_name_value", ) ) - response = await client.create_finding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_finding.Finding) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.resource_name == "resource_name_value" - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == "category_value" - assert response.external_uri == "external_uri_value" - assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == "canonical_name_value" @pytest.mark.asyncio @@ -838,17 +844,17 @@ async def test_create_finding_async_from_dict(): def test_create_finding_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.CreateFindingRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_finding), "__call__") as call: call.return_value = gcs_finding.Finding() - client.create_finding(request) # Establish that the underlying gRPC stub method was called. @@ -863,17 +869,19 @@ def test_create_finding_field_headers(): @pytest.mark.asyncio async def test_create_finding_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.CreateFindingRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_finding), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.create_finding(request) # Establish that the underlying gRPC stub method was called. @@ -887,13 +895,12 @@ async def test_create_finding_field_headers_async(): def test_create_finding_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_finding), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_finding( @@ -906,16 +913,13 @@ def test_create_finding_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].finding_id == "finding_id_value" - assert args[0].finding == gcs_finding.Finding(name="name_value") def test_create_finding_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -930,7 +934,9 @@ def test_create_finding_flattened_error(): @pytest.mark.asyncio async def test_create_finding_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_finding), "__call__") as call: @@ -950,17 +956,16 @@ async def test_create_finding_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].finding_id == "finding_id_value" - assert args[0].finding == gcs_finding.Finding(name="name_value") @pytest.mark.asyncio async def test_create_finding_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -978,7 +983,7 @@ def test_create_notification_config( request_type=securitycenter_service.CreateNotificationConfigRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1000,30 +1005,22 @@ def test_create_notification_config( filter="filter_value" ), ) - response = client.create_notification_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == "name_value" - assert response.description == "description_value" - assert ( response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING ) - assert response.pubsub_topic == "pubsub_topic_value" - assert response.service_account == "service_account_value" @@ -1035,7 +1032,7 @@ def test_create_notification_config_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1045,7 +1042,6 @@ def test_create_notification_config_empty_call(): client.create_notification_config() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() @@ -1055,7 +1051,7 @@ async def test_create_notification_config_async( request_type=securitycenter_service.CreateNotificationConfigRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1076,29 +1072,22 @@ async def test_create_notification_config_async( service_account="service_account_value", ) ) - response = await client.create_notification_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == "name_value" - assert response.description == "description_value" - assert ( response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING ) - assert response.pubsub_topic == "pubsub_topic_value" - assert response.service_account == "service_account_value" @@ -1108,11 +1097,12 @@ async def test_create_notification_config_async_from_dict(): def test_create_notification_config_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.CreateNotificationConfigRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1120,7 +1110,6 @@ def test_create_notification_config_field_headers(): type(client.transport.create_notification_config), "__call__" ) as call: call.return_value = gcs_notification_config.NotificationConfig() - client.create_notification_config(request) # Establish that the underlying gRPC stub method was called. @@ -1135,11 +1124,14 @@ def test_create_notification_config_field_headers(): @pytest.mark.asyncio async def test_create_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.CreateNotificationConfigRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1149,7 +1141,6 @@ async def test_create_notification_config_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcs_notification_config.NotificationConfig() ) - await client.create_notification_config(request) # Establish that the underlying gRPC stub method was called. @@ -1163,7 +1154,7 @@ async def test_create_notification_config_field_headers_async(): def test_create_notification_config_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1171,7 +1162,6 @@ def test_create_notification_config_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcs_notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_notification_config( @@ -1186,11 +1176,8 @@ def test_create_notification_config_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].config_id == "config_id_value" - assert args[ 0 ].notification_config == gcs_notification_config.NotificationConfig( @@ -1199,7 +1186,7 @@ def test_create_notification_config_flattened(): def test_create_notification_config_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1216,7 +1203,9 @@ def test_create_notification_config_flattened_error(): @pytest.mark.asyncio async def test_create_notification_config_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1242,11 +1231,8 @@ async def test_create_notification_config_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].config_id == "config_id_value" - assert args[ 0 ].notification_config == gcs_notification_config.NotificationConfig( @@ -1256,7 +1242,9 @@ async def test_create_notification_config_flattened_async(): @pytest.mark.asyncio async def test_create_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1276,7 +1264,7 @@ def test_delete_notification_config( request_type=securitycenter_service.DeleteNotificationConfigRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1289,13 +1277,11 @@ def test_delete_notification_config( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_notification_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() # Establish that the response is the type that we expect. @@ -1310,7 +1296,7 @@ def test_delete_notification_config_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1320,7 +1306,6 @@ def test_delete_notification_config_empty_call(): client.delete_notification_config() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() @@ -1330,7 +1315,7 @@ async def test_delete_notification_config_async( request_type=securitycenter_service.DeleteNotificationConfigRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1343,13 +1328,11 @@ async def test_delete_notification_config_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_notification_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() # Establish that the response is the type that we expect. @@ -1362,11 +1345,12 @@ async def test_delete_notification_config_async_from_dict(): def test_delete_notification_config_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.DeleteNotificationConfigRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1374,7 +1358,6 @@ def test_delete_notification_config_field_headers(): type(client.transport.delete_notification_config), "__call__" ) as call: call.return_value = None - client.delete_notification_config(request) # Establish that the underlying gRPC stub method was called. @@ -1389,11 +1372,14 @@ def test_delete_notification_config_field_headers(): @pytest.mark.asyncio async def test_delete_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.DeleteNotificationConfigRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1401,7 +1387,6 @@ async def test_delete_notification_config_field_headers_async(): type(client.transport.delete_notification_config), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_notification_config(request) # Establish that the underlying gRPC stub method was called. @@ -1415,7 +1400,7 @@ async def test_delete_notification_config_field_headers_async(): def test_delete_notification_config_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1423,7 +1408,6 @@ def test_delete_notification_config_flattened(): ) 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_notification_config(name="name_value",) @@ -1432,12 +1416,11 @@ def test_delete_notification_config_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_notification_config_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1449,7 +1432,9 @@ def test_delete_notification_config_flattened_error(): @pytest.mark.asyncio async def test_delete_notification_config_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1467,13 +1452,14 @@ async def test_delete_notification_config_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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1484,10 +1470,10 @@ async def test_delete_notification_config_flattened_error_async(): def test_get_iam_policy( - transport: str = "grpc", request_type=iam_policy.GetIamPolicyRequest + transport: str = "grpc", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1497,22 +1483,17 @@ def test_get_iam_policy( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy(version=774, etag=b"etag_blob",) - + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) response = client.get_iam_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] == iam_policy.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -1524,7 +1505,7 @@ def test_get_iam_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1532,16 +1513,15 @@ def test_get_iam_policy_empty_call(): client.get_iam_policy() call.assert_called() _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() @pytest.mark.asyncio async def test_get_iam_policy_async( - transport: str = "grpc_asyncio", request_type=iam_policy.GetIamPolicyRequest + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1552,22 +1532,18 @@ async def test_get_iam_policy_async( with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy.Policy(version=774, etag=b"etag_blob",) + policy_pb2.Policy(version=774, etag=b"etag_blob",) ) - response = await client.get_iam_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -1577,17 +1553,17 @@ async def test_get_iam_policy_async_from_dict(): def test_get_iam_policy_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = iam_policy.GetIamPolicyRequest() + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() client.get_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1602,17 +1578,19 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = iam_policy.GetIamPolicyRequest() + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) - + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) await client.get_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1626,29 +1604,27 @@ async def test_get_iam_policy_field_headers_async(): def test_get_iam_policy_from_dict_foreign(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() response = client.get_iam_policy( request={ "resource": "resource_value", - "options": options.GetPolicyOptions(requested_policy_version=2598), + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), } ) call.assert_called() def test_get_iam_policy_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_iam_policy(resource="resource_value",) @@ -1657,31 +1633,32 @@ def test_get_iam_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" def test_get_iam_policy_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.get_iam_policy( - iam_policy.GetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.GetIamPolicyRequest(), resource="resource_value", ) @pytest.mark.asyncio async def test_get_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() + call.return_value = policy_pb2.Policy() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_iam_policy(resource="resource_value",) @@ -1690,19 +1667,20 @@ async def test_get_iam_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" @pytest.mark.asyncio async def test_get_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.get_iam_policy( - iam_policy.GetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.GetIamPolicyRequest(), resource="resource_value", ) @@ -1711,7 +1689,7 @@ def test_get_notification_config( request_type=securitycenter_service.GetNotificationConfigRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1733,29 +1711,21 @@ def test_get_notification_config( filter="filter_value" ), ) - response = client.get_notification_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == "name_value" - assert response.description == "description_value" - assert ( response.event_type == notification_config.NotificationConfig.EventType.FINDING ) - assert response.pubsub_topic == "pubsub_topic_value" - assert response.service_account == "service_account_value" @@ -1767,7 +1737,7 @@ def test_get_notification_config_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1777,7 +1747,6 @@ def test_get_notification_config_empty_call(): client.get_notification_config() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() @@ -1787,7 +1756,7 @@ async def test_get_notification_config_async( request_type=securitycenter_service.GetNotificationConfigRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1808,28 +1777,21 @@ async def test_get_notification_config_async( service_account="service_account_value", ) ) - response = await client.get_notification_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() # Establish that the response is the type that we expect. assert isinstance(response, notification_config.NotificationConfig) - assert response.name == "name_value" - assert response.description == "description_value" - assert ( response.event_type == notification_config.NotificationConfig.EventType.FINDING ) - assert response.pubsub_topic == "pubsub_topic_value" - assert response.service_account == "service_account_value" @@ -1839,11 +1801,12 @@ async def test_get_notification_config_async_from_dict(): def test_get_notification_config_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.GetNotificationConfigRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1851,7 +1814,6 @@ def test_get_notification_config_field_headers(): type(client.transport.get_notification_config), "__call__" ) as call: call.return_value = notification_config.NotificationConfig() - client.get_notification_config(request) # Establish that the underlying gRPC stub method was called. @@ -1866,11 +1828,14 @@ def test_get_notification_config_field_headers(): @pytest.mark.asyncio async def test_get_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GetNotificationConfigRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1880,7 +1845,6 @@ async def test_get_notification_config_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( notification_config.NotificationConfig() ) - await client.get_notification_config(request) # Establish that the underlying gRPC stub method was called. @@ -1894,7 +1858,7 @@ async def test_get_notification_config_field_headers_async(): def test_get_notification_config_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1902,7 +1866,6 @@ def test_get_notification_config_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_notification_config(name="name_value",) @@ -1911,12 +1874,11 @@ def test_get_notification_config_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_notification_config_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1928,7 +1890,9 @@ def test_get_notification_config_flattened_error(): @pytest.mark.asyncio async def test_get_notification_config_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1948,13 +1912,14 @@ async def test_get_notification_config_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_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1969,7 +1934,7 @@ def test_get_organization_settings( request_type=securitycenter_service.GetOrganizationSettingsRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1984,21 +1949,16 @@ def test_get_organization_settings( call.return_value = organization_settings.OrganizationSettings( name="name_value", enable_asset_discovery=True, ) - response = client.get_organization_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == "name_value" - assert response.enable_asset_discovery is True @@ -2010,7 +1970,7 @@ def test_get_organization_settings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2020,7 +1980,6 @@ def test_get_organization_settings_empty_call(): client.get_organization_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() @@ -2030,7 +1989,7 @@ async def test_get_organization_settings_async( request_type=securitycenter_service.GetOrganizationSettingsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2047,20 +2006,16 @@ async def test_get_organization_settings_async( name="name_value", enable_asset_discovery=True, ) ) - response = await client.get_organization_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == "name_value" - assert response.enable_asset_discovery is True @@ -2070,11 +2025,12 @@ async def test_get_organization_settings_async_from_dict(): def test_get_organization_settings_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.GetOrganizationSettingsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2082,7 +2038,6 @@ def test_get_organization_settings_field_headers(): type(client.transport.get_organization_settings), "__call__" ) as call: call.return_value = organization_settings.OrganizationSettings() - client.get_organization_settings(request) # Establish that the underlying gRPC stub method was called. @@ -2097,11 +2052,14 @@ def test_get_organization_settings_field_headers(): @pytest.mark.asyncio async def test_get_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GetOrganizationSettingsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2111,7 +2069,6 @@ async def test_get_organization_settings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( organization_settings.OrganizationSettings() ) - await client.get_organization_settings(request) # Establish that the underlying gRPC stub method was called. @@ -2125,7 +2082,7 @@ async def test_get_organization_settings_field_headers_async(): def test_get_organization_settings_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2133,7 +2090,6 @@ def test_get_organization_settings_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_organization_settings(name="name_value",) @@ -2142,12 +2098,11 @@ def test_get_organization_settings_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_organization_settings_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2159,7 +2114,9 @@ def test_get_organization_settings_flattened_error(): @pytest.mark.asyncio async def test_get_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2179,13 +2136,14 @@ async def test_get_organization_settings_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_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2199,7 +2157,7 @@ def test_get_source( transport: str = "grpc", request_type=securitycenter_service.GetSourceRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2213,25 +2171,21 @@ def test_get_source( name="name_value", display_name="display_name_value", description="description_value", + canonical_name="canonical_name_value", ) - response = client.get_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" def test_get_source_from_dict(): @@ -2242,7 +2196,7 @@ def test_get_source_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2250,7 +2204,6 @@ def test_get_source_empty_call(): client.get_source() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() @@ -2260,7 +2213,7 @@ async def test_get_source_async( request_type=securitycenter_service.GetSourceRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2275,25 +2228,22 @@ async def test_get_source_async( name="name_value", display_name="display_name_value", description="description_value", + canonical_name="canonical_name_value", ) ) - response = await client.get_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() # Establish that the response is the type that we expect. assert isinstance(response, source.Source) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" @pytest.mark.asyncio @@ -2302,17 +2252,17 @@ async def test_get_source_async_from_dict(): def test_get_source_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.GetSourceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_source), "__call__") as call: call.return_value = source.Source() - client.get_source(request) # Establish that the underlying gRPC stub method was called. @@ -2327,17 +2277,19 @@ def test_get_source_field_headers(): @pytest.mark.asyncio async def test_get_source_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GetSourceRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_source), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - await client.get_source(request) # Establish that the underlying gRPC stub method was called. @@ -2351,13 +2303,12 @@ async def test_get_source_field_headers_async(): def test_get_source_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_source), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = source.Source() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_source(name="name_value",) @@ -2366,12 +2317,11 @@ def test_get_source_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_source_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2383,7 +2333,9 @@ def test_get_source_flattened_error(): @pytest.mark.asyncio async def test_get_source_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_source), "__call__") as call: @@ -2399,13 +2351,14 @@ async def test_get_source_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_source_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2419,7 +2372,7 @@ def test_group_assets( transport: str = "grpc", request_type=securitycenter_service.GroupAssetsRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2432,21 +2385,16 @@ def test_group_assets( call.return_value = securitycenter_service.GroupAssetsResponse( next_page_token="next_page_token_value", total_size=1086, ) - response = client.group_assets(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -2458,7 +2406,7 @@ def test_group_assets_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2466,7 +2414,6 @@ def test_group_assets_empty_call(): client.group_assets() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() @@ -2476,7 +2423,7 @@ async def test_group_assets_async( request_type=securitycenter_service.GroupAssetsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2491,20 +2438,16 @@ async def test_group_assets_async( next_page_token="next_page_token_value", total_size=1086, ) ) - response = await client.group_assets(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.GroupAssetsAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -2514,17 +2457,17 @@ async def test_group_assets_async_from_dict(): def test_group_assets_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.GroupAssetsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_assets), "__call__") as call: call.return_value = securitycenter_service.GroupAssetsResponse() - client.group_assets(request) # Establish that the underlying gRPC stub method was called. @@ -2539,11 +2482,14 @@ def test_group_assets_field_headers(): @pytest.mark.asyncio async def test_group_assets_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GroupAssetsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2551,7 +2497,6 @@ async def test_group_assets_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( securitycenter_service.GroupAssetsResponse() ) - await client.group_assets(request) # Establish that the underlying gRPC stub method was called. @@ -2565,7 +2510,7 @@ async def test_group_assets_field_headers_async(): def test_group_assets_pager(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_assets), "__call__") as call: @@ -2609,7 +2554,7 @@ def test_group_assets_pager(): def test_group_assets_pages(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_assets), "__call__") as call: @@ -2645,7 +2590,7 @@ def test_group_assets_pages(): @pytest.mark.asyncio async def test_group_assets_async_pager(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2688,7 +2633,7 @@ async def test_group_assets_async_pager(): @pytest.mark.asyncio async def test_group_assets_async_pages(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2730,7 +2675,7 @@ def test_group_findings( transport: str = "grpc", request_type=securitycenter_service.GroupFindingsRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2743,21 +2688,16 @@ def test_group_findings( call.return_value = securitycenter_service.GroupFindingsResponse( next_page_token="next_page_token_value", total_size=1086, ) - response = client.group_findings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -2769,7 +2709,7 @@ def test_group_findings_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2777,7 +2717,6 @@ def test_group_findings_empty_call(): client.group_findings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() @@ -2787,7 +2726,7 @@ async def test_group_findings_async( request_type=securitycenter_service.GroupFindingsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2802,20 +2741,16 @@ async def test_group_findings_async( next_page_token="next_page_token_value", total_size=1086, ) ) - response = await client.group_findings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.GroupFindingsAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -2825,17 +2760,17 @@ async def test_group_findings_async_from_dict(): def test_group_findings_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.GroupFindingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_findings), "__call__") as call: call.return_value = securitycenter_service.GroupFindingsResponse() - client.group_findings(request) # Establish that the underlying gRPC stub method was called. @@ -2850,11 +2785,14 @@ def test_group_findings_field_headers(): @pytest.mark.asyncio async def test_group_findings_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) - + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GroupFindingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2862,7 +2800,6 @@ async def test_group_findings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( securitycenter_service.GroupFindingsResponse() ) - await client.group_findings(request) # Establish that the underlying gRPC stub method was called. @@ -2876,13 +2813,12 @@ async def test_group_findings_field_headers_async(): def test_group_findings_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_findings), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = securitycenter_service.GroupFindingsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.group_findings( @@ -2893,14 +2829,12 @@ def test_group_findings_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].group_by == "group_by_value" def test_group_findings_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2914,7 +2848,9 @@ def test_group_findings_flattened_error(): @pytest.mark.asyncio async def test_group_findings_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_findings), "__call__") as call: @@ -2934,15 +2870,15 @@ async def test_group_findings_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].group_by == "group_by_value" @pytest.mark.asyncio async def test_group_findings_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2955,7 +2891,7 @@ async def test_group_findings_flattened_error_async(): def test_group_findings_pager(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_findings), "__call__") as call: @@ -2999,7 +2935,7 @@ def test_group_findings_pager(): def test_group_findings_pages(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.group_findings), "__call__") as call: @@ -3035,7 +2971,7 @@ def test_group_findings_pages(): @pytest.mark.asyncio async def test_group_findings_async_pager(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3078,7 +3014,7 @@ async def test_group_findings_async_pager(): @pytest.mark.asyncio async def test_group_findings_async_pages(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3120,7 +3056,7 @@ def test_list_assets( transport: str = "grpc", request_type=securitycenter_service.ListAssetsRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3133,21 +3069,16 @@ def test_list_assets( call.return_value = securitycenter_service.ListAssetsResponse( next_page_token="next_page_token_value", total_size=1086, ) - response = client.list_assets(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -3159,7 +3090,7 @@ def test_list_assets_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3167,7 +3098,6 @@ def test_list_assets_empty_call(): client.list_assets() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() @@ -3177,7 +3107,7 @@ async def test_list_assets_async( request_type=securitycenter_service.ListAssetsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3192,20 +3122,16 @@ async def test_list_assets_async( next_page_token="next_page_token_value", total_size=1086, ) ) - response = await client.list_assets(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAssetsAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -3215,17 +3141,17 @@ async def test_list_assets_async_from_dict(): def test_list_assets_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.ListAssetsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_assets), "__call__") as call: call.return_value = securitycenter_service.ListAssetsResponse() - client.list_assets(request) # Establish that the underlying gRPC stub method was called. @@ -3240,11 +3166,14 @@ def test_list_assets_field_headers(): @pytest.mark.asyncio async def test_list_assets_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListAssetsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3252,7 +3181,6 @@ async def test_list_assets_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( securitycenter_service.ListAssetsResponse() ) - await client.list_assets(request) # Establish that the underlying gRPC stub method was called. @@ -3266,13 +3194,12 @@ async def test_list_assets_field_headers_async(): def test_list_assets_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_assets), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = securitycenter_service.ListAssetsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_assets(parent="parent_value",) @@ -3281,12 +3208,11 @@ def test_list_assets_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_assets_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3298,7 +3224,9 @@ def test_list_assets_flattened_error(): @pytest.mark.asyncio async def test_list_assets_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_assets), "__call__") as call: @@ -3316,13 +3244,14 @@ async def test_list_assets_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_assets_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3333,7 +3262,7 @@ async def test_list_assets_flattened_error_async(): def test_list_assets_pager(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_assets), "__call__") as call: @@ -3382,7 +3311,7 @@ def test_list_assets_pager(): def test_list_assets_pages(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_assets), "__call__") as call: @@ -3420,7 +3349,7 @@ def test_list_assets_pages(): @pytest.mark.asyncio async def test_list_assets_async_pager(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3468,7 +3397,7 @@ async def test_list_assets_async_pager(): @pytest.mark.asyncio async def test_list_assets_async_pages(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3512,7 +3441,7 @@ def test_list_findings( transport: str = "grpc", request_type=securitycenter_service.ListFindingsRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3525,21 +3454,16 @@ def test_list_findings( call.return_value = securitycenter_service.ListFindingsResponse( next_page_token="next_page_token_value", total_size=1086, ) - response = client.list_findings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -3551,7 +3475,7 @@ def test_list_findings_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3559,7 +3483,6 @@ def test_list_findings_empty_call(): client.list_findings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() @@ -3569,7 +3492,7 @@ async def test_list_findings_async( request_type=securitycenter_service.ListFindingsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3584,20 +3507,16 @@ async def test_list_findings_async( next_page_token="next_page_token_value", total_size=1086, ) ) - response = await client.list_findings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListFindingsAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 @@ -3607,17 +3526,17 @@ async def test_list_findings_async_from_dict(): def test_list_findings_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.ListFindingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_findings), "__call__") as call: call.return_value = securitycenter_service.ListFindingsResponse() - client.list_findings(request) # Establish that the underlying gRPC stub method was called. @@ -3632,11 +3551,14 @@ def test_list_findings_field_headers(): @pytest.mark.asyncio async def test_list_findings_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListFindingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -3644,7 +3566,6 @@ async def test_list_findings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( securitycenter_service.ListFindingsResponse() ) - await client.list_findings(request) # Establish that the underlying gRPC stub method was called. @@ -3658,13 +3579,12 @@ async def test_list_findings_field_headers_async(): def test_list_findings_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_findings), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = securitycenter_service.ListFindingsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_findings(parent="parent_value",) @@ -3673,12 +3593,11 @@ def test_list_findings_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_findings_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3690,7 +3609,9 @@ def test_list_findings_flattened_error(): @pytest.mark.asyncio async def test_list_findings_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_findings), "__call__") as call: @@ -3708,13 +3629,14 @@ async def test_list_findings_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_findings_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3725,7 +3647,7 @@ async def test_list_findings_flattened_error_async(): def test_list_findings_pager(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_findings), "__call__") as call: @@ -3776,7 +3698,7 @@ def test_list_findings_pager(): def test_list_findings_pages(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_findings), "__call__") as call: @@ -3814,7 +3736,7 @@ def test_list_findings_pages(): @pytest.mark.asyncio async def test_list_findings_async_pager(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3864,7 +3786,7 @@ async def test_list_findings_async_pager(): @pytest.mark.asyncio async def test_list_findings_async_pages(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3909,7 +3831,7 @@ def test_list_notification_configs( request_type=securitycenter_service.ListNotificationConfigsRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3924,19 +3846,15 @@ def test_list_notification_configs( call.return_value = securitycenter_service.ListNotificationConfigsResponse( next_page_token="next_page_token_value", ) - response = client.list_notification_configs(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsPager) - assert response.next_page_token == "next_page_token_value" @@ -3948,7 +3866,7 @@ def test_list_notification_configs_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3958,7 +3876,6 @@ def test_list_notification_configs_empty_call(): client.list_notification_configs() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() @@ -3968,7 +3885,7 @@ async def test_list_notification_configs_async( request_type=securitycenter_service.ListNotificationConfigsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3985,18 +3902,15 @@ async def test_list_notification_configs_async( next_page_token="next_page_token_value", ) ) - response = await client.list_notification_configs(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -4006,11 +3920,12 @@ async def test_list_notification_configs_async_from_dict(): def test_list_notification_configs_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.ListNotificationConfigsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -4018,7 +3933,6 @@ def test_list_notification_configs_field_headers(): type(client.transport.list_notification_configs), "__call__" ) as call: call.return_value = securitycenter_service.ListNotificationConfigsResponse() - client.list_notification_configs(request) # Establish that the underlying gRPC stub method was called. @@ -4033,11 +3947,14 @@ def test_list_notification_configs_field_headers(): @pytest.mark.asyncio async def test_list_notification_configs_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListNotificationConfigsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -4047,7 +3964,6 @@ async def test_list_notification_configs_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( securitycenter_service.ListNotificationConfigsResponse() ) - await client.list_notification_configs(request) # Establish that the underlying gRPC stub method was called. @@ -4061,7 +3977,7 @@ async def test_list_notification_configs_field_headers_async(): def test_list_notification_configs_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4069,7 +3985,6 @@ def test_list_notification_configs_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = securitycenter_service.ListNotificationConfigsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_notification_configs(parent="parent_value",) @@ -4078,12 +3993,11 @@ def test_list_notification_configs_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_notification_configs_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4096,7 +4010,9 @@ def test_list_notification_configs_flattened_error(): @pytest.mark.asyncio async def test_list_notification_configs_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4116,13 +4032,14 @@ async def test_list_notification_configs_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_notification_configs_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4134,7 +4051,7 @@ async def test_list_notification_configs_flattened_error_async(): def test_list_notification_configs_pager(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4182,7 +4099,7 @@ def test_list_notification_configs_pager(): def test_list_notification_configs_pages(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4220,7 +4137,7 @@ def test_list_notification_configs_pages(): @pytest.mark.asyncio async def test_list_notification_configs_async_pager(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4267,7 +4184,7 @@ async def test_list_notification_configs_async_pager(): @pytest.mark.asyncio async def test_list_notification_configs_async_pages(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4311,7 +4228,7 @@ def test_list_sources( transport: str = "grpc", request_type=securitycenter_service.ListSourcesRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4324,19 +4241,15 @@ def test_list_sources( call.return_value = securitycenter_service.ListSourcesResponse( next_page_token="next_page_token_value", ) - response = client.list_sources(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == "next_page_token_value" @@ -4348,7 +4261,7 @@ def test_list_sources_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4356,7 +4269,6 @@ def test_list_sources_empty_call(): client.list_sources() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() @@ -4366,7 +4278,7 @@ async def test_list_sources_async( request_type=securitycenter_service.ListSourcesRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4381,18 +4293,15 @@ async def test_list_sources_async( next_page_token="next_page_token_value", ) ) - response = await client.list_sources(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListSourcesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -4402,17 +4311,17 @@ async def test_list_sources_async_from_dict(): def test_list_sources_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.ListSourcesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_sources), "__call__") as call: call.return_value = securitycenter_service.ListSourcesResponse() - client.list_sources(request) # Establish that the underlying gRPC stub method was called. @@ -4427,11 +4336,14 @@ def test_list_sources_field_headers(): @pytest.mark.asyncio async def test_list_sources_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListSourcesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -4439,7 +4351,6 @@ async def test_list_sources_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( securitycenter_service.ListSourcesResponse() ) - await client.list_sources(request) # Establish that the underlying gRPC stub method was called. @@ -4453,13 +4364,12 @@ async def test_list_sources_field_headers_async(): def test_list_sources_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_sources), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = securitycenter_service.ListSourcesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_sources(parent="parent_value",) @@ -4468,12 +4378,11 @@ def test_list_sources_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_sources_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4485,7 +4394,9 @@ def test_list_sources_flattened_error(): @pytest.mark.asyncio async def test_list_sources_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_sources), "__call__") as call: @@ -4503,13 +4414,14 @@ async def test_list_sources_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_sources_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4520,7 +4432,7 @@ async def test_list_sources_flattened_error_async(): def test_list_sources_pager(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_sources), "__call__") as call: @@ -4556,7 +4468,7 @@ def test_list_sources_pager(): def test_list_sources_pages(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_sources), "__call__") as call: @@ -4584,7 +4496,7 @@ def test_list_sources_pages(): @pytest.mark.asyncio async def test_list_sources_async_pager(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4619,7 +4531,7 @@ async def test_list_sources_async_pager(): @pytest.mark.asyncio async def test_list_sources_async_pages(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials,) + client = SecurityCenterAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4654,7 +4566,7 @@ def test_run_asset_discovery( request_type=securitycenter_service.RunAssetDiscoveryRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4667,13 +4579,11 @@ def test_run_asset_discovery( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.run_asset_discovery(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() # Establish that the response is the type that we expect. @@ -4688,7 +4598,7 @@ def test_run_asset_discovery_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4698,7 +4608,6 @@ def test_run_asset_discovery_empty_call(): client.run_asset_discovery() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() @@ -4708,7 +4617,7 @@ async def test_run_asset_discovery_async( request_type=securitycenter_service.RunAssetDiscoveryRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4723,13 +4632,11 @@ async def test_run_asset_discovery_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.run_asset_discovery(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() # Establish that the response is the type that we expect. @@ -4742,11 +4649,12 @@ async def test_run_asset_discovery_async_from_dict(): def test_run_asset_discovery_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.RunAssetDiscoveryRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -4754,7 +4662,6 @@ def test_run_asset_discovery_field_headers(): type(client.transport.run_asset_discovery), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.run_asset_discovery(request) # Establish that the underlying gRPC stub method was called. @@ -4769,11 +4676,14 @@ def test_run_asset_discovery_field_headers(): @pytest.mark.asyncio async def test_run_asset_discovery_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.RunAssetDiscoveryRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -4783,7 +4693,6 @@ async def test_run_asset_discovery_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.run_asset_discovery(request) # Establish that the underlying gRPC stub method was called. @@ -4797,7 +4706,7 @@ async def test_run_asset_discovery_field_headers_async(): def test_run_asset_discovery_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4805,7 +4714,6 @@ def test_run_asset_discovery_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.run_asset_discovery(parent="parent_value",) @@ -4814,12 +4722,11 @@ def test_run_asset_discovery_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_run_asset_discovery_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4831,7 +4738,9 @@ def test_run_asset_discovery_flattened_error(): @pytest.mark.asyncio async def test_run_asset_discovery_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4851,13 +4760,14 @@ async def test_run_asset_discovery_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_run_asset_discovery_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4871,7 +4781,7 @@ def test_set_finding_state( transport: str = "grpc", request_type=securitycenter_service.SetFindingStateRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4891,33 +4801,25 @@ def test_set_finding_state( category="category_value", external_uri="external_uri_value", severity=finding.Finding.Severity.CRITICAL, + canonical_name="canonical_name_value", ) - response = client.set_finding_state(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.resource_name == "resource_name_value" - assert response.state == finding.Finding.State.ACTIVE - assert response.category == "category_value" - assert response.external_uri == "external_uri_value" - assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == "canonical_name_value" def test_set_finding_state_from_dict(): @@ -4928,7 +4830,7 @@ def test_set_finding_state_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4938,7 +4840,6 @@ def test_set_finding_state_empty_call(): client.set_finding_state() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() @@ -4948,7 +4849,7 @@ async def test_set_finding_state_async( request_type=securitycenter_service.SetFindingStateRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4969,33 +4870,26 @@ async def test_set_finding_state_async( category="category_value", external_uri="external_uri_value", severity=finding.Finding.Severity.CRITICAL, + canonical_name="canonical_name_value", ) ) - response = await client.set_finding_state(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() # Establish that the response is the type that we expect. assert isinstance(response, finding.Finding) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.resource_name == "resource_name_value" - assert response.state == finding.Finding.State.ACTIVE - assert response.category == "category_value" - assert response.external_uri == "external_uri_value" - assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == "canonical_name_value" @pytest.mark.asyncio @@ -5004,11 +4898,12 @@ async def test_set_finding_state_async_from_dict(): def test_set_finding_state_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.SetFindingStateRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -5016,7 +4911,6 @@ def test_set_finding_state_field_headers(): type(client.transport.set_finding_state), "__call__" ) as call: call.return_value = finding.Finding() - client.set_finding_state(request) # Establish that the underlying gRPC stub method was called. @@ -5031,11 +4925,14 @@ def test_set_finding_state_field_headers(): @pytest.mark.asyncio async def test_set_finding_state_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.SetFindingStateRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -5043,7 +4940,6 @@ async def test_set_finding_state_field_headers_async(): type(client.transport.set_finding_state), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.set_finding_state(request) # Establish that the underlying gRPC stub method was called. @@ -5057,7 +4953,7 @@ async def test_set_finding_state_field_headers_async(): def test_set_finding_state_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -5065,31 +4961,25 @@ def test_set_finding_state_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = finding.Finding() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.set_finding_state( name="name_value", state=finding.Finding.State.ACTIVE, - start_time=timestamp.Timestamp(seconds=751), + start_time=timestamp_pb2.Timestamp(seconds=751), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].state == finding.Finding.State.ACTIVE - - assert TimestampRule().to_proto(args[0].start_time) == timestamp.Timestamp( - seconds=751 - ) + # # # # assert args[0].start_time == timestamp_pb2.Timestamp(seconds=751) def test_set_finding_state_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5098,13 +4988,15 @@ def test_set_finding_state_flattened_error(): securitycenter_service.SetFindingStateRequest(), name="name_value", state=finding.Finding.State.ACTIVE, - start_time=timestamp.Timestamp(seconds=751), + start_time=timestamp_pb2.Timestamp(seconds=751), ) @pytest.mark.asyncio async def test_set_finding_state_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -5119,26 +5011,23 @@ async def test_set_finding_state_flattened_async(): response = await client.set_finding_state( name="name_value", state=finding.Finding.State.ACTIVE, - start_time=timestamp.Timestamp(seconds=751), + start_time=timestamp_pb2.Timestamp(seconds=751), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].state == finding.Finding.State.ACTIVE - - assert TimestampRule().to_proto(args[0].start_time) == timestamp.Timestamp( - seconds=751 - ) + # # # # assert args[0].start_time == timestamp_pb2.Timestamp(seconds=751) @pytest.mark.asyncio async def test_set_finding_state_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5147,15 +5036,15 @@ async def test_set_finding_state_flattened_error_async(): securitycenter_service.SetFindingStateRequest(), name="name_value", state=finding.Finding.State.ACTIVE, - start_time=timestamp.Timestamp(seconds=751), + start_time=timestamp_pb2.Timestamp(seconds=751), ) def test_set_iam_policy( - transport: str = "grpc", request_type=iam_policy.SetIamPolicyRequest + transport: str = "grpc", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5165,22 +5054,17 @@ def test_set_iam_policy( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy(version=774, etag=b"etag_blob",) - + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) response = client.set_iam_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] == iam_policy.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -5192,7 +5076,7 @@ def test_set_iam_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5200,16 +5084,15 @@ def test_set_iam_policy_empty_call(): client.set_iam_policy() call.assert_called() _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() @pytest.mark.asyncio async def test_set_iam_policy_async( - transport: str = "grpc_asyncio", request_type=iam_policy.SetIamPolicyRequest + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5220,22 +5103,18 @@ async def test_set_iam_policy_async( with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy.Policy(version=774, etag=b"etag_blob",) + policy_pb2.Policy(version=774, etag=b"etag_blob",) ) - response = await client.set_iam_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -5245,17 +5124,17 @@ async def test_set_iam_policy_async_from_dict(): def test_set_iam_policy_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = iam_policy.SetIamPolicyRequest() + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() client.set_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -5270,17 +5149,19 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = iam_policy.SetIamPolicyRequest() + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) - + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) await client.set_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -5294,29 +5175,27 @@ async def test_set_iam_policy_field_headers_async(): def test_set_iam_policy_from_dict_foreign(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() response = client.set_iam_policy( request={ "resource": "resource_value", - "policy": policy.Policy(version=774), + "policy": policy_pb2.Policy(version=774), } ) call.assert_called() def test_set_iam_policy_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.set_iam_policy(resource="resource_value",) @@ -5325,31 +5204,32 @@ def test_set_iam_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" def test_set_iam_policy_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.set_iam_policy( - iam_policy.SetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.SetIamPolicyRequest(), resource="resource_value", ) @pytest.mark.asyncio async def test_set_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() + call.return_value = policy_pb2.Policy() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.set_iam_policy(resource="resource_value",) @@ -5358,27 +5238,28 @@ async def test_set_iam_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" @pytest.mark.asyncio async def test_set_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.set_iam_policy( - iam_policy.SetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.SetIamPolicyRequest(), resource="resource_value", ) def test_test_iam_permissions( - transport: str = "grpc", request_type=iam_policy.TestIamPermissionsRequest + transport: str = "grpc", request_type=iam_policy_pb2.TestIamPermissionsRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5390,22 +5271,18 @@ def test_test_iam_permissions( type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = iam_policy.TestIamPermissionsResponse( + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( permissions=["permissions_value"], ) - response = client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, iam_policy.TestIamPermissionsResponse) - + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] @@ -5417,7 +5294,7 @@ def test_test_iam_permissions_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5427,16 +5304,16 @@ def test_test_iam_permissions_empty_call(): client.test_iam_permissions() call.assert_called() _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() @pytest.mark.asyncio async def test_test_iam_permissions_async( - transport: str = "grpc_asyncio", request_type=iam_policy.TestIamPermissionsRequest + transport: str = "grpc_asyncio", + request_type=iam_policy_pb2.TestIamPermissionsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5449,20 +5326,19 @@ async def test_test_iam_permissions_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse(permissions=["permissions_value"],) + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) ) - response = await client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy.TestIamPermissionsResponse) - + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] @@ -5472,19 +5348,19 @@ async def test_test_iam_permissions_async_from_dict(): def test_test_iam_permissions_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = iam_policy.TestIamPermissionsRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.test_iam_permissions), "__call__" ) as call: - call.return_value = iam_policy.TestIamPermissionsResponse() - + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. @@ -5499,11 +5375,14 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = iam_policy.TestIamPermissionsRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -5511,9 +5390,8 @@ async def test_test_iam_permissions_field_headers_async(): type(client.transport.test_iam_permissions), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) - await client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. @@ -5527,14 +5405,13 @@ async def test_test_iam_permissions_field_headers_async(): def test_test_iam_permissions_from_dict_foreign(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = iam_policy.TestIamPermissionsResponse() - + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() response = client.test_iam_permissions( request={ "resource": "resource_value", @@ -5545,15 +5422,14 @@ def test_test_iam_permissions_from_dict_foreign(): def test_test_iam_permissions_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = iam_policy.TestIamPermissionsResponse() - + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.test_iam_permissions( @@ -5564,20 +5440,18 @@ def test_test_iam_permissions_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" - assert args[0].permissions == ["permissions_value"] def test_test_iam_permissions_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.test_iam_permissions( - iam_policy.TestIamPermissionsRequest(), + iam_policy_pb2.TestIamPermissionsRequest(), resource="resource_value", permissions=["permissions_value"], ) @@ -5585,17 +5459,19 @@ def test_test_iam_permissions_flattened_error(): @pytest.mark.asyncio async def test_test_iam_permissions_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = iam_policy.TestIamPermissionsResponse() + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. @@ -5607,21 +5483,21 @@ async def test_test_iam_permissions_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" - assert args[0].permissions == ["permissions_value"] @pytest.mark.asyncio async def test_test_iam_permissions_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.test_iam_permissions( - iam_policy.TestIamPermissionsRequest(), + iam_policy_pb2.TestIamPermissionsRequest(), resource="resource_value", permissions=["permissions_value"], ) @@ -5631,7 +5507,7 @@ def test_update_finding( transport: str = "grpc", request_type=securitycenter_service.UpdateFindingRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5649,33 +5525,25 @@ def test_update_finding( category="category_value", external_uri="external_uri_value", severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name="canonical_name_value", ) - response = client.update_finding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.resource_name == "resource_name_value" - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == "category_value" - assert response.external_uri == "external_uri_value" - assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == "canonical_name_value" def test_update_finding_from_dict(): @@ -5686,7 +5554,7 @@ def test_update_finding_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5694,7 +5562,6 @@ def test_update_finding_empty_call(): client.update_finding() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() @@ -5704,7 +5571,7 @@ async def test_update_finding_async( request_type=securitycenter_service.UpdateFindingRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5723,33 +5590,26 @@ async def test_update_finding_async( category="category_value", external_uri="external_uri_value", severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name="canonical_name_value", ) ) - response = await client.update_finding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_finding.Finding) - assert response.name == "name_value" - assert response.parent == "parent_value" - assert response.resource_name == "resource_name_value" - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == "category_value" - assert response.external_uri == "external_uri_value" - assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == "canonical_name_value" @pytest.mark.asyncio @@ -5758,17 +5618,17 @@ async def test_update_finding_async_from_dict(): def test_update_finding_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.UpdateFindingRequest() + request.finding.name = "finding.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_finding), "__call__") as call: call.return_value = gcs_finding.Finding() - client.update_finding(request) # Establish that the underlying gRPC stub method was called. @@ -5785,17 +5645,19 @@ def test_update_finding_field_headers(): @pytest.mark.asyncio async def test_update_finding_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateFindingRequest() + request.finding.name = "finding.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_finding), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.update_finding(request) # Establish that the underlying gRPC stub method was called. @@ -5811,32 +5673,29 @@ async def test_update_finding_field_headers_async(): def test_update_finding_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_finding), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_finding( finding=gcs_finding.Finding(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].finding == gcs_finding.Finding(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_finding_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5844,13 +5703,15 @@ def test_update_finding_flattened_error(): client.update_finding( securitycenter_service.UpdateFindingRequest(), finding=gcs_finding.Finding(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_finding_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_finding), "__call__") as call: @@ -5862,22 +5723,22 @@ async def test_update_finding_flattened_async(): # using the keyword arguments to the method. response = await client.update_finding( finding=gcs_finding.Finding(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].finding == gcs_finding.Finding(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_finding_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5885,7 +5746,7 @@ async def test_update_finding_flattened_error_async(): await client.update_finding( securitycenter_service.UpdateFindingRequest(), finding=gcs_finding.Finding(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -5894,7 +5755,7 @@ def test_update_notification_config( request_type=securitycenter_service.UpdateNotificationConfigRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5916,30 +5777,22 @@ def test_update_notification_config( filter="filter_value" ), ) - response = client.update_notification_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == "name_value" - assert response.description == "description_value" - assert ( response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING ) - assert response.pubsub_topic == "pubsub_topic_value" - assert response.service_account == "service_account_value" @@ -5951,7 +5804,7 @@ def test_update_notification_config_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5961,7 +5814,6 @@ def test_update_notification_config_empty_call(): client.update_notification_config() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() @@ -5971,7 +5823,7 @@ async def test_update_notification_config_async( request_type=securitycenter_service.UpdateNotificationConfigRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5992,29 +5844,22 @@ async def test_update_notification_config_async( service_account="service_account_value", ) ) - response = await client.update_notification_config(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == "name_value" - assert response.description == "description_value" - assert ( response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING ) - assert response.pubsub_topic == "pubsub_topic_value" - assert response.service_account == "service_account_value" @@ -6024,11 +5869,12 @@ async def test_update_notification_config_async_from_dict(): def test_update_notification_config_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.UpdateNotificationConfigRequest() + request.notification_config.name = "notification_config.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -6036,7 +5882,6 @@ def test_update_notification_config_field_headers(): type(client.transport.update_notification_config), "__call__" ) as call: call.return_value = gcs_notification_config.NotificationConfig() - client.update_notification_config(request) # Establish that the underlying gRPC stub method was called. @@ -6054,11 +5899,14 @@ def test_update_notification_config_field_headers(): @pytest.mark.asyncio async def test_update_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateNotificationConfigRequest() + request.notification_config.name = "notification_config.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -6068,7 +5916,6 @@ async def test_update_notification_config_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcs_notification_config.NotificationConfig() ) - await client.update_notification_config(request) # Establish that the underlying gRPC stub method was called. @@ -6085,7 +5932,7 @@ async def test_update_notification_config_field_headers_async(): def test_update_notification_config_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -6093,32 +5940,29 @@ def test_update_notification_config_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcs_notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_notification_config( notification_config=gcs_notification_config.NotificationConfig( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[ 0 ].notification_config == gcs_notification_config.NotificationConfig( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_notification_config_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -6128,13 +5972,15 @@ def test_update_notification_config_flattened_error(): notification_config=gcs_notification_config.NotificationConfig( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_notification_config_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -6152,26 +5998,26 @@ async def test_update_notification_config_flattened_async(): notification_config=gcs_notification_config.NotificationConfig( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[ 0 ].notification_config == gcs_notification_config.NotificationConfig( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -6181,7 +6027,7 @@ async def test_update_notification_config_flattened_error_async(): notification_config=gcs_notification_config.NotificationConfig( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -6190,7 +6036,7 @@ def test_update_organization_settings( request_type=securitycenter_service.UpdateOrganizationSettingsRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -6205,21 +6051,16 @@ def test_update_organization_settings( call.return_value = gcs_organization_settings.OrganizationSettings( name="name_value", enable_asset_discovery=True, ) - response = client.update_organization_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == "name_value" - assert response.enable_asset_discovery is True @@ -6231,7 +6072,7 @@ def test_update_organization_settings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6241,7 +6082,6 @@ def test_update_organization_settings_empty_call(): client.update_organization_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() @@ -6251,7 +6091,7 @@ async def test_update_organization_settings_async( request_type=securitycenter_service.UpdateOrganizationSettingsRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -6268,20 +6108,16 @@ async def test_update_organization_settings_async( name="name_value", enable_asset_discovery=True, ) ) - response = await client.update_organization_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == "name_value" - assert response.enable_asset_discovery is True @@ -6291,11 +6127,12 @@ async def test_update_organization_settings_async_from_dict(): def test_update_organization_settings_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.UpdateOrganizationSettingsRequest() + request.organization_settings.name = "organization_settings.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -6303,7 +6140,6 @@ def test_update_organization_settings_field_headers(): type(client.transport.update_organization_settings), "__call__" ) as call: call.return_value = gcs_organization_settings.OrganizationSettings() - client.update_organization_settings(request) # Establish that the underlying gRPC stub method was called. @@ -6321,11 +6157,14 @@ def test_update_organization_settings_field_headers(): @pytest.mark.asyncio async def test_update_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateOrganizationSettingsRequest() + request.organization_settings.name = "organization_settings.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -6335,7 +6174,6 @@ async def test_update_organization_settings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcs_organization_settings.OrganizationSettings() ) - await client.update_organization_settings(request) # Establish that the underlying gRPC stub method was called. @@ -6352,7 +6190,7 @@ async def test_update_organization_settings_field_headers_async(): def test_update_organization_settings_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -6360,7 +6198,6 @@ def test_update_organization_settings_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcs_organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_organization_settings( @@ -6373,7 +6210,6 @@ def test_update_organization_settings_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[ 0 ].organization_settings == gcs_organization_settings.OrganizationSettings( @@ -6382,7 +6218,7 @@ def test_update_organization_settings_flattened(): def test_update_organization_settings_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -6397,7 +6233,9 @@ def test_update_organization_settings_flattened_error(): @pytest.mark.asyncio async def test_update_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -6421,7 +6259,6 @@ async def test_update_organization_settings_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[ 0 ].organization_settings == gcs_organization_settings.OrganizationSettings( @@ -6431,7 +6268,9 @@ async def test_update_organization_settings_flattened_async(): @pytest.mark.asyncio async def test_update_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -6448,7 +6287,7 @@ def test_update_source( transport: str = "grpc", request_type=securitycenter_service.UpdateSourceRequest ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -6462,25 +6301,21 @@ def test_update_source( name="name_value", display_name="display_name_value", description="description_value", + canonical_name="canonical_name_value", ) - response = client.update_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" def test_update_source_from_dict(): @@ -6491,7 +6326,7 @@ def test_update_source_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6499,7 +6334,6 @@ def test_update_source_empty_call(): client.update_source() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() @@ -6509,7 +6343,7 @@ async def test_update_source_async( request_type=securitycenter_service.UpdateSourceRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -6524,25 +6358,22 @@ async def test_update_source_async( name="name_value", display_name="display_name_value", description="description_value", + canonical_name="canonical_name_value", ) ) - response = await client.update_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_source.Source) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" @pytest.mark.asyncio @@ -6551,17 +6382,17 @@ async def test_update_source_async_from_dict(): def test_update_source_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.UpdateSourceRequest() + request.source.name = "source.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_source), "__call__") as call: call.return_value = gcs_source.Source() - client.update_source(request) # Establish that the underlying gRPC stub method was called. @@ -6576,17 +6407,19 @@ def test_update_source_field_headers(): @pytest.mark.asyncio async def test_update_source_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateSourceRequest() + request.source.name = "source.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_source), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.update_source(request) # Establish that the underlying gRPC stub method was called. @@ -6600,32 +6433,29 @@ async def test_update_source_field_headers_async(): def test_update_source_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_source), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_source( source=gcs_source.Source(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].source == gcs_source.Source(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_source_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -6633,13 +6463,15 @@ def test_update_source_flattened_error(): client.update_source( securitycenter_service.UpdateSourceRequest(), source=gcs_source.Source(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_source_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_source), "__call__") as call: @@ -6651,22 +6483,22 @@ async def test_update_source_flattened_async(): # using the keyword arguments to the method. response = await client.update_source( source=gcs_source.Source(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].source == gcs_source.Source(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_source_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -6674,7 +6506,7 @@ async def test_update_source_flattened_error_async(): await client.update_source( securitycenter_service.UpdateSourceRequest(), source=gcs_source.Source(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -6683,7 +6515,7 @@ def test_update_security_marks( request_type=securitycenter_service.UpdateSecurityMarksRequest, ): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -6695,21 +6527,20 @@ def test_update_security_marks( type(client.transport.update_security_marks), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks(name="name_value",) - + call.return_value = gcs_security_marks.SecurityMarks( + name="name_value", canonical_name="canonical_name_value", + ) response = client.update_security_marks(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == "name_value" + assert response.canonical_name == "canonical_name_value" def test_update_security_marks_from_dict(): @@ -6720,7 +6551,7 @@ def test_update_security_marks_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 = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -6730,7 +6561,6 @@ def test_update_security_marks_empty_call(): client.update_security_marks() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() @@ -6740,7 +6570,7 @@ async def test_update_security_marks_async( request_type=securitycenter_service.UpdateSecurityMarksRequest, ): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -6753,21 +6583,21 @@ async def test_update_security_marks_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gcs_security_marks.SecurityMarks(name="name_value",) + gcs_security_marks.SecurityMarks( + name="name_value", canonical_name="canonical_name_value", + ) ) - response = await client.update_security_marks(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == "name_value" + assert response.canonical_name == "canonical_name_value" @pytest.mark.asyncio @@ -6776,11 +6606,12 @@ async def test_update_security_marks_async_from_dict(): def test_update_security_marks_field_headers(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(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 = securitycenter_service.UpdateSecurityMarksRequest() + request.security_marks.name = "security_marks.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -6788,7 +6619,6 @@ def test_update_security_marks_field_headers(): type(client.transport.update_security_marks), "__call__" ) as call: call.return_value = gcs_security_marks.SecurityMarks() - client.update_security_marks(request) # Establish that the underlying gRPC stub method was called. @@ -6806,11 +6636,14 @@ def test_update_security_marks_field_headers(): @pytest.mark.asyncio async def test_update_security_marks_field_headers_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateSecurityMarksRequest() + request.security_marks.name = "security_marks.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -6820,7 +6653,6 @@ async def test_update_security_marks_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcs_security_marks.SecurityMarks() ) - await client.update_security_marks(request) # Establish that the underlying gRPC stub method was called. @@ -6837,7 +6669,7 @@ async def test_update_security_marks_field_headers_async(): def test_update_security_marks_flattened(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -6845,28 +6677,25 @@ def test_update_security_marks_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcs_security_marks.SecurityMarks() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_security_marks( security_marks=gcs_security_marks.SecurityMarks(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].security_marks == gcs_security_marks.SecurityMarks( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_security_marks_flattened_error(): - client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -6874,13 +6703,15 @@ def test_update_security_marks_flattened_error(): client.update_security_marks( securitycenter_service.UpdateSecurityMarksRequest(), security_marks=gcs_security_marks.SecurityMarks(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_security_marks_flattened_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -6896,24 +6727,24 @@ async def test_update_security_marks_flattened_async(): # using the keyword arguments to the method. response = await client.update_security_marks( security_marks=gcs_security_marks.SecurityMarks(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].security_marks == gcs_security_marks.SecurityMarks( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_security_marks_flattened_error_async(): - client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -6921,23 +6752,23 @@ async def test_update_security_marks_flattened_error_async(): await client.update_security_marks( securitycenter_service.UpdateSecurityMarksRequest(), security_marks=gcs_security_marks.SecurityMarks(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SecurityCenterGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecurityCenterClient( - 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.SecurityCenterGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecurityCenterClient( @@ -6947,7 +6778,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SecurityCenterGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecurityCenterClient( @@ -6958,7 +6789,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SecurityCenterGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SecurityCenterClient(transport=transport) assert client.transport is transport @@ -6967,13 +6798,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.SecurityCenterGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.SecurityCenterGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -6988,23 +6819,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 = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + client = SecurityCenterClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.SecurityCenterGrpcTransport,) def test_security_center_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.SecurityCenterTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -7016,7 +6847,7 @@ def test_security_center_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SecurityCenterTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -7056,15 +6887,37 @@ def test_security_center_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_security_center_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.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport._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.SecurityCenterTransport( + 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_security_center_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.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SecurityCenterTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -7077,19 +6930,33 @@ def test_security_center_base_transport_with_credentials_file(): def test_security_center_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.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SecurityCenterTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_security_center_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) + SecurityCenterClient() + 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_security_center_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) SecurityCenterClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -7097,20 +6964,156 @@ def test_security_center_auth_adc(): ) -def test_security_center_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_security_center_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.SecurityCenterGrpcTransport( - 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.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_security_center_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.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_security_center_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( + "securitycenter.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="securitycenter.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.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_security_center_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( + "securitycenter.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.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_security_center_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( + "securitycenter.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", [ @@ -7119,7 +7122,7 @@ def test_security_center_transport_auth_adc(): ], ) def test_security_center_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: @@ -7158,7 +7161,7 @@ def test_security_center_grpc_transport_client_cert_source_for_mtls(transport_cl def test_security_center_host_no_port(): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="securitycenter.googleapis.com" ), @@ -7168,7 +7171,7 @@ def test_security_center_host_no_port(): def test_security_center_host_with_port(): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="securitycenter.googleapis.com:8000" ), @@ -7224,9 +7227,9 @@ def test_security_center_transport_channel_mtls_with_client_cert_source( 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", @@ -7302,7 +7305,7 @@ def test_security_center_transport_channel_mtls_with_adc(transport_class): def test_security_center_grpc_lro_client(): client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -7315,7 +7318,7 @@ def test_security_center_grpc_lro_client(): def test_security_center_grpc_lro_async_client(): client = SecurityCenterAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -7329,7 +7332,6 @@ def test_security_center_grpc_lro_async_client(): def test_asset_path(): organization = "squid" asset = "clam" - expected = "organizations/{organization}/assets/{asset}".format( organization=organization, asset=asset, ) @@ -7353,7 +7355,6 @@ def test_finding_path(): organization = "oyster" source = "nudibranch" finding = "cuttlefish" - expected = "organizations/{organization}/sources/{source}/findings/{finding}".format( organization=organization, source=source, finding=finding, ) @@ -7377,7 +7378,6 @@ def test_parse_finding_path(): def test_notification_config_path(): organization = "scallop" notification_config = "abalone" - expected = "organizations/{organization}/notificationConfigs/{notification_config}".format( organization=organization, notification_config=notification_config, ) @@ -7401,7 +7401,6 @@ def test_parse_notification_config_path(): def test_organization_settings_path(): organization = "whelk" - expected = "organizations/{organization}/organizationSettings".format( organization=organization, ) @@ -7423,7 +7422,6 @@ def test_parse_organization_settings_path(): def test_security_marks_path(): organization = "oyster" asset = "nudibranch" - expected = "organizations/{organization}/assets/{asset}/securityMarks".format( organization=organization, asset=asset, ) @@ -7446,7 +7444,6 @@ def test_parse_security_marks_path(): def test_source_path(): organization = "winkle" source = "nautilus" - expected = "organizations/{organization}/sources/{source}".format( organization=organization, source=source, ) @@ -7469,7 +7466,6 @@ def test_parse_source_path(): def test_topic_path(): project = "squid" topic = "clam" - expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic,) actual = SecurityCenterClient.topic_path(project, topic) assert expected == actual @@ -7489,7 +7485,6 @@ def test_parse_topic_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -7510,7 +7505,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = SecurityCenterClient.common_folder_path(folder) assert expected == actual @@ -7529,7 +7523,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = SecurityCenterClient.common_organization_path(organization) assert expected == actual @@ -7548,7 +7541,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = SecurityCenterClient.common_project_path(project) assert expected == actual @@ -7568,7 +7560,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -7595,7 +7586,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SecurityCenterTransport, "_prep_wrapped_messages" ) as prep: client = SecurityCenterClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -7604,6 +7595,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SecurityCenterClient.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 284366dd10b913c4cb576faad5c3580ca54aa096 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Wed, 19 May 2021 23:02:04 +0000 Subject: [PATCH 23/23] chore: release 1.2.0 (#148) :robot: I have created a release \*beep\* \*boop\* --- ## [1.2.0](https://www.github.com/googleapis/python-securitycenter/compare/v1.1.0...v1.2.0) (2021-05-19) ### Features * add canonical_name and folder fields ([16a33f4](https://www.github.com/googleapis/python-securitycenter/commit/16a33f4c994b80d9c50537f2e1299282d525171e)) * support self-signed JWT flow for service accounts ([16a33f4](https://www.github.com/googleapis/python-securitycenter/commit/16a33f4c994b80d9c50537f2e1299282d525171e)) ### Bug Fixes * add async client to %name_%version/init.py ([16a33f4](https://www.github.com/googleapis/python-securitycenter/commit/16a33f4c994b80d9c50537f2e1299282d525171e)) * fix retry deadlines ([#116](https://www.github.com/googleapis/python-securitycenter/issues/116)) ([15c28e8](https://www.github.com/googleapis/python-securitycenter/commit/15c28e88f5b52a6e4f608198446b0753bf48734e)) ### Documentation * Fix conflict tag introduced in PR 104 ([#106](https://www.github.com/googleapis/python-securitycenter/issues/106)) ([f4f14ee](https://www.github.com/googleapis/python-securitycenter/commit/f4f14ee32602aad7b7a4837e330919b4276d7b18)) * standardize new tag with existing tags from other languages ([#104](https://www.github.com/googleapis/python-securitycenter/issues/104)) ([55582ac](https://www.github.com/googleapis/python-securitycenter/commit/55582acd814f7cd290580d5caa531725d2ff58b8)) --- 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 | 20 +++++++++++++++++++ setup.py | 2 +- .../securitycenter_v1/test_security_center.py | 4 ++-- .../test_security_center.py | 4 ++-- .../test_security_center.py | 4 ++-- 5 files changed, 27 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dbdfcafd..4894d414 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,26 @@ [1]: https://pypi.org/project/google-cloud-securitycenter/#history +## [1.2.0](https://www.github.com/googleapis/python-securitycenter/compare/v1.1.0...v1.2.0) (2021-05-19) + + +### Features + +* add canonical_name and folder fields ([16a33f4](https://www.github.com/googleapis/python-securitycenter/commit/16a33f4c994b80d9c50537f2e1299282d525171e)) +* support self-signed JWT flow for service accounts ([16a33f4](https://www.github.com/googleapis/python-securitycenter/commit/16a33f4c994b80d9c50537f2e1299282d525171e)) + + +### Bug Fixes + +* add async client to %name_%version/init.py ([16a33f4](https://www.github.com/googleapis/python-securitycenter/commit/16a33f4c994b80d9c50537f2e1299282d525171e)) +* fix retry deadlines ([#116](https://www.github.com/googleapis/python-securitycenter/issues/116)) ([15c28e8](https://www.github.com/googleapis/python-securitycenter/commit/15c28e88f5b52a6e4f608198446b0753bf48734e)) + + +### Documentation + +* Fix conflict tag introduced in PR 104 ([#106](https://www.github.com/googleapis/python-securitycenter/issues/106)) ([f4f14ee](https://www.github.com/googleapis/python-securitycenter/commit/f4f14ee32602aad7b7a4837e330919b4276d7b18)) +* standardize new tag with existing tags from other languages ([#104](https://www.github.com/googleapis/python-securitycenter/issues/104)) ([55582ac](https://www.github.com/googleapis/python-securitycenter/commit/55582acd814f7cd290580d5caa531725d2ff58b8)) + ## [1.1.0](https://www.github.com/googleapis/python-securitycenter/compare/v1.0.0...v1.1.0) (2020-12-15) diff --git a/setup.py b/setup.py index 0f264290..9636ca1b 100644 --- a/setup.py +++ b/setup.py @@ -21,7 +21,7 @@ name = "google-cloud-securitycenter" description = "Cloud Security Command Center API client library" -version = "1.1.0" +version = "1.2.0" release_status = "Development Status :: 3 - Alpha" dependencies = [ "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", diff --git a/tests/unit/gapic/securitycenter_v1/test_security_center.py b/tests/unit/gapic/securitycenter_v1/test_security_center.py index 9d0a6e4e..077678ef 100644 --- a/tests/unit/gapic/securitycenter_v1/test_security_center.py +++ b/tests/unit/gapic/securitycenter_v1/test_security_center.py @@ -4817,7 +4817,7 @@ def test_set_finding_state_flattened(): _, args, _ = call.mock_calls[0] assert args[0].name == "name_value" assert args[0].state == finding.Finding.State.ACTIVE - # # # # assert args[0].start_time == timestamp_pb2.Timestamp(seconds=751) + # # # # # # # assert args[0].start_time == timestamp_pb2.Timestamp(seconds=751) def test_set_finding_state_flattened_error(): @@ -4862,7 +4862,7 @@ async def test_set_finding_state_flattened_async(): _, args, _ = call.mock_calls[0] assert args[0].name == "name_value" assert args[0].state == finding.Finding.State.ACTIVE - # # # # assert args[0].start_time == timestamp_pb2.Timestamp(seconds=751) + # # # # # # # assert args[0].start_time == timestamp_pb2.Timestamp(seconds=751) @pytest.mark.asyncio diff --git a/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py b/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py index 7a968277..4c680dd9 100644 --- a/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py +++ b/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py @@ -3622,7 +3622,7 @@ def test_set_finding_state_flattened(): _, args, _ = call.mock_calls[0] assert args[0].name == "name_value" assert args[0].state == finding.Finding.State.ACTIVE - # # # # assert args[0].start_time == timestamp_pb2.Timestamp(seconds=751) + # # # # # # # assert args[0].start_time == timestamp_pb2.Timestamp(seconds=751) def test_set_finding_state_flattened_error(): @@ -3667,7 +3667,7 @@ async def test_set_finding_state_flattened_async(): _, args, _ = call.mock_calls[0] assert args[0].name == "name_value" assert args[0].state == finding.Finding.State.ACTIVE - # # # # assert args[0].start_time == timestamp_pb2.Timestamp(seconds=751) + # # # # # # # assert args[0].start_time == timestamp_pb2.Timestamp(seconds=751) @pytest.mark.asyncio diff --git a/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py b/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py index 4051107d..6c45b6cc 100644 --- a/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py +++ b/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py @@ -4975,7 +4975,7 @@ def test_set_finding_state_flattened(): _, args, _ = call.mock_calls[0] assert args[0].name == "name_value" assert args[0].state == finding.Finding.State.ACTIVE - # # # # assert args[0].start_time == timestamp_pb2.Timestamp(seconds=751) + # # # # # # # assert args[0].start_time == timestamp_pb2.Timestamp(seconds=751) def test_set_finding_state_flattened_error(): @@ -5020,7 +5020,7 @@ async def test_set_finding_state_flattened_async(): _, args, _ = call.mock_calls[0] assert args[0].name == "name_value" assert args[0].state == finding.Finding.State.ACTIVE - # # # # assert args[0].start_time == timestamp_pb2.Timestamp(seconds=751) + # # # # # # # assert args[0].start_time == timestamp_pb2.Timestamp(seconds=751) @pytest.mark.asyncio