Repository navigation
Conversation
Auditing configured FGAC database roles calls DatabaseAdminClient.list_database_roles. Add a standalone spanner_list_database_roles sample with unit and live tests.
|
Here is the summary of changes. You are about to add 1 region tag.
This comment is generated by snippet-bot.
|
There was a problem hiding this comment.
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.
| import sys | ||
|
|
||
| from google.api_core import exceptions | ||
| from google.cloud import spanner_admin_database_v1 |
There was a problem hiding this comment.
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.
| import sys | |
| from google.api_core import exceptions | |
| from google.cloud import spanner_admin_database_v1 | |
| from google.cloud import spanner_admin_database_v1 |
There was a problem hiding this comment.
Thanks! The sample keeps its exception handling (see the reply below), so these imports are still used.
| 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)}") |
There was a problem hiding this comment.
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)}")There was a problem hiding this comment.
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.
| @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 |
There was a problem hiding this comment.
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)There was a problem hiding this comment.
Thanks! Since the sample keeps its explicit exception handling and stderr reporting, this test keeps its capsys stderr assertions.
Description
Adds
spanner_list_database_rolesenumerating database roles viaDatabaseAdminClient.list_database_roles.Checklist
Testing
Compliance & Style
spanner/, which the default repository owners cover.Post-Approval Actions