| 1 |
""" |
| 2 |
Tests for dbbackup command. |
| 3 |
""" |
| 4 |
|
| 5 |
import os |
| 6 |
import shutil |
| 7 |
from unittest.mock import patch |
| 8 |
|
| 9 |
GPG_AVAILABLE = shutil.which("gpg") is not None |
| 10 |
|
| 11 |
import pytest |
| 12 |
from django.test import TestCase |
| 13 |
|
| 14 |
from dbbackup.db.base import get_connector |
| 15 |
from dbbackup.management.commands.dbbackup import Command as DbbackupCommand |
| 16 |
from dbbackup.storage import get_storage |
| 17 |
from tests.utils import ( |
| 18 |
DEV_NULL, |
| 19 |
HANDLED_FILES, |
| 20 |
TEST_DATABASE, |
| 21 |
add_public_gpg, |
| 22 |
clean_gpg_keys, |
| 23 |
) |
| 24 |
|
| 25 |
|
| 26 |
@patch("dbbackup.settings.GPG_RECIPIENT", "test@test") |
| 27 |
@patch("sys.stdout", DEV_NULL) |
| 28 |
class DbbackupCommandSaveNewBackupTest(TestCase): |
| 29 |
def setUp(self): |
| 30 |
HANDLED_FILES.clean() |
| 31 |
self.command = DbbackupCommand() |
| 32 |
self.command.servername = "foo-server" |
| 33 |
self.command.encrypt = False |
| 34 |
self.command.compress = False |
| 35 |
self.command.database = TEST_DATABASE["NAME"] |
| 36 |
self.command.storage = get_storage() |
| 37 |
self.command.connector = get_connector() |
| 38 |
self.command.stdout = DEV_NULL |
| 39 |
self.command.filename = None |
| 40 |
self.command.path = None |
| 41 |
self.command.schemas = [] |
| 42 |
|
| 43 |
def tearDown(self): |
| 44 |
clean_gpg_keys() |
| 45 |
|
| 46 |
def test_func(self): |
| 47 |
self.command._save_new_backup(TEST_DATABASE) |
| 48 |
|
| 49 |
def test_compress(self): |
| 50 |
self.command.compress = True |
| 51 |
self.command._save_new_backup(TEST_DATABASE) |
| 52 |
assert len(HANDLED_FILES["written_files"]) == 2 |
| 53 |
assert HANDLED_FILES["written_files"][0][0].endswith(".gz") |
| 54 |
assert HANDLED_FILES["written_files"][1][0].endswith(".gz.metadata") |
| 55 |
|
| 56 |
def test_encrypt(self): |
| 57 |
if not GPG_AVAILABLE: |
| 58 |
self.skipTest("gpg executable not available") |
| 59 |
add_public_gpg() |
| 60 |
self.command.encrypt = True |
| 61 |
self.command._save_new_backup(TEST_DATABASE) |
| 62 |
assert len(HANDLED_FILES["written_files"]) == 2 |
| 63 |
assert HANDLED_FILES["written_files"][0][0].endswith(".gpg") |
| 64 |
assert HANDLED_FILES["written_files"][1][0].endswith(".gpg.metadata") |
| 65 |
|
| 66 |
def test_path(self): |
| 67 |
local_tmp = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "tmp") |
| 68 |
os.makedirs(local_tmp, exist_ok=True) |
| 69 |
self.command.path = os.path.join(local_tmp, "foo.bak") |
| 70 |
self.command._save_new_backup(TEST_DATABASE) |
| 71 |
assert os.path.exists(self.command.path) |
| 72 |
assert os.path.exists(f"{self.command.path}.metadata") |
| 73 |
# tearDown |
| 74 |
os.remove(self.command.path) |
| 75 |
os.remove(f"{self.command.path}.metadata") |
| 76 |
|
| 77 |
def test_schema(self): |
| 78 |
self.command.schemas = ["public"] |
| 79 |
result = self.command._save_new_backup(TEST_DATABASE) |
| 80 |
|
| 81 |
assert result is None |
| 82 |
|
| 83 |
def test_metadata_is_bytes(self): |
| 84 |
"""Test that metadata content is passed as bytes to storage.""" |
| 85 |
self.command._save_new_backup(TEST_DATABASE) |
| 86 |
|
| 87 |
# Find the metadata file in HANDLED_FILES |
| 88 |
# HANDLED_FILES["written_files"] contains tuples (name, file_object) |
| 89 |
metadata_file_entry = next((f for f in HANDLED_FILES["written_files"] if f[0].endswith(".metadata")), None) |
| 90 |
assert metadata_file_entry is not None |
| 91 |
|
| 92 |
metadata_file = metadata_file_entry[1] |
| 93 |
metadata_file.open() |
| 94 |
content = metadata_file.read() |
| 95 |
|
| 96 |
# Check if content is bytes |
| 97 |
assert isinstance(content, bytes), f"Metadata content should be bytes, but got {type(content)}" |
| 98 |
|
| 99 |
@patch("dbbackup.management.commands._base.BaseDbBackupCommand.write_to_storage") |
| 100 |
def test_path_s3_uri(self, mock_write_to_storage): |
| 101 |
"""Test that S3 URIs in output path are handled by write_to_storage instead of write_local_file.""" |
| 102 |
self.command.path = "s3://mybucket/backups/db.bak" |
| 103 |
self.command._save_new_backup(TEST_DATABASE) |
| 104 |
assert mock_write_to_storage.called |
| 105 |
# Verify the S3 path was passed correctly to write_to_storage |
| 106 |
# The first call should be the backup file |
| 107 |
args, _kwargs = mock_write_to_storage.call_args_list[0] |
| 108 |
assert args[1] == "s3://mybucket/backups/db.bak" |
| 109 |
|
| 110 |
@patch("dbbackup.management.commands._base.BaseDbBackupCommand.write_to_storage") |
| 111 |
def test_path_s3_uri_variants(self, mock_write_to_storage): |
| 112 |
"""Test various S3 URI formats.""" |
| 113 |
test_cases = [ |
| 114 |
"s3://bucket/file.bak", |
| 115 |
"s3://bucket/folder/file.bak", |
| 116 |
"s3://bucket-with-dashes/nested/folders/file.bak", |
| 117 |
"s3://bucket/path/without/trailing/slash", |
| 118 |
] |
| 119 |
|
| 120 |
for s3_uri in test_cases: |
| 121 |
with self.subTest(s3_uri=s3_uri): |
| 122 |
mock_write_to_storage.reset_mock() |
| 123 |
self.command.path = s3_uri |
| 124 |
self.command._save_new_backup(TEST_DATABASE) |
| 125 |
assert mock_write_to_storage.called |
| 126 |
# The first call should be the backup file |
| 127 |
args, _kwargs = mock_write_to_storage.call_args_list[0] |
| 128 |
assert args[1] == s3_uri |
| 129 |
|
| 130 |
def test_path_local_file_still_works(self): |
| 131 |
"""Test that regular local file paths still use write_local_file.""" |
| 132 |
local_tmp = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "tmp") |
| 133 |
os.makedirs(local_tmp, exist_ok=True) |
| 134 |
|
| 135 |
# Test with a real local path that should work |
| 136 |
local_path = os.path.join(local_tmp, "test_local.bak") |
| 137 |
self.command.path = local_path |
| 138 |
self.command._save_new_backup(TEST_DATABASE) |
| 139 |
|
| 140 |
# Verify the file was created (meaning write_local_file was used) |
| 141 |
assert os.path.exists(local_path) |
| 142 |
assert os.path.exists(f"{local_path}.metadata") |
| 143 |
|
| 144 |
# Cleanup |
| 145 |
os.remove(local_path) |
| 146 |
os.remove(f"{local_path}.metadata") |
| 147 |
|
| 148 |
# Test that paths containing 's3' but not starting with 's3://' are treated as local |
| 149 |
with patch("dbbackup.management.commands._base.BaseDbBackupCommand.write_local_file") as mock_write_local_file: |
| 150 |
mock_write_local_file.side_effect = FileNotFoundError("Mocked error") |
| 151 |
|
| 152 |
test_cases = [ |
| 153 |
"/path/with/s3/in/name/backup.bak", |
| 154 |
"s3_backup.bak", # starts with s3 but not s3:// |
| 155 |
"bucket-s3-backup.bak", |
| 156 |
] |
| 157 |
|
| 158 |
for local_path in test_cases: |
| 159 |
with self.subTest(local_path=local_path): |
| 160 |
mock_write_local_file.reset_mock() |
| 161 |
self.command.path = local_path |
| 162 |
# This should call write_local_file (and raise our mocked error) |
| 163 |
with pytest.raises(FileNotFoundError): |
| 164 |
self.command._save_new_backup(TEST_DATABASE) |
| 165 |
# Verify write_local_file was called |
| 166 |
assert mock_write_local_file.called |
| 167 |
args, _kwargs = mock_write_local_file.call_args |
| 168 |
assert args[1] == local_path |
| 169 |
|
| 170 |
@patch("dbbackup.settings.DATABASES", ["db-from-settings"]) |
| 171 |
def test_get_database_keys(self): |
| 172 |
with self.subTest("use --database from CLI"): |
| 173 |
self.command.database = "db-from-cli" |
| 174 |
assert self.command._get_database_keys() == ["db-from-cli"] |
| 175 |
|
| 176 |
with self.subTest("fallback to DBBACKUP_DATABASES"): |
| 177 |
self.command.database = "" |
| 178 |
assert self.command._get_database_keys() == ["db-from-settings"] |
| 179 |
|
| 180 |
with self.subTest("multiple databases"): |
| 181 |
self.command.database = "db1,db2" |
| 182 |
assert self.command._get_database_keys() == ["db1", "db2"] |
| 183 |
|
| 184 |
with self.subTest("multiple databases with whitespace"): |
| 185 |
self.command.database = " db1 , db2 " |
| 186 |
assert self.command._get_database_keys() == ["db1", "db2"] |
| 187 |
|
| 188 |
with self.subTest("filter out empty strings to prevent get_connector('') bug"): |
| 189 |
self.command.database = "db1,,db2" |
| 190 |
assert self.command._get_database_keys() == ["db1", "db2"] |
| 191 |
|
| 192 |
with self.subTest("just comma returns empty list"): |
| 193 |
self.command.database = "," |
| 194 |
assert self.command._get_database_keys() == [] |
| 195 |
|
| 196 |
with self.subTest("just spaces returns empty list"): |
| 197 |
self.command.database = " " |
| 198 |
assert self.command._get_database_keys() == [] |
| 199 |
|
| 200 |
|
| 201 |
@patch("dbbackup.settings.GPG_RECIPIENT", "test@test") |
| 202 |
@patch("sys.stdout", DEV_NULL) |
| 203 |
@patch("dbbackup.db.sqlite.SqliteConnector.create_dump") |
| 204 |
@patch("dbbackup.utils.handle_size", returned_value=4.2) |
| 205 |
class DbbackupCommandSaveNewMongoBackupTest(TestCase): |
| 206 |
def setUp(self): |
| 207 |
self.command = DbbackupCommand() |
| 208 |
self.command.servername = "foo-server" |
| 209 |
self.command.encrypt = False |
| 210 |
self.command.compress = False |
| 211 |
self.command.storage = get_storage() |
| 212 |
self.command.stdout = DEV_NULL |
| 213 |
self.command.filename = None |
| 214 |
self.command.path = None |
| 215 |
self.command.connector = get_connector("default") |
| 216 |
self.command.schemas = [] |
| 217 |
|
| 218 |
def tearDown(self): |
| 219 |
clean_gpg_keys() |
| 220 |
|
| 221 |
def test_func(self, mock_run_commands, mock_handle_size): |
| 222 |
self.command._save_new_backup(TEST_DATABASE) |
| 223 |
assert mock_run_commands.called |