Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)}")
Comment on lines +33 to +51

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Swallowing API exceptions and printing them to sys.stderr prevents 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.

    configs = list(client.list_instance_configs(request=request))
    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)}")

Copy link
Copy Markdown
Contributor Author

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.exceptions inside the sample function and print actionable diagnostic messages to stderr so readers can see concrete error handling directly in context, so we are keeping the try/except block.



# [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)
99 changes: 99 additions & 0 deletions spanner/instance_admin/tests/list_instance_configs_test.py
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.raises.

@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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Since the sample keeps its explicit exception handling and stderr reporting, this test keeps its capsys stderr assertions.



@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