| 1 |
""" |
| 2 |
Tests for dbrestore command. |
| 3 |
""" |
| 4 |
|
| 5 |
import io |
| 6 |
import shutil |
| 7 |
from io import BytesIO |
| 8 |
from shutil import copyfileobj |
| 9 |
from tempfile import mktemp |
| 10 |
from unittest.mock import Mock, patch |
| 11 |
|
| 12 |
import pytest |
| 13 |
from django.conf import settings |
| 14 |
from django.core.files import File |
| 15 |
from django.core.management.base import CommandError |
| 16 |
from django.test import TestCase, override_settings |
| 17 |
|
| 18 |
from dbbackup import utils |
| 19 |
from dbbackup.db.base import get_connector |
| 20 |
from dbbackup.db.mongodb import MongoDumpConnector |
| 21 |
from dbbackup.db.postgresql import PgDumpConnector |
| 22 |
from dbbackup.management.commands.dbbackup import Command as DbbackupCommand |
| 23 |
from dbbackup.management.commands.dbrestore import Command as DbrestoreCommand |
| 24 |
from dbbackup.settings import HOSTNAME |
| 25 |
from dbbackup.storage import get_storage |
| 26 |
from tests.utils import ( |
| 27 |
DEV_NULL, |
| 28 |
HANDLED_FILES, |
| 29 |
TARED_FILE, |
| 30 |
TEST_DATABASE, |
| 31 |
TEST_MONGODB, |
| 32 |
LocationPrefixedFakeStorage, |
| 33 |
add_private_gpg, |
| 34 |
clean_gpg_keys, |
| 35 |
get_dump, |
| 36 |
get_dump_name, |
| 37 |
) |
| 38 |
|
| 39 |
GPG_AVAILABLE = shutil.which("gpg") is not None |
| 40 |
|
| 41 |
|
| 42 |
@patch("dbbackup.management.commands._base.input", return_value="y") |
| 43 |
class DbrestoreCommandWithLocationTest(TestCase): |
| 44 |
def setUp(self): |
| 45 |
self.dbbackup_command = DbbackupCommand() |
| 46 |
self.dbbackup_command.stdout = DEV_NULL |
| 47 |
self.dbrestore_command = DbrestoreCommand() |
| 48 |
self.dbrestore_command.stdout = DEV_NULL |
| 49 |
self.dbrestore_command.interactive = False |
| 50 |
HANDLED_FILES.clean() |
| 51 |
|
| 52 |
def tearDown(self): |
| 53 |
clean_gpg_keys() |
| 54 |
|
| 55 |
@override_settings(DBBACKUP_STORAGE="tests.utils.LocationPrefixedFakeStorage") |
| 56 |
def test_restore_with_storage_location(self, *args): |
| 57 |
""" |
| 58 |
GIVEN a storage that lists files with its location prefix |
| 59 |
WHEN running dbrestore without --input-filename |
| 60 |
THEN dbrestore should still resolve the latest backup correctly |
| 61 |
""" |
| 62 |
self.dbbackup_command.handle(verbosity=1) |
| 63 |
|
| 64 |
stored_names = [name for name, _file in HANDLED_FILES["written_files"]] |
| 65 |
assert stored_names |
| 66 |
assert all(not name.startswith(f"{LocationPrefixedFakeStorage.location}/") for name in stored_names) |
| 67 |
|
| 68 |
self.dbrestore_command.handle(verbosity=1) |
| 69 |
|
| 70 |
|
| 71 |
@patch("dbbackup.management.commands._base.input", return_value="y") |
| 72 |
class DbrestoreCommandRestoreBackupTest(TestCase): |
| 73 |
def setUp(self): |
| 74 |
self.command = DbrestoreCommand() |
| 75 |
self.command.stdout = DEV_NULL |
| 76 |
self.command.uncompress = False |
| 77 |
self.command.decrypt = False |
| 78 |
self.command.backup_extension = "bak" |
| 79 |
self.command.filename = "foofile" |
| 80 |
self.command.database = TEST_DATABASE |
| 81 |
self.command.passphrase = None |
| 82 |
self.command.interactive = True |
| 83 |
self.command.storage = get_storage() |
| 84 |
self.command.servername = HOSTNAME |
| 85 |
self.command.input_database_name = None |
| 86 |
self.command.database_name = "default" |
| 87 |
self.command.connector = get_connector("default") |
| 88 |
self.command.schemas = [] |
| 89 |
HANDLED_FILES.clean() |
| 90 |
|
| 91 |
def tearDown(self): |
| 92 |
clean_gpg_keys() |
| 93 |
|
| 94 |
def test_no_filename(self, *args): |
| 95 |
# Prepare backup |
| 96 |
HANDLED_FILES["written_files"].append((utils.filename_generate("default"), File(get_dump()))) |
| 97 |
# Check |
| 98 |
self.command.path = None |
| 99 |
self.command.filename = None |
| 100 |
self.command._restore_backup() |
| 101 |
|
| 102 |
def test_no_backup_found(self, *args): |
| 103 |
self.command.path = None |
| 104 |
self.command.filename = None |
| 105 |
with pytest.raises(CommandError): |
| 106 |
self.command._restore_backup() |
| 107 |
|
| 108 |
def test_uncompress(self, *args): |
| 109 |
self.command.path = None |
| 110 |
compressed_file, self.command.filename = utils.compress_file(get_dump(), get_dump_name()) |
| 111 |
HANDLED_FILES["written_files"].append((self.command.filename, File(compressed_file))) |
| 112 |
self.command.uncompress = True |
| 113 |
self.command._restore_backup() |
| 114 |
|
| 115 |
@patch("dbbackup.utils.getpass", return_value=None) |
| 116 |
def test_decrypt(self, *args): |
| 117 |
if not GPG_AVAILABLE: |
| 118 |
self.skipTest("gpg executable not available") |
| 119 |
add_private_gpg() |
| 120 |
self.command.path = None |
| 121 |
self.command.decrypt = True |
| 122 |
encrypted_file, self.command.filename = utils.encrypt_file(get_dump(), get_dump_name()) |
| 123 |
HANDLED_FILES["written_files"].append((self.command.filename, File(encrypted_file))) |
| 124 |
self.command._restore_backup() |
| 125 |
|
| 126 |
def test_path(self, *args): |
| 127 |
temp_dump = get_dump() |
| 128 |
dump_path = mktemp() |
| 129 |
with open(dump_path, "wb") as dump: |
| 130 |
copyfileobj(temp_dump, dump) |
| 131 |
self.command.path = dump.name |
| 132 |
self.command._restore_backup() |
| 133 |
self.command.decrypt = False |
| 134 |
self.command.filepath = get_dump_name() |
| 135 |
HANDLED_FILES["written_files"].append((self.command.filepath, get_dump())) |
| 136 |
self.command._restore_backup() |
| 137 |
|
| 138 |
@patch("dbbackup.management.commands.dbrestore.get_connector") |
| 139 |
@patch("dbbackup.db.base.BaseDBConnector.restore_dump") |
| 140 |
def test_schema(self, mock_restore_dump, mock_get_connector, *args): |
| 141 |
"""Schema is only used for postgresql.""" |
| 142 |
mock_get_connector.return_value = PgDumpConnector() |
| 143 |
mock_restore_dump.return_value = True |
| 144 |
|
| 145 |
mock_file = File(get_dump()) |
| 146 |
HANDLED_FILES["written_files"].append((self.command.filename, mock_file)) |
| 147 |
|
| 148 |
with self.assertLogs("dbbackup.command", "INFO") as cm: |
| 149 |
# Without |
| 150 |
self.command.path = None |
| 151 |
self.command._restore_backup() |
| 152 |
assert self.command.connector.schemas == [] |
| 153 |
|
| 154 |
# With |
| 155 |
self.command.path = None |
| 156 |
self.command.schemas = ["public"] |
| 157 |
self.command._restore_backup() |
| 158 |
assert self.command.connector.schemas == ["public"] |
| 159 |
assert "INFO:dbbackup.command:Restoring schemas: ['public']" in cm.output |
| 160 |
|
| 161 |
# With multiple |
| 162 |
self.command.path = None |
| 163 |
self.command.schemas = ["public", "other"] |
| 164 |
self.command._restore_backup() |
| 165 |
assert self.command.connector.schemas == ["public", "other"] |
| 166 |
assert "INFO:dbbackup.command:Restoring schemas: ['public', 'other']" in cm.output |
| 167 |
|
| 168 |
mock_get_connector.assert_called_with("default") |
| 169 |
mock_restore_dump.assert_called_with(mock_file) |
| 170 |
|
| 171 |
|
| 172 |
class MockFTPFile(BytesIO): |
| 173 |
"""Mock file object similar to what FTP storage returns without fileno() support.""" |
| 174 |
|
| 175 |
def __init__(self, content: bytes): |
| 176 |
super().__init__(content) |
| 177 |
self.name = "test-backup.psql.bin" |
| 178 |
# Keep original payload so repeated open() calls return a fresh BytesIO |
| 179 |
# instance (mimics Django Storage behavior) and avoid dead-code warning. |
| 180 |
self._file_content = content |
| 181 |
|
| 182 |
def fileno(self): |
| 183 |
"""Simulate FTP file object that doesn't support fileno().""" |
| 184 |
msg = "fileno" |
| 185 |
raise io.UnsupportedOperation(msg) |
| 186 |
|
| 187 |
def open(self, mode: str = "rb"): |
| 188 |
"""Return a new readable stream each time open() is called.""" |
| 189 |
return BytesIO(self._file_content) |
| 190 |
|
| 191 |
|
| 192 |
@patch("dbbackup.management.commands._base.input", return_value="y") |
| 193 |
class DbrestoreCommandFTPFileTest(TestCase): |
| 194 |
"""Test restore functionality with FTP-like file objects that don't support fileno().""" |
| 195 |
|
| 196 |
def setUp(self): |
| 197 |
self.command = DbrestoreCommand() |
| 198 |
self.command.stdout = DEV_NULL |
| 199 |
self.command.uncompress = False |
| 200 |
self.command.decrypt = False |
| 201 |
self.command.backup_extension = "bak" |
| 202 |
self.command.filename = "foofile" |
| 203 |
self.command.database = TEST_DATABASE |
| 204 |
self.command.passphrase = None |
| 205 |
self.command.interactive = True |
| 206 |
self.command.storage = get_storage() |
| 207 |
self.command.servername = HOSTNAME |
| 208 |
self.command.input_database_name = None |
| 209 |
self.command.database_name = "default" |
| 210 |
self.command.schemas = [] |
| 211 |
HANDLED_FILES.clean() |
| 212 |
|
| 213 |
@patch("dbbackup.management.commands.dbrestore.get_connector") |
| 214 |
def test_ftp_file_restore_with_postgresql(self, mock_get_connector, *args): |
| 215 |
"""Test that restore works with FTP-like files that don't support fileno() using PostgreSQL.""" |
| 216 |
# Create mock PgDumpBinaryConnector that would trigger the fileno() issue |
| 217 |
mock_connector = Mock(spec=PgDumpConnector) |
| 218 |
mock_connector.schemas = [] |
| 219 |
mock_get_connector.return_value = mock_connector |
| 220 |
|
| 221 |
# Create mock FTP file with dump content |
| 222 |
dump_content = get_dump().read() |
| 223 |
ftp_file = MockFTPFile(dump_content) |
| 224 |
|
| 225 |
# Mock the storage to return our FTP-like file |
| 226 |
with patch.object(self.command.storage, "read_file", return_value=ftp_file): |
| 227 |
# Ensure the backup filename exists in storage |
| 228 |
HANDLED_FILES["written_files"].append((self.command.filename, File(BytesIO(dump_content)))) |
| 229 |
|
| 230 |
# Set up command with PostgreSQL connector |
| 231 |
self.command.connector = mock_connector |
| 232 |
|
| 233 |
# This should not raise io.UnsupportedOperation: fileno when using external tools |
| 234 |
self.command.path = None |
| 235 |
self.command._restore_backup() |
| 236 |
|
| 237 |
# Verify the restore_dump was called with a file object |
| 238 |
mock_connector.restore_dump.assert_called_once() |
| 239 |
|
| 240 |
# Get the file object that was passed to restore_dump |
| 241 |
called_file = mock_connector.restore_dump.call_args[0][0] |
| 242 |
|
| 243 |
# The file should be converted to a SpooledTemporaryFile with content |
| 244 |
assert called_file is not None |
| 245 |
# Verify content is preserved |
| 246 |
called_file.seek(0) |
| 247 |
assert called_file.read() == dump_content |
| 248 |
|
| 249 |
|
| 250 |
class DbrestoreCommandGetDatabaseTest(TestCase): |
| 251 |
def setUp(self): |
| 252 |
self.command = DbrestoreCommand() |
| 253 |
|
| 254 |
def test_give_db_name(self): |
| 255 |
name, db = self.command._get_database("default") |
| 256 |
assert name == "default" |
| 257 |
assert db == settings.DATABASES["default"] |
| 258 |
|
| 259 |
def test_no_given_db(self): |
| 260 |
name, db = self.command._get_database(None) |
| 261 |
assert name == "default" |
| 262 |
assert db == settings.DATABASES["default"] |
| 263 |
|
| 264 |
@patch("django.conf.settings.DATABASES", {"db1": {}, "db2": {}}) |
| 265 |
def test_no_given_db_multidb(self): |
| 266 |
with pytest.raises(CommandError): |
| 267 |
self.command._get_database({}) |
| 268 |
|
| 269 |
|
| 270 |
@patch("dbbackup.management.commands._base.input", return_value="y") |
| 271 |
@patch( |
| 272 |
"dbbackup.management.commands.dbrestore.get_connector", |
| 273 |
return_value=MongoDumpConnector(), |
| 274 |
) |
| 275 |
@patch("dbbackup.db.mongodb.MongoDumpConnector.restore_dump") |
| 276 |
class DbMongoRestoreCommandRestoreBackupTest(TestCase): |
| 277 |
def setUp(self): |
| 278 |
if not GPG_AVAILABLE: |
| 279 |
self.skipTest("gpg executable not available") |
| 280 |
self.command = DbrestoreCommand() |
| 281 |
self.command.stdout = DEV_NULL |
| 282 |
self.command.uncompress = False |
| 283 |
self.command.decrypt = False |
| 284 |
self.command.backup_extension = "bak" |
| 285 |
self.command.path = None |
| 286 |
self.command.filename = "foofile" |
| 287 |
self.command.database = TEST_MONGODB |
| 288 |
self.command.passphrase = None |
| 289 |
self.command.interactive = True |
| 290 |
self.command.storage = get_storage() |
| 291 |
self.command.connector = MongoDumpConnector() |
| 292 |
self.command.database_name = "mongo" |
| 293 |
self.command.input_database_name = None |
| 294 |
self.command.servername = HOSTNAME |
| 295 |
self.command.schemas = [] |
| 296 |
HANDLED_FILES.clean() |
| 297 |
add_private_gpg() |
| 298 |
|
| 299 |
def test_mongo_settings_backup_command(self, mock_runcommands, *args): |
| 300 |
self.command.storage.file_read = TARED_FILE |
| 301 |
self.command.filename = TARED_FILE |
| 302 |
with open(TARED_FILE, "rb") as f: |
| 303 |
HANDLED_FILES["written_files"].append((TARED_FILE, f)) |
| 304 |
self.command._restore_backup() |
| 305 |
assert mock_runcommands.called |