from unittest import mock import faker import pytest from anydi import Container from preference_center.profile.dispatcher import ProfileDispatcher from preference_center.profile.handlers import ( UnsubscribeAllByEmailHandler, UnsubscribeAllByEmailRequest, ) from preference_center.profile.models import ( Profile, Subscription, ) from tests.unit.types import CreateModel class TestUnsubscribeAllByEmailHandler: @pytest.mark.db def test_unsubscribe_all_by_email( self, container: Container, handler: UnsubscribeAllByEmailHandler, create_model: CreateModel, faker: faker.Faker, ) -> None: profile = create_model(Profile) email_campaign_id = faker.uuid4() subscription_2 = create_model( Subscription, profile_id=profile.id, is_active=True, ) dispatcher_mock = mock.MagicMock(spec=ProfileDispatcher) with container.override(ProfileDispatcher, dispatcher_mock): handler.handle( UnsubscribeAllByEmailRequest( email=profile.email, origin_id=email_campaign_id, origin_type="EMAIL_CAMPAIGN", automated_email_trigger_id=None, ) ) assert not subscription_2.is_active dispatcher_mock.dispatch_subscriptions_updated.assert_called_once_with( profile, subscriptions=[subscription_2], origin_id=email_campaign_id, origin_type="EMAIL_CAMPAIGN", automated_email_trigger_id=None, ) @pytest.mark.db def test_unsubscribe_all_by_email_no_changes( self, container: Container, handler: UnsubscribeAllByEmailHandler, create_model: CreateModel, faker: faker.Faker, ) -> None: profile = create_model(Profile) email_campaign_id = faker.uuid4() subscription_1 = create_model( Subscription, profile_id=profile.id, is_active=False, ) subscription_2 = create_model( Subscription, profile_id=profile.id, is_active=False, ) dispatcher_mock = mock.MagicMock(spec=ProfileDispatcher) with container.override(ProfileDispatcher, dispatcher_mock): handler.handle( UnsubscribeAllByEmailRequest( email=profile.email, origin_id=email_campaign_id, origin_type="EMAIL_CAMPAIGN", automated_email_trigger_id=None, ) ) assert not subscription_1.is_active assert not subscription_2.is_active dispatcher_mock.dispatch_subscriptions_updated.assert_not_called()