Repository navigation
feat(spanner): Add DeleteBackupSchedule cleanup sample #14987
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
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,93 @@ | ||
| # 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_delete_backup_schedule] | ||
| import sys | ||
|
|
||
| from google.api_core import exceptions | ||
| from google.cloud import spanner_admin_database_v1 | ||
|
|
||
|
|
||
| def delete_backup_schedule( | ||
| project_id: str, | ||
| instance_id: str, | ||
| database_id: str, | ||
| schedule_id: str, | ||
| ) -> None: | ||
| """Deletes a backup schedule from a Cloud Spanner database. | ||
|
|
||
| Args: | ||
| project_id: The Google Cloud project ID. | ||
| instance_id: The Spanner instance ID. | ||
| database_id: The Spanner database ID. | ||
| schedule_id: The backup schedule ID to delete. | ||
| """ | ||
| client = spanner_admin_database_v1.DatabaseAdminClient() | ||
| schedule_path = client.backup_schedule_path( | ||
| project_id, instance_id, database_id, schedule_id | ||
| ) | ||
| request = spanner_admin_database_v1.DeleteBackupScheduleRequest(name=schedule_path) | ||
|
|
||
| try: | ||
| client.delete_backup_schedule(request=request) | ||
| except exceptions.NotFound as err: | ||
| print( | ||
| f"error: backup schedule '{schedule_id}' on database " | ||
| f"'{database_id}' in instance '{instance_id}' was not found: " | ||
| f"{err.message}", | ||
| file=sys.stderr, | ||
| ) | ||
| except exceptions.GoogleAPICallError as err: | ||
| print( | ||
| f"error: failed to delete backup schedule '{schedule_id}' on " | ||
| f"database '{database_id}': {err.message}", | ||
| file=sys.stderr, | ||
| ) | ||
| else: | ||
| print(f"Resource ID: {schedule_id}") | ||
| print(f"Deleted Schedule: {schedule_id}") | ||
|
|
||
|
|
||
| # [END spanner_delete_backup_schedule] | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| import argparse | ||
| import os | ||
|
|
||
| parser = argparse.ArgumentParser(description="Delete a Spanner backup schedule.") | ||
| parser.add_argument( | ||
| "--project-id", | ||
| default=os.environ.get("GOOGLE_CLOUD_PROJECT", "example-project-id"), | ||
| ) | ||
| parser.add_argument( | ||
| "--instance-id", | ||
| default=os.environ.get("SPANNER_INSTANCE_ID", "example-instance"), | ||
| ) | ||
| parser.add_argument( | ||
| "--database-id", | ||
| default=os.environ.get("SPANNER_DATABASE_ID", "example-db"), | ||
| ) | ||
| parser.add_argument( | ||
| "--schedule-id", | ||
| default="example-backup-schedule", | ||
| ) | ||
| args = parser.parse_args() | ||
|
|
||
| delete_backup_schedule( | ||
| project_id=args.project_id, | ||
| instance_id=args.instance_id, | ||
| database_id=args.database_id, | ||
| schedule_id=args.schedule_id, | ||
| ) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
| # 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 | ||
| import uuid | ||
|
|
||
| from google.api_core import exceptions | ||
| from google.cloud import spanner_admin_database_v1 | ||
| import pytest | ||
| from spanner_backups import create_full_backup_schedule | ||
| from spanner_backups import delete_backup_schedule | ||
|
|
||
| from . import conftest | ||
|
|
||
| PROJECT_ID = "example-project-id" | ||
| INSTANCE_ID = "example-instance" | ||
| DATABASE_ID = "example-db" | ||
| SCHEDULE_ID = "example-backup-schedule" | ||
| ADMIN_CLIENT = "google.cloud.spanner_admin_database_v1.DatabaseAdminClient" | ||
|
|
||
|
|
||
| def _setup_admin(mock_client_class: mock.MagicMock) -> None: | ||
| mock_client_class.return_value.backup_schedule_path.return_value = ( | ||
| f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}" | ||
| f"/databases/{DATABASE_ID}/backupSchedules/{SCHEDULE_ID}" | ||
| ) | ||
|
|
||
|
|
||
| @mock.patch(ADMIN_CLIENT) | ||
| def test_delete_backup_schedule_success( | ||
| mock_client_class: mock.MagicMock, capsys: pytest.CaptureFixture[str] | ||
| ) -> None: | ||
| _setup_admin(mock_client_class) | ||
|
|
||
| delete_backup_schedule.delete_backup_schedule( | ||
| PROJECT_ID, INSTANCE_ID, DATABASE_ID, SCHEDULE_ID | ||
| ) | ||
|
|
||
| mock_client_class.return_value.delete_backup_schedule.assert_called_once() | ||
| out, err = capsys.readouterr() | ||
| assert f"Resource ID: {SCHEDULE_ID}" in out | ||
| assert f"Deleted Schedule: {SCHEDULE_ID}" in out | ||
| assert PROJECT_ID not in out | ||
| assert err == "" | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "error, expected_prefix", | ||
| [ | ||
| ( | ||
| exceptions.NotFound("missing"), | ||
| "error: backup schedule 'example-backup-schedule'", | ||
| ), | ||
| ( | ||
| exceptions.PermissionDenied("denied"), | ||
| "error: failed to delete backup schedule", | ||
| ), | ||
| ], | ||
| ) | ||
| @mock.patch(ADMIN_CLIENT) | ||
| def test_delete_backup_schedule_errors( | ||
| mock_client_class: mock.MagicMock, | ||
| capsys: pytest.CaptureFixture[str], | ||
| error: Exception, | ||
| expected_prefix: str, | ||
| ) -> None: | ||
| _setup_admin(mock_client_class) | ||
| mock_client_class.return_value.delete_backup_schedule.side_effect = error | ||
|
|
||
| delete_backup_schedule.delete_backup_schedule( | ||
| PROJECT_ID, INSTANCE_ID, DATABASE_ID, SCHEDULE_ID | ||
| ) | ||
|
|
||
| _out, err = capsys.readouterr() | ||
| assert err.startswith(expected_prefix) | ||
| assert PROJECT_ID not in err | ||
|
Comment on lines
+59
to
+88
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. If the @pytest.mark.parametrize(
"error",
[
exceptions.NotFound("missing"),
exceptions.PermissionDenied("denied"),
],
)
@mock.patch(ADMIN_CLIENT)
def test_delete_backup_schedule_errors(
mock_client_class: mock.MagicMock,
error: Exception,
) -> None:
_setup_admin(mock_client_class)
mock_client_class.return_value.delete_backup_schedule.side_effect = error
with pytest.raises(type(error)):
delete_backup_schedule.delete_backup_schedule(
PROJECT_ID, INSTANCE_ID, DATABASE_ID, SCHEDULE_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_delete_backup_schedule_cli_entrypoint( | ||
| mock_client_class: mock.MagicMock, | ||
| monkeypatch: pytest.MonkeyPatch, | ||
| capsys: pytest.CaptureFixture[str], | ||
| ) -> None: | ||
| _setup_admin(mock_client_class) | ||
| monkeypatch.setattr( | ||
| "sys.argv", | ||
| [ | ||
| "delete_backup_schedule.py", | ||
| "--project-id", | ||
| PROJECT_ID, | ||
| "--instance-id", | ||
| INSTANCE_ID, | ||
| "--database-id", | ||
| DATABASE_ID, | ||
| "--schedule-id", | ||
| SCHEDULE_ID, | ||
| ], | ||
| ) | ||
|
|
||
| runpy.run_module("spanner_backups.delete_backup_schedule", run_name="__main__") | ||
|
|
||
| assert f"Deleted Schedule: {SCHEDULE_ID}" in capsys.readouterr().out | ||
|
|
||
|
|
||
| @conftest.live_only | ||
| def test_delete_backup_schedule_live(capsys: pytest.CaptureFixture[str]) -> None: | ||
| admin = spanner_admin_database_v1.DatabaseAdminClient() | ||
| sid = f"example-dsc-{uuid.uuid4().hex[:6]}" | ||
| spath = admin.backup_schedule_path( | ||
| conftest.LIVE_PROJECT_ID, | ||
| conftest.LIVE_INSTANCE_ID, | ||
| conftest.LIVE_DATABASE_ID, | ||
| sid, | ||
| ) | ||
| try: | ||
| create_full_backup_schedule.create_full_backup_schedule( | ||
| conftest.LIVE_PROJECT_ID, | ||
| conftest.LIVE_INSTANCE_ID, | ||
| conftest.LIVE_DATABASE_ID, | ||
| sid, | ||
| ) | ||
| capsys.readouterr() | ||
| delete_backup_schedule.delete_backup_schedule( | ||
| conftest.LIVE_PROJECT_ID, | ||
| conftest.LIVE_INSTANCE_ID, | ||
| conftest.LIVE_DATABASE_ID, | ||
| sid, | ||
| ) | ||
| out, err = capsys.readouterr() | ||
| assert err == "" | ||
| assert conftest.LIVE_PROJECT_ID not in out | ||
| assert f"Deleted Schedule: {sid}" in out | ||
| finally: | ||
| try: | ||
| admin.delete_backup_schedule(name=spath) | ||
| except exceptions.NotFound: | ||
| pass | ||
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.
Catching and swallowing API exceptions (
exceptions.NotFoundandexceptions.GoogleAPICallError) inside the sample function makes it difficult for programmatic callers to detect and handle failures. If this function is integrated into a larger application, failures will go unnoticed because the function silently returnsNone. Additionally, when run as a CLI script, the process will exit with a status code of0(success) even if the deletion failed.It is more idiomatic for sample functions to let exceptions propagate naturally to the caller. If you want to avoid raw tracebacks for CLI users, you can catch the exceptions in the
__main__block and exit with a non-zero status code (e.g.,sys.exit(1)).Note: If you apply this change, you will also need to update
test_delete_backup_schedule_errorsindelete_backup_schedule_test.pyto usepytest.raisesinstead of asserting oncapsys.References
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.