Debian Codegraph @

tests/commands/test_dbrestore_metadata.py

raw
1 import importlib
2 import json
3 from unittest.mock import Mock, patch
4
5 import pytest
6 from django.conf import settings
7 from django.core.management.base import CommandError
8 from django.test import TestCase
9 from django.test.utils import override_settings
10
11 from dbbackup.management.commands import dbbackup
12 from dbbackup.management.commands.dbrestore import Command as DbrestoreCommand
13
14
15 class DbrestoreMetadataTest(TestCase):
16 def setUp(self):
17 self.command = DbrestoreCommand()
18 self.command.database_name = "default"
19 self.command.logger = Mock()
20 self.command.storage = Mock()
21 self.command.path = None
22
23 def test_metadata_match(self):
24 # Setup metadata
25 metadata = {"engine": settings.DATABASES["default"]["ENGINE"]}
26 self.command.storage.read_file.return_value = Mock(read=lambda: json.dumps(metadata))
27
28 # Should not raise
29 self.command._check_metadata("backup.dump")
30
31 def test_metadata_mismatch(self):
32 # Setup metadata with different engine
33 metadata = {"engine": "django.db.backends.postgresql"}
34 self.command.storage.read_file.return_value = Mock(read=lambda: json.dumps(metadata))
35
36 # Should raise
37 with pytest.raises(CommandError) as cm:
38 self.command._check_metadata("backup.dump")
39
40 assert "Restoring to a different database engine is not supported" in str(cm.value)
41
42 def test_no_metadata(self):
43 # Setup storage to raise exception when reading metadata
44 self.command.storage.read_file.side_effect = Exception("File not found")
45
46 # Should not raise (backwards compatibility)
47 self.command._check_metadata("backup.dump")
48
49 def test_local_file_metadata_match(self):
50 self.command.path = "local_backup.dump"
51 metadata = {"engine": settings.DATABASES["default"]["ENGINE"]}
52
53 with patch("os.path.exists", return_value=True), patch("builtins.open", new_callable=Mock) as mock_open:
54 # Configure the mock to behave like a file object
55 file_mock = Mock()
56 file_mock.read.return_value = json.dumps(metadata)
57 # Set up the context manager
58 mock_open.return_value.__enter__ = Mock(return_value=file_mock)
59 mock_open.return_value.__exit__ = Mock(return_value=None)
60
61 self.command._check_metadata("local_backup.dump")
62
63 def test_local_file_metadata_mismatch(self):
64 self.command.path = "local_backup.dump"
65 metadata = {"engine": "django.db.backends.postgresql"}
66
67 with patch("os.path.exists", return_value=True), patch("builtins.open", new_callable=Mock) as mock_open:
68 # Configure the mock to behave like a file object
69 file_mock = Mock()
70 file_mock.read.return_value = json.dumps(metadata)
71 # Set up the context manager
72 mock_open.return_value.__enter__ = Mock(return_value=file_mock)
73 mock_open.return_value.__exit__ = Mock(return_value=None)
74
75 with pytest.raises(CommandError):
76 self.command._check_metadata("local_backup.dump")
77
78 def test_django_connector_mismatch_allowed(self):
79 # Setup metadata with different engine but DjangoConnector
80 metadata = {
81 "engine": "django.db.backends.postgresql",
82 "connector": "dbbackup.db.django.DjangoConnector",
83 }
84 self.command.storage.read_file.return_value = Mock(read=lambda: json.dumps(metadata))
85
86 # Should not raise
87 self.command._check_metadata("backup.dump")
88
89 @override_settings(DBBACKUP_RESTORE_METADATA_VALIDATOR="tests.test_user_metadata.dummy_validator")
90 def test_metadata_match_custom(self):
91 importlib.reload(dbbackup.settings)
92 # Setup metadata
93 metadata = {"engine": settings.DATABASES["default"]["ENGINE"], "CSMT_VAL": "aabbcc-1122-3344_eu-west"}
94 self.command.storage.read_file.return_value = Mock(read=lambda: json.dumps(metadata))
95
96 # Should not raise
97 self.command._check_metadata("backup.dump")
98
99 @override_settings(DBBACKUP_RESTORE_METADATA_VALIDATOR="tests.test_user_metadata.dummy_validator")
100 def test_metadata_match_custom_fail(self):
101 importlib.reload(dbbackup.settings)
102 # Setup metadata
103 metadata = {"engine": settings.DATABASES["default"]["ENGINE"], "CSMT_VAL": "aabbcc-1122-3344_eu-ttt"}
104 self.command.storage.read_file.return_value = Mock(read=lambda: json.dumps(metadata))
105
106 # Should raise CommandError due to validation failure
107 with pytest.raises(CommandError):
108 self.command._check_metadata("backup.dump")
109
110 @override_settings(DBBACKUP_RESTORE_METADATA_VALIDATOR="tests.test_user_metadata.dummy_validator")
111 def test_metadata_match_custom_failwithcustomerror(self):
112 importlib.reload(dbbackup.settings)
113 # Setup metadata
114 metadata = {"engine": settings.DATABASES["default"]["ENGINE"], "CSMT_VAL": "xx-1122-3344_eu-west"}
115 self.command.storage.read_file.return_value = Mock(read=lambda: json.dumps(metadata))
116
117 # Should raise CommandError due to validation failure
118 with pytest.raises(ValueError, match="CSMT_VAL must start with 'aabbcc'"):
119 self.command._check_metadata("backup.dump")
120
121 @override_settings(DBBACKUP_RESTORE_METADATA_VALIDATOR="tests.test_user_metadata.dummy_validator")
122 def test_metadata_mismatch_custom_valid(self):
123 """Test that built-in validation runs before custom validation."""
124 importlib.reload(dbbackup.settings)
125 # Setup metadata with different engine (primary fail) but valid custom data
126 metadata = {"engine": "django.db.backends.postgresql", "CSMT_VAL": "aabbcc-1122-3344_eu-west"}
127 self.command.storage.read_file.return_value = Mock(read=lambda: json.dumps(metadata))
128
129 # Should raise CommandError due to engine mismatch (primary), not custom validation
130 with pytest.raises(CommandError) as cm:
131 self.command._check_metadata("backup.dump")
132
133 assert "Restoring to a different database engine is not supported" in str(cm.value)
134
135
136 class DbrestoreConnectorOverrideTest(TestCase):
137 def setUp(self):
138 self.command = DbrestoreCommand()
139 self.command.database_name = "default"
140 self.command.logger = Mock()
141 self.command.storage = Mock()
142 self.command.path = None
143 self.command.interactive = False
144 self.command.decrypt = False
145 self.command.uncompress = False
146 self.command.schemas = []
147 self.command.no_drop = False
148 self.command.pg_options = ""
149 self.command.servername = "testserver"
150 self.command.input_database_name = "default"
151 self.command.database = settings.DATABASES["default"]
152
153 # Mock _get_backup_file
154 mock_file = Mock()
155 mock_file.fileno.return_value = 1
156 mock_file.size = 1024
157 self.command._get_backup_file = Mock(return_value=("backup.dump", mock_file))
158
159 # Mock _ask_confirmation
160 self.command._ask_confirmation = Mock()
161
162 @patch("dbbackup.management.commands.dbrestore.get_connector")
163 @patch("dbbackup.management.commands.dbrestore.import_module")
164 def test_connector_override(self, mock_import_module, mock_get_connector):
165 # Setup metadata with a specific connector
166 metadata = {"engine": settings.DATABASES["default"]["ENGINE"], "connector": "my.custom.Connector"}
167 self.command.storage.read_file.return_value = Mock(read=lambda: json.dumps(metadata))
168
169 # Mock the custom connector class
170 mock_module = Mock()
171 mock_connector_class = Mock()
172 mock_connector_instance = Mock()
173 mock_connector_class.return_value = mock_connector_instance
174
175 mock_import_module.return_value = mock_module
176 mock_module.Connector = mock_connector_class
177
178 # Run restore
179 self.command._restore_backup()
180
181 # Verify import_module was called with "my.custom"
182 mock_import_module.assert_called_with("my.custom")
183
184 # Verify connector was instantiated
185 mock_connector_class.assert_called_with("default")
186
187 # Verify self.command.connector is the custom one
188 assert self.command.connector == mock_connector_instance
189
190 # Verify get_connector was NOT called
191 mock_get_connector.assert_not_called()
192
193 @patch("dbbackup.management.commands.dbrestore.get_connector")
194 def test_connector_fallback_on_import_error(self, mock_get_connector):
195 # Setup metadata with a specific connector that fails to import
196 metadata = {"engine": settings.DATABASES["default"]["ENGINE"], "connector": "my.broken.Connector"}
197 self.command.storage.read_file.return_value = Mock(read=lambda: json.dumps(metadata))
198
199 # Mock default connector
200 mock_default_connector = Mock()
201 mock_get_connector.return_value = mock_default_connector
202
203 # We don't mock import_module, so it will raise ImportError (or we can mock it to raise)
204 with patch("dbbackup.management.commands.dbrestore.import_module", side_effect=ImportError):
205 self.command._restore_backup()
206
207 # Verify get_connector WAS called
208 mock_get_connector.assert_called_with("default")
209
210 # Verify self.command.connector is the default one
211 assert self.command.connector == mock_default_connector
212
213 @patch("dbbackup.management.commands.dbrestore.get_connector")
214 @patch("builtins.input", return_value="y")
215 def test_connector_fallback_interactive_yes(self, mock_input, mock_get_connector):
216 self.command.interactive = True
217 # Setup metadata with a specific connector that fails to import
218 metadata = {"engine": settings.DATABASES["default"]["ENGINE"], "connector": "my.broken.Connector"}
219 self.command.storage.read_file.return_value = Mock(read=lambda: json.dumps(metadata))
220
221 # Mock default connector
222 mock_default_connector = Mock()
223 mock_get_connector.return_value = mock_default_connector
224
225 with patch("dbbackup.management.commands.dbrestore.import_module", side_effect=ImportError):
226 self.command._restore_backup()
227
228 # Verify input was called
229 mock_input.assert_called()
230 # Verify get_connector WAS called
231 mock_get_connector.assert_called_with("default")
232
233 @patch("dbbackup.management.commands.dbrestore.get_connector")
234 @patch("builtins.input", return_value="n")
235 def test_connector_fallback_interactive_no(self, mock_input, mock_get_connector):
236 self.command.interactive = True
237 # Setup metadata with a specific connector that fails to import
238 metadata = {"engine": settings.DATABASES["default"]["ENGINE"], "connector": "my.broken.Connector"}
239 self.command.storage.read_file.return_value = Mock(read=lambda: json.dumps(metadata))
240
241 with (
242 patch("dbbackup.management.commands.dbrestore.import_module", side_effect=ImportError),
243 pytest.raises(SystemExit),
244 ):
245 self.command._restore_backup()
246
247 # Verify input was called
248 mock_input.assert_called()
249 # Verify get_connector was NOT called
250 mock_get_connector.assert_not_called()