diff --git a/spanner/backups/README.md b/spanner/backups/README.md new file mode 100644 index 0000000000..40b6d780ca --- /dev/null +++ b/spanner/backups/README.md @@ -0,0 +1,27 @@ +# Cloud Spanner Backup & Restore Samples + +Python samples demonstrating Cloud Spanner backup creation, cross-instance backup copying, and listing copy-backup long-running operations. + +## Setup + +1. Create and activate a Python 3.13+ virtual environment: + + ```sh + python3 -m venv env + source env/bin/activate + ``` + +2. Install dependencies: + + ```sh + pip install -r requirements.txt + ``` + +## Running Tests + +Run unit tests offline: + +```sh +pip install -r requirements-test.txt +pytest tests +``` diff --git a/spanner/backups/noxfile_config.py b/spanner/backups/noxfile_config.py new file mode 100644 index 0000000000..fe371aaf48 --- /dev/null +++ b/spanner/backups/noxfile_config.py @@ -0,0 +1,21 @@ +# 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. + +TEST_CONFIG_OVERRIDE = { + "ignored_versions": ["2.7", "3.7", "3.8", "3.9", "3.10", "3.11", "3.12"], + "enforce_type_hints": True, + "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", + "pip_version_override": None, + "envs": {}, +} diff --git a/spanner/backups/pyproject.toml b/spanner/backups/pyproject.toml new file mode 100644 index 0000000000..439c3f3ae0 --- /dev/null +++ b/spanner/backups/pyproject.toml @@ -0,0 +1,30 @@ +# 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. + +# Local samples only. This package isn't published: install it from this +# directory with `pip install -e .`, never by name from PyPI. +[build-system] +requires = ["setuptools>=64"] +build-backend = "setuptools.build_meta" + +[project] +name = "spanner-backups-samples" +version = "0.0.0" +requires-python = ">=3.13" +dependencies = [ + "google-api-core==2.44.0", + "google-cloud-spanner==3.72.0", +] +# PyPI rejects uploads with this classifier. +classifiers = ["Private :: Do Not Upload"] diff --git a/spanner/backups/requirements-test.txt b/spanner/backups/requirements-test.txt new file mode 100644 index 0000000000..ac63bdc5a9 --- /dev/null +++ b/spanner/backups/requirements-test.txt @@ -0,0 +1,2 @@ +-e . +pytest==9.2.0 diff --git a/spanner/backups/requirements.txt b/spanner/backups/requirements.txt new file mode 100644 index 0000000000..a56c81cc2e --- /dev/null +++ b/spanner/backups/requirements.txt @@ -0,0 +1,2 @@ +google-api-core==2.44.0 +google-cloud-spanner==3.72.0 diff --git a/spanner/backups/src/spanner_backups/__init__.py b/spanner/backups/src/spanner_backups/__init__.py new file mode 100644 index 0000000000..58d482ea38 --- /dev/null +++ b/spanner/backups/src/spanner_backups/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/spanner/backups/src/spanner_backups/copy_backup.py b/spanner/backups/src/spanner_backups/copy_backup.py new file mode 100644 index 0000000000..1b9b413713 --- /dev/null +++ b/spanner/backups/src/spanner_backups/copy_backup.py @@ -0,0 +1,124 @@ +# 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_copy_backup] +from datetime import datetime, timedelta, timezone +import sys + +from google.api_core import exceptions +from google.cloud import spanner_admin_database_v1 + + +def copy_backup( + project_id: str, + instance_id: str, + backup_id: str, + source_backup_path: str, +) -> None: + """Copies an existing Spanner backup to a destination instance. + + Args: + project_id: The destination Google Cloud project ID. + instance_id: The destination Spanner instance ID. + backup_id: The ID for the newly copied backup. + source_backup_path: Full resource path of the source backup + (projects//instances//backups/). + """ + client = spanner_admin_database_v1.DatabaseAdminClient() + parent = client.instance_path(project_id, instance_id) + expire_time = datetime.now(timezone.utc) + timedelta(days=14) + + source_backup_id = source_backup_path.split("/")[-1] + request = spanner_admin_database_v1.CopyBackupRequest( + parent=parent, + backup_id=backup_id, + source_backup=source_backup_path, + expire_time=expire_time, + ) + + try: + operation = client.copy_backup(request=request) + print(f"Waiting for backup copy '{backup_id}' to complete...") + copied = operation.result(timeout=2100) + except exceptions.AlreadyExists as err: + print( + f"error: backup '{backup_id}' already exists on instance " + f"'{instance_id}': {err.message}", + file=sys.stderr, + ) + except exceptions.NotFound as err: + print( + f"error: source backup '{source_backup_id}' or destination " + f"instance '{instance_id}' was not found: {err.message}", + file=sys.stderr, + ) + except TimeoutError as err: + print( + f"error: timed out waiting for the operation on backup '{backup_id}' " + f"to complete; the operation may still be running: {err}", + file=sys.stderr, + ) + except exceptions.GoogleAPICallError as err: + print( + f"error: failed to copy backup '{source_backup_id}' to " + f"'{backup_id}' on instance '{instance_id}': {err.message}", + file=sys.stderr, + ) + else: + print(f"Resource ID: {backup_id}") + print(f"Backup State: {copied.state.name}") + print(f"Size Bytes: {copied.size_bytes}") + + +# [END spanner_copy_backup] + + +if __name__ == "__main__": + import argparse + import os + + parser = argparse.ArgumentParser( + description="Copy an existing Cloud Spanner backup." + ) + parser.add_argument( + "--project-id", + default=os.environ.get("GOOGLE_CLOUD_PROJECT", "example-project-id"), + help="Destination Google Cloud project ID (default: $GOOGLE_CLOUD_PROJECT)", + ) + parser.add_argument( + "--instance-id", + default=os.environ.get("SPANNER_INSTANCE_ID", "example-instance"), + help="Destination Spanner instance ID (default: $SPANNER_INSTANCE_ID)", + ) + parser.add_argument( + "--backup-id", + default=os.environ.get("SPANNER_BACKUP_ID", "example-copied-backup"), + help="New copied backup ID (default: $SPANNER_BACKUP_ID)", + ) + parser.add_argument( + "--source-backup-path", + default=os.environ.get( + "SPANNER_SOURCE_BACKUP_PATH", + "projects/example-project-id/instances/example-instance/backups/example-source-backup", + ), + help="Full resource path of the source backup", + ) + args = parser.parse_args() + + copy_backup( + project_id=args.project_id, + instance_id=args.instance_id, + backup_id=args.backup_id, + source_backup_path=args.source_backup_path, + ) diff --git a/spanner/backups/src/spanner_backups/delete_backup_schedule.py b/spanner/backups/src/spanner_backups/delete_backup_schedule.py new file mode 100644 index 0000000000..0acca2dfc9 --- /dev/null +++ b/spanner/backups/src/spanner_backups/delete_backup_schedule.py @@ -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, + ) diff --git a/spanner/backups/src/spanner_backups/update_backup_schedule.py b/spanner/backups/src/spanner_backups/update_backup_schedule.py new file mode 100644 index 0000000000..74efa3772b --- /dev/null +++ b/spanner/backups/src/spanner_backups/update_backup_schedule.py @@ -0,0 +1,121 @@ +# 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_update_backup_schedule] +import datetime +import sys + +from google.api_core import exceptions +from google.cloud import spanner_admin_database_v1 + + +def update_backup_schedule( + project_id: str, + instance_id: str, + database_id: str, + schedule_id: str, +) -> None: + """Updates cron frequency and retention duration on a backup schedule. + + 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 update. + """ + client = spanner_admin_database_v1.DatabaseAdminClient() + schedule_path = client.backup_schedule_path( + project_id, instance_id, database_id, schedule_id + ) + cron_spec = spanner_admin_database_v1.CrontabSpec(text="45 15 * * *") + schedule_spec = spanner_admin_database_v1.BackupScheduleSpec(cron_spec=cron_spec) + enc_type = ( + spanner_admin_database_v1.CreateBackupEncryptionConfig.EncryptionType.USE_DATABASE_ENCRYPTION + ) + enc_config = spanner_admin_database_v1.CreateBackupEncryptionConfig( + encryption_type=enc_type + ) + schedule_pb = spanner_admin_database_v1.BackupSchedule( + name=schedule_path, + spec=schedule_spec, + retention_duration=datetime.timedelta(hours=48), + encryption_config=enc_config, + ) + request = spanner_admin_database_v1.UpdateBackupScheduleRequest( + backup_schedule=schedule_pb, + update_mask={ + "paths": [ + "spec.cron_spec.text", + "retention_duration", + "encryption_config", + ] + }, + ) + + try: + updated = client.update_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 update backup schedule '{schedule_id}' on " + f"database '{database_id}': {err.message}", + file=sys.stderr, + ) + else: + retention_hours = int(updated.retention_duration.total_seconds() // 3600) + print(f"Resource ID: {schedule_id}") + print(f"Cron Expression: {updated.spec.cron_spec.text}") + print(f"Retention Hours: {retention_hours}") + + +# [END spanner_update_backup_schedule] + + +if __name__ == "__main__": + import argparse + import os + + parser = argparse.ArgumentParser( + description="Update cron and retention on a 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() + + update_backup_schedule( + project_id=args.project_id, + instance_id=args.instance_id, + database_id=args.database_id, + schedule_id=args.schedule_id, + ) diff --git a/spanner/backups/tests/__init__.py b/spanner/backups/tests/__init__.py new file mode 100644 index 0000000000..58d482ea38 --- /dev/null +++ b/spanner/backups/tests/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/spanner/backups/tests/conftest.py b/spanner/backups/tests/conftest.py new file mode 100644 index 0000000000..c5d8098a0b --- /dev/null +++ b/spanner/backups/tests/conftest.py @@ -0,0 +1,36 @@ +# 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. + +"""Shared live-test configuration for Cloud Spanner Backup & Restore Samples.""" + +import os + +import pytest + +LIVE_PROJECT_ID = os.environ.get("GOOGLE_CLOUD_PROJECT", "") +LIVE_INSTANCE_ID = os.environ.get("SPANNER_INSTANCE_ID", "") +LIVE_DATABASE_ID = os.environ.get("SPANNER_DATABASE_ID", "") + +if os.environ.get("RUN_INTEGRATION_TESTS") == "true" and ( + not LIVE_PROJECT_ID or not LIVE_INSTANCE_ID +): + raise RuntimeError( + "Set GOOGLE_CLOUD_PROJECT and SPANNER_INSTANCE_ID when " + "RUN_INTEGRATION_TESTS=true." + ) + +live_only = pytest.mark.skipif( + os.environ.get("RUN_INTEGRATION_TESTS") != "true", + reason="Set RUN_INTEGRATION_TESTS=true to run integration tests.", +) diff --git a/spanner/backups/tests/copy_backup_test.py b/spanner/backups/tests/copy_backup_test.py new file mode 100644 index 0000000000..411c78c8fd --- /dev/null +++ b/spanner/backups/tests/copy_backup_test.py @@ -0,0 +1,185 @@ +# 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. + +from datetime import datetime, timedelta, timezone +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 copy_backup + +from . import conftest + +PROJECT_ID = "example-project-id" +INSTANCE_ID = "example-instance" +BACKUP_ID = "example-copied-backup" +SOURCE_BACKUP = f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}/backups/example-src" +COPIED_NAME = f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}/backups/{BACKUP_ID}" +ADMIN_CLIENT = "google.cloud.spanner_admin_database_v1.DatabaseAdminClient" + + +def _fake_backup() -> spanner_admin_database_v1.Backup: + return spanner_admin_database_v1.Backup( + name=COPIED_NAME, + state=spanner_admin_database_v1.Backup.State.READY, + size_bytes=4096, + ) + + +@mock.patch(ADMIN_CLIENT) +def test_copy_backup_success( + mock_client_class: mock.MagicMock, capsys: pytest.CaptureFixture[str] +) -> None: + client = mock_client_class.return_value + client.instance_path.return_value = f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}" + client.copy_backup.return_value.result.return_value = _fake_backup() + + copy_backup.copy_backup(PROJECT_ID, INSTANCE_ID, BACKUP_ID, SOURCE_BACKUP) + + req = client.copy_backup.call_args.kwargs["request"] + assert req.backup_id == BACKUP_ID + assert req.source_backup == SOURCE_BACKUP + out, err = capsys.readouterr() + assert f"Resource ID: {BACKUP_ID}" in out + assert PROJECT_ID not in out + assert "Backup State: READY" in out + assert "Size Bytes: 4096" in out + assert err == "" + + +@pytest.mark.parametrize( + "error, expected_prefix", + [ + (TimeoutError("deadline"), "error: timed out waiting for the operation"), + ( + exceptions.AlreadyExists("exists"), + "error: backup 'example-copied-backup' already exists", + ), + ( + exceptions.NotFound("missing"), + "error: source backup", + ), + ( + exceptions.PermissionDenied("denied"), + "error: failed to copy backup", + ), + ], +) +@mock.patch(ADMIN_CLIENT) +def test_copy_backup_errors( + mock_client_class: mock.MagicMock, + capsys: pytest.CaptureFixture[str], + error: Exception, + expected_prefix: str, +) -> None: + client = mock_client_class.return_value + client.instance_path.return_value = f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}" + client.copy_backup.side_effect = error + + copy_backup.copy_backup(PROJECT_ID, INSTANCE_ID, BACKUP_ID, SOURCE_BACKUP) + + _out, err = capsys.readouterr() + assert err.startswith(expected_prefix) + assert PROJECT_ID not in err + assert PROJECT_ID not in err + + +@mock.patch(ADMIN_CLIENT) +def test_copy_backup_cli_entrypoint( + mock_client_class: mock.MagicMock, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + client = mock_client_class.return_value + client.instance_path.return_value = f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}" + client.copy_backup.return_value.result.return_value = _fake_backup() + monkeypatch.setattr( + "sys.argv", + [ + "copy_backup.py", + "--project-id", + PROJECT_ID, + "--instance-id", + INSTANCE_ID, + "--backup-id", + BACKUP_ID, + "--source-backup-path", + SOURCE_BACKUP, + ], + ) + + runpy.run_module("spanner_backups.copy_backup", run_name="__main__") + + assert "Backup State: READY" in capsys.readouterr().out + + +@conftest.live_only +def test_copy_backup_live(capsys: pytest.CaptureFixture[str]) -> None: + admin = spanner_admin_database_v1.DatabaseAdminClient() + parent = admin.instance_path(conftest.LIVE_PROJECT_ID, conftest.LIVE_INSTANCE_ID) + suffix = uuid.uuid4().hex[:6] + temp_db_id = f"example-bkp-db-{suffix}" + db_path = admin.database_path( + conftest.LIVE_PROJECT_ID, + conftest.LIVE_INSTANCE_ID, + temp_db_id, + ) + src_id = f"example-src-bkp-{suffix}" + dst_id = f"example-cpy-bkp-{suffix}" + src_name = f"{parent}/backups/{src_id}" + dst_name = f"{parent}/backups/{dst_id}" + + try: + admin.create_database( + request=spanner_admin_database_v1.CreateDatabaseRequest( + parent=parent, + create_statement=f"CREATE DATABASE `{temp_db_id}`", + ) + ).result(timeout=300) + + admin.create_backup( + request=spanner_admin_database_v1.CreateBackupRequest( + parent=parent, + backup_id=src_id, + backup=spanner_admin_database_v1.Backup( + database=db_path, + expire_time=datetime.now(timezone.utc) + timedelta(hours=8), + ), + ) + ).result(timeout=1800) + + copy_backup.copy_backup( + conftest.LIVE_PROJECT_ID, + conftest.LIVE_INSTANCE_ID, + dst_id, + src_name, + ) + out, err = capsys.readouterr() + assert err == "" + assert conftest.LIVE_PROJECT_ID not in out + assert f"Resource ID: {dst_id}" in out + assert "Backup State: READY" in out + finally: + for bkp in (dst_name, src_name): + try: + admin.delete_backup(name=bkp) + except exceptions.NotFound: + pass + try: + admin.drop_database(database=db_path) + except exceptions.NotFound: + pass diff --git a/spanner/backups/tests/delete_backup_schedule_test.py b/spanner/backups/tests/delete_backup_schedule_test.py new file mode 100644 index 0000000000..fa90c36c84 --- /dev/null +++ b/spanner/backups/tests/delete_backup_schedule_test.py @@ -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 + + +@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 diff --git a/spanner/backups/tests/update_backup_schedule_test.py b/spanner/backups/tests/update_backup_schedule_test.py new file mode 100644 index 0000000000..03d55c5c44 --- /dev/null +++ b/spanner/backups/tests/update_backup_schedule_test.py @@ -0,0 +1,155 @@ +# 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 datetime +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 update_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: + client = mock_client_class.return_value + client.backup_schedule_path.return_value = ( + f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}" + f"/databases/{DATABASE_ID}/backupSchedules/{SCHEDULE_ID}" + ) + sched = mock.MagicMock(retention_duration=datetime.timedelta(hours=48)) + sched.spec.cron_spec.text = "45 15 * * *" + client.update_backup_schedule.return_value = sched + + +@mock.patch(ADMIN_CLIENT) +def test_update_backup_schedule_success( + mock_client_class: mock.MagicMock, capsys: pytest.CaptureFixture[str] +) -> None: + _setup_admin(mock_client_class) + + update_backup_schedule.update_backup_schedule( + PROJECT_ID, INSTANCE_ID, DATABASE_ID, SCHEDULE_ID + ) + + out, err = capsys.readouterr() + assert f"Resource ID: {SCHEDULE_ID}" in out + assert "Cron Expression: 45 15 * * *" in out + assert "Retention Hours: 48" 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.InvalidArgument("bad mask"), + "error: failed to update backup schedule", + ), + ], +) +@mock.patch(ADMIN_CLIENT) +def test_update_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.update_backup_schedule.side_effect = error + + update_backup_schedule.update_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 + + +@mock.patch(ADMIN_CLIENT) +def test_update_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", + [ + "update_backup_schedule.py", + "--project-id", + PROJECT_ID, + "--instance-id", + INSTANCE_ID, + "--database-id", + DATABASE_ID, + "--schedule-id", + SCHEDULE_ID, + ], + ) + + runpy.run_module("spanner_backups.update_backup_schedule", run_name="__main__") + + assert "Retention Hours: 48" in capsys.readouterr().out + + +@conftest.live_only +def test_update_backup_schedule_live(capsys: pytest.CaptureFixture[str]) -> None: + admin = spanner_admin_database_v1.DatabaseAdminClient() + sid = f"example-usc-{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() + update_backup_schedule.update_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 "Retention Hours: 48" in out + finally: + try: + admin.delete_backup_schedule(name=spath) + except exceptions.NotFound: + pass