Skip to content

feat(spanner): Add ListDatabaseRoles FGAC inspection sample - #14959

Open
iennae wants to merge 1 commit into
feat/spanner-create-databasefrom
feat/spanner-list-database-roles
Open

iennae wants to merge 1 commit into
feat/spanner-create-databasefrom
feat/spanner-list-database-roles

Conversation

@iennae

@iennae iennae commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Description

Adds spanner_list_database_roles enumerating database roles via DatabaseAdminClient.list_database_roles.

Note: Stacked on #14943 (feat/spanner-create-database) so this PR shows only this sample's diff. It will merge into main after #14943.

Checklist

Testing

  • I have tested this change on a live environment and verified it works as intended. Unit and live integration tests pass on Python 3.13.

Compliance & Style


Post-Approval Actions

  • Please merge this PR for me once it is approved

Auditing configured FGAC database roles calls DatabaseAdminClient.list_database_roles. Add a standalone spanner_list_database_roles sample with unit and live tests.
@iennae
iennae requested review from a team as code owners November 18, 2026 22:18
@snippet-bot

snippet-bot Bot commented Nov 18, 2026

Copy link
Copy Markdown

Here is the summary of changes.

You are about to add 1 region tag.

This comment is generated by snippet-bot.
If you find problems with this result, please file an issue at:
https://github.com/googleapis/repo-automation-bots/issues.
To update this comment, add snippet-bot:force-run label or use the checkbox below:

  • Refresh this comment

@product-auto-label product-auto-label Bot added api: spanner Issues related to the Spanner API. samples Issues that are directly related to samples. labels Nov 18, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

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.

Code Review

This pull request introduces a new script and tests for listing Google Cloud Spanner database roles. The review feedback suggests refactoring the exception handling in list_database_roles to propagate exceptions rather than swallowing them and printing to stderr. This change would allow callers to handle errors programmatically, ensure the CLI exits with a non-zero status on failure, and simplify the code. Consequently, unused imports should be removed, and the unit tests should be updated to assert that the expected exceptions are raised using pytest.raises.

Comment on lines +16 to +19
import sys

from google.api_core import exceptions
from google.cloud import spanner_admin_database_v1

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

With the exception handling refactored to propagate exceptions, the sys and google.api_core.exceptions modules are no longer used and can be safely removed.

Suggested change
import sys
from google.api_core import exceptions
from google.cloud import spanner_admin_database_v1
from google.cloud import spanner_admin_database_v1

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! The sample keeps its exception handling (see the reply below), so these imports are still used.

Comment on lines +34 to +53
try:
roles = list(client.list_database_roles(request=request))
except exceptions.NotFound as err:
print(
f"error: database '{database_id}' on instance '{instance_id}' "
f"was not found: {err.message}",
file=sys.stderr,
)
except exceptions.GoogleAPICallError as err:
print(
f"error: failed to list database roles on database "
f"'{database_id}' in instance '{instance_id}': {err.message}",
file=sys.stderr,
)
else:
print(f"Resource ID: {database_id}")
for role in roles:
role_id = role.name.split("/")[-1]
print(f"Database Role: {role_id}")
print(f"Role Count: {len(roles)}")

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 exceptions and printing them to sys.stderr inside a library/sample function is an anti-pattern. It prevents callers (including tests and other scripts) from programmatically detecting failures, and causes the CLI script to exit with a success status code (0) even when an error occurs.

Instead, let the exceptions propagate naturally. This simplifies the code, ensures the CLI exits with a non-zero status on failure, and makes the function much easier to test using pytest.raises.

    roles = list(client.list_database_roles(request=request))

    print(f"Resource ID: {database_id}")
    for role in roles:
        role_id = role.name.split("/")[-1]
        print(f"Database Role: {role_id}")
    print(f"Role Count: {len(roles)}")

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.

Comment on lines +51 to +77
@pytest.mark.parametrize(
"error, expected_prefix",
[
(exceptions.NotFound("missing"), "error: database 'example-db'"),
(
exceptions.PermissionDenied("denied"),
"error: failed to list database roles",
),
],
)
@mock.patch(ADMIN_CLIENT)
def test_list_database_roles_errors(
mock_client_class: mock.MagicMock,
capsys: pytest.CaptureFixture[str],
error: Exception,
expected_prefix: str,
) -> None:
mock_client_class.return_value.database_path.return_value = (
f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}/databases/{DATABASE_ID}"
)
mock_client_class.return_value.list_database_roles.side_effect = error

list_database_roles.list_database_roles(PROJECT_ID, INSTANCE_ID, DATABASE_ID)

_out, err = capsys.readouterr()
assert err.startswith(expected_prefix)
assert PROJECT_ID not in err

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 the list_database_roles function has been refactored to propagate exceptions rather than swallowing them, update the unit tests to assert that the expected exceptions are raised using pytest.raises.

@pytest.mark.parametrize(
    "error",
    [
        exceptions.NotFound("missing"),
        exceptions.PermissionDenied("denied"),
    ],
)
@mock.patch(ADMIN_CLIENT)
def test_list_database_roles_errors(
    mock_client_class: mock.MagicMock,
    error: Exception,
) -> None:
    mock_client_class.return_value.database_path.return_value = (
        f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}/databases/{DATABASE_ID}"
    )
    mock_client_class.return_value.list_database_roles.side_effect = error

    with pytest.raises(type(error)):
        list_database_roles.list_database_roles(PROJECT_ID, INSTANCE_ID, DATABASE_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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api: spanner Issues related to the Spanner API. samples Issues that are directly related to samples.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant