Debian Codegraph @

tests/test_connectors/test_django.py

raw
1 """
2 Tests for Django native serializer connector.
3 """
4
5 from tempfile import SpooledTemporaryFile
6 from unittest.mock import patch
7
8 from django.test import TestCase
9
10 from dbbackup.db.django import DjangoConnector
11
12
13 class DjangoConnectorTest(TestCase):
14 """Tests for DjangoConnector."""
15
16 def setUp(self):
17 self.connector = DjangoConnector()
18
19 def test_init(self):
20 """Test connector initialization."""
21 assert isinstance(self.connector, DjangoConnector)
22 assert self.connector.extension == "json"
23
24 @patch("dbbackup.db.django.call_command")
25 def test_create_dump(self, mock_call_command):
26 """Test dump creation using Django's dumpdata."""
27
28 # Mock the dumpdata command to write JSON to stdout
29 def mock_dumpdata(*args, **kwargs):
30 if "stdout" in kwargs:
31 kwargs["stdout"].write('[{"model": "auth.user", "pk": 1, "fields": {"username": "test"}}]')
32
33 mock_call_command.side_effect = mock_dumpdata
34
35 # Create the dump
36 dump = self.connector.create_dump()
37
38 # Verify call_command was called with correct parameters
39 mock_call_command.assert_called_once()
40 call_args = mock_call_command.call_args
41 assert call_args[0] == ("dumpdata",)
42 assert call_args[1]["format"] == "json"
43 assert call_args[1]["verbosity"] == 0
44 assert call_args[1]["use_natural_foreign_keys"]
45 assert call_args[1]["use_natural_primary_keys"]
46
47 # Verify dump content
48 assert isinstance(dump, SpooledTemporaryFile)
49 dump.seek(0)
50 content = dump.read()
51 assert b'"model": "auth.user"' in content
52 assert b'"username": "test"' in content
53
54 @patch("dbbackup.db.django.call_command")
55 def test_create_dump_with_exclude_app_model_format(self, mock_call_command):
56 """Test dump creation with exclude parameter in app.model format."""
57 # Set exclude parameter with app.model format for available apps
58 self.connector.exclude = ["testapp.CharModel"]
59
60 # Mock the dumpdata command
61 def mock_dumpdata(*args, **kwargs):
62 if "stdout" in kwargs:
63 kwargs["stdout"].write("[]")
64
65 mock_call_command.side_effect = mock_dumpdata
66
67 # Create the dump
68 dump = self.connector.create_dump()
69
70 # Verify call_command was called with correct exclude parameter
71 mock_call_command.assert_called_once()
72 call_args = mock_call_command.call_args
73 # Should have exclude parameter since testapp.CharModel exists
74 assert "exclude" in call_args[1]
75 assert call_args[1]["exclude"] == ["testapp.CharModel"]
76 assert isinstance(dump, SpooledTemporaryFile)
77
78 @patch("dbbackup.db.django.call_command")
79 def test_create_dump_with_exclude_table_names(self, mock_call_command):
80 """Test dump creation with exclude parameter as table names."""
81 # Set exclude parameter with table names that won't be converted
82 # since auth app is not available in test environment
83 self.connector.exclude = ["auth_user", "django_session"]
84
85 # Mock the dumpdata command
86 def mock_dumpdata(*args, **kwargs):
87 if "stdout" in kwargs:
88 kwargs["stdout"].write("[]")
89
90 mock_call_command.side_effect = mock_dumpdata
91
92 # Create the dump
93 dump = self.connector.create_dump()
94
95 # Verify call_command was called
96 mock_call_command.assert_called_once()
97 call_args = mock_call_command.call_args
98 # Should NOT have exclude parameter since auth/sessions apps don't exist
99 # and table names can't be converted
100 assert "exclude" not in call_args[1]
101 assert isinstance(dump, SpooledTemporaryFile)
102
103 @patch("dbbackup.db.django.call_command")
104 def test_create_dump_with_exclude_mixed_format(self, mock_call_command):
105 """Test dump creation with exclude parameter in mixed formats."""
106 # Set exclude parameter with mixed formats - valid and invalid
107 self.connector.exclude = ["testapp.TextModel", "auth_user", "unknown_table"]
108
109 # Mock the dumpdata command
110 def mock_dumpdata(*args, **kwargs):
111 if "stdout" in kwargs:
112 kwargs["stdout"].write("[]")
113
114 mock_call_command.side_effect = mock_dumpdata
115
116 # Create the dump
117 dump = self.connector.create_dump()
118
119 # Verify call_command was called with properly handled exclude parameter
120 mock_call_command.assert_called_once()
121 call_args = mock_call_command.call_args
122 # Should have exclude parameter with only the valid testapp.TextModel
123 assert "exclude" in call_args[1]
124 assert call_args[1]["exclude"] == ["testapp.TextModel"]
125 assert isinstance(dump, SpooledTemporaryFile)
126
127 @patch("dbbackup.db.django.call_command")
128 def test_create_dump_with_exclude_invalid_only(self, mock_call_command):
129 """Test dump creation with exclude parameter containing only invalid entries."""
130 # Set exclude parameter with only invalid entries
131 self.connector.exclude = ["nonexistent.Model", "auth_user", "unknown_table"]
132
133 # Mock the dumpdata command
134 def mock_dumpdata(*args, **kwargs):
135 if "stdout" in kwargs:
136 kwargs["stdout"].write("[]")
137
138 mock_call_command.side_effect = mock_dumpdata
139
140 # Create the dump
141 dump = self.connector.create_dump()
142
143 # Verify call_command was called without exclude parameter
144 mock_call_command.assert_called_once()
145 call_args = mock_call_command.call_args
146 # Should NOT have exclude parameter since all entries are invalid
147 assert "exclude" not in call_args[1]
148 assert isinstance(dump, SpooledTemporaryFile)
149
150 @patch("dbbackup.db.django.call_command")
151 @patch("dbbackup.db.django.os.unlink")
152 def test_restore_dump(self, mock_unlink, mock_call_command):
153 """Test dump restoration using Django's loaddata."""
154 # Create a mock dump file in text mode (consistent with new create_dump behavior)
155 dump_content = '[{"model": "auth.user", "pk": 1, "fields": {"username": "test"}}]'
156 dump = SpooledTemporaryFile(mode="w+t", encoding="utf-8")
157 dump.write(dump_content)
158 dump.seek(0)
159
160 # Restore the dump
161 self.connector.restore_dump(dump)
162
163 # Verify call_command was called with loaddata
164 mock_call_command.assert_called_once()
165 call_args = mock_call_command.call_args
166 assert call_args[0][0] == "loaddata"
167 assert call_args[1]["verbosity"] == 0
168
169 # Verify temporary file was cleaned up
170 mock_unlink.assert_called_once()
171
172 @patch("dbbackup.db.django.call_command")
173 @patch("dbbackup.db.django.os.unlink")
174 def test_restore_dump_with_django_file(self, mock_unlink, mock_call_command):
175 """Test dump restoration with Django File object."""
176 from django.core.files.base import ContentFile
177
178 # Create a mock Django File
179 dump_content = '[{"model": "auth.user", "pk": 1, "fields": {"username": "test"}}]'
180 dump = ContentFile(dump_content.encode("utf-8"))
181
182 # Restore the dump
183 self.connector.restore_dump(dump)
184
185 # Verify call_command was called with loaddata
186 mock_call_command.assert_called_once()
187 call_args = mock_call_command.call_args
188 assert call_args[0][0] == "loaddata"
189 assert call_args[1]["verbosity"] == 0
190
191 # Verify temporary file was cleaned up
192 mock_unlink.assert_called_once()
193
194 @patch("dbbackup.db.django.call_command")
195 @patch("dbbackup.db.django.os.unlink")
196 def test_restore_dump_cleanup_failure(self, mock_unlink, mock_call_command):
197 """Test that cleanup failure doesn't raise an exception."""
198 # Make unlink raise an exception
199 mock_unlink.side_effect = OSError("File not found")
200
201 # Create a mock dump file in text mode (consistent with new create_dump behavior)
202 dump_content = "[]"
203 dump = SpooledTemporaryFile(mode="w+t", encoding="utf-8")
204 dump.write(dump_content)
205 dump.seek(0)
206
207 # This should not raise an exception despite unlink failure
208 self.connector.restore_dump(dump)
209
210 # Verify call_command was still called
211 mock_call_command.assert_called_once()
212
213 def test_generate_filename(self):
214 """Test filename generation."""
215 filename = self.connector.generate_filename()
216 assert filename.endswith(".json")
217
218 @patch("dbbackup.db.django.call_command")
219 def test_integration_create_and_restore(self, mock_call_command):
220 """Test integration between create_dump and restore_dump."""
221 # Mock dumpdata to return some JSON
222 dump_content = '[{"model": "auth.user", "pk": 1, "fields": {"username": "testuser"}}]'
223
224 def mock_dumpdata(*args, **kwargs):
225 if "stdout" in kwargs:
226 kwargs["stdout"].write(dump_content)
227
228 mock_call_command.side_effect = mock_dumpdata
229
230 # Create dump
231 dump = self.connector.create_dump()
232
233 # Verify dumpdata was called
234 assert mock_call_command.call_count == 1
235
236 # Reset mock for restore
237 mock_call_command.reset_mock()
238 mock_call_command.side_effect = None
239
240 # Restore dump
241 with patch("dbbackup.db.django.os.unlink"):
242 self.connector.restore_dump(dump)
243
244 # Verify loaddata was called
245 assert mock_call_command.call_count == 1
246
247 @patch("dbbackup.db.django.call_command")
248 def test_dump_is_binary(self, mock_call_command):
249 """Test that the created dump is a binary file and can be compressed."""
250
251 # Mock the dumpdata command to write JSON to stdout
252 def mock_dumpdata(*args, **kwargs):
253 if "stdout" in kwargs:
254 kwargs["stdout"].write('[{"model": "auth.user", "pk": 1, "fields": {"username": "test"}}]')
255
256 mock_call_command.side_effect = mock_dumpdata
257
258 # Create the dump
259 dump_file = self.connector.create_dump()
260 dump_file.seek(0)
261
262 # Try to compress it (this will fail if it's not a binary file)
263 import gzip
264
265 compressed_file = SpooledTemporaryFile()
266 with gzip.GzipFile(fileobj=compressed_file, mode="wb") as gz_file:
267 gz_file.write(dump_file.read())
268
269 # Check that we have compressed data
270 compressed_file.seek(0)
271 assert len(compressed_file.read()) > 0