Debian Codegraph @

t/unit/backends/test_gcs.py

raw
1 from datetime import datetime, timedelta
2 from unittest.mock import MagicMock, Mock, call, patch
3
4 import pytest
5 from google.cloud.exceptions import NotFound
6
7 from celery.backends.gcs import GCSBackend
8 from celery.exceptions import ImproperlyConfigured
9
10
11 class test_GCSBackend:
12 def setup_method(self):
13 self.app.conf.gcs_bucket = 'bucket'
14 self.app.conf.gcs_project = 'project'
15
16 @pytest.fixture(params=['', 'test_folder/'])
17 def base_path(self, request):
18 return request.param
19
20 @pytest.fixture(params=[86400, None])
21 def gcs_ttl(self, request):
22 return request.param
23
24 def test_missing_storage_module(self):
25 with patch('celery.backends.gcs.storage', None):
26 with pytest.raises(
27 ImproperlyConfigured, match='You must install'
28 ):
29 GCSBackend(app=self.app)
30
31 def test_missing_firestore_module(self):
32 with patch('celery.backends.gcs.firestore', None):
33 with pytest.raises(
34 ImproperlyConfigured, match='You must install'
35 ):
36 GCSBackend(app=self.app)
37
38 def test_missing_bucket(self):
39 self.app.conf.gcs_bucket = None
40
41 with pytest.raises(ImproperlyConfigured, match='Missing bucket name'):
42 GCSBackend(app=self.app)
43
44 def test_missing_project(self):
45 self.app.conf.gcs_project = None
46
47 with pytest.raises(ImproperlyConfigured, match='Missing project'):
48 GCSBackend(app=self.app)
49
50 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
51 def test_firestore_project(self, mock_firestore_ttl):
52 mock_firestore_ttl.return_value = True
53 b = GCSBackend(app=self.app)
54 assert b.firestore_project == 'project'
55 self.app.conf.firestore_project = 'project2'
56 b = GCSBackend(app=self.app)
57 assert b.firestore_project == 'project2'
58
59 def test_invalid_ttl(self):
60 self.app.conf.gcs_bucket = 'bucket'
61 self.app.conf.gcs_project = 'project'
62 self.app.conf.gcs_ttl = -1
63
64 with pytest.raises(ImproperlyConfigured, match='Invalid ttl'):
65 GCSBackend(app=self.app)
66
67 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
68 def test_firestore_ttl_policy_disabled(self, mock_firestore_ttl):
69 self.app.conf.gcs_bucket = 'bucket'
70 self.app.conf.gcs_project = 'project'
71 self.app.conf.gcs_ttl = 0
72
73 mock_firestore_ttl.return_value = False
74 with pytest.raises(ImproperlyConfigured, match='Missing TTL policy'):
75 GCSBackend(app=self.app)
76
77 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
78 def test_parse_url(self, mock_firestore_ttl, base_path):
79 self.app.conf.gcs_bucket = None
80 self.app.conf.gcs_project = None
81
82 mock_firestore_ttl.return_value = True
83 backend = GCSBackend(
84 app=self.app,
85 url=f'gcs://bucket/{base_path}?gcs_project=project',
86 )
87 assert backend.bucket_name == 'bucket'
88 assert backend.base_path == base_path.strip('/')
89
90 @patch.object(GCSBackend, '_is_bucket_lifecycle_rule_exists')
91 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
92 def test_bucket_ttl_missing_lifecycle_rule(
93 self, mock_firestore_ttl, mock_lifecycle
94 ):
95 self.app.conf.gcs_ttl = 86400
96
97 mock_lifecycle.return_value = False
98 mock_firestore_ttl.return_value = True
99 with pytest.raises(
100 ImproperlyConfigured, match='Missing lifecycle rule'
101 ):
102 GCSBackend(app=self.app)
103 mock_lifecycle.assert_called_once()
104
105 @patch.object(GCSBackend, '_get_blob')
106 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
107 def test_get_key(self, mock_ttl, mock_get_blob, base_path):
108 self.app.conf.gcs_base_path = base_path
109
110 mock_ttl.return_value = True
111 mock_blob = Mock()
112 mock_get_blob.return_value = mock_blob
113 backend = GCSBackend(app=self.app)
114 backend.get(b"testkey1")
115
116 mock_get_blob.assert_called_once_with('testkey1')
117 mock_blob.download_as_bytes.assert_called_once()
118
119 @patch.object(GCSBackend, 'bucket')
120 @patch.object(GCSBackend, '_get_blob')
121 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
122 def test_set_key(
123 self,
124 mock_firestore_ttl,
125 mock_get_blob,
126 mock_bucket_prop,
127 base_path,
128 gcs_ttl,
129 ):
130 self.app.conf.gcs_base_path = base_path
131 self.app.conf.gcs_ttl = gcs_ttl
132
133 mock_firestore_ttl.return_value = True
134 mock_blob = Mock()
135 mock_get_blob.return_value = mock_blob
136 mock_bucket_prop.lifecycle_rules = [{'action': {'type': 'Delete'}}]
137 backend = GCSBackend(app=self.app)
138 backend.set('testkey', 'testvalue')
139 mock_get_blob.assert_called_once_with('testkey')
140 mock_blob.upload_from_string.assert_called_once_with(
141 'testvalue', retry=backend._retry_policy
142 )
143 if gcs_ttl:
144 assert mock_blob.custom_time >= datetime.utcnow()
145
146 @patch.object(GCSBackend, '_get_blob')
147 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
148 def test_get_missing_key(self, mock_firestore_ttl, mock_get_blob):
149 self.app.conf.gcs_bucket = 'bucket'
150 self.app.conf.gcs_project = 'project'
151
152 mock_firestore_ttl.return_value = True
153 mock_blob = Mock()
154 mock_get_blob.return_value = mock_blob
155
156 mock_blob.download_as_bytes.side_effect = NotFound('not found')
157 gcs_backend = GCSBackend(app=self.app)
158 result = gcs_backend.get('some-key')
159
160 assert result is None
161
162 @patch.object(GCSBackend, '_get_blob')
163 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
164 def test_delete_existing_key(
165 self, mock_firestore_ttl, mock_get_blob, base_path
166 ):
167 self.app.conf.gcs_base_path = base_path
168
169 mock_firestore_ttl.return_value = True
170 mock_blob = Mock()
171 mock_get_blob.return_value = mock_blob
172 mock_blob.exists.return_value = True
173 backend = GCSBackend(app=self.app)
174 backend.delete(b"testkey2")
175
176 mock_get_blob.assert_called_once_with('testkey2')
177 mock_blob.exists.assert_called_once()
178 mock_blob.delete.assert_called_once()
179
180 @patch.object(GCSBackend, '_get_blob')
181 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
182 def test_delete_missing_key(
183 self, mock_firestore_ttl, mock_get_blob, base_path
184 ):
185 self.app.conf.gcs_base_path = base_path
186
187 mock_firestore_ttl.return_value = True
188 mock_blob = Mock()
189 mock_get_blob.return_value = mock_blob
190 mock_blob.exists.return_value = False
191 backend = GCSBackend(app=self.app)
192 backend.delete(b"testkey2")
193
194 mock_get_blob.assert_called_once_with('testkey2')
195 mock_blob.exists.assert_called_once()
196 mock_blob.delete.assert_not_called()
197
198 @patch.object(GCSBackend, 'get')
199 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
200 def test_mget(self, mock_firestore_ttl, mock_get, base_path):
201 self.app.conf.gcs_base_path = base_path
202 mock_firestore_ttl.return_value = True
203 backend = GCSBackend(app=self.app)
204 mock_get.side_effect = ['value1', 'value2']
205 result = backend.mget([b'key1', b'key2'])
206 mock_get.assert_has_calls(
207 [call(b'key1'), call(b'key2')], any_order=True
208 )
209 assert sorted(result) == sorted(['value1', 'value2'])
210
211 @patch.object(GCSBackend, 'client')
212 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
213 def test_bucket(self, mock_firestore_ttl, mock_client):
214 mock_bucket = MagicMock()
215 mock_client.bucket.return_value = mock_bucket
216 mock_firestore_ttl.return_value = True
217 backend = GCSBackend(app=self.app)
218 result = backend.bucket
219 mock_client.bucket.assert_called_once_with(backend.bucket_name)
220 assert result == mock_bucket
221
222 @patch.object(GCSBackend, 'bucket')
223 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
224 def test_get_blob(self, mock_firestore_ttl, mock_bucket):
225 key = 'test_key'
226 mock_blob = MagicMock()
227 mock_bucket.blob.return_value = mock_blob
228 mock_firestore_ttl.return_value = True
229
230 backend = GCSBackend(app=self.app)
231 result = backend._get_blob(key)
232
233 key_bucket_path = (
234 f'{backend.base_path}/{key}' if backend.base_path else key
235 )
236 mock_bucket.blob.assert_called_once_with(key_bucket_path)
237 assert result == mock_blob
238
239 @patch('celery.backends.gcs.Client')
240 @patch('celery.backends.gcs.getpid')
241 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
242 def test_new_client_after_fork(
243 self, mock_firestore_ttl, mock_pid, mock_client
244 ):
245 mock_firestore_ttl.return_value = True
246 mock_pid.return_value = 123
247 backend = GCSBackend(app=self.app)
248 client1 = backend.client
249 assert client1 == backend.client
250 mock_pid.assert_called()
251 mock_client.assert_called()
252 mock_pid.return_value = 456
253 mock_client.return_value = Mock()
254 assert client1 != backend.client
255 mock_client.assert_called_with(project='project')
256
257 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
258 @patch('celery.backends.gcs.firestore.Client')
259 @patch('celery.backends.gcs.getpid')
260 def test_new_firestore_client_after_fork(
261 self, mock_pid, mock_firestore_client, mock_firestore_ttl
262 ):
263 mock_firestore_instance = MagicMock()
264 mock_firestore_client.return_value = mock_firestore_instance
265
266 backend = GCSBackend(app=self.app)
267 mock_pid.return_value = 123
268 client1 = backend.firestore_client
269 client2 = backend.firestore_client
270
271 mock_firestore_client.assert_called_once_with(
272 project=backend.firestore_project
273 )
274 assert client1 == mock_firestore_instance
275 assert client2 == mock_firestore_instance
276 assert backend._pid == 123
277 mock_pid.return_value = 456
278 _ = backend.firestore_client
279 assert backend._pid == 456
280
281 @patch('celery.backends.gcs.firestore_admin_v1.FirestoreAdminClient')
282 @patch('celery.backends.gcs.firestore_admin_v1.GetFieldRequest')
283 def test_is_firestore_ttl_policy_enabled(
284 self, mock_get_field_request, mock_firestore_admin_client
285 ):
286 mock_client_instance = MagicMock()
287 mock_firestore_admin_client.return_value = mock_client_instance
288 mock_field = MagicMock()
289 mock_field.ttl_config.state = 2 # State.ENABLED
290 mock_client_instance.get_field.return_value = mock_field
291
292 backend = GCSBackend(app=self.app)
293 result = backend._is_firestore_ttl_policy_enabled()
294
295 assert result
296 mock_field.ttl_config.state = 3 # State.NEEDS_REPAIR
297 mock_client_instance.get_field.return_value = mock_field
298 result = backend._is_firestore_ttl_policy_enabled()
299 assert not result
300
301 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
302 @patch.object(GCSBackend, '_expire_chord_key')
303 @patch.object(GCSBackend, 'get_key_for_chord')
304 @patch('celery.backends.gcs.KeyValueStoreBackend._apply_chord_incr')
305 def test_apply_chord_incr(
306 self,
307 mock_super_apply_chord_incr,
308 mock_get_key_for_chord,
309 mock_expire_chord_key,
310 mock_firestore_ttl,
311 ):
312 mock_firestore_ttl.return_value = True
313 mock_get_key_for_chord.return_value = b'group_key'
314 header_result_args = [MagicMock()]
315 body = MagicMock()
316
317 backend = GCSBackend(app=self.app)
318 backend._apply_chord_incr(header_result_args, body)
319
320 mock_get_key_for_chord.assert_called_once_with(header_result_args[0])
321 mock_expire_chord_key.assert_called_once_with('group_key', 86400)
322 mock_super_apply_chord_incr.assert_called_once_with(
323 header_result_args, body
324 )
325
326 @patch.object(GCSBackend, '_firestore_document')
327 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
328 def test_incr(self, mock_firestore_ttl, mock_firestore_document):
329 self.app.conf.gcs_bucket = 'bucket'
330 self.app.conf.gcs_project = 'project'
331
332 mock_firestore_ttl.return_value = True
333 gcs_backend = GCSBackend(app=self.app)
334 gcs_backend.incr(b'some-key')
335 assert mock_firestore_document.call_count == 1
336
337 @patch('celery.backends.gcs.maybe_signature')
338 @patch.object(GCSBackend, 'incr')
339 @patch.object(GCSBackend, '_restore_deps')
340 @patch.object(GCSBackend, '_delete_chord_key')
341 @patch('celery.backends.gcs.allow_join_result')
342 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
343 def test_on_chord_part_return(
344 self,
345 mock_firestore_ttl,
346 mock_allow_join_result,
347 mock_delete_chord_key,
348 mock_restore_deps,
349 mock_incr,
350 mock_maybe_signature,
351 ):
352 request = MagicMock()
353 request.group = 'group_id'
354 request.chord = {'chord_size': 2}
355 state = MagicMock()
356 result = MagicMock()
357 mock_firestore_ttl.return_value = True
358 mock_incr.return_value = 2
359 mock_restore_deps.return_value = MagicMock()
360 mock_restore_deps.return_value.join_native.return_value = [
361 'result1',
362 'result2',
363 ]
364 mock_maybe_signature.return_value = MagicMock()
365
366 b = GCSBackend(app=self.app)
367 b.on_chord_part_return(request, state, result)
368
369 group_key = b.chord_keyprefix + b'group_id'
370 mock_incr.assert_called_once_with(group_key)
371 mock_restore_deps.assert_called_once_with('group_id', request)
372 mock_maybe_signature.assert_called_once_with(
373 request.chord, app=self.app
374 )
375 mock_restore_deps.return_value.join_native.assert_called_once_with(
376 timeout=self.app.conf.result_chord_join_timeout,
377 propagate=True,
378 )
379 mock_maybe_signature.return_value.delay.assert_called_once_with(
380 ['result1', 'result2']
381 )
382 mock_delete_chord_key.assert_called_once_with(group_key)
383
384 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
385 @patch('celery.backends.gcs.GroupResult.restore')
386 @patch('celery.backends.gcs.maybe_signature')
387 @patch.object(GCSBackend, 'chord_error_from_stack')
388 def test_restore_deps(
389 self,
390 mock_chord_error_from_stack,
391 mock_maybe_signature,
392 mock_group_result_restore,
393 mock_firestore_ttl,
394 ):
395 gid = 'group_id'
396 request = MagicMock()
397 mock_group_result_restore.return_value = MagicMock()
398
399 backend = GCSBackend(app=self.app)
400 deps = backend._restore_deps(gid, request)
401
402 mock_group_result_restore.assert_called_once_with(
403 gid, backend=backend
404 )
405 assert deps is not None
406 mock_chord_error_from_stack.assert_not_called()
407
408 mock_group_result_restore.side_effect = Exception('restore error')
409 deps = backend._restore_deps(gid, request)
410 mock_maybe_signature.assert_called_with(request.chord, app=self.app)
411 mock_chord_error_from_stack.assert_called_once()
412 assert deps is None
413
414 mock_group_result_restore.side_effect = None
415 mock_group_result_restore.return_value = None
416 deps = backend._restore_deps(gid, request)
417 mock_chord_error_from_stack.assert_called()
418 assert deps is None
419
420 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
421 @patch.object(GCSBackend, '_firestore_document')
422 def test_delete_chord_key(
423 self, mock_firestore_document, mock_firestore_ttl
424 ):
425 key = 'test_key'
426 mock_document = MagicMock()
427 mock_firestore_document.return_value = mock_document
428
429 backend = GCSBackend(app=self.app)
430 backend._delete_chord_key(key)
431
432 mock_firestore_document.assert_called_once_with(key)
433 mock_document.delete.assert_called_once()
434
435 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
436 @patch.object(GCSBackend, '_firestore_document')
437 def test_expire_chord_key(
438 self, mock_firestore_document, mock_firestore_ttl
439 ):
440 key = 'test_key'
441 expires = 86400
442 mock_document = MagicMock()
443 mock_firestore_document.return_value = mock_document
444 expected_expiry = datetime.utcnow() + timedelta(seconds=expires)
445
446 backend = GCSBackend(app=self.app)
447 backend._expire_chord_key(key, expires)
448
449 mock_firestore_document.assert_called_once_with(key)
450 mock_document.set.assert_called_once()
451 args, kwargs = mock_document.set.call_args
452 assert backend._field_expires in args[0]
453 assert args[0][backend._field_expires] >= expected_expiry
454
455 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
456 @patch.object(GCSBackend, 'firestore_client')
457 def test_firestore_document(
458 self, mock_firestore_client, mock_firestore_ttl
459 ):
460 key = b'test_key'
461 mock_collection = MagicMock()
462 mock_document = MagicMock()
463 mock_firestore_client.collection.return_value = mock_collection
464 mock_collection.document.return_value = mock_document
465
466 backend = GCSBackend(app=self.app)
467 result = backend._firestore_document(key)
468
469 mock_firestore_client.collection.assert_called_once_with(
470 backend._collection_name
471 )
472 mock_collection.document.assert_called_once_with('test_key')
473 assert result == mock_document
474
475 @patch('celery.backends.gcs.maybe_signature')
476 @patch.object(GCSBackend, 'incr')
477 @patch.object(GCSBackend, '_restore_deps')
478 @patch.object(GCSBackend, '_delete_chord_key')
479 @patch.object(GCSBackend, 'chord_error_from_stack')
480 @patch('celery.backends.gcs.allow_join_result')
481 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
482 def test_on_chord_part_return_join_exception(
483 self,
484 mock_firestore_ttl,
485 mock_allow_join_result_,
486 mock_chord_error_from_stack,
487 mock_delete_chord_key,
488 mock_restore_deps,
489 mock_incr,
490 mock_maybe_signature,
491 ):
492 """Test on_chord_part_return when join_native raises exception."""
493 request = MagicMock()
494 request.group = 'group_id'
495 request.chord = {'chord_size': 2}
496 state = MagicMock()
497 result = MagicMock()
498
499 mock_firestore_ttl.return_value = True
500 mock_incr.return_value = 2
501
502 # Mock dependencies and callback
503 mock_deps = MagicMock()
504 mock_restore_deps.return_value = mock_deps
505 mock_callback = MagicMock()
506 mock_maybe_signature.return_value = mock_callback
507
508 # Make join_native raise an exception
509 join_exception = ValueError('Join failed')
510 mock_deps.join_native.side_effect = join_exception
511 mock_deps._failed_join_report.return_value = iter([]) # No culprit found
512
513 backend = GCSBackend(app=self.app)
514 backend.on_chord_part_return(request, state, result)
515
516 # Verify chord_error_from_stack was called with the exception
517 mock_chord_error_from_stack.assert_called_once()
518 call_args = mock_chord_error_from_stack.call_args
519 assert call_args[0][0] == mock_callback # callback argument
520 chord_error_arg = call_args[0][1] # exc argument
521 assert 'ValueError' in str(chord_error_arg)
522 assert chord_error_arg.__cause__ == join_exception
523
524 # Verify cleanup still happens
525 mock_deps.delete.assert_called_once()
526 mock_delete_chord_key.assert_called_once()
527
528 @patch('celery.backends.gcs.maybe_signature')
529 @patch.object(GCSBackend, 'incr')
530 @patch.object(GCSBackend, '_restore_deps')
531 @patch.object(GCSBackend, '_delete_chord_key')
532 @patch.object(GCSBackend, 'chord_error_from_stack')
533 @patch('celery.backends.gcs.allow_join_result')
534 @patch.object(GCSBackend, '_is_firestore_ttl_policy_enabled')
535 def test_on_chord_part_return_callback_exception(
536 self,
537 mock_firestore_ttl,
538 mock_allow_join_result_,
539 mock_chord_error_from_stack,
540 mock_delete_chord_key,
541 mock_restore_deps,
542 mock_incr,
543 mock_maybe_signature,
544 ):
545 """Test on_chord_part_return when callback.delay raises exception (line 302)."""
546 request = MagicMock()
547 request.group = 'group_id'
548 request.chord = {'chord_size': 2}
549 state = MagicMock()
550 result = MagicMock()
551
552 mock_firestore_ttl.return_value = True
553 mock_incr.return_value = 2
554
555 # Mock dependencies and callback
556 mock_deps = MagicMock()
557 mock_restore_deps.return_value = mock_deps
558 mock_deps.join_native.return_value = ['result1', 'result2']
559
560 mock_callback = MagicMock()
561 mock_maybe_signature.return_value = mock_callback
562
563 # Make callback.delay raise an exception
564 callback_exception = RuntimeError('Callback failed')
565 mock_callback.delay.side_effect = callback_exception
566
567 backend = GCSBackend(app=self.app)
568 backend.on_chord_part_return(request, state, result)
569
570 # Verify join was successful first
571 mock_deps.join_native.assert_called_once_with(
572 timeout=self.app.conf.result_chord_join_timeout,
573 propagate=True,
574 )
575
576 # Verify callback.delay was called and failed
577 mock_callback.delay.assert_called_once_with(['result1', 'result2'])
578
579 # Verify chord_error_from_stack was called with ChordError
580 mock_chord_error_from_stack.assert_called_once()
581 call_args = mock_chord_error_from_stack.call_args
582 assert call_args[0][0] == mock_callback # callback argument
583 chord_error_arg = call_args[0][1] # exc argument
584 assert 'Callback error:' in str(chord_error_arg)
585 assert 'RuntimeError' in str(chord_error_arg)
586
587 # Verify cleanup still happens
588 mock_deps.delete.assert_called_once()
589 mock_delete_chord_key.assert_called_once()