|
| 1 | +# docker-compose -f local.yml run --rm django pytest sde_collections/tests/test_database_backup.py |
| 2 | +import gzip |
| 3 | +import os |
| 4 | +import subprocess |
| 5 | +from datetime import datetime |
| 6 | +from unittest.mock import Mock, patch |
| 7 | + |
| 8 | +import pytest |
| 9 | +from django.core.management import call_command |
| 10 | + |
| 11 | +from sde_collections.management.commands import database_backup |
| 12 | +from sde_collections.management.commands.database_backup import ( |
| 13 | + Server, |
| 14 | + temp_file_handler, |
| 15 | +) |
| 16 | + |
| 17 | + |
| 18 | +@pytest.fixture |
| 19 | +def mock_subprocess(): |
| 20 | + with patch("subprocess.run") as mock_run: |
| 21 | + mock_run.return_value.returncode = 0 |
| 22 | + yield mock_run |
| 23 | + |
| 24 | + |
| 25 | +@pytest.fixture |
| 26 | +def mock_date(): |
| 27 | + with patch("sde_collections.management.commands.database_backup.datetime") as mock_dt: |
| 28 | + mock_dt.now.return_value = datetime(2024, 1, 15) |
| 29 | + yield mock_dt |
| 30 | + |
| 31 | + |
| 32 | +@pytest.fixture |
| 33 | +def mock_settings(settings): |
| 34 | + """Configure test database settings.""" |
| 35 | + settings.DATABASES = { |
| 36 | + "default": { |
| 37 | + "HOST": "test-db-host", |
| 38 | + "NAME": "test_db", |
| 39 | + "USER": "test_user", |
| 40 | + "PASSWORD": "test_password", |
| 41 | + } |
| 42 | + } |
| 43 | + return settings |
| 44 | + |
| 45 | + |
| 46 | +@pytest.fixture |
| 47 | +def command(): |
| 48 | + return database_backup.Command() |
| 49 | + |
| 50 | + |
| 51 | +class TestBackupCommand: |
| 52 | + def test_get_backup_filename_compressed(self, command, mock_date): |
| 53 | + """Test backup filename generation with compression.""" |
| 54 | + backup_file, dump_file = command.get_backup_filename(Server.STAGING, compress=True) |
| 55 | + assert backup_file == "staging_backup_20240115.sql.gz" |
| 56 | + assert dump_file == "staging_backup_20240115.sql" |
| 57 | + |
| 58 | + def test_get_backup_filename_uncompressed(self, command, mock_date): |
| 59 | + """Test backup filename generation without compression.""" |
| 60 | + backup_file, dump_file = command.get_backup_filename(Server.PRODUCTION, compress=False) |
| 61 | + assert backup_file == "production_backup_20240115.sql" |
| 62 | + assert dump_file == backup_file |
| 63 | + |
| 64 | + def test_run_pg_dump(self, command, mock_subprocess, mock_settings): |
| 65 | + """Test pg_dump command execution.""" |
| 66 | + env = {"PGPASSWORD": "test_password"} |
| 67 | + command.run_pg_dump("test_output.sql", env) |
| 68 | + |
| 69 | + mock_subprocess.assert_called_once() |
| 70 | + cmd_args = mock_subprocess.call_args[0][0] |
| 71 | + assert cmd_args == [ |
| 72 | + "pg_dump", |
| 73 | + "-h", |
| 74 | + "test-db-host", |
| 75 | + "-U", |
| 76 | + "test_user", |
| 77 | + "-d", |
| 78 | + "test_db", |
| 79 | + "--no-owner", |
| 80 | + "--no-privileges", |
| 81 | + "-f", |
| 82 | + "test_output.sql", |
| 83 | + ] |
| 84 | + |
| 85 | + def test_compress_file(self, command, tmp_path): |
| 86 | + """Test file compression.""" |
| 87 | + input_file = tmp_path / "test.sql" |
| 88 | + output_file = tmp_path / "test.sql.gz" |
| 89 | + test_content = b"Test database content" |
| 90 | + |
| 91 | + # Create test input file |
| 92 | + input_file.write_bytes(test_content) |
| 93 | + |
| 94 | + # Compress the file |
| 95 | + command.compress_file(str(input_file), str(output_file)) |
| 96 | + |
| 97 | + # Verify compression |
| 98 | + assert output_file.exists() |
| 99 | + with gzip.open(output_file, "rb") as f: |
| 100 | + assert f.read() == test_content |
| 101 | + |
| 102 | + def test_temp_file_handler_cleanup(self, tmp_path): |
| 103 | + """Test temporary file cleanup.""" |
| 104 | + test_file = tmp_path / "temp.sql" |
| 105 | + test_file.touch() |
| 106 | + |
| 107 | + with temp_file_handler(str(test_file)): |
| 108 | + assert test_file.exists() |
| 109 | + assert not test_file.exists() |
| 110 | + |
| 111 | + def test_temp_file_handler_cleanup_on_error(self, tmp_path): |
| 112 | + """Test temporary file cleanup when an error occurs.""" |
| 113 | + test_file = tmp_path / "temp.sql" |
| 114 | + test_file.touch() |
| 115 | + |
| 116 | + with pytest.raises(ValueError): |
| 117 | + with temp_file_handler(str(test_file)): |
| 118 | + assert test_file.exists() |
| 119 | + raise ValueError("Test error") |
| 120 | + assert not test_file.exists() |
| 121 | + |
| 122 | + @patch("socket.gethostname") |
| 123 | + def test_server_detection(self, mock_hostname): |
| 124 | + """Test server environment detection.""" |
| 125 | + test_cases = [ |
| 126 | + ("PRODUCTION-SERVER", Server.PRODUCTION), |
| 127 | + ("STAGING-DB", Server.STAGING), |
| 128 | + ("DEV-HOST", Server.UNKNOWN), |
| 129 | + ] |
| 130 | + |
| 131 | + for hostname, expected_server in test_cases: |
| 132 | + mock_hostname.return_value = hostname |
| 133 | + with patch("sde_collections.management.commands.database_backup.detect_server") as mock_detect: |
| 134 | + mock_detect.return_value = expected_server |
| 135 | + server = database_backup.detect_server() |
| 136 | + assert server == expected_server |
| 137 | + |
| 138 | + @pytest.mark.parametrize( |
| 139 | + "compress,hostname", |
| 140 | + [ |
| 141 | + (True, "PRODUCTION-SERVER"), |
| 142 | + (False, "STAGING-SERVER"), |
| 143 | + (True, "UNKNOWN-SERVER"), |
| 144 | + ], |
| 145 | + ) |
| 146 | + def test_handle_integration(self, compress, hostname, mock_subprocess, mock_date, mock_settings): |
| 147 | + """Test full backup process integration.""" |
| 148 | + with patch("socket.gethostname", return_value=hostname): |
| 149 | + call_command("database_backup", no_compress=not compress) |
| 150 | + |
| 151 | + # Verify correct command execution |
| 152 | + mock_subprocess.assert_called_once() |
| 153 | + |
| 154 | + # Verify correct filename used |
| 155 | + cmd_args = mock_subprocess.call_args[0][0] |
| 156 | + date_str = "20240115" |
| 157 | + server_type = hostname.split("-")[0].lower() |
| 158 | + expected_base = f"{server_type}_backup_{date_str}.sql" |
| 159 | + |
| 160 | + if compress: |
| 161 | + assert cmd_args[-1] == expected_base # Temporary file |
| 162 | + # Verify cleanup attempted |
| 163 | + assert not os.path.exists(expected_base) |
| 164 | + else: |
| 165 | + assert cmd_args[-1] == expected_base |
| 166 | + |
| 167 | + def test_handle_pg_dump_error(self, mock_subprocess, mock_date): |
| 168 | + """Test error handling when pg_dump fails.""" |
| 169 | + mock_subprocess.side_effect = subprocess.CalledProcessError(1, "pg_dump") |
| 170 | + |
| 171 | + with patch("socket.gethostname", return_value="STAGING-SERVER"): |
| 172 | + call_command("database_backup") |
| 173 | + |
| 174 | + # Verify error handling and cleanup |
| 175 | + date_str = "20240115" |
| 176 | + temp_file = f"staging_backup_{date_str}.sql" |
| 177 | + assert not os.path.exists(temp_file) |
| 178 | + |
| 179 | + def test_handle_compression_error(self, mock_subprocess, mock_date, command): |
| 180 | + """Test error handling during compression.""" |
| 181 | + # Mock compression to fail |
| 182 | + command.compress_file = Mock(side_effect=Exception("Compression failed")) |
| 183 | + |
| 184 | + with patch("socket.gethostname", return_value="STAGING-SERVER"): |
| 185 | + call_command("database_backup") |
| 186 | + |
| 187 | + # Verify cleanup |
| 188 | + date_str = "20240115" |
| 189 | + temp_file = f"staging_backup_{date_str}.sql" |
| 190 | + assert not os.path.exists(temp_file) |
0 commit comments