-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathtest_contact_task.py
872 lines (785 loc) · 29.9 KB
/
test_contact_task.py
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
import datetime
import json
import logging
import uuid
from unittest import mock
from unittest.mock import patch
import boto3
import pytest
from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.test import override_settings
from django.utils import timezone
from freezegun import freeze_time
from moto import mock_aws
from requests import ConnectTimeout
from rest_framework import status
from datahub.company.models.contact import Contact
from datahub.company.tasks import (
automatic_contact_archive,
update_contact_consent,
)
from datahub.company.tasks.contact import (
BUCKET,
CONSENT_PREFIX,
ContactConsentIngestionTask,
ingest_contact_consent_data,
REGION,
schedule_automatic_contact_archive,
schedule_update_contact_consent,
)
from datahub.company.test.factories import CompanyFactory, ContactFactory
from datahub.core.queues.errors import RetryError
from datahub.core.test_utils import HawkMockJSONResponse
def generate_hawk_response(payload):
"""Mocks HAWK server validation for content."""
return HawkMockJSONResponse(
api_id=settings.CONSENT_SERVICE_HAWK_ID,
api_key=settings.CONSENT_SERVICE_HAWK_KEY,
response=payload,
)
@pytest.mark.django_db
class TestConsentServiceTask:
"""
tests for the task that sends email marketing consent status to the
DIT consent service / legal basis API
"""
@override_settings(
CONSENT_SERVICE_BASE_URL=None,
)
def test_not_configured_error(
self,
):
"""
Test that if feature flag is enabled, but environment variables are not set
then task will throw a caught exception and no retries or updates will occur
"""
update_succeeds = update_contact_consent('example@example.com', True)
assert update_succeeds is False
@pytest.mark.parametrize(
'email_address, accepts_dit_email_marketing, modified_at',
(
('example@example.com', True, None),
('example@example.com', False, None),
('example@example.com', True, '2020-01-01-12:00:00Z'),
('example@example.com', False, '2020-01-01-12:00:00Z'),
),
)
def test_task_makes_http_request(
self,
requests_mock,
email_address,
accepts_dit_email_marketing,
modified_at,
):
"""
Ensure correct http request with correct payload is generated when task
executes.
"""
matcher = requests_mock.post(
'/api/v1/person/',
text=generate_hawk_response({}),
status_code=status.HTTP_201_CREATED,
)
update_contact_consent(
email_address,
accepts_dit_email_marketing,
modified_at=modified_at,
)
assert matcher.called_once
expected = {
'email': email_address,
'consents': ['email_marketing'] if accepts_dit_email_marketing else [],
}
if modified_at:
expected['modified_at'] = modified_at
assert matcher.last_request.json() == expected
@pytest.mark.parametrize(
'status_code',
(
(status.HTTP_404_NOT_FOUND),
(status.HTTP_403_FORBIDDEN),
(status.HTTP_500_INTERNAL_SERVER_ERROR),
),
)
def test_task_retries_on_request_exceptions(
self,
requests_mock,
status_code,
):
"""
Test to ensure that rq receives exceptions like 5xx, 404 and then will retry based on
job_scheduler configuration
"""
matcher = requests_mock.post(
'/api/v1/person/',
text=generate_hawk_response({}),
status_code=status_code,
)
with pytest.raises(RetryError):
update_contact_consent('example@example.com', True)
assert matcher.called_once
@patch('datahub.company.consent.APIClient.request', side_effect=ConnectTimeout)
def test_task_retries_on_connect_timeout(
self,
mock_post,
):
"""
Test to ensure that RQ retries on connect timeout by virtue of the exception forcing
a retry within RQ and configured settings
"""
with pytest.raises(RetryError):
update_contact_consent('example@example.com', True)
assert mock_post.called
@patch('datahub.company.consent.APIClient.request', side_effect=Exception)
def test_task_doesnt_retry_on_other_exception(
self,
mock_post,
):
"""
Test to ensure that RQ raises on non-requests exception
"""
update_succeeds = update_contact_consent('example@example.com', True)
assert mock_post.called
assert update_succeeds is False
@pytest.mark.parametrize(
'status_code',
(
(status.HTTP_200_OK),
(status.HTTP_201_CREATED),
),
)
def test_update_succeeds(
self,
requests_mock,
status_code,
):
"""
Test success occurs when update succeeds
"""
matcher = requests_mock.post(
'/api/v1/person/',
text=generate_hawk_response({}),
status_code=status_code,
)
update_success = update_contact_consent('example@example.com', True)
assert matcher.called_once
assert update_success is True
@pytest.mark.parametrize(
'bad_email',
(
None,
'',
' ',
),
)
def test_none_or_empty_email_assigned_fails(
self,
requests_mock,
bad_email,
):
matcher = requests_mock.post(
'/api/v1/person/',
text=generate_hawk_response({}),
status_code=status.HTTP_201_CREATED,
)
update_success = update_contact_consent(bad_email, False)
assert not matcher.called_once
assert update_success is False
def test_job_schedules_with_correct_update_contact_consent_details(self):
actual_job = schedule_update_contact_consent('example@example.com', True)
assert actual_job is not None
assert actual_job._func_name == 'datahub.company.tasks.contact.update_contact_consent'
assert actual_job._args == ('example@example.com', True, None)
assert actual_job.retries_left == 5
assert actual_job.retry_intervals == [30, 961, 1024, 1089, 1156]
assert actual_job.origin == 'short-running'
@pytest.mark.django_db
class TestContactArchiveTask:
"""
Tests for the task that archives contacts
"""
@pytest.mark.parametrize(
'lock_acquired, call_count',
(
(False, 0),
(True, 1),
),
)
def test_lock(
self,
monkeypatch,
lock_acquired,
call_count,
):
"""
Test that the task doesn't run if it cannot acquire the advisory_lock
"""
mock_advisory_lock = mock.MagicMock()
mock_advisory_lock.return_value.__enter__.return_value = lock_acquired
monkeypatch.setattr(
'datahub.company.tasks.contact.advisory_lock',
mock_advisory_lock,
)
mock_automatic_contact_archive = mock.Mock()
monkeypatch.setattr(
'datahub.company.tasks.contact._automatic_contact_archive',
mock_automatic_contact_archive,
)
automatic_contact_archive()
assert mock_automatic_contact_archive.call_count == call_count
def test_limit(self):
"""
Test contact archiving query limit
"""
limit = 2
contacts = [ContactFactory(company=CompanyFactory(archived=True)) for _ in range(3)]
automatic_contact_archive(limit=limit)
count = 0
for contact in contacts:
contact.refresh_from_db()
if contact.archived:
count += 1
assert count == limit
@pytest.mark.parametrize('simulate', (True, False))
def test_simulate(self, caplog, simulate):
"""
Test contact archiving simulate flag
"""
caplog.set_level(logging.INFO, logger='datahub.company.tasks.contact')
date = timezone.now() - relativedelta(days=10)
with freeze_time(date):
company1 = CompanyFactory()
company2 = CompanyFactory(archived=True)
contact1 = ContactFactory(company=company1)
contact2 = ContactFactory(company=company2)
automatic_contact_archive(simulate=simulate)
contact1.refresh_from_db()
contact2.refresh_from_db()
if simulate:
assert caplog.messages == [
f'[SIMULATION] Automatically archived contact: {contact2.id}',
]
else:
assert contact1.archived is False
assert contact2.archived is True
assert caplog.messages == [f'Automatically archived contact: {contact2.id}']
@pytest.mark.parametrize(
'contacts, message',
(
(
(False, False, False),
'datahub.company.tasks.automatic_contact_archive archived: 0',
),
(
(False, False, True),
'datahub.company.tasks.automatic_contact_archive archived: 1',
),
(
(True, True, True),
'datahub.company.tasks.automatic_contact_archive archived: 3',
),
),
)
def test_realtime_messages_sent(
self,
monkeypatch,
contacts,
message,
):
"""
Test that appropriate realtime messaging is sent which reflects the archiving actions
"""
for is_archived in contacts:
company = CompanyFactory(archived=is_archived)
ContactFactory(company=company)
mock_send_realtime_message = mock.Mock()
monkeypatch.setattr(
'datahub.company.tasks.contact.send_realtime_message',
mock_send_realtime_message,
)
automatic_contact_archive()
mock_send_realtime_message.assert_called_once_with(message)
def test_archive_no_updates(self):
"""
Test contact archiving with no updates on contacts
"""
date = timezone.now() - relativedelta(days=10)
with freeze_time(date):
company1 = CompanyFactory()
company2 = CompanyFactory()
contact1 = ContactFactory(company=company1)
contact2 = ContactFactory(company=company2)
contact3 = ContactFactory(company=company2)
for contact in [contact1, contact2, contact3]:
assert contact.archived is False
assert contact.archived_reason is None
assert contact.archived_on is None
# run task twice expecting same result
for _ in range(2):
automatic_contact_archive(limit=200)
for contact in [contact1, contact2, contact3]:
contact.refresh_from_db()
assert contact.archived is False
assert contact.archived_reason is None
assert contact.archived_on is None
def test_archive_with_updates(self):
"""
Test contact archiving with updates on correct contacts
"""
date = timezone.now() - relativedelta(days=10)
with freeze_time(date):
company1 = CompanyFactory()
company2 = CompanyFactory(archived=True)
contact1 = ContactFactory(company=company1)
contact2 = ContactFactory(company=company2)
contact3 = ContactFactory(company=company2)
for contact in [contact1, contact2, contact3]:
assert contact.archived is False
assert contact.archived_reason is None
assert contact.archived_on is None
# run task twice expecting same result
for _ in range(2):
automatic_contact_archive(limit=200)
contact1.refresh_from_db()
contact2.refresh_from_db()
contact3.refresh_from_db()
assert contact1.archived is False
assert contact2.archived is True
assert contact3.archived is True
assert contact1.archived_reason is None
assert contact2.archived_reason is not None
assert contact3.archived_reason is not None
assert contact1.archived_on is None
assert contact2.archived_on == date
assert contact3.archived_on == date
# run again at later time expecting no changes
automatic_contact_archive(limit=200)
contact1.refresh_from_db()
contact2.refresh_from_db()
contact3.refresh_from_db()
assert contact1.archived is False
assert contact2.archived is True
assert contact3.archived is True
assert contact1.archived_reason is None
assert contact2.archived_reason is not None
assert contact3.archived_reason is not None
assert contact1.archived_on is None
assert contact2.archived_on == date
assert contact3.archived_on == date
def test_job_schedules_with_correct_contact_archive_details(self):
actual_job = schedule_automatic_contact_archive(limit=1000, simulate=True)
assert actual_job is not None
assert actual_job._func_name == 'datahub.company.tasks.contact.automatic_contact_archive'
assert actual_job._args == (1000, True)
assert actual_job.retries_left == 3
assert actual_job.origin == 'long-running'
@pytest.fixture
def test_files():
files = [
f'FILE_A/{uuid.uuid4()}/full_ingestion.jsonl',
f'FILE_B/{uuid.uuid4()}/full_ingestion.jsonl',
f'FILE_C/{uuid.uuid4()}/full_ingestion.jsonl',
]
return list(map(lambda x: CONSENT_PREFIX + x, files))
@mock_aws
def setup_s3_bucket(bucket_name, test_files):
mock_s3_client = _create_bucket(bucket_name)
last_modfied = datetime.datetime.now()
for file in test_files:
# use freeze_time to allow uploaded files to have a different LastModified date
with freeze_time(last_modfied):
mock_s3_client.put_object(
Bucket=bucket_name,
Key=file,
Body=json.dumps('Test contents'),
)
last_modfied = last_modfied + datetime.timedelta(seconds=3)
def _create_bucket(bucket_name):
mock_s3_client = boto3.client('s3', REGION)
mock_s3_client.create_bucket(
Bucket=bucket_name,
CreateBucketConfiguration={'LocationConstraint': REGION},
)
return mock_s3_client
@mock_aws
def upload_file_to_s3(bucket_name, file_key, contents):
mock_s3_client = _create_bucket(bucket_name)
mock_s3_client.put_object(Bucket=bucket_name, Key=file_key, Body=contents)
@pytest.mark.django_db
class TestContactConsentIngestionTaskScheduler:
@pytest.mark.parametrize(
'lock_acquired, call_count',
(
(False, 0),
(True, 1),
),
)
def test_lock(
self,
monkeypatch,
lock_acquired,
call_count,
):
"""
Test that the task doesn't run if it cannot acquire the advisory_lock
"""
mock_advisory_lock = mock.MagicMock()
mock_advisory_lock.return_value.__enter__.return_value = lock_acquired
monkeypatch.setattr(
'datahub.company.tasks.contact.advisory_lock',
mock_advisory_lock,
)
mock_ingest_contact_consent_data = mock.Mock()
monkeypatch.setattr(
'datahub.company.tasks.contact.ContactConsentIngestionTask.ingest',
mock_ingest_contact_consent_data,
)
ingest_contact_consent_data()
assert mock_ingest_contact_consent_data.call_count == call_count
@pytest.mark.django_db
class TestContactConsentIngestionTask:
FROZEN_TIME = datetime.datetime(2024, 6, 1, 2, tzinfo=timezone.utc)
@mock_aws
@override_settings(S3_LOCAL_ENDPOINT_URL=None)
def test_ingest_with_exception_logs_error_and_reraises_original_exception(self, test_files):
"""
Test that the task can catch and log any unhandled exceptions
"""
setup_s3_bucket(BUCKET, test_files)
with mock.patch.object(
ContactConsentIngestionTask,
'sync_file_with_database',
side_effect=AttributeError('Original error message'),
), pytest.raises(AttributeError, match='Original error message'):
task = ContactConsentIngestionTask()
task.ingest()
@mock_aws
def test_ingest_with_empty_s3_bucket_does_not_call_sync(self):
"""
Test that the task can handle an empty S3 bucket
"""
setup_s3_bucket(BUCKET, [])
task = ContactConsentIngestionTask()
with mock.patch.multiple(
task,
sync_file_with_database=mock.DEFAULT,
):
task.ingest()
task.sync_file_with_database.assert_not_called()
@mock_aws
@override_settings(S3_LOCAL_ENDPOINT_URL=None)
def test_ingest_calls_sync_with_newest_file_order(self, test_files):
"""
Test that the ingest calls the sync with the files in correct order
"""
setup_s3_bucket(BUCKET, test_files)
task = ContactConsentIngestionTask()
with mock.patch.multiple(
task,
sync_file_with_database=mock.DEFAULT,
):
task.ingest()
task.sync_file_with_database.assert_called_once_with(
mock.ANY,
test_files[-1],
)
@mock_aws
def test_sync_file_without_contacts_stops_job_processing(self):
"""
Test when no contacts are found, the function doesn't continue
"""
filename = f'{CONSENT_PREFIX}file_{uuid.uuid4()}.jsonl'
assert (
ContactConsentIngestionTask().sync_file_with_database(
boto3.client('s3', REGION),
filename,
)
is None
)
@mock_aws
def test_sync_file_with_row_without_email_key(self):
"""
Test when a row is processed that has no email key it is skipped
"""
contact = ContactFactory()
row = {'consents': 'A'}
filename = f'{CONSENT_PREFIX}file_{uuid.uuid4()}.jsonl'
upload_file_to_s3(BUCKET, filename, json.dumps(row))
ContactConsentIngestionTask().sync_file_with_database(boto3.client('s3', REGION), filename)
assert Contact.objects.filter(id=contact.id).first().consent_data is None
@mock_aws
def test_sync_file_with_row_with_email_key_that_is_blank(self):
"""
Test when a row is processed that has no an email key that contains a blank string it
is skipped
"""
contact = ContactFactory()
file_row = {'email': '', 'consents': 'A'}
filename = f'{CONSENT_PREFIX}file_{uuid.uuid4()}.jsonl'
upload_file_to_s3(BUCKET, filename, json.dumps(file_row))
ContactConsentIngestionTask().sync_file_with_database(boto3.client('s3', REGION), filename)
assert Contact.objects.filter(id=contact.id).first().consent_data is None
@mock_aws
def test_sync_file_with_row_without_consents_key(self):
"""
Test when a row is processed that has no consents key it is skipped
"""
contact = ContactFactory()
file_row = {'email': contact.email}
filename = f'{CONSENT_PREFIX}file_{uuid.uuid4()}.jsonl'
upload_file_to_s3(BUCKET, filename, json.dumps(file_row))
ContactConsentIngestionTask().sync_file_with_database(boto3.client('s3', REGION), filename)
assert Contact.objects.filter(id=contact.id).first().consent_data is None
@mock_aws
@override_settings(ENABLE_CONTACT_CONSENT_INGEST=True)
def test_sync_file_without_matching_email_does_not_update_contact(self):
"""
Test when a row has an email that does not match a contact no changes are made
"""
file_row = {
'email': 'not_matching@bar.com',
'consents': [{'consent_domain': 'Domestic', 'email_contact_consent': True}],
}
filename = f'{CONSENT_PREFIX}file_{uuid.uuid4()}.jsonl'
upload_file_to_s3(BUCKET, filename, json.dumps(file_row))
contact = ContactFactory(consent_data='A')
task = ContactConsentIngestionTask()
task.sync_file_with_database(boto3.client('s3', REGION), filename)
assert Contact.objects.filter(id=contact.id).first().consent_data == 'A'
assert Contact.objects.filter(email='not_matching@bar.com').first() is None
@mock_aws
@override_settings(ENABLE_CONTACT_CONSENT_INGEST=True)
def test_sync_file_with_matching_email_without_loaded_contacts_does_not_update_contact(self):
"""
Test when a row has an email that has a key in the contacts grouped dictionary, but not
any contacts on the value, no changes are made
"""
filename = f'{CONSENT_PREFIX}file_{uuid.uuid4()}.jsonl'
contact = ContactFactory(consent_data='A')
file_row = {
'email': contact.email,
'consents': [{'consent_domain': 'Domestic', 'email_contact_consent': True}],
}
upload_file_to_s3(BUCKET, filename, json.dumps(file_row))
with mock.patch.object(
ContactConsentIngestionTask,
'get_grouped_contacts',
return_value={contact.email: []},
):
task = ContactConsentIngestionTask()
task.sync_file_with_database(boto3.client('s3', REGION), filename)
assert Contact.objects.filter(id=contact.id).first().consent_data == 'A'
assert Contact.objects.filter(email='not_matching@bar.com').first() is None
@mock_aws
@override_settings(ENABLE_CONTACT_CONSENT_INGEST=True)
def test_sync_file_with_matching_email_but_fails_contact_check_does_not_update_contact(
self,
):
"""
Test when a row has an email that matches a contact, but doesn't pass the check on
whether the contact should be updated
"""
contact = ContactFactory(
consent_data='A',
)
file_row = {
'email': contact.email,
'consents': {'consent': True},
}
filename = f'{CONSENT_PREFIX}file_{uuid.uuid4()}.jsonl'
upload_file_to_s3(BUCKET, filename, json.dumps(file_row))
task = ContactConsentIngestionTask()
with mock.patch.multiple(
task,
should_update_contact=mock.MagicMock(
return_value=False,
),
):
task.sync_file_with_database(boto3.client('s3', REGION), filename)
assert Contact.objects.filter(id=contact.id).first().consent_data == 'A'
@mock_aws
@override_settings(ENABLE_CONTACT_CONSENT_INGEST=True)
def test_sync_file_with_matching_email_and_passes_contact_check_does_update_contact(
self,
):
"""
Test when a row has an email that matches a contact, and passes the check on
whether the contact should be updated, the contact is updated
"""
contact = ContactFactory(consent_data='A', consent_data_last_modified=None)
file_row = {
'email': contact.email,
'consents': {'consent': True},
'last_modified': '2023-07-20T12:00:00',
}
filename = f'{CONSENT_PREFIX}file_{uuid.uuid4()}.jsonl'
upload_file_to_s3(BUCKET, filename, json.dumps(file_row))
task = ContactConsentIngestionTask()
with mock.patch.multiple(
task,
should_update_contact=mock.MagicMock(
return_value=True,
),
):
task.sync_file_with_database(boto3.client('s3', REGION), filename)
matching_contact = Contact.objects.filter(id=contact.id).first()
assert matching_contact is not None
assert matching_contact.consent_data == {'consent': True}
assert matching_contact.consent_data_last_modified is not None
@mock_aws
@freeze_time(FROZEN_TIME)
@override_settings(ENABLE_CONTACT_CONSENT_INGEST=True)
def test_sync_file_with_multiple_contacts_matching_email_does_update_contact(self):
"""
Test when a row has an email that matches multiple contacts all contacts are updated
"""
test_email = 'duplicate@test.com'
ContactFactory.create()
ContactFactory.create_batch(
3,
email=test_email,
consent_data='A',
consent_data_last_modified='2023-07-20T12:00:00',
)
file_row = {
'email': test_email,
'last_modified': None,
'consents': {'consent': True},
}
filename = f'{CONSENT_PREFIX}file_{uuid.uuid4()}.jsonl'
upload_file_to_s3(BUCKET, filename, json.dumps(file_row))
task = ContactConsentIngestionTask()
task.sync_file_with_database(boto3.client('s3', REGION), filename)
for contact in Contact.objects.filter(email=test_email):
assert contact.consent_data == {'consent': True}
assert contact.consent_data_last_modified == self.FROZEN_TIME
@mock_aws
@override_settings(ENABLE_CONTACT_CONSENT_INGEST=False)
def test_sync_file_with_matching_email_but_ingest_setting_false_does_not_update_contact(self):
"""
Test when a row has an email that matches a contact but the ENABLE_CONTACT_CONSENT_INGEST
setting is false the contact is not updated
"""
contact = ContactFactory(
consent_data='A',
)
file_row = {
'email': contact.email,
'consents': {'consent': True},
}
filename = f'{CONSENT_PREFIX}file_{uuid.uuid4()}.jsonl'
upload_file_to_s3(BUCKET, filename, json.dumps(file_row))
task = ContactConsentIngestionTask()
with mock.patch.multiple(
task,
should_update_contact=mock.MagicMock(
return_value=True,
),
):
task.sync_file_with_database(boto3.client('s3', REGION), filename)
assert Contact.objects.filter(id=contact.id).first().consent_data == 'A'
def test_get_grouped_contacts_returns_empty_dict_when_no_contacts(self):
"""
Test when no contacts are present an empty dictionary is returned
"""
assert ContactConsentIngestionTask().get_grouped_contacts() == {}
def test_get_grouped_contacts_returns_unique_contacts_with_different_emails(self):
"""
Test when contacts with a unique email are present, the dictionary returns 1 row per
unique email with only the contacts matching that email as the value
"""
contact1 = ContactFactory.create(email='unique1@test.com')
contact2 = ContactFactory.create(email='unique2@test.com')
assert ContactConsentIngestionTask().get_grouped_contacts() == {
'unique1@test.com': [contact1],
'unique2@test.com': [contact2],
}
def test_get_grouped_contacts_returns_grouped_contacts_with_same_email(self):
"""
Test when contacts with a duplicate emails are present, the dictionary returns a row with
the duplicate email as the key and all contacts matching that email as the value
"""
contacts = ContactFactory.create_batch(3, email='grouped@test.com')
assert ContactConsentIngestionTask().get_grouped_contacts() == {
'grouped@test.com': contacts,
}
def test_should_update_contact_with_row_date_missing_should_return_true(
self,
):
"""
Test when a row has an email that matches a contact, but the file has missing date,
returns True
"""
task = ContactConsentIngestionTask()
contact = ContactFactory.create(consent_data_last_modified=datetime.datetime.now())
row = {
'email': 'a',
'last_modified': None,
'consents': {'consent': True},
}
assert task.should_update_contact(
contact,
row,
)
def test_should_update_contact_with_contact_date_missing_should_return_true(
self,
):
"""
Test when a row has an email that matches a contact, but the contact has missing date,
returns True
"""
task = ContactConsentIngestionTask()
contact = ContactFactory.create(consent_data_last_modified=None)
row = {
'email': 'a',
'last_modified': '2023-07-20T12:00:00',
'consents': {'consent': True},
}
assert task.should_update_contact(
contact,
row,
)
def test_should_update_contact_with_row_date_older_contact_date_should_return_false(
self,
):
"""
Test when a row has an email that matches a contact, but the file has an older modified
date, returns False
"""
task = ContactConsentIngestionTask()
contact = ContactFactory.create(
consent_data_last_modified=datetime.datetime.fromisoformat('2024-08-02T12:00:00'),
)
row = {
'email': 'a',
'last_modified': '2023-07-20T12:00:00',
'consents': {'consent': True},
}
assert (
task.should_update_contact(
contact,
row,
)
is False
)
def test_should_update_contact_with_row_date_newer_than_contact_date_should_return_true(
self,
):
"""
Test when a row has an email that matches a contact, but the file has an newer modified
date, returns True
"""
task = ContactConsentIngestionTask()
contact = ContactFactory.create(
consent_data_last_modified=datetime.datetime.fromisoformat('2023-07-20T12:00:00'),
)
row = {
'email': 'a',
'last_modified': '2024-08-02T12:00:00',
'consents': {'consent': True},
}
assert task.should_update_contact(
contact,
row,
)