From c66f58abc6233aec883d75b9bcac64e0a32aec8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Chlo=C3=A9?= Date: Wed, 6 Nov 2024 18:14:23 +0100 Subject: [PATCH] tests --- .../commands/crm_brevo_sync_companies.py | 9 +-- lemarche/crm/tests.py | 62 ++++++++++++------- lemarche/siaes/models.py | 50 +++++---------- 3 files changed, 57 insertions(+), 64 deletions(-) diff --git a/lemarche/crm/management/commands/crm_brevo_sync_companies.py b/lemarche/crm/management/commands/crm_brevo_sync_companies.py index 0418c6d2a..d35b7d2bf 100644 --- a/lemarche/crm/management/commands/crm_brevo_sync_companies.py +++ b/lemarche/crm/management/commands/crm_brevo_sync_companies.py @@ -39,24 +39,19 @@ def handle(self, recently_updated: bool, **options): # Step 2: loop on the siaes for index, siae in enumerate(siaes_qs): - recent_tender_detail_click_count = siae.tendersiae_set.filter( - detail_contact_click_date__gte=timezone.now() - timedelta(days=90) - ).count() - print("HANDLE : old siae.extra_data", siae.extra_data) new_extra_data = { "completion_rate": siae.completion_rate, "tender_email_send_count": siae.tender_email_send_count, - "recent_tender_detail_click_count": recent_tender_detail_click_count, + "recent_tender_detail_click_count": siae.recent_tender_detail_click_count, } - print("HANDLE : new siae.extra_data", new_extra_data) - if siae.extra_data != new_extra_data: siae.extra_data = new_extra_data siae.save(update_fields=["extra_data"]) + print("HANDLE : new siae.extra_data", siae.extra_data) api_brevo.create_or_update_company(siae) if (index % 10) == 0: # avoid API rate-limiting time.sleep(1) diff --git a/lemarche/crm/tests.py b/lemarche/crm/tests.py index 2f7bc8c4d..90449a84d 100644 --- a/lemarche/crm/tests.py +++ b/lemarche/crm/tests.py @@ -1,16 +1,12 @@ -from datetime import timedelta +from unittest.mock import MagicMock, patch from django.core.management import call_command from django.test import TestCase -from django.utils import timezone from lemarche.siaes.factories import SiaeFactory -from lemarche.users.factories import UserFactory from lemarche.utils.apis.api_brevo import create_or_update_company from lemarche.utils.urls import get_object_admin_url, get_object_share_url -from unittest.mock import patch, MagicMock - class CrmBrevoSyncCompaniesCommandTest(TestCase): @patch("lemarche.utils.apis.api_brevo.sib_api_v3_sdk.Body") @@ -46,49 +42,67 @@ def test_create_or_update_company_with_mocked_body(self, mock_body): mock_body.assert_called_once_with(name="Test Company", attributes=expected_attributes) - @patch('lemarche.utils.apis.api_brevo.create_or_update_company') + @patch("lemarche.utils.apis.api_brevo.create_or_update_company") def test_new_siaes_are_synced_in_brevo(self, mock_create_or_update_company): - """ Test new siaes are synced in brevo """ + """Test new siaes are synced in brevo""" siae1 = SiaeFactory() siae2 = SiaeFactory() - call_command('crm_brevo_sync_companies') + call_command("crm_brevo_sync_companies") mock_create_or_update_company.assert_any_call(siae1) mock_create_or_update_company.assert_any_call(siae2) self.assertEqual(mock_create_or_update_company.call_count, 2) - @patch('lemarche.utils.apis.api_brevo.create_or_update_company') + @patch("lemarche.utils.apis.api_brevo.create_or_update_company") def test_siae_sync_even_if_extra_data_unchanged(self, mock_create_or_update_company): """Test siae is not updated if extra_data is unchanged.""" siae = SiaeFactory(brevo_company_id="12345") - call_command('crm_brevo_sync_companies', recently_updated=True) + call_command("crm_brevo_sync_companies", recently_updated=True) mock_create_or_update_company.assert_called_once_with(siae) - @patch('lemarche.utils.apis.api_brevo.create_or_update_company') - def test_extra_data_is_updated(self, mock_create_or_update_company): + @patch("lemarche.utils.apis.api_brevo.create_or_update_company") + def test_siae_extra_data_is_updated(self, mock_create_or_update_company): """Test siae is updated if extra_data is changed.""" siae = SiaeFactory(brevo_company_id="12345") siae.save() - print("old siae.extra_data", siae.extra_data) - siae.completion_rate = 75 - siae.tender_email_send_count = 20 - siae.save() + initial_extra_data = siae.extra_data.copy() - print("TEST : new siae.extra_data", siae.extra_data) + siae.completion_rate = 70 + siae.tender_email_send_count = 10 + siae.save() - call_command('crm_brevo_sync_companies', recently_updated=True) + call_command("crm_brevo_sync_companies", recently_updated=True) self.assertTrue(mock_create_or_update_company.called) - new_extra_data = { - "completion_rate": 75, - "tender_email_send_count": 20, - "recent_tender_detail_click_count": 0, + siae.refresh_from_db() + expected_extra_data = { + "completion_rate": siae.completion_rate, + "tender_email_send_count": siae.tender_email_send_count, + "recent_tender_detail_click_count": siae.recent_tender_detail_click_count, } - print("TEST : new_extra_data", new_extra_data) + + self.assertNotEqual(initial_extra_data, expected_extra_data, "siae.extra_data aurait dût être mis à jour.") + + @patch("lemarche.utils.apis.api_brevo.create_or_update_company") + def test_siae_extra_data_is_not_updated_if_no_change(self, mock_create_or_update_company): + """Test siae is not updated if no change in extra_data.""" + siae = SiaeFactory(brevo_company_id="12345") + siae.save() + + initial_extra_data = siae.extra_data.copy() + + call_command("crm_brevo_sync_companies", recently_updated=True) + + self.assertTrue(mock_create_or_update_company.called) + siae.refresh_from_db() - self.assertEqual(siae.extra_data, new_extra_data) + self.assertEqual( + initial_extra_data, + siae.extra_data, + "siae.extra_data a été mis à jour alors qu'il n'y avait pas de changement.", + ) diff --git a/lemarche/siaes/models.py b/lemarche/siaes/models.py index e9a8e7c81..f7611ceae 100644 --- a/lemarche/siaes/models.py +++ b/lemarche/siaes/models.py @@ -1,5 +1,4 @@ from datetime import timedelta - from uuid import uuid4 from django.conf import settings @@ -969,6 +968,14 @@ def __init__(self, *args, **kwargs): for field_name in self.TRACK_UPDATE_FIELDS: setattr(self, f"__previous_{field_name}", getattr(self, field_name)) + # siae.extra_data tracked for updates in brevo sync command + if not self.extra_data: + self.extra_data = { + "completion_rate": self.completion_rate, + "tender_email_send_count": self.tender_email_send_count, + "recent_tender_detail_click_count": self.recent_tender_detail_click_count, + } + def set_slug(self, with_uuid=False): """ The slug field should be unique. @@ -1028,6 +1035,7 @@ def save(self, *args, **kwargs): self.set_last_updated_fields() self.set_related_counts() self.set_content_fill_dates() + try: self.set_slug() with transaction.atomic(): @@ -1296,6 +1304,13 @@ def elasticsearch_index_metadata(self): return metadata + @property + def recent_tender_detail_click_count(self): + """Calcule le nombre de clics récents pour cette instance de Siae.""" + if not self.pk: + return 0 + return self.tendersiae_set.filter(detail_contact_click_date__gte=timezone.now() - timedelta(days=90)).count() + def sectors_list_string(self, display_max=3): sectors_name_list = self.sectors.form_filter_queryset().values_list("name", flat=True) if display_max and len(sectors_name_list) > display_max: @@ -1350,38 +1365,7 @@ def set_super_badge(self): @receiver(post_save, sender=Siae) -def siae_post_save(sender, instance, created, **kwargs): - if created: - instance.extra_data = { - "completion_rate": instance.completion_rate, - "tender_email_send_count": instance.tender_email_send_count, - "recent_tender_detail_click_count": instance.tendersiae_set.filter( - detail_contact_click_date__gte=timezone.now() - timedelta(days=90) - ).count(), # Calculer le nombre de clics récents - } - instance.save(update_fields=["extra_data"]) # Sauvegarder pour initialiser extra_data - else: - # Récupérer l'instance précédente pour comparer les valeurs - previous_instance = Siae.objects.get(pk=instance.pk) - - # Compter le nombre de clics récents pour l'instance actuelle - new_recent_tender_detail_click_count = instance.tendersiae_set.filter( - detail_contact_click_date__gte=timezone.now() - timedelta(days=90) - ).count() - - # Comparer les valeurs pour voir si l'un des attributs a changé - if (instance.completion_rate != previous_instance.completion_rate or - instance.tender_email_send_count != previous_instance.tender_email_send_count or - new_recent_tender_detail_click_count != previous_instance.extra_data.get('recent_tender_detail_click_count', 0)): - - # Mettre à jour extra_data - instance.extra_data = { - "completion_rate": instance.completion_rate, - "tender_email_send_count": instance.tender_email_send_count, - "recent_tender_detail_click_count": new_recent_tender_detail_click_count, - } - instance.save(update_fields=["extra_data"]) - +def siae_post_save(sender, instance, **kwargs): field_name = "address" previous_field_name = f"__previous_{field_name}" if getattr(instance, field_name) and getattr(instance, field_name) != getattr(instance, previous_field_name):