Debian Codegraph @

tests/test_utils.py

raw
1 import os
2 import shlex
3 import shutil
4 import tempfile
5 import unittest
6 from datetime import datetime, timezone
7 from io import StringIO
8 from unittest.mock import patch
9
10 import django
11 import pytest
12 from django.core import mail
13 from django.test import TestCase
14
15 from dbbackup import settings, utils
16 from tests.utils import (
17 COMPRESSED_FILE,
18 ENCRYPTED_FILE,
19 add_private_gpg,
20 add_public_gpg,
21 callable_for_filename_template,
22 clean_gpg_keys,
23 )
24
25
26 class BytesToStrTest(TestCase):
27 def test_get_gb(self):
28 value = utils.bytes_to_str(byte_val=2**31)
29 assert value == "2.0 GiB"
30
31 def test_0_decimal(self):
32 value = utils.bytes_to_str(byte_val=1.01, decimals=0)
33 assert value == "1 B"
34
35 def test_2_decimal(self):
36 value = utils.bytes_to_str(byte_val=1.01, decimals=2)
37 assert value == "1.01 B"
38
39
40 class HandleSizeTest(TestCase):
41 def test_func(self):
42 filehandle = StringIO("Test string")
43 value = utils.handle_size(filehandle=filehandle)
44 assert value == "11.0 B"
45
46
47 class MailAdminsTest(TestCase):
48 def test_func(self):
49 subject = "foo subject"
50 msg = "bar message"
51
52 utils.mail_admins(subject, msg)
53 assert len(mail.outbox) == 1
54
55 sent_mail = mail.outbox[0]
56 expected_subject = f"{settings.EMAIL_SUBJECT_PREFIX}{subject}"
57 expected_to = settings.ADMINS[0][1]
58 expected_from = settings.SERVER_EMAIL
59
60 assert sent_mail.subject == expected_subject
61 assert sent_mail.body == msg
62 assert sent_mail.to[0] == expected_to
63 assert sent_mail.from_email == expected_from
64
65 @patch("dbbackup.settings.ADMINS", None)
66 def test_no_admin(self):
67 subject = "foo subject"
68 msg = "bar message"
69 assert utils.mail_admins(subject, msg) is None
70 assert len(mail.outbox) == 0
71
72
73 class EmailUncaughtExceptionTest(TestCase):
74 def test_success(self):
75 def func():
76 pass
77
78 utils.email_uncaught_exception(func)
79 assert len(mail.outbox) == 0
80
81 @patch("dbbackup.settings.SEND_EMAIL", False)
82 def test_raise_error_without_mail(self):
83 def func():
84 msg = "Foo"
85 raise Exception(msg) # noqa: TRY002
86
87 with pytest.raises(Exception): # noqa
88 utils.email_uncaught_exception(func)()
89 assert len(mail.outbox) == 0
90
91 @patch("dbbackup.settings.SEND_EMAIL", True)
92 @patch("dbbackup.settings.ADMINS", ["foo@bar"])
93 def test_raise_with_mail(self):
94 def func():
95 raise Exception("Foo") # noqa
96
97 # Clear the mail outbox
98 mail.outbox.clear()
99
100 with pytest.raises(Exception): # noqa
101 utils.email_uncaught_exception(func)()
102 assert len(mail.outbox) == 1
103 error_mail = mail.outbox[0]
104 # The recipients might be processed differently, so let's be more flexible
105 assert len(error_mail.to) > 0 # Just ensure someone gets the email
106 assert 'Exception("Foo")' in error_mail.subject
107 if django.VERSION >= (1, 7):
108 assert 'Exception("Foo")' in error_mail.body
109
110
111 GPG_AVAILABLE = shutil.which("gpg") is not None
112
113
114 @unittest.skipIf(not GPG_AVAILABLE, "gpg executable not available")
115 class EncryptFileTest(TestCase):
116 def setUp(self):
117 self.path = tempfile.mktemp()
118 with open(self.path, "a") as fd:
119 fd.write("foo")
120 add_public_gpg()
121
122 def tearDown(self):
123 os.remove(self.path)
124 clean_gpg_keys()
125
126 def test_func(self, *args):
127 with open(self.path, mode="rb") as fd:
128 encrypted_file, _filename = utils.encrypt_file(inputfile=fd, filename="foo.txt")
129 encrypted_file.seek(0)
130 assert encrypted_file.read()
131
132 def test_encrypt_file_invalid_mode(self):
133 """Test encrypt_file with non-binary mode file"""
134 import os
135 import tempfile
136
137 # Create a temporary file in text mode
138 with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
139 f.write("test content")
140 temp_path = f.name
141
142 try:
143 with (
144 open(temp_path) as text_file,
145 pytest.raises(ValueError, match="Input file must be opened in binary mode"),
146 ):
147 utils.encrypt_file(inputfile=text_file, filename="test.txt")
148 finally:
149 os.unlink(temp_path)
150
151
152 @unittest.skipIf(not GPG_AVAILABLE, "gpg executable not available")
153 class UnencryptFileTest(TestCase):
154 def setUp(self):
155 add_private_gpg()
156
157 def tearDown(self):
158 clean_gpg_keys()
159
160 @patch("dbbackup.utils.input", return_value=None)
161 @patch("dbbackup.utils.getpass", return_value=None)
162 def test_unencrypt(self, *args):
163 with open(ENCRYPTED_FILE, "r+b") as inputfile:
164 uncryptfile, _filename = utils.unencrypt_file(inputfile, "foofile.gpg")
165 uncryptfile.seek(0)
166 assert uncryptfile.read() == b"foo\n"
167
168
169 @unittest.skipIf(not GPG_AVAILABLE, "gpg executable not available")
170 class CompressFileTest(TestCase):
171 def setUp(self):
172 self.path = tempfile.mktemp()
173 with open(self.path, "a+b") as fd:
174 fd.write(b"foo")
175
176 def tearDown(self):
177 os.remove(self.path)
178
179 def test_func(self, *args):
180 with open(self.path, mode="rb") as fd:
181 _compressed_file, _filename = utils.encrypt_file(inputfile=fd, filename="foo.txt")
182
183
184 @unittest.skipIf(not GPG_AVAILABLE, "gpg executable not available")
185 class EncryptionDecryptionEdgeCasesTest(TestCase):
186 def test_encrypt_file_gpg_failure(self):
187 """Test encrypt_file when GPG encryption fails"""
188 import os
189 import tempfile
190 from unittest.mock import MagicMock, patch
191
192 # Create a temporary file
193 with tempfile.NamedTemporaryFile(mode="w+b", delete=False) as f:
194 f.write(b"test content")
195 temp_path = f.name
196
197 try:
198 with open(temp_path, "rb") as binary_file:
199 # Mock GPG to return a failed result
200 mock_result = MagicMock()
201 mock_result.__bool__ = lambda self: False # Indicates failure
202 mock_result.status = "FAILURE"
203
204 with patch("gnupg.GPG") as mock_gpg_class:
205 mock_gpg = mock_gpg_class.return_value
206 mock_gpg.encrypt_file.return_value = mock_result
207
208 from dbbackup.utils import EncryptionError
209
210 with pytest.raises(EncryptionError) as context:
211 utils.encrypt_file(inputfile=binary_file, filename="test.txt")
212
213 assert "Encryption failed" in str(context)
214 finally:
215 os.unlink(temp_path)
216
217
218 class UncompressFileTest(TestCase):
219 def test_func(self):
220 with open(COMPRESSED_FILE, "rb") as inputfile:
221 fd, _filename = utils.uncompress_file(inputfile, "foo.gz")
222 fd.seek(0)
223 assert fd.read() == b"foo\n"
224
225
226 class CreateSpooledTemporaryFileTest(TestCase):
227 def setUp(self):
228 self.path = tempfile.mktemp()
229 with open(self.path, "a") as fd:
230 fd.write("foo")
231
232 def tearDown(self):
233 os.remove(self.path)
234
235 def test_func(self, *args):
236 utils.create_spooled_temporary_file(filepath=self.path)
237
238
239 class TimestampTest(TestCase):
240 def test_naive_value(self):
241 with self.settings(USE_TZ=False):
242 timestamp = utils.timestamp(datetime(2015, 8, 15, 8, 15, 12, 0)) # noqa
243 assert timestamp == "2015-08-15-081512"
244
245 def test_aware_value(self):
246 with self.settings(USE_TZ=True) and self.settings(TIME_ZONE="Europe/Rome"):
247 timestamp = utils.timestamp(datetime(2015, 8, 15, 8, 15, 12, 0, tzinfo=timezone.utc))
248 assert timestamp == "2015-08-15-101512"
249
250
251 class DatefmtToRegex(TestCase):
252 def test_patterns(self):
253 now = datetime.now()
254 for datefmt, regex in utils.PATTERN_MATCHNG:
255 date_string = datetime.strftime(now, datefmt)
256 regex = utils.datefmt_to_regex(datefmt)
257 match = regex.match(date_string)
258 assert match
259 assert match.groups()[0] == date_string
260
261 def test_complex_pattern(self):
262 now = datetime.now()
263 datefmt = "Foo%a_%A-%w-%d-%b-%B_%m_%y_%Y-%H-%I-%M_%S_%f_%j-%U-%W-Bar"
264 date_string = datetime.strftime(now, datefmt)
265 regex = utils.datefmt_to_regex(datefmt)
266 assert regex.pattern.startswith("(Foo")
267 assert regex.pattern.endswith("Bar)")
268 match = regex.match(date_string)
269 assert match
270 assert match.groups()[0] == date_string
271
272
273 class FilenameToDatestringTest(TestCase):
274 def test_func(self):
275 now = datetime.now()
276 datefmt = settings.DATE_FORMAT
277 filename = f"{datetime.strftime(now, datefmt)}-foo.gz.gpg"
278 datestring = utils.filename_to_datestring(filename, datefmt)
279 assert datestring in filename
280
281 def test_generated_filename(self):
282 filename = utils.filename_generate("bak", "default")
283 datestring = utils.filename_to_datestring(filename)
284 assert datestring in filename
285
286
287 class FilenameToDateTest(TestCase):
288 def test_func(self):
289 now = datetime.now()
290 datefmt = settings.DATE_FORMAT
291 filename = f"{datetime.strftime(now, datefmt)}-foo.gz.gpg"
292 date = utils.filename_to_date(filename, datefmt)
293 assert date.timetuple()[:5] == now.timetuple()[:5]
294
295 def test_generated_filename(self):
296 filename = utils.filename_generate("bak", "default")
297 utils.filename_to_date(filename)
298
299
300 @patch("dbbackup.settings.HOSTNAME", "test")
301 class FilenameGenerateTest(TestCase):
302 @patch(
303 "dbbackup.settings.FILENAME_TEMPLATE",
304 "---{databasename}--{servername}-{datetime}.{extension}",
305 )
306 def test_func(self, *args):
307 extension = "foo"
308 generated_name = utils.filename_generate(extension)
309 assert "--" not in generated_name
310 assert not generated_name.startswith("-")
311
312 def test_db(self, *args):
313 extension = "foo"
314 generated_name = utils.filename_generate(extension)
315 assert generated_name.startswith(settings.HOSTNAME)
316 assert generated_name.endswith(extension)
317
318 def test_media(self, *args):
319 extension = "foo"
320 generated_name = utils.filename_generate(extension, content_type="media")
321 assert generated_name.startswith(settings.HOSTNAME)
322 assert generated_name.endswith(extension)
323
324 @patch("django.utils.timezone.settings.USE_TZ", True)
325 def test_tz_true(self):
326 filename = utils.filename_generate("bak", "default")
327 datestring = utils.filename_to_datestring(filename)
328 assert datestring in filename
329
330 @patch("dbbackup.settings.FILENAME_TEMPLATE", callable_for_filename_template)
331 def test_template_is_callable(self, *args):
332 extension = "foo"
333 generated_name = utils.filename_generate(extension)
334 assert generated_name.endswith("foo")
335
336
337 class QuoteCommandArg(TestCase):
338 def test_arg_with_space(self):
339 assert shlex.quote("foo bar") == "'foo bar'"
340
341 def test_arg_with_special_chars(self):
342 """Test escaping with various special characters that could break MySQL commands."""
343 # Test simple password with special characters
344 result = shlex.quote("pass!@#$%^&*()")
345 assert isinstance(result, str)
346 # Should be quoted if it contains special chars
347 assert "pass!@#$%^&*()" in result
348
349 # Test password with quotes
350 result = shlex.quote("pass'word\"test")
351 assert isinstance(result, str)
352 assert "pass" in result
353 assert "word" in result
354 assert "test" in result
355
356 # Test password with shell metacharacters
357 result = shlex.quote("pass;word&command")
358 assert isinstance(result, str)
359 assert "pass" in result
360 assert "word" in result
361 assert "command" in result
362
363 # Test password with spaces and special chars combined
364 result = shlex.quote("my password with spaces!")
365 assert isinstance(result, str)
366 assert "my password with spaces!" in result
367
368 def test_complete_password_handling_flow(self):
369 """Test the complete flow from password to properly parsed command arguments."""
370
371 test_passwords = ["simple", "password with spaces", "pass!@#$%^&*()", "pass'word\"test", "pass;word&command"]
372
373 for password in test_passwords:
374 with self.subTest(password=password):
375 # Step 1: Escape the password (as MySQL connector does)
376 escaped = shlex.quote(password)
377
378 # Step 2: Form command string (as MySQL connector does)
379 cmd = f"mysqldump testdb --password={escaped}"
380
381 # Step 3: Parse command (as BaseCommandDBConnector does)
382 args = shlex.split(cmd)
383
384 # Step 4: Extract password from parsed args
385 password_arg = None
386 for arg in args:
387 if arg.startswith("--password="):
388 password_arg = arg[11:] # Remove "--password=" prefix
389 break
390
391 # Step 5: Verify the password is preserved correctly
392 assert password_arg == password, (
393 f"Password {password!r} was not preserved correctly through the escaping/parsing flow. "
394 f"Got {password_arg!r} instead."
395 )
396
397
398 class BytesToStrEdgeCasesTest(TestCase):
399 def test_bytes_to_str_fallback_to_bytes(self):
400 """Test bytes_to_str when value is smaller than all units"""
401 # Test the fallback line that returns plain bytes
402 value = utils.bytes_to_str(byte_val=0.5)
403 assert value == "0.5 B"
404
405
406 class EmailUncaughtExceptionEdgeCaseTest(TestCase):
407 @patch("dbbackup.settings.SEND_EMAIL", True)
408 @patch("dbbackup.settings.ADMINS", [])
409 def test_email_uncaught_exception_empty_recipients(self):
410 """Test email sending with empty recipients list"""
411
412 def func():
413 msg = "Test error"
414 raise Exception(msg) # noqa
415
416 # Clear mail outbox before test
417 mail.outbox.clear()
418
419 # Should not raise error even with empty recipients
420 with pytest.raises(Exception): # noqa
421 utils.email_uncaught_exception(func)()
422
423 # Check what was actually sent - with empty recipients, mail may still be sent to admins
424 # The key is that the function doesn't crash with empty recipients
425 assert True # The test passed if we got here without errors
426
427
428 class FilenameGenerateEdgeCasesTest(TestCase):
429 def test_filename_generate_with_slash_in_database_name(self):
430 """Test filename_generate with slash in database name"""
431 filename = utils.filename_generate(extension="dump", content_type="db", database_name="/path/to/database")
432 # Should extract basename from database path
433 assert "database" in filename
434 assert "/path/to/" not in filename
435
436 def test_filename_generate_with_dot_in_database_name(self):
437 """Test filename_generate with dot in database name"""
438 filename = utils.filename_generate(extension="dump", content_type="db", database_name="database.sqlite3")
439 # Should remove extension from database name
440 assert "database" in filename
441 assert ".sqlite3" not in filename
442
443 def test_filename_generate_unknown_content_type(self):
444 """Test filename_generate with unknown content type falls back to db template"""
445 filename = utils.filename_generate(extension="dump", content_type="unknown", database_name="test")
446 # Should use FILENAME_TEMPLATE for unknown content types
447 assert filename.endswith(".dump")
448
449 def test_filename_details(self):
450 """Test filename_details function"""
451 # This function always returns empty string according to the TODO comment
452 result = utils.filename_details("any_file.txt")
453 assert result == ""