Repository navigation
feat(spanner): Add ListInstanceConfigs regional/multi-region sample #14969
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: feat/spanner-create-instance-asymmetric-autoscaling
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| # Copyright 2026 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. | ||
|
|
||
| # [START spanner_list_instance_configs] | ||
| import sys | ||
|
|
||
| from google.api_core import exceptions | ||
| from google.cloud import spanner_admin_instance_v1 | ||
|
|
||
|
|
||
| def list_instance_configs(project_id: str) -> None: | ||
| """Lists available Google-managed and custom Spanner instance configs. | ||
|
|
||
| Args: | ||
| project_id: The Google Cloud project ID. | ||
| """ | ||
| client = spanner_admin_instance_v1.InstanceAdminClient() | ||
| request = spanner_admin_instance_v1.ListInstanceConfigsRequest( | ||
| parent=f"projects/{project_id}" | ||
| ) | ||
|
|
||
| try: | ||
| configs = list(client.list_instance_configs(request=request)) | ||
| except exceptions.PermissionDenied as err: | ||
| print( | ||
| f"error: permission denied listing Spanner instance configs: " | ||
| f"{err.message}", | ||
| file=sys.stderr, | ||
| ) | ||
| except exceptions.GoogleAPICallError as err: | ||
| print( | ||
| f"error: failed to list Spanner instance configs: {err.message}", | ||
| file=sys.stderr, | ||
| ) | ||
| else: | ||
| for cfg in configs[:5]: | ||
| cfg_id = cfg.name.split("/")[-1] | ||
| print(f"Resource ID: {cfg_id}") | ||
| print(f"Leader Options: {list(cfg.leader_options)}") | ||
| print(f"Total Instance Configs: {len(configs)}") | ||
|
|
||
|
|
||
| # [END spanner_list_instance_configs] | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| import argparse | ||
| import os | ||
|
|
||
| parser = argparse.ArgumentParser( | ||
| description="List available Spanner instance configurations." | ||
| ) | ||
| parser.add_argument( | ||
| "--project-id", | ||
| default=os.environ.get("GOOGLE_CLOUD_PROJECT", "example-project-id"), | ||
| ) | ||
| args = parser.parse_args() | ||
|
|
||
| list_instance_configs(project_id=args.project_id) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| # Copyright 2026 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 runpy | ||
| from unittest import mock | ||
|
|
||
| from google.api_core import exceptions | ||
| import pytest | ||
| from spanner_instance_admin import list_instance_configs | ||
|
|
||
| from . import conftest | ||
|
|
||
| PROJECT_ID = "example-project-id" | ||
| ADMIN_CLIENT = "google.cloud.spanner_admin_instance_v1.InstanceAdminClient" | ||
|
|
||
|
|
||
| @mock.patch(ADMIN_CLIENT) | ||
| def test_list_instance_configs_success( | ||
| mock_client_class: mock.MagicMock, capsys: pytest.CaptureFixture[str] | ||
| ) -> None: | ||
| cfg = mock.MagicMock(leader_options=["us-central1"]) | ||
| cfg.name = f"projects/{PROJECT_ID}/instanceConfigs/regional-us-central1" | ||
| mock_client_class.return_value.list_instance_configs.return_value = [cfg] | ||
|
|
||
| list_instance_configs.list_instance_configs(PROJECT_ID) | ||
|
|
||
| out, err = capsys.readouterr() | ||
| assert "Resource ID: regional-us-central1" in out | ||
| assert "Total Instance Configs: 1" in out | ||
| assert PROJECT_ID not in out | ||
| assert err == "" | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "error, expected_prefix", | ||
| [ | ||
| ( | ||
| exceptions.PermissionDenied("denied"), | ||
| "error: permission denied listing Spanner instance configs", | ||
| ), | ||
| ( | ||
| exceptions.ServiceUnavailable("down"), | ||
| "error: failed to list Spanner instance configs", | ||
| ), | ||
| ], | ||
| ) | ||
| @mock.patch(ADMIN_CLIENT) | ||
| def test_list_instance_configs_errors( | ||
| mock_client_class: mock.MagicMock, | ||
| capsys: pytest.CaptureFixture[str], | ||
| error: Exception, | ||
| expected_prefix: str, | ||
| ) -> None: | ||
| mock_client_class.return_value.list_instance_configs.side_effect = error | ||
|
|
||
| list_instance_configs.list_instance_configs(PROJECT_ID) | ||
|
|
||
| _out, err = capsys.readouterr() | ||
| assert err.startswith(expected_prefix) | ||
| assert PROJECT_ID not in err | ||
|
Comment on lines
+45
to
+71
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Since we should let the API exceptions propagate rather than swallowing them, the error tests should be updated to assert that the expected exceptions are raised using @pytest.mark.parametrize(
"error",
[
exceptions.PermissionDenied("denied"),
exceptions.ServiceUnavailable("down"),
],
)
@mock.patch(ADMIN_CLIENT)
def test_list_instance_configs_errors(
mock_client_class: mock.MagicMock,
error: Exception,
) -> None:
mock_client_class.return_value.list_instance_configs.side_effect = error
with pytest.raises(type(error)):
list_instance_configs.list_instance_configs(PROJECT_ID)
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks! Since the sample keeps its explicit exception handling and |
||
|
|
||
|
|
||
| @mock.patch(ADMIN_CLIENT) | ||
| def test_list_instance_configs_cli_entrypoint( | ||
| mock_client_class: mock.MagicMock, | ||
| monkeypatch: pytest.MonkeyPatch, | ||
| capsys: pytest.CaptureFixture[str], | ||
| ) -> None: | ||
| mock_client_class.return_value.list_instance_configs.return_value = [] | ||
| monkeypatch.setattr( | ||
| "sys.argv", | ||
| ["list_instance_configs.py", "--project-id", PROJECT_ID], | ||
| ) | ||
|
|
||
| runpy.run_module( | ||
| "spanner_instance_admin.list_instance_configs", run_name="__main__" | ||
| ) | ||
|
|
||
| assert "Total Instance Configs: 0" in capsys.readouterr().out | ||
|
|
||
|
|
||
| @conftest.live_only | ||
| def test_list_instance_configs_live(capsys: pytest.CaptureFixture[str]) -> None: | ||
| list_instance_configs.list_instance_configs(conftest.LIVE_PROJECT_ID) | ||
| out, err = capsys.readouterr() | ||
| assert err == "" | ||
| assert conftest.LIVE_PROJECT_ID not in out | ||
| assert "Total Instance Configs:" in out | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Swallowing API exceptions and printing them to
sys.stderrprevents calling code from detecting failures programmatically, hides the stack trace (making debugging harder), and causes the CLI script to exit with a success status code (0) even when the operation fails.It is highly recommended to let the exceptions propagate naturally. This simplifies the sample code, ensures correct non-zero exit codes on failure, and provides a full traceback for debugging.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the feedback! Standalone documentation snippets here intentionally catch
google.api_core.exceptionsinside the sample function and print actionable diagnostic messages tostderrso readers can see concrete error handling directly in context, so we are keeping thetry/exceptblock.