Debian Codegraph @

tests/test_connectors/test_sqlite.py

raw
1 from io import BytesIO
2 from unittest.mock import mock_open, patch
3
4 from django.db import connection
5 from django.test import TestCase
6
7 from dbbackup.db.sqlite import SqliteBackupConnector, SqliteConnector, SqliteCPConnector
8 from tests.testapp.models import CharModel, TextModel
9
10
11 class SqliteConnectorTest(TestCase):
12 def test_write_dump(self):
13 dump_file = BytesIO()
14 connector = SqliteConnector()
15 connector._write_dump(dump_file)
16 dump_file.seek(0)
17 for line in dump_file:
18 assert line.strip().endswith(b";")
19
20 def test_create_dump(self):
21 connector = SqliteConnector()
22 dump = connector.create_dump()
23 assert dump.read()
24
25 def test_create_dump_with_unicode(self):
26 CharModel.objects.create(field="\xe9")
27 connector = SqliteConnector()
28 dump = connector.create_dump()
29 assert dump.read()
30
31 def test_create_dump_with_newline(self):
32 TextModel.objects.create(field=f'INSERT ({"foo" * 5000}\nbar\n WHERE \nbaz IS\n "great" );\n')
33
34 connector = SqliteConnector()
35 dump = connector.create_dump()
36 assert dump.read()
37
38 def test_restore_dump(self):
39 TextModel.objects.create(field="T\nf\nw\nnl")
40 connector = SqliteConnector()
41 dump = connector.create_dump()
42 connector.restore_dump(dump)
43
44 def test_restore_dump_with_multiline_js_content(self):
45 """Test restore of objects with JavaScript/HTML content containing '); patterns"""
46 # Create content that contains "); patterns that could confuse the restore logic
47 js_content = """function showAlert() {
48 alert("Hello world!");
49 console.log("Debug info");
50 return true;
51 }
52
53 <script>
54 document.addEventListener("DOMContentLoaded", function() {
55 console.log("Ready!");
56 });
57 </script>"""
58
59 # Create, backup, delete, restore cycle
60 original_obj = TextModel.objects.create(field=js_content)
61 original_id = original_obj.id
62
63 connector = SqliteConnector()
64 dump = connector.create_dump()
65
66 # Delete the original
67 original_obj.delete()
68 assert not TextModel.objects.filter(id=original_id).exists()
69
70 # Restore and verify
71 dump.seek(0)
72 connector.restore_dump(dump)
73
74 restored_objects = TextModel.objects.filter(id=original_id)
75 assert restored_objects.exists(), "Object should be restored"
76
77 restored_obj = restored_objects.first()
78 assert restored_obj.field == js_content, "Content should match exactly"
79
80 def test_restore_dump_may_warn_for_already_exists(self):
81 """Test that restore may produce warnings for already existing objects"""
82 import warnings
83
84 # Create some test data
85 CharModel.objects.create(field="test1")
86 TextModel.objects.create(field="test content")
87
88 connector = SqliteConnector()
89 dump = connector.create_dump()
90
91 # Clear all data but keep schema (tables/indexes still exist)
92 CharModel.objects.all().delete()
93 TextModel.objects.all().delete()
94
95 # Restore may produce warnings for already existing schema objects
96 dump.seek(0)
97 with warnings.catch_warnings(record=True):
98 warnings.simplefilter("always") # Capture all warnings
99 connector.restore_dump(dump)
100
101 # Verify data was restored despite any warnings
102 assert CharModel.objects.filter(field="test1").exists()
103 assert TextModel.objects.filter(field="test content").exists()
104
105 def test_restore_dump_warns_only_for_serious_errors(self):
106 """Test that restore only warns for serious errors like 'no such table'"""
107 import warnings
108 from io import BytesIO
109
110 # Create a malformed dump with reference to non-existent table
111 bad_dump = BytesIO()
112 bad_dump.write(b"INSERT INTO nonexistent_table VALUES(1, 'test');\n")
113 bad_dump.seek(0)
114
115 connector = SqliteConnector()
116
117 with warnings.catch_warnings(record=True) as warning_list:
118 warnings.simplefilter("always")
119 connector.restore_dump(bad_dump)
120
121 # Should warn about the serious error
122 dbbackup_warnings = [w for w in warning_list if "dbbackup" in str(w.filename)]
123 assert dbbackup_warnings, "Should warn about 'no such table' error"
124
125 warning_messages = [str(w.message) for w in dbbackup_warnings]
126 assert any("no such table" in msg.lower() for msg in warning_messages), (
127 f"Should warn about 'no such table', got: {warning_messages}"
128 )
129
130 def test_create_dump_with_virtual_tables(self):
131 with connection.cursor() as c:
132 c.execute("CREATE VIRTUAL TABLE lookup USING fts5(field)")
133
134 connector = SqliteConnector()
135 dump = connector.create_dump()
136 assert dump.read()
137
138 def test_restore_dump_unique_conflict_updates_row(self):
139 """
140 Test that restoring a dump updates an existing row when a UNIQUE constraint conflict occurs,
141 verifying that INSERT OR REPLACE is used to restore the original data.
142 """
143 # Create initial row
144 obj = CharModel.objects.create(field="original")
145 obj_id = obj.id
146 # Backup
147 connector = SqliteConnector()
148 dump = connector.create_dump()
149 # Modify the existing row so that restoring will cause UNIQUE constraint failure on primary key
150 CharModel.objects.filter(id=obj_id).update(field="changed")
151 # Restore should update row back to original content via INSERT OR REPLACE retry
152 dump.seek(0)
153 connector.restore_dump(dump)
154 assert CharModel.objects.get(id=obj_id).field == "original"
155
156 def test_schema_objects_use_if_not_exists(self):
157 """Test that indexes, triggers, and views use IF NOT EXISTS syntax"""
158 from io import BytesIO
159
160 # Create a test table, index, trigger, and view
161 with connection.cursor() as c:
162 c.execute("CREATE TABLE test_schema (id INTEGER PRIMARY KEY, value TEXT)")
163 c.execute("CREATE INDEX test_idx ON test_schema(value)")
164 c.execute(
165 "CREATE TRIGGER test_trigger AFTER INSERT ON test_schema BEGIN UPDATE test_schema SET value = NEW.value || '_triggered' WHERE id = NEW.id; END"
166 )
167 c.execute("CREATE VIEW test_view AS SELECT * FROM test_schema WHERE value IS NOT NULL")
168
169 connector = SqliteConnector()
170 dump_file = BytesIO()
171 connector._write_dump(dump_file)
172
173 # Check that the dump contains IF NOT EXISTS for all schema objects
174 dump_content = dump_file.getvalue().decode("utf-8")
175
176 assert "CREATE INDEX IF NOT EXISTS" in dump_content, "Indexes should use IF NOT EXISTS"
177 assert "CREATE TRIGGER IF NOT EXISTS" in dump_content, "Triggers should use IF NOT EXISTS"
178 assert "CREATE VIEW IF NOT EXISTS" in dump_content, "Views should use IF NOT EXISTS"
179
180 def test_restore_warns_about_already_exists_errors(self):
181 """Test that restore warns about 'already exists' errors"""
182 import warnings
183 from io import BytesIO
184
185 # Create dump content that would trigger "already exists" errors - WITHOUT IF NOT EXISTS
186 dump_content = """
187 CREATE TABLE test_exists (id INTEGER PRIMARY KEY);
188 CREATE INDEX test_exists_idx ON test_exists(id);
189 CREATE TRIGGER test_exists_trigger AFTER INSERT ON test_exists BEGIN UPDATE test_exists SET id = NEW.id; END;
190 CREATE VIEW test_exists_view AS SELECT * FROM test_exists;
191 """.strip()
192
193 dump_file = BytesIO(dump_content.encode("utf-8"))
194 connector = SqliteConnector()
195
196 # First create the schema objects to ensure "already exists" situations
197 with connection.cursor() as c:
198 c.execute("CREATE TABLE test_exists (id INTEGER PRIMARY KEY)")
199 c.execute("CREATE INDEX test_exists_idx ON test_exists(id)")
200 c.execute(
201 "CREATE TRIGGER test_exists_trigger AFTER INSERT ON test_exists BEGIN UPDATE test_exists SET id = NEW.id; END"
202 )
203 c.execute("CREATE VIEW test_exists_view AS SELECT * FROM test_exists")
204
205 with warnings.catch_warnings(record=True) as warning_list:
206 warnings.simplefilter("always")
207 connector.restore_dump(dump_file)
208
209 # Filter warnings from this package
210 dbbackup_warnings = [w for w in warning_list if "dbbackup" in str(w.filename)]
211
212 # Should warn about "already exists" errors now that filtering is removed
213 assert dbbackup_warnings, "Should have warnings for 'already exists' errors"
214
215 # Verify we get warnings about "already exists"
216 already_exists_warnings = [w for w in dbbackup_warnings if "already exists" in str(w.message).lower()]
217 assert already_exists_warnings, "Should warn about 'already exists' errors"
218
219
220 @patch("dbbackup.db.sqlite.open", mock_open(read_data=b"foo"), create=True)
221 class SqliteCPConnectorTest(TestCase):
222 def test_create_dump(self):
223 connector = SqliteCPConnector()
224 dump = connector.create_dump()
225 dump_content = dump.read()
226 assert dump_content
227 assert dump_content == b"foo"
228
229 def test_restore_dump(self):
230 connector = SqliteCPConnector()
231 dump = connector.create_dump()
232 connector.restore_dump(dump)
233
234
235 class SqliteBackupConnectorTest(TestCase):
236 def test_create_dump(self):
237 connector = SqliteBackupConnector()
238 dump = connector.create_dump()
239 dump_content = dump.read()
240 assert dump_content
241 assert dump_content.startswith(b"SQLite format 3")
242
243 def test_restore_dump(self):
244 connector = SqliteBackupConnector()
245 dump = connector.create_dump()
246 connector.restore_dump(dump)
247
248
249 class SqliteConnectionHandlingTest(TestCase):
250 """Test connection handling edge cases"""
251
252 def test_sqlite_connector_restore_dump_with_unusable_connection(self):
253 """Test restore_dump when connection is not usable"""
254 from io import BytesIO
255 from unittest.mock import Mock
256
257 from dbbackup.db.sqlite import SqliteConnector
258
259 connector = SqliteConnector()
260
261 # Mock the connection to be unusable
262 mock_connection = Mock()
263 mock_connection.is_usable.return_value = False
264 mock_cursor = Mock()
265 mock_connection.cursor.return_value = mock_cursor
266 connector.connection = mock_connection
267
268 # Create a simple dump
269 dump = BytesIO(b"SELECT 1;\n")
270
271 # Call restore_dump which should reconnect
272 connector.restore_dump(dump)
273
274 # Verify connection.connect() was called
275 mock_connection.connect.assert_called_once()
276
277 def test_sqlite_backup_connector_create_dump_with_unusable_connection(self):
278 """Test SqliteBackupConnector create_dump when connection is not usable"""
279 from unittest.mock import Mock
280
281 from dbbackup.db.sqlite import SqliteBackupConnector
282
283 connector = SqliteBackupConnector()
284
285 # Mock the connection to be unusable
286 mock_connection = Mock()
287 mock_connection.is_usable.return_value = False
288 connector.connection = mock_connection
289
290 # Call create_dump which should reconnect
291 # This will call the _write_dump method which is a pass
292 connector.create_dump()
293
294 # Verify connection.connect() was called
295 mock_connection.connect.assert_called_once()