Bin
2025-12-17 262fecaa75b2909ad244f12c3b079ed3ff4ae329
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
from unittest.mock import MagicMock, patch
 
import pytest
from core.migration_helpers import execute_sql_job, make_sql_migration
from core.models import AsyncMigrationStatus
from django.test import TestCase, override_settings
 
 
class TestExecuteSqlJob(TestCase):
    """Test execute_sql_job function."""
 
    def setUp(self):
        self.migration_name = 'test.migrations.test_migration'
        self.sql = 'CREATE INDEX test_idx ON test_table (col1);'
 
    @patch('core.migration_helpers.connection')
    def test_creates_migration_status_record(self, mock_connection):
        """Test that a new AsyncMigrationStatus record is created."""
        mock_cursor = MagicMock()
        mock_connection.cursor.return_value.__enter__.return_value = mock_cursor
        mock_connection.vendor = 'postgresql'
 
        execute_sql_job(migration_name=self.migration_name, sql=self.sql)
 
        migration = AsyncMigrationStatus.objects.get(name=self.migration_name)
        assert migration.status == AsyncMigrationStatus.STATUS_FINISHED
        mock_cursor.execute.assert_called_once_with(self.sql)
 
    @patch('core.migration_helpers.connection')
    def test_skips_if_already_finished(self, mock_connection):
        """Test that migration is skipped if already finished."""
        mock_cursor = MagicMock()
        mock_connection.cursor.return_value.__enter__.return_value = mock_cursor
        mock_connection.vendor = 'postgresql'
 
        # Create finished migration
        AsyncMigrationStatus.objects.create(
            name=self.migration_name,
            status=AsyncMigrationStatus.STATUS_FINISHED,
        )
 
        execute_sql_job(migration_name=self.migration_name, sql=self.sql)
 
        # SQL should not be executed
        mock_cursor.execute.assert_not_called()
 
    @patch('core.migration_helpers.connection')
    def test_updates_scheduled_to_started(self, mock_connection):
        """Test that SCHEDULED status is updated to STARTED before execution."""
        mock_cursor = MagicMock()
        mock_connection.cursor.return_value.__enter__.return_value = mock_cursor
        mock_connection.vendor = 'postgresql'
 
        # Create scheduled migration
        migration = AsyncMigrationStatus.objects.create(
            name=self.migration_name,
            status=AsyncMigrationStatus.STATUS_SCHEDULED,
        )
 
        execute_sql_job(migration_name=self.migration_name, sql=self.sql)
 
        migration.refresh_from_db()
        assert migration.status == AsyncMigrationStatus.STATUS_FINISHED
        mock_cursor.execute.assert_called_once_with(self.sql)
 
    @patch('core.migration_helpers.connection')
    def test_skips_sqlite_when_requested(self, mock_connection):
        """Test that SQLite is skipped when apply_on_sqlite=False."""
        mock_cursor = MagicMock()
        mock_connection.cursor.return_value.__enter__.return_value = mock_cursor
        mock_connection.vendor = 'sqlite'
 
        execute_sql_job(
            migration_name=self.migration_name,
            sql=self.sql,
            apply_on_sqlite=False,
        )
 
        migration = AsyncMigrationStatus.objects.get(name=self.migration_name)
        assert migration.status == AsyncMigrationStatus.STATUS_FINISHED
        # SQL should not be executed on SQLite
        mock_cursor.execute.assert_not_called()
 
    @patch('core.migration_helpers.connection')
    def test_executes_on_sqlite_when_requested(self, mock_connection):
        """Test that SQLite execution works when apply_on_sqlite=True."""
        mock_cursor = MagicMock()
        mock_connection.cursor.return_value.__enter__.return_value = mock_cursor
        mock_connection.vendor = 'sqlite'
 
        execute_sql_job(
            migration_name=self.migration_name,
            sql=self.sql,
            apply_on_sqlite=True,
        )
 
        migration = AsyncMigrationStatus.objects.get(name=self.migration_name)
        assert migration.status == AsyncMigrationStatus.STATUS_FINISHED
        mock_cursor.execute.assert_called_once_with(self.sql)
 
    @patch('core.migration_helpers.connection')
    def test_marks_error_on_exception(self, mock_connection):
        """Test that exceptions are caught and migration is marked as ERROR."""
        mock_cursor = MagicMock()
        mock_connection.cursor.return_value.__enter__.return_value = mock_cursor
        mock_connection.vendor = 'postgresql'
        mock_cursor.execute.side_effect = Exception('Test error')
 
        with pytest.raises(Exception, match='Test error'):
            execute_sql_job(migration_name=self.migration_name, sql=self.sql)
 
        migration = AsyncMigrationStatus.objects.get(name=self.migration_name)
        assert migration.status == AsyncMigrationStatus.STATUS_ERROR
        assert migration.meta['error'] == 'Test error'
 
    @patch('core.migration_helpers.connection')
    def test_reverse_does_not_create_status(self, mock_connection):
        """Test that reverse migrations don't create/update AsyncMigrationStatus."""
        mock_cursor = MagicMock()
        mock_connection.cursor.return_value.__enter__.return_value = mock_cursor
        mock_connection.vendor = 'postgresql'
 
        execute_sql_job(
            migration_name=self.migration_name,
            sql=self.sql,
            reverse=True,
        )
 
        # No status should be created
        assert not AsyncMigrationStatus.objects.filter(name=self.migration_name).exists()
        mock_cursor.execute.assert_called_once_with(self.sql)
 
    @patch('core.migration_helpers.connection')
    def test_reverse_skips_sqlite_when_requested(self, mock_connection):
        """Test that reverse migrations skip SQLite when apply_on_sqlite=False."""
        mock_cursor = MagicMock()
        mock_connection.cursor.return_value.__enter__.return_value = mock_cursor
        mock_connection.vendor = 'sqlite'
 
        execute_sql_job(
            migration_name=self.migration_name,
            sql=self.sql,
            apply_on_sqlite=False,
            reverse=True,
        )
 
        mock_cursor.execute.assert_not_called()
 
    @patch('core.migration_helpers.connection')
    def test_reverse_raises_on_exception(self, mock_connection):
        """Test that reverse migrations raise exceptions properly."""
        mock_cursor = MagicMock()
        mock_connection.cursor.return_value.__enter__.return_value = mock_cursor
        mock_connection.vendor = 'postgresql'
        mock_cursor.execute.side_effect = Exception('Test reverse error')
 
        with pytest.raises(Exception, match='Test reverse error'):
            execute_sql_job(
                migration_name=self.migration_name,
                sql=self.sql,
                reverse=True,
            )
 
 
class TestMakeSqlMigration(TestCase):
    """Test make_sql_migration function."""
 
    def setUp(self):
        self.sql_forwards = 'CREATE INDEX test_idx ON test_table (col1);'
        self.sql_backwards = 'DROP INDEX test_idx;'
        self.migration_name = 'test.migrations.test_migration'
 
    def test_requires_migration_name(self):
        """Test that migration_name is required."""
        with pytest.raises(ValueError, match='explicit migration_name'):
            make_sql_migration(
                self.sql_forwards,
                self.sql_backwards,
            )
 
    @override_settings(ALLOW_SCHEDULED_MIGRATIONS=False)
    @patch('core.migration_helpers.start_job_async_or_sync')
    def test_executes_immediately_when_scheduled_disabled(self, mock_start):
        """Test that migration executes immediately when ALLOW_SCHEDULED_MIGRATIONS=False."""
        forwards, backwards = make_sql_migration(
            self.sql_forwards,
            self.sql_backwards,
            migration_name=self.migration_name,
        )
 
        apps = MagicMock()
        schema_editor = MagicMock()
        schema_editor.connection.vendor = 'postgresql'
 
        forwards(apps, schema_editor)
 
        mock_start.assert_called_once()
        args, kwargs = mock_start.call_args
        assert kwargs['migration_name'] == self.migration_name
        assert kwargs['sql'] == self.sql_forwards
        assert kwargs['reverse'] is False
 
    @override_settings(ALLOW_SCHEDULED_MIGRATIONS=True)
    def test_creates_scheduled_status_when_enabled(self):
        """Test that SCHEDULED status is created when ALLOW_SCHEDULED_MIGRATIONS=True."""
        forwards, backwards = make_sql_migration(
            self.sql_forwards,
            self.sql_backwards,
            migration_name=self.migration_name,
            execute_immediately=False,
        )
 
        apps = MagicMock()
        apps.get_model.return_value = AsyncMigrationStatus
        schema_editor = MagicMock()
        schema_editor.connection.vendor = 'postgresql'
 
        forwards(apps, schema_editor)
 
        migration = AsyncMigrationStatus.objects.get(name=self.migration_name)
        assert migration.status == AsyncMigrationStatus.STATUS_SCHEDULED
 
    @override_settings(ALLOW_SCHEDULED_MIGRATIONS=True)
    @patch('core.migration_helpers.start_job_async_or_sync')
    def test_executes_immediately_when_forced(self, mock_start):
        """Test that migration executes immediately when execute_immediately=True."""
        forwards, backwards = make_sql_migration(
            self.sql_forwards,
            self.sql_backwards,
            migration_name=self.migration_name,
            execute_immediately=True,
        )
 
        apps = MagicMock()
        schema_editor = MagicMock()
        schema_editor.connection.vendor = 'postgresql'
 
        forwards(apps, schema_editor)
 
        mock_start.assert_called_once()
        args, kwargs = mock_start.call_args
        assert kwargs['migration_name'] == self.migration_name
        assert kwargs['sql'] == self.sql_forwards
 
    def test_skips_sqlite_when_requested(self):
        """Test that SQLite is skipped when apply_on_sqlite=False."""
        forwards, backwards = make_sql_migration(
            self.sql_forwards,
            self.sql_backwards,
            migration_name=self.migration_name,
            apply_on_sqlite=False,
        )
 
        apps = MagicMock()
        schema_editor = MagicMock()
        schema_editor.connection.vendor = 'sqlite'
 
        # Should return early without creating status
        forwards(apps, schema_editor)
 
        assert not AsyncMigrationStatus.objects.filter(name=self.migration_name).exists()
 
    @patch('core.migration_helpers.start_job_async_or_sync')
    def test_backwards_always_executes(self, mock_start):
        """Test that backwards migration always executes immediately."""
        forwards, backwards = make_sql_migration(
            self.sql_forwards,
            self.sql_backwards,
            migration_name=self.migration_name,
        )
 
        apps = MagicMock()
        schema_editor = MagicMock()
        schema_editor.connection.vendor = 'postgresql'
 
        backwards(apps, schema_editor)
 
        mock_start.assert_called_once()
        args, kwargs = mock_start.call_args
        assert kwargs['migration_name'] == self.migration_name
        assert kwargs['sql'] == self.sql_backwards
        assert kwargs['reverse'] is True
 
    @patch('core.migration_helpers.start_job_async_or_sync')
    def test_passes_apply_on_sqlite_parameter(self, mock_start):
        """Test that apply_on_sqlite parameter is passed to execute_sql_job."""
        forwards, backwards = make_sql_migration(
            self.sql_forwards,
            self.sql_backwards,
            migration_name=self.migration_name,
            apply_on_sqlite=True,
            execute_immediately=True,
        )
 
        apps = MagicMock()
        schema_editor = MagicMock()
        schema_editor.connection.vendor = 'postgresql'
 
        forwards(apps, schema_editor)
 
        args, kwargs = mock_start.call_args
        assert kwargs['apply_on_sqlite'] is True