diff --git a/README.md b/README.md index ff58f73..3c86384 100644 --- a/README.md +++ b/README.md @@ -256,6 +256,9 @@ The same situation applies to both `client.batch_send()` and `client.sending_api ### Email Campaigns API: - Email Campaigns (list, create, get, update, delete, lifecycle actions, stats) – [`email_campaigns/email_campaigns.py`](examples/email_campaigns/email_campaigns.py) +### Subscription Topics API: +- Subscription Topics (list & get) – [`subscription_topics/subscription_topics.py`](examples/subscription_topics/subscription_topics.py) + ### Webhooks API: - Webhooks management – [`webhooks/webhooks.py`](examples/webhooks/webhooks.py) - Verifying webhook signatures – [`webhooks/verify_signature.py`](examples/webhooks/verify_signature.py) diff --git a/examples/contacts/contact_imports.py b/examples/contacts/contact_imports.py index c5c7c73..d5c7a85 100644 --- a/examples/contacts/contact_imports.py +++ b/examples/contacts/contact_imports.py @@ -1,4 +1,5 @@ import os +from typing import Optional import mailtrap as mt from mailtrap.models.contacts import ContactImport @@ -14,16 +15,45 @@ def import_contacts(contacts: list[mt.ImportContactParams]) -> ContactImport: return contact_imports_api.import_contacts(contacts=contacts) +def find_topic_preference() -> Optional[mt.ContactSubscriptionTopic]: + # The first subscription topic, on its sending domain or, for a topic that + # covers every domain, on the first non-demo one. The topics list answers 403 when + # the account has no subscription topics. + try: + topics = client.subscription_topics_api.subscription_topics.get_list().data + except mt.APIError as error: + if error.status == 403: + return None + raise + if not topics: + return None + domain_id = topics[0].domain_id + if domain_id is None: + # Skip demo domains: the API doesn't take topic preferences on the + # inbound replies one. + domain_id = next( + (d.id for d in client.domains_api.domains.get_list() if not d.demo), None + ) + if domain_id is None: + return None + return mt.ContactSubscriptionTopic( + subscription_topic_id=topics[0].id, domain_id=domain_id, status="unsubscribed" + ) + + def get_contact_import(import_id: int) -> ContactImport: return contact_imports_api.get_by_id(import_id) if __name__ == "__main__": + preference = find_topic_preference() contact_import = import_contacts( contacts=[ mt.ImportContactParams( email="testemail@test.com", fields={"first_name": "Test", "last_name": "Test"}, + # Left out of the request when None. + subscription_topics=[preference] if preference else None, ) ] ) diff --git a/examples/contacts/contacts.py b/examples/contacts/contacts.py index c899f19..2937078 100644 --- a/examples/contacts/contacts.py +++ b/examples/contacts/contacts.py @@ -1,4 +1,5 @@ import os +from dataclasses import replace from typing import Optional from typing import Union @@ -33,13 +34,17 @@ def update_contact( list_ids_included: Optional[list[int]] = None, list_ids_excluded: Optional[list[int]] = None, unsubscribed: Optional[bool] = None, + subscription_topics: Optional[list[mt.ContactSubscriptionTopic]] = None, ) -> Contact: + # Only the topic and domain pairs in `subscription_topics` change; the + # contact's other topic preferences keep their status. params = mt.UpdateContactParams( email=new_email, fields=fields, list_ids_included=list_ids_included, list_ids_excluded=list_ids_excluded, unsubscribed=unsubscribed, + subscription_topics=subscription_topics, ) return contacts_api.update(contact_id_or_email, params) @@ -74,5 +79,15 @@ def delete_contact(contact_id_or_email: str) -> DeletedObject: contact = get_contact(updated_contact.id) print(contact) + # The contact's status for every subscription topic on every sending + # domain; None when the account has no subscription topics. + if contact.subscription_topics: + preference = contact.subscription_topics[0] + unsubscribed_contact = update_contact( + contact.id, + subscription_topics=[replace(preference, status="unsubscribed")], + ) + print(unsubscribed_contact.subscription_topics) + deleted_contact = delete_contact(updated_contact.id) print(deleted_contact) diff --git a/examples/email_campaigns/email_campaigns.py b/examples/email_campaigns/email_campaigns.py index c61a2f1..20ab5ce 100644 --- a/examples/email_campaigns/email_campaigns.py +++ b/examples/email_campaigns/email_campaigns.py @@ -1,6 +1,7 @@ from datetime import datetime from datetime import timedelta from datetime import timezone +from typing import Optional import mailtrap as mt from mailtrap.models.common import DeletedObject @@ -29,10 +30,34 @@ def get_email_campaign(email_campaign_id: int) -> EmailCampaign: return email_campaigns_api.get_by_id(email_campaign_id=email_campaign_id) +def find_subscription_topic_id(domain_id: int) -> Optional[int]: + # A topic covers the campaign's domain when its `domain_id` is that domain + # or None (every domain). The list is paginated, so follow `next_token` + # (with the same `per_page`) until a match turns up. It answers 403 when + # the account has no subscription topics. + topics_api = client.subscription_topics_api.subscription_topics + token: Optional[int] = None + while True: + try: + page = topics_api.get_list( + mt.SubscriptionTopicListParams(per_page=100, token=token) + ) + except mt.APIError as error: + if error.status == 403: + return None + raise + for topic in page.data: + if topic.domain_id in (None, domain_id): + return topic.id + if page.pagination is None or page.pagination.next_token is None: + return None + token = page.pagination.next_token + + def create_email_campaign() -> EmailCampaign: # A campaign is created in the `draft` state and must reference a verified # sending domain via `domain_id` (as returned by the Sending Domains - # endpoints). + # endpoints). `subscription_topic_id` is left out of the request when None. return email_campaigns_api.create( mt.CreateEmailCampaignParams( name="Spring Sale", @@ -47,6 +72,7 @@ def create_email_campaign() -> EmailCampaign: template_attributes=mt.CreateEmailCampaignTemplateAttributes( subject="Spring is here — 30% off" ), + subscription_topic_id=find_subscription_topic_id(DOMAIN_ID), ) ) diff --git a/examples/email_logs/email_logs.py b/examples/email_logs/email_logs.py index fc95af3..130f92b 100644 --- a/examples/email_logs/email_logs.py +++ b/examples/email_logs/email_logs.py @@ -61,3 +61,7 @@ def get_message(message_id: str): if response.messages: detail = get_message(response.messages[0].message_id) print(f"Detail: {detail.subject}, events: {len(detail.events)}") + for event in detail.events: + # topic_unsubscribe and topic_resubscribe events carry the + # subscription_topic_id in their details. + print(f" {event.created_at} {event.event_type}: {event.details}") diff --git a/examples/subscription_topics/subscription_topics.py b/examples/subscription_topics/subscription_topics.py new file mode 100644 index 0000000..5131c4a --- /dev/null +++ b/examples/subscription_topics/subscription_topics.py @@ -0,0 +1,46 @@ +import os +from typing import Optional + +import mailtrap as mt +from mailtrap.models.subscription_topics import SubscriptionTopic +from mailtrap.models.subscription_topics import SubscriptionTopicListResponse + +API_KEY = os.environ["MAILTRAP_API_KEY"] + +client = mt.MailtrapClient(token=API_KEY) +subscription_topics_api = client.subscription_topics_api.subscription_topics + + +def list_subscription_topics( + token: Optional[int] = None, +) -> SubscriptionTopicListResponse: + # `token` is the page number (page-token pagination); `per_page` caps at + # 100 (default 50). Deleted topics are left out. + return subscription_topics_api.get_list( + mt.SubscriptionTopicListParams(per_page=50, token=token) + ) + + +def get_subscription_topic(subscription_topic_id: int) -> SubscriptionTopic: + # A deleted topic is returned too, with `deleted_at` set. + return subscription_topics_api.get_by_id(subscription_topic_id) + + +if __name__ == "__main__": + try: + page = list_subscription_topics() + except mt.APIError as error: + if error.status != 403: + raise + raise SystemExit("Subscription topics aren't available for this account.") + + while True: + for topic in page.data: + # `domain_id` is None when the topic covers every sending domain. + print(f"{topic.id}: {topic.name} (domain: {topic.domain_id or 'all'})") + if page.pagination is None or page.pagination.next_token is None: + break + page = list_subscription_topics(token=page.pagination.next_token) + + if page.data: + print(get_subscription_topic(page.data[0].id)) diff --git a/examples/suppressions/suppressions.py b/examples/suppressions/suppressions.py index faee550..a4418ed 100644 --- a/examples/suppressions/suppressions.py +++ b/examples/suppressions/suppressions.py @@ -11,8 +11,14 @@ suppressions_api = client.suppressions_api.suppressions -def list_suppressions(email: Optional[str] = None) -> list[Suppression]: - return suppressions_api.get_list(email) +def list_suppressions( + email: Optional[str] = None, include_topic_unsubscriptions: bool = False +) -> list[Suppression]: + # With `include_topic_unsubscriptions`, the list also has unsubscribes from + # single subscription topics, of type "topic unsubscription". + return suppressions_api.get_list( + email, include_topic_unsubscriptions=include_topic_unsubscriptions + ) def create_suppression() -> Suppression: @@ -37,3 +43,11 @@ def delete_suppression(suppression_id: str) -> Suppression: if suppressions: deleted_suppression = delete_suppression(suppressions[0].id) print(deleted_suppression) + + # A topic unsubscription can't be deleted, so only print them. + for suppression in list_suppressions(include_topic_unsubscriptions=True): + if suppression.type == "topic unsubscription": + print( + f"{suppression.email} left topic {suppression.subscription_topic_id}" + f" on {suppression.domain_name}" + ) diff --git a/examples/webhooks/webhooks.py b/examples/webhooks/webhooks.py index e7029d3..8f852bc 100644 --- a/examples/webhooks/webhooks.py +++ b/examples/webhooks/webhooks.py @@ -33,6 +33,20 @@ def create_webhook() -> WebhookWithSecret: ) +def create_bulk_webhook() -> WebhookWithSecret: + # `subscription_preferences_update` is sent when a contact changes their + # subscription topic preferences. It is available only for the bulk stream + # and on `campaigns` webhooks. + return webhooks_api.create( + mt.CreateWebhookParams( + url="https://example.com/mailtrap/webhooks", + webhook_type="email_sending", + sending_stream="bulk", + event_types=["delivery", "unsubscribe", "subscription_preferences_update"], + ) + ) + + def update_webhook(webhook_id: int) -> Webhook: return webhooks_api.update( webhook_id=webhook_id, diff --git a/mailtrap/__init__.py b/mailtrap/__init__.py index 8c246e9..ccb4031 100644 --- a/mailtrap/__init__.py +++ b/mailtrap/__init__.py @@ -16,6 +16,7 @@ from .models.contacts import ContactEventParams from .models.contacts import ContactExportFilter from .models.contacts import ContactListParams +from .models.contacts import ContactSubscriptionTopic from .models.contacts import CreateContactExportParams from .models.contacts import CreateContactFieldParams from .models.contacts import CreateContactParams @@ -78,6 +79,9 @@ from .models.sending_domains import CreateSendingDomainParams from .models.sending_domains import UpdateSendingDomainParams from .models.stats import StatsFilterParams +from .models.subscription_topics import SubscriptionTopic +from .models.subscription_topics import SubscriptionTopicListParams +from .models.subscription_topics import SubscriptionTopicListResponse from .models.suppressions import CreateSuppressionParams from .models.templates import CreateEmailTemplateParams from .models.templates import UpdateEmailTemplateParams diff --git a/mailtrap/api/resources/subscription_topics.py b/mailtrap/api/resources/subscription_topics.py new file mode 100644 index 0000000..6a542ab --- /dev/null +++ b/mailtrap/api/resources/subscription_topics.py @@ -0,0 +1,44 @@ +from typing import Optional + +from mailtrap.http import HttpClient +from mailtrap.models.subscription_topics import SubscriptionTopic +from mailtrap.models.subscription_topics import SubscriptionTopicListParams +from mailtrap.models.subscription_topics import SubscriptionTopicListResponse +from mailtrap.models.subscription_topics import SubscriptionTopicResponse + + +class SubscriptionTopicsApi: + """ + Subscription Topics API. On an account without subscription topics, both + calls raise ``APIError`` with status ``403``. + """ + + def __init__(self, client: HttpClient) -> None: + self._client = client + + def get_list( + self, params: Optional[SubscriptionTopicListParams] = None + ) -> SubscriptionTopicListResponse: + """ + List the account's subscription topics, one page at a time, leaving out + deleted ones. Pass ``pagination.next_token`` with the same ``per_page`` + to get the next page. Omit ``params`` for the first page with API + defaults. + """ + query_params = params.api_query_params if params else None + response = self._client.get(self._api_path(), params=query_params or None) + return SubscriptionTopicListResponse(**response) + + def get_by_id(self, subscription_topic_id: int) -> SubscriptionTopic: + """ + Get a subscription topic by ID. A deleted topic is returned too, with + ``deleted_at`` set. + """ + response = self._client.get(self._api_path(subscription_topic_id)) + return SubscriptionTopicResponse(**response).data + + def _api_path(self, subscription_topic_id: Optional[int] = None) -> str: + path = "/api/subscription_topics" + if subscription_topic_id is not None: + return f"{path}/{subscription_topic_id}" + return path diff --git a/mailtrap/api/resources/suppressions.py b/mailtrap/api/resources/suppressions.py index d9f680e..1d0d6b8 100644 --- a/mailtrap/api/resources/suppressions.py +++ b/mailtrap/api/resources/suppressions.py @@ -11,13 +11,23 @@ def __init__(self, client: HttpClient, account_id: str) -> None: self._account_id = account_id self._client = client - def get_list(self, email: Optional[str] = None) -> list[Suppression]: + def get_list( + self, email: Optional[str] = None, include_topic_unsubscriptions: bool = False + ) -> list[Suppression]: """ List and search suppressions by email. The endpoint returns up to 1000 suppressions per request. + With `include_topic_unsubscriptions`, the list also has the contacts' + unsubscribes from single subscription topics, of type + "topic unsubscription". """ - params = {"email": email} if email is not None else None - response = self._client.get(self._api_path(), params=params) + params: dict[str, str] = {} + if email is not None: + params["email"] = email + if include_topic_unsubscriptions: + # The API opts in on the exact string "true"; requests would send "True". + params["include_topic_unsubscriptions"] = "true" + response = self._client.get(self._api_path(), params=params or None) return [Suppression(**suppression) for suppression in response] def create(self, params: CreateSuppressionParams) -> Suppression: @@ -32,6 +42,7 @@ def delete(self, suppression_id: str) -> Suppression: """ Delete a suppression by ID. Mailtrap will no longer prevent sending to this email unless it's recorded in suppressions again. + A "topic unsubscription" can't be deleted: the API returns 404. """ response = self._client.delete(self._api_path(suppression_id)) return Suppression(**response) diff --git a/mailtrap/api/subscription_topics.py b/mailtrap/api/subscription_topics.py new file mode 100644 index 0000000..ae56b27 --- /dev/null +++ b/mailtrap/api/subscription_topics.py @@ -0,0 +1,11 @@ +from mailtrap.api.resources.subscription_topics import SubscriptionTopicsApi +from mailtrap.http import HttpClient + + +class SubscriptionTopicsBaseApi: + def __init__(self, client: HttpClient) -> None: + self._client = client + + @property + def subscription_topics(self) -> SubscriptionTopicsApi: + return SubscriptionTopicsApi(client=self._client) diff --git a/mailtrap/client.py b/mailtrap/client.py index 5feb9c1..836305b 100644 --- a/mailtrap/client.py +++ b/mailtrap/client.py @@ -23,6 +23,7 @@ from mailtrap.api.sandbox import SandboxApi from mailtrap.api.sending import SendingApi from mailtrap.api.sending_domains import SendingDomainsBaseApi +from mailtrap.api.subscription_topics import SubscriptionTopicsBaseApi from mailtrap.api.suppressions import SuppressionsBaseApi from mailtrap.api.templates import EmailTemplatesApi from mailtrap.api.testing import TestingApi @@ -202,6 +203,12 @@ def marketing_stats_api(self) -> MarketingStatsBaseApi: client=HttpClient(host=GENERAL_HOST, headers=self.headers), ) + @property + def subscription_topics_api(self) -> SubscriptionTopicsBaseApi: + return SubscriptionTopicsBaseApi( + client=HttpClient(host=GENERAL_HOST, headers=self.headers), + ) + @property def email_logs_api(self) -> EmailLogsBaseApi: self._validate_account_id("Email Logs API") diff --git a/mailtrap/models/contacts.py b/mailtrap/models/contacts.py index 8bbf219..b87938d 100644 --- a/mailtrap/models/contacts.py +++ b/mailtrap/models/contacts.py @@ -50,6 +50,20 @@ class ContactList: name: str +@dataclass +class ContactSubscriptionTopic: + """ + A contact's status for one subscription topic on one sending domain. + ``status`` is ``"subscribed"`` or ``"unsubscribed"``; ``domain_id`` is the + sending domain's ID, as in the Domains API, or ``None`` when the API leaves + it out. + """ + + subscription_topic_id: int + status: str + domain_id: Optional[int] = None + + @dataclass class CreateContactParams(RequestParams): email: str @@ -57,6 +71,8 @@ class CreateContactParams(RequestParams): None # field_merge_tag: value ) list_ids: Optional[list[int]] = None + # Topic and domain pairs left out keep their status. + subscription_topics: Optional[list[ContactSubscriptionTopic]] = None @dataclass @@ -68,6 +84,8 @@ class UpdateContactParams(RequestParams): list_ids_included: Optional[list[int]] = None list_ids_excluded: Optional[list[int]] = None unsubscribed: Optional[bool] = None + # Topic and domain pairs left out keep their status. + subscription_topics: Optional[list[ContactSubscriptionTopic]] = None def __post_init__(self) -> None: if all( @@ -78,6 +96,7 @@ def __post_init__(self) -> None: self.list_ids_included, self.list_ids_excluded, self.unsubscribed, + self.subscription_topics, ] ): raise ValueError("At least one field must be provided for update action") @@ -85,6 +104,12 @@ def __post_init__(self) -> None: @dataclass class Contact: + """ + ``subscription_topics`` has the contact's status for every topic on every + sending domain. It is ``None`` both when the account has no subscription + topics and when the preferences couldn't be read (retry the request). + """ + id: str email: str fields: dict[str, Union[str, int, float, bool]] # field_merge_tag: value @@ -92,6 +117,7 @@ class Contact: status: str created_at: int updated_at: int + subscription_topics: Optional[list[ContactSubscriptionTopic]] = None @dataclass @@ -116,6 +142,7 @@ class ImportContactParams(RequestParams): ) list_ids_included: Optional[list[int]] = None list_ids_excluded: Optional[list[int]] = None + subscription_topics: Optional[list[ContactSubscriptionTopic]] = None @dataclass diff --git a/mailtrap/models/email_campaigns.py b/mailtrap/models/email_campaigns.py index bbdfffc..3af29c7 100644 --- a/mailtrap/models/email_campaigns.py +++ b/mailtrap/models/email_campaigns.py @@ -129,6 +129,7 @@ class EmailCampaign: contact_segment_ids: list[int] = Field(default_factory=list) delivery_mode: Optional[str] = None delivery_options: Optional[EmailCampaignDeliveryOptions] = None + subscription_topic_id: Optional[int] = None template: Optional[EmailCampaignTemplate] = None @@ -179,6 +180,8 @@ class CreateEmailCampaignParams(RequestParams): """ Attributes for creating an email campaign (sent as a flat JSON body). The campaign is always created in the ``draft`` state. + ``subscription_topic_id`` is the subscription topic the campaign is sent + under; it must cover the campaign's domain. """ name: str @@ -191,13 +194,15 @@ class CreateEmailCampaignParams(RequestParams): delivery_options: Optional[EmailCampaignDeliveryOptions] = None contact_list_ids: Optional[list[int]] = None contact_segment_ids: Optional[list[int]] = None + subscription_topic_id: Optional[int] = None @dataclass class UpdateEmailCampaignParams(RequestParams): """ Attributes for updating a draft email campaign (sent as a flat JSON body). - All fields are optional; only provided fields are changed. + All fields are optional; only provided fields are changed. A campaign's + ``subscription_topic_id`` can be changed but not removed. """ name: Optional[str] = None @@ -210,6 +215,7 @@ class UpdateEmailCampaignParams(RequestParams): delivery_options: Optional[EmailCampaignDeliveryOptions] = None contact_list_ids: Optional[list[int]] = None contact_segment_ids: Optional[list[int]] = None + subscription_topic_id: Optional[int] = None @dataclass diff --git a/mailtrap/models/email_logs.py b/mailtrap/models/email_logs.py index 6ffaba4..7e2da99 100644 --- a/mailtrap/models/email_logs.py +++ b/mailtrap/models/email_logs.py @@ -8,6 +8,9 @@ from pydantic import BaseModel from pydantic import ConfigDict from pydantic import Field +from pydantic import ValidationInfo +from pydantic import ValidatorFunctionWrapHandler +from pydantic import field_validator from pydantic.dataclasses import dataclass # --- Event details (for get-by-id) --- @@ -56,71 +59,65 @@ class EventDetailsReject: reject_reason: Optional[str] = None +@dataclass +class EventDetailsTopicSubscription: + """Details of a ``topic_unsubscribe`` or ``topic_resubscribe`` event.""" + + web_ip_address: Optional[str] = None + subscription_topic_id: Optional[int] = None + + +EventDetails = Union[ + EventDetailsDelivery, + EventDetailsOpen, + EventDetailsClick, + EventDetailsBounce, + EventDetailsSpam, + EventDetailsUnsubscribe, + EventDetailsReject, + EventDetailsTopicSubscription, + dict[str, Any], +] + + +_DETAILS_TYPE_BY_EVENT_TYPE: dict[str, type[Any]] = { + "delivery": EventDetailsDelivery, + "open": EventDetailsOpen, + "click": EventDetailsClick, + "soft_bounce": EventDetailsBounce, + "bounce": EventDetailsBounce, + "spam": EventDetailsSpam, + "unsubscribe": EventDetailsUnsubscribe, + "suspension": EventDetailsReject, + "reject": EventDetailsReject, + "topic_unsubscribe": EventDetailsTopicSubscription, + "topic_resubscribe": EventDetailsTopicSubscription, +} + + @dataclass class MessageEvent: - """Event attached to a message (delivery, open, click, bounce, etc.).""" + """ + Event attached to a message (delivery, open, click, bounce, etc.). + ``details`` of an event type the SDK doesn't know stay the API's dict. + """ event_type: str created_at: str - details: Optional[ - Union[ - EventDetailsDelivery, - EventDetailsOpen, - EventDetailsClick, - EventDetailsBounce, - EventDetailsSpam, - EventDetailsUnsubscribe, - EventDetailsReject, - dict[str, Any], - ] - ] = None - - -def _parse_event_details( - event_type: str, - data: Optional[dict[str, Any]], -) -> Optional[ - Union[ - EventDetailsDelivery, - EventDetailsOpen, - EventDetailsClick, - EventDetailsBounce, - EventDetailsSpam, - EventDetailsUnsubscribe, - EventDetailsReject, - dict[str, Any], - ] -]: - """Build the correct EventDetails* from event_type and raw details dict.""" - if data is None: - return None - if event_type == "delivery": - return EventDetailsDelivery(**data) - if event_type == "open": - return EventDetailsOpen(**data) - if event_type == "click": - return EventDetailsClick(**data) - if event_type in ("soft_bounce", "bounce"): - return EventDetailsBounce(**data) - if event_type == "spam": - return EventDetailsSpam(**data) - if event_type == "unsubscribe": - return EventDetailsUnsubscribe(**data) - if event_type in ("suspension", "reject"): - return EventDetailsReject(**data) - return data - - -def _parse_message_event(event_dict: dict[str, Any]) -> MessageEvent: - """Build MessageEvent from API dict using event_type to select details type.""" - event_type = event_dict["event_type"] - created_at = event_dict["created_at"] - details = _parse_event_details(event_type, event_dict.get("details")) - return MessageEvent( - event_type=event_type, - created_at=created_at, - details=details, - ) + details: Optional[EventDetails] = None + + @field_validator("details", mode="wrap") + @classmethod + def _details_by_event_type( + cls, value: Any, handler: ValidatorFunctionWrapHandler, info: ValidationInfo + ) -> Any: + # The union alone would pick whichever EventDetails* fits the dict's + # keys best, dropping the keys that class doesn't have. + if isinstance(value, dict): + event_type = info.data.get("event_type", "") + details_type = _DETAILS_TYPE_BY_EVENT_TYPE.get(event_type) + return details_type(**value) if details_type else value + return handler(value) class EmailLogMessage(BaseModel): @@ -159,8 +156,6 @@ def from_api(cls, data: dict[str, Any]) -> "EmailLogMessage": payload = dict(data) if payload.get("events") is None: payload["events"] = [] - else: - payload["events"] = [_parse_message_event(e) for e in payload["events"]] if payload.get("custom_variables") is None: payload["custom_variables"] = {} if payload.get("template_variables") is None: diff --git a/mailtrap/models/subscription_topics.py b/mailtrap/models/subscription_topics.py new file mode 100644 index 0000000..4edf0d5 --- /dev/null +++ b/mailtrap/models/subscription_topics.py @@ -0,0 +1,53 @@ +"""Models for the Subscription Topics API (``/api/subscription_topics``).""" + +from typing import Optional + +from pydantic import Field +from pydantic.dataclasses import dataclass + +from mailtrap.models.common import Pagination +from mailtrap.models.common import RequestParams + + +@dataclass +class SubscriptionTopic: + """ + A subscription topic contacts can unsubscribe from on its own. + ``domain_id`` is the sending domain the topic covers, or ``None`` when it + covers every domain. ``deleted_at`` is set only on a deleted topic, which + the list leaves out but ``get_by_id`` still returns. + """ + + id: int + name: str + created_at: str + updated_at: str + description: Optional[str] = None + domain_id: Optional[int] = None + deleted_at: Optional[str] = None + + +@dataclass +class SubscriptionTopicResponse: + """Envelope of a single-topic response.""" + + data: SubscriptionTopic + + +@dataclass +class SubscriptionTopicListResponse: + """Paginated response from listing subscription topics.""" + + data: list[SubscriptionTopic] = Field(default_factory=list) + pagination: Optional[Pagination] = None + + +@dataclass +class SubscriptionTopicListParams(RequestParams): + """ + Query params for listing subscription topics. ``token`` is the page number + and ``per_page`` is capped at 100 (default 50). + """ + + per_page: Optional[int] = None + token: Optional[int] = None diff --git a/mailtrap/models/suppressions.py b/mailtrap/models/suppressions.py index b64a923..636fb14 100644 --- a/mailtrap/models/suppressions.py +++ b/mailtrap/models/suppressions.py @@ -15,6 +15,8 @@ class Suppression: email: str sending_stream: str domain_name: Optional[str] = None + # Set on a "topic unsubscription", the topic the contact unsubscribed from. + subscription_topic_id: Optional[int] = None message_bounce_category: Optional[str] = None message_category: Optional[str] = None message_client_ip: Optional[str] = None @@ -37,4 +39,4 @@ class CreateSuppressionParams(RequestParams): email: str domain_id: int sending_stream: str - type: Optional[str] = None + type: Optional[str] = None # not "topic unsubscription", which can't be created diff --git a/mailtrap/models/webhooks.py b/mailtrap/models/webhooks.py index cb06888..1af8f76 100644 --- a/mailtrap/models/webhooks.py +++ b/mailtrap/models/webhooks.py @@ -41,6 +41,13 @@ class WebhookListResponse: @dataclass class CreateWebhookParams(RequestParams): + """ + ``event_types`` can include ``subscription_preferences_update``, sent when a + contact changes their subscription topic preferences. It is available only + on a ``campaigns`` webhook or an ``email_sending`` one for the ``bulk`` + stream. + """ + url: str webhook_type: str active: Optional[bool] = None @@ -53,6 +60,11 @@ class CreateWebhookParams(RequestParams): @dataclass class UpdateWebhookParams(RequestParams): + """ + ``event_types`` can include ``subscription_preferences_update`` on a + ``campaigns`` webhook or an ``email_sending`` one for the ``bulk`` stream. + """ + url: Optional[str] = None active: Optional[bool] = None payload_format: Optional[str] = None diff --git a/tests/unit/api/contacts/test_contact_imports.py b/tests/unit/api/contacts/test_contact_imports.py index e264b6f..83de9fa 100644 --- a/tests/unit/api/contacts/test_contact_imports.py +++ b/tests/unit/api/contacts/test_contact_imports.py @@ -1,3 +1,4 @@ +import json from typing import Any import pytest @@ -8,6 +9,7 @@ from mailtrap.exceptions import APIError from mailtrap.http import HttpClient from mailtrap.models.contacts import ContactImport +from mailtrap.models.contacts import ContactSubscriptionTopic from mailtrap.models.contacts import ImportContactParams from tests import conftest @@ -92,6 +94,20 @@ class TestContactImportsApi: }, "contacts limit reached", ), + ( + conftest.VALIDATION_ERRORS_STATUS_CODE, + { + "errors": [ + { + "base": [ + "subscription topics are not available for this" + " account" + ] + } + ] + }, + "subscription topics are not available for this account", + ), ], ) @responses.activate @@ -136,6 +152,32 @@ def test_import_contacts_should_return_started_import( assert contact_import.id == IMPORT_ID assert contact_import.status == "started" + @responses.activate + def test_import_contacts_should_send_subscription_topics( + self, contact_imports_api: ContactImportsApi + ) -> None: + responses.post( + BASE_CONTACT_IMPORTS_URL, json={"id": IMPORT_ID, "status": "started"} + ) + topic = {"subscription_topic_id": 17, "domain_id": 4321, "status": "unsubscribed"} + + contact_imports_api.import_contacts( + [ + ImportContactParams( + email="john.smith@example.com", + subscription_topics=[ContactSubscriptionTopic(**topic)], + ), + ImportContactParams(email="john.doe@example.com"), + ] + ) + + assert json.loads(responses.calls[0].request.body) == { + "contacts": [ + {"email": "john.smith@example.com", "subscription_topics": [topic]}, + {"email": "john.doe@example.com"}, + ] + } + @pytest.mark.parametrize( "status_code,response_json,expected_error_message", [ diff --git a/tests/unit/api/contacts/test_contacts.py b/tests/unit/api/contacts/test_contacts.py index 1793c78..97f09d3 100644 --- a/tests/unit/api/contacts/test_contacts.py +++ b/tests/unit/api/contacts/test_contacts.py @@ -1,3 +1,4 @@ +import json from typing import Any import pytest @@ -9,6 +10,7 @@ from mailtrap.http import HttpClient from mailtrap.models.common import DeletedObject from mailtrap.models.contacts import Contact +from mailtrap.models.contacts import ContactSubscriptionTopic from mailtrap.models.contacts import CreateContactParams from mailtrap.models.contacts import UpdateContactParams from tests import conftest @@ -16,6 +18,15 @@ ACCOUNT_ID = "321" CONTACT_ID = "018dd5e3-f6d2-7c00-8f9b-e5c3f2d8a132" BASE_CONTACTS_URL = f"https://{GENERAL_HOST}/api/accounts/{ACCOUNT_ID}/contacts" +TOPIC_ID = 17 +DOMAIN_ID = 4321 +TOPICS_UNAVAILABLE_RESPONSE = { + "errors": {"subscription_topics": ["are not available for this account"]} +} +TOPICS_NOT_SAVED_MESSAGE = ( + "The contact was saved, but its subscription topic preferences were not. " + f"Send them again in an update of contact {CONTACT_ID}." +) @pytest.fixture @@ -125,6 +136,69 @@ def test_get_contact_should_return_contact( assert contact.fields["first_name"] == "John" assert contact.fields["last_name"] == "Smith" assert contact.list_ids == [1, 2, 3] + # The account has no subscription topics: the key is absent. + assert contact.subscription_topics is None + + @pytest.mark.parametrize( + "subscription_topics,expected", + [ + ( + [ + { + "subscription_topic_id": TOPIC_ID, + "domain_id": DOMAIN_ID, + "status": "unsubscribed", + }, + { + "subscription_topic_id": 18, + "domain_id": DOMAIN_ID, + "status": "subscribed", + }, + ], + [ + ContactSubscriptionTopic( + subscription_topic_id=TOPIC_ID, + domain_id=DOMAIN_ID, + status="unsubscribed", + ), + ContactSubscriptionTopic( + subscription_topic_id=18, + domain_id=DOMAIN_ID, + status="subscribed", + ), + ], + ), + # Preferences without a sending domain. + ( + [{"subscription_topic_id": TOPIC_ID, "status": "unsubscribed"}], + [ + ContactSubscriptionTopic( + subscription_topic_id=TOPIC_ID, status="unsubscribed" + ) + ], + ), + # The preferences couldn't be read. + (None, None), + ], + ) + @responses.activate + def test_get_contact_should_return_subscription_topics( + self, + contacts_api: ContactsApi, + sample_contact_dict: dict, + subscription_topics: Any, + expected: Any, + ) -> None: + sample_contact_dict["data"]["subscription_topics"] = subscription_topics + responses.get( + f"{BASE_CONTACTS_URL}/{CONTACT_ID}", + json=sample_contact_dict, + status=200, + ) + + contact = contacts_api.get_by_id(CONTACT_ID) + + assert contact.subscription_topics == expected @pytest.mark.parametrize( "status_code,response_json,expected_error_message", @@ -159,6 +233,16 @@ def test_get_contact_should_return_contact( {"errors": {"email": ["Email is invalid"]}}, "Email is invalid", ), + ( + conftest.VALIDATION_ERRORS_STATUS_CODE, + TOPICS_UNAVAILABLE_RESPONSE, + "subscription_topics: are not available for this account", + ), + ( + 503, + {"errors": TOPICS_NOT_SAVED_MESSAGE}, + TOPICS_NOT_SAVED_MESSAGE, + ), ], ) @responses.activate @@ -214,6 +298,33 @@ def test_create_contact_should_return_created_contact( assert contact.fields["last_name"] == "Smith" assert contact.list_ids == [1, 2, 3] + @responses.activate + def test_create_contact_should_send_subscription_topics( + self, contacts_api: ContactsApi, sample_contact_dict: dict + ) -> None: + topic = { + "subscription_topic_id": TOPIC_ID, + "domain_id": DOMAIN_ID, + "status": "unsubscribed", + } + sample_contact_dict["data"]["subscription_topics"] = [topic] + responses.post(BASE_CONTACTS_URL, json=sample_contact_dict, status=201) + + contact = contacts_api.create( + CreateContactParams( + email="john.smith@example.com", + subscription_topics=[ContactSubscriptionTopic(**topic)], + ) + ) + + assert json.loads(responses.calls[0].request.body) == { + "contact": { + "email": "john.smith@example.com", + "subscription_topics": [topic], + } + } + assert contact.subscription_topics == [ContactSubscriptionTopic(**topic)] + @pytest.mark.parametrize( "status_code,response_json,expected_error_message", [ @@ -247,6 +358,16 @@ def test_create_contact_should_return_created_contact( {"errors": {"email": [["is invalid"]], "birthdate": [["is invalid"]]}}, "email: ['is invalid']; birthdate: ['is invalid']", ), + ( + conftest.VALIDATION_ERRORS_STATUS_CODE, + TOPICS_UNAVAILABLE_RESPONSE, + "subscription_topics: are not available for this account", + ), + ( + 503, + {"errors": TOPICS_NOT_SAVED_MESSAGE}, + TOPICS_NOT_SAVED_MESSAGE, + ), ], ) @responses.activate @@ -300,6 +421,30 @@ def test_update_contact_should_return_updated_contact( assert contact.fields["first_name"] == "John Updated" assert contact.fields["last_name"] == "Smith Updated" + @responses.activate + def test_update_contact_should_send_only_subscription_topics( + self, contacts_api: ContactsApi, sample_contact_dict: dict + ) -> None: + topic = { + "subscription_topic_id": TOPIC_ID, + "domain_id": DOMAIN_ID, + "status": "subscribed", + } + sample_contact_dict["data"]["subscription_topics"] = [topic] + responses.patch( + f"{BASE_CONTACTS_URL}/{CONTACT_ID}", json=sample_contact_dict, status=200 + ) + + contact = contacts_api.update( + CONTACT_ID, + UpdateContactParams(subscription_topics=[ContactSubscriptionTopic(**topic)]), + ) + + assert json.loads(responses.calls[0].request.body) == { + "contact": {"subscription_topics": [topic]} + } + assert contact.subscription_topics == [ContactSubscriptionTopic(**topic)] + @pytest.mark.parametrize( "status_code,response_json,expected_error_message", [ diff --git a/tests/unit/api/email_campaigns/test_email_campaigns.py b/tests/unit/api/email_campaigns/test_email_campaigns.py index b0cd395..37cbd8d 100644 --- a/tests/unit/api/email_campaigns/test_email_campaigns.py +++ b/tests/unit/api/email_campaigns/test_email_campaigns.py @@ -27,6 +27,7 @@ CAMPAIGN_ID = 4567 DOMAIN_ID = 4321 +TOPIC_ID = 17 BASE_CAMPAIGNS_URL = f"https://{GENERAL_HOST}/api/email_campaigns" @@ -79,6 +80,7 @@ def sample_campaign_dict() -> dict[str, Any]: "contact_segment_ids": [12], "delivery_mode": "rapid", "delivery_options": {"emails_per_hour": 1000}, + "subscription_topic_id": None, "template": { "id": 789, "subject": "Spring is here — 30% off", @@ -260,6 +262,21 @@ def test_get_by_id_should_unwrap_data_envelope( assert campaign.template.body_html is not None assert campaign.delivery_options is not None assert campaign.delivery_options.emails_per_hour == 1000 + assert campaign.subscription_topic_id is None + + @responses.activate + def test_get_by_id_should_parse_subscription_topic_id( + self, client: EmailCampaignsApi, sample_campaign_dict: dict + ) -> None: + responses.get( + f"{BASE_CAMPAIGNS_URL}/{CAMPAIGN_ID}", + json={"data": {**sample_campaign_dict, "subscription_topic_id": TOPIC_ID}}, + status=200, + ) + + campaign = client.get_by_id(CAMPAIGN_ID) + + assert campaign.subscription_topic_id == TOPIC_ID @responses.activate def test_get_by_id_should_parse_state_metadata_errors( @@ -375,6 +392,56 @@ def test_create_should_send_flat_body_and_unwrap_data_envelope( "contact_list_ids": [55, 56], } + @responses.activate + def test_create_should_send_subscription_topic_id( + self, client: EmailCampaignsApi, sample_campaign_dict: dict + ) -> None: + responses.post( + BASE_CAMPAIGNS_URL, + json={"data": {**sample_campaign_dict, "subscription_topic_id": TOPIC_ID}}, + status=201, + ) + + campaign = client.create( + CreateEmailCampaignParams( + name="Spring Sale", + domain_id=DOMAIN_ID, + from_local_part="news", + template_attributes=CreateEmailCampaignTemplateAttributes( + subject="Spring!" + ), + subscription_topic_id=TOPIC_ID, + ) + ) + + assert campaign.subscription_topic_id == TOPIC_ID + assert json.loads(responses.calls[0].request.body) == { + "name": "Spring Sale", + "domain_id": DOMAIN_ID, + "from_local_part": "news", + "template_attributes": {"subject": "Spring!"}, + "subscription_topic_id": TOPIC_ID, + } + + @responses.activate + def test_update_should_send_subscription_topic_id( + self, client: EmailCampaignsApi, sample_campaign_dict: dict + ) -> None: + responses.patch( + f"{BASE_CAMPAIGNS_URL}/{CAMPAIGN_ID}", + json={"data": {**sample_campaign_dict, "subscription_topic_id": TOPIC_ID}}, + status=200, + ) + + campaign = client.update( + CAMPAIGN_ID, UpdateEmailCampaignParams(subscription_topic_id=TOPIC_ID) + ) + + assert campaign.subscription_topic_id == TOPIC_ID + assert json.loads(responses.calls[0].request.body) == { + "subscription_topic_id": TOPIC_ID + } + @responses.activate def test_update_should_send_only_supplied_fields_flat( self, client: EmailCampaignsApi, sample_campaign_dict: dict diff --git a/tests/unit/api/subscription_topics/__init__.py b/tests/unit/api/subscription_topics/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/unit/api/subscription_topics/test_subscription_topics.py b/tests/unit/api/subscription_topics/test_subscription_topics.py new file mode 100644 index 0000000..32be194 --- /dev/null +++ b/tests/unit/api/subscription_topics/test_subscription_topics.py @@ -0,0 +1,208 @@ +from typing import Any +from typing import Optional +from urllib.parse import parse_qs +from urllib.parse import urlparse + +import pytest +import responses + +from mailtrap.api.resources.subscription_topics import SubscriptionTopicsApi +from mailtrap.config import GENERAL_HOST +from mailtrap.exceptions import APIError +from mailtrap.http import HttpClient +from mailtrap.models.subscription_topics import SubscriptionTopic +from mailtrap.models.subscription_topics import SubscriptionTopicListParams +from mailtrap.models.subscription_topics import SubscriptionTopicListResponse +from tests import conftest + +TOPIC_ID = 17 +DOMAIN_ID = 4321 +BASE_TOPICS_URL = f"https://{GENERAL_HOST}/api/subscription_topics" + + +@pytest.fixture +def client() -> SubscriptionTopicsApi: + return SubscriptionTopicsApi(client=HttpClient(GENERAL_HOST)) + + +@pytest.fixture +def sample_topic_dict() -> dict[str, Any]: + return { + "id": TOPIC_ID, + "name": "Weekly digest", + "description": "A summary of the week, every Monday", + "domain_id": DOMAIN_ID, + "deleted_at": None, + "created_at": "2026-05-01T10:15:00.000Z", + "updated_at": "2026-05-02T09:00:00.000Z", + } + + +class TestSubscriptionTopicsApi: + + @pytest.mark.parametrize( + "status_code,response_json,expected_error_message", + [ + ( + conftest.UNAUTHORIZED_STATUS_CODE, + conftest.UNAUTHORIZED_RESPONSE, + conftest.UNAUTHORIZED_ERROR_MESSAGE, + ), + ( + conftest.RATE_LIMIT_ERROR_STATUS_CODE, + conftest.RATE_LIMIT_ERROR_RESPONSE, + conftest.RATE_LIMIT_ERROR_MESSAGE, + ), + ( + conftest.VALIDATION_ERRORS_STATUS_CODE, + {"errors": "token is out of range"}, + "token is out of range", + ), + ], + ) + @responses.activate + def test_get_list_should_raise_api_errors( + self, + client: SubscriptionTopicsApi, + status_code: int, + response_json: dict, + expected_error_message: str, + ) -> None: + responses.get(BASE_TOPICS_URL, status=status_code, json=response_json) + + with pytest.raises(APIError) as exc_info: + client.get_list() + + assert expected_error_message in str(exc_info.value) + + @responses.activate + def test_get_list_should_raise_forbidden_without_topics( + self, client: SubscriptionTopicsApi + ) -> None: + # An account without subscription topics gets a 403 with an empty body. + responses.get(BASE_TOPICS_URL, status=conftest.FORBIDDEN_STATUS_CODE, body="") + + with pytest.raises(APIError) as exc_info: + client.get_list() + + assert exc_info.value.status == conftest.FORBIDDEN_STATUS_CODE + + @responses.activate + def test_get_list_should_return_topics_and_pagination( + self, client: SubscriptionTopicsApi, sample_topic_dict: dict + ) -> None: + all_domains_topic = { + **sample_topic_dict, + "id": 18, + "name": "Product news", + "description": None, + "domain_id": None, + } + responses.get( + BASE_TOPICS_URL, + json={ + "data": [sample_topic_dict, all_domains_topic], + "pagination": { + "token": 1, + "prev_token": None, + "next_token": 2, + "first_url": f"{BASE_TOPICS_URL}?per_page=2&token=1", + "prev_url": None, + "current_url": f"{BASE_TOPICS_URL}?per_page=2&token=1", + "next_url": f"{BASE_TOPICS_URL}?per_page=2&token=2", + }, + }, + status=200, + ) + + result = client.get_list() + + assert isinstance(result, SubscriptionTopicListResponse) + assert all(isinstance(t, SubscriptionTopic) for t in result.data) + assert result.data[0] == SubscriptionTopic(**sample_topic_dict) + assert result.data[1].description is None + assert result.data[1].domain_id is None + assert result.pagination is not None + assert result.pagination.token == 1 + assert result.pagination.next_token == 2 + + @responses.activate + def test_get_list_should_return_empty_list( + self, client: SubscriptionTopicsApi + ) -> None: + responses.get( + BASE_TOPICS_URL, json={"data": [], "pagination": {"token": 1}}, status=200 + ) + + result = client.get_list() + + assert result.data == [] + + @responses.activate + def test_get_list_should_send_per_page_and_token_query_params( + self, client: SubscriptionTopicsApi + ) -> None: + responses.get(BASE_TOPICS_URL, json={"data": [], "pagination": {}}, status=200) + + client.get_list(SubscriptionTopicListParams(per_page=25, token=2)) + + query = parse_qs(urlparse(responses.calls[0].request.url).query) + assert query == {"per_page": ["25"], "token": ["2"]} + + @responses.activate + def test_get_list_should_send_no_query_params_by_default( + self, client: SubscriptionTopicsApi + ) -> None: + responses.get(BASE_TOPICS_URL, json={"data": [], "pagination": {}}, status=200) + + client.get_list() + + assert urlparse(responses.calls[0].request.url).query == "" + + @pytest.mark.parametrize( + "status_code,response_json,expected_error_message", + [ + ( + conftest.UNAUTHORIZED_STATUS_CODE, + conftest.UNAUTHORIZED_RESPONSE, + conftest.UNAUTHORIZED_ERROR_MESSAGE, + ), + ( + conftest.NOT_FOUND_STATUS_CODE, + conftest.NOT_FOUND_RESPONSE, + conftest.NOT_FOUND_ERROR_MESSAGE, + ), + ], + ) + @responses.activate + def test_get_by_id_should_raise_api_errors( + self, + client: SubscriptionTopicsApi, + status_code: int, + response_json: dict, + expected_error_message: str, + ) -> None: + responses.get( + f"{BASE_TOPICS_URL}/{TOPIC_ID}", status=status_code, json=response_json + ) + + with pytest.raises(APIError) as exc_info: + client.get_by_id(TOPIC_ID) + + assert expected_error_message in str(exc_info.value) + + # A deleted topic is returned too, with deleted_at set. + @pytest.mark.parametrize("deleted_at", [None, "2026-05-03T12:00:00.000Z"]) + @responses.activate + def test_get_by_id_should_unwrap_data_envelope( + self, + client: SubscriptionTopicsApi, + sample_topic_dict: dict, + deleted_at: Optional[str], + ) -> None: + data = {**sample_topic_dict, "deleted_at": deleted_at} + responses.get(f"{BASE_TOPICS_URL}/{TOPIC_ID}", json={"data": data}, status=200) + + topic = client.get_by_id(TOPIC_ID) + + assert topic == SubscriptionTopic(**data) diff --git a/tests/unit/api/suppressions/test_suppressions.py b/tests/unit/api/suppressions/test_suppressions.py index 363ce9d..1ebe75b 100644 --- a/tests/unit/api/suppressions/test_suppressions.py +++ b/tests/unit/api/suppressions/test_suppressions.py @@ -115,6 +115,62 @@ def test_get_suppressions_with_email_filter_should_return_filtered_list( assert suppressions[0].email == email_filter assert isinstance(suppressions[0].created_at, datetime) + @pytest.mark.parametrize( + "kwargs,expected_params", + [ + ({}, {}), + # The API opts in only on the exact string "true". + ( + {"include_topic_unsubscriptions": True}, + {"include_topic_unsubscriptions": "true"}, + ), + ( + {"email": "recipient@example.com", "include_topic_unsubscriptions": True}, + { + "email": "recipient@example.com", + "include_topic_unsubscriptions": "true", + }, + ), + ], + ) + @responses.activate + def test_get_suppressions_should_send_query_params( + self, + suppressions_api: SuppressionsApi, + kwargs: dict[str, Any], + expected_params: dict[str, str], + ) -> None: + responses.get(BASE_SUPPRESSIONS_URL, json=[]) + + suppressions_api.get_list(**kwargs) + + assert responses.calls[0].request.params == expected_params + + @responses.activate + def test_get_suppressions_should_parse_topic_unsubscriptions( + self, suppressions_api: SuppressionsApi, sample_suppression_dict: dict + ) -> None: + topic_unsubscription = { + "id": "supp_654321", + "type": "topic unsubscription", + "created_at": "2024-12-27T09:40:44.161Z", + "email": "recipient@example.com", + "sending_stream": "bulk", + "domain_name": "sender.com", + "subscription_topic_id": 17, + } + responses.get( + BASE_SUPPRESSIONS_URL, + json=[sample_suppression_dict, topic_unsubscription], + ) + + suppressions = suppressions_api.get_list(include_topic_unsubscriptions=True) + + assert suppressions[0].subscription_topic_id is None + assert suppressions[1].type == "topic unsubscription" + assert suppressions[1].domain_name == "sender.com" + assert suppressions[1].subscription_topic_id == 17 + @pytest.mark.parametrize( "status_code,response_json,expected_error_message", [ diff --git a/tests/unit/models/test_contacts.py b/tests/unit/models/test_contacts.py index 6e36c56..eb64b21 100644 --- a/tests/unit/models/test_contacts.py +++ b/tests/unit/models/test_contacts.py @@ -3,6 +3,7 @@ from mailtrap.models.contacts import ContactEventParams from mailtrap.models.contacts import ContactExportFilter from mailtrap.models.contacts import ContactListParams +from mailtrap.models.contacts import ContactSubscriptionTopic from mailtrap.models.contacts import CreateContactExportParams from mailtrap.models.contacts import CreateContactFieldParams from mailtrap.models.contacts import CreateContactParams @@ -99,6 +100,23 @@ def test_update_contact_params_with_none_values_should_raise_error( ): _ = UpdateContactParams() + def test_update_contact_params_with_only_subscription_topics_should_not_raise( + self, + ) -> None: + params = UpdateContactParams( + subscription_topics=[ + ContactSubscriptionTopic( + subscription_topic_id=17, domain_id=4321, status="unsubscribed" + ) + ] + ) + + assert params.api_data == { + "subscription_topics": [ + {"subscription_topic_id": 17, "domain_id": 4321, "status": "unsubscribed"} + ] + } + def test_update_contact_params_api_data_should_exclude_none_values( self, ) -> None: diff --git a/tests/unit/models/test_email_log_models.py b/tests/unit/models/test_email_log_models.py index 1df4ee6..d817194 100644 --- a/tests/unit/models/test_email_log_models.py +++ b/tests/unit/models/test_email_log_models.py @@ -2,12 +2,17 @@ from typing import Any +import pytest + from mailtrap.models.email_logs import EmailLogMessage from mailtrap.models.email_logs import EmailLogsListFilters from mailtrap.models.email_logs import EventDetailsBounce from mailtrap.models.email_logs import EventDetailsClick from mailtrap.models.email_logs import EventDetailsDelivery from mailtrap.models.email_logs import EventDetailsOpen +from mailtrap.models.email_logs import EventDetailsReject +from mailtrap.models.email_logs import EventDetailsSpam +from mailtrap.models.email_logs import EventDetailsTopicSubscription from mailtrap.models.email_logs import EventDetailsUnsubscribe from mailtrap.models.email_logs import MessageEvent from mailtrap.models.email_logs import filter_ci_equal @@ -220,6 +225,162 @@ def test_from_api_parses_delivery_event(self) -> None: assert isinstance(msg.events[0].details, EventDetailsDelivery) assert msg.events[0].details.email_service_provider == "Google" + def test_from_api_parses_topic_events(self) -> None: + """Both topic events get EventDetailsTopicSubscription with the topic id.""" + details = {"web_ip_address": "198.51.100.50", "subscription_topic_id": 17} + msg = EmailLogMessage.from_api( + { + **_message_dict(), + "events": [ + { + "event_type": "topic_unsubscribe", + "created_at": "2025-01-15T10:40:00Z", + "details": details, + }, + { + "event_type": "topic_resubscribe", + "created_at": "2025-01-15T10:45:00Z", + "details": details, + }, + ], + } + ) + + assert [event.event_type for event in msg.events] == [ + "topic_unsubscribe", + "topic_resubscribe", + ] + for event in msg.events: + assert event.details == EventDetailsTopicSubscription(**details) + + def test_from_api_keeps_details_of_unknown_event_as_dict(self) -> None: + """An event type the SDK doesn't know keeps the API's details as they are.""" + details = {"web_ip_address": "198.51.100.50", "new_field": [1, 2]} + msg = EmailLogMessage.from_api( + { + **_message_dict(), + "events": [ + { + "event_type": "future_event", + "created_at": "2025-01-15T10:40:00Z", + "details": details, + } + ], + } + ) + + assert msg.events[0].event_type == "future_event" + assert msg.events[0].details == details + + @pytest.mark.parametrize( + "event_type,details,expected", + [ + # A dict gets its class by event_type, not by which class fits its keys. + ( + "unsubscribe", + {"web_ip_address": "198.51.100.50"}, + EventDetailsUnsubscribe(web_ip_address="198.51.100.50"), + ), + ( + "delivery", + {"sending_ip": "192.0.2.1"}, + EventDetailsDelivery(sending_ip="192.0.2.1"), + ), + ( + "soft_bounce", + {"bounce_category": "mailbox_full"}, + EventDetailsBounce(bounce_category="mailbox_full"), + ), + ( + "spam", + {"spam_feedback_type": "abuse"}, + EventDetailsSpam(spam_feedback_type="abuse"), + ), + ( + "suspension", + {"reject_reason": "account_suspended"}, + EventDetailsReject(reject_reason="account_suspended"), + ), + ( + "reject", + {"reject_reason": "unsubscribed"}, + EventDetailsReject(reject_reason="unsubscribed"), + ), + ( + "future_event", + {"web_ip_address": "198.51.100.50"}, + {"web_ip_address": "198.51.100.50"}, + ), + # An EventDetails* instance is kept as given. + ( + "unsubscribe", + EventDetailsUnsubscribe(web_ip_address="198.51.100.50"), + EventDetailsUnsubscribe(web_ip_address="198.51.100.50"), + ), + ( + "topic_unsubscribe", + EventDetailsTopicSubscription( + web_ip_address="198.51.100.50", subscription_topic_id=17 + ), + EventDetailsTopicSubscription( + web_ip_address="198.51.100.50", subscription_topic_id=17 + ), + ), + ], + ) + def test_message_event_details_type( + self, event_type: str, details: Any, expected: Any + ) -> None: + event = MessageEvent( + event_type=event_type, created_at="2025-01-15T10:40:00Z", details=details + ) + + assert type(event.details) is type(expected) + assert event.details == expected + + def test_message_round_trips_through_model_dump(self) -> None: + """Validating a dumped message gives back the same typed details.""" + msg = EmailLogMessage.from_api( + { + **_message_dict(), + "events": [ + { + "event_type": "topic_unsubscribe", + "created_at": "2025-01-15T10:40:00Z", + "details": { + "web_ip_address": "198.51.100.50", + "subscription_topic_id": 17, + }, + }, + { + "event_type": "future_event", + "created_at": "2025-01-15T10:45:00Z", + "details": {"new_field": 1}, + }, + ], + } + ) + + restored = EmailLogMessage.model_validate(msg.model_dump(by_alias=True)) + + assert restored == msg + assert isinstance(restored.events[0].details, EventDetailsTopicSubscription) + + +def _message_dict() -> dict[str, Any]: + return { + "message_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", + "status": "delivered", + "subject": "Welcome", + "from": "sender@example.com", + "to": "recipient@example.com", + "sent_at": "2025-01-15T10:30:00Z", + "sending_stream": "bulk", + "sending_domain_id": 3938, + "opens_count": 0, + "clicks_count": 0, + } + class TestEmailLogsListFilters: def test_to_params_date_range(self) -> None: diff --git a/tests/unit/test_client.py b/tests/unit/test_client.py index 24bcc56..b8fc106 100644 --- a/tests/unit/test_client.py +++ b/tests/unit/test_client.py @@ -92,6 +92,11 @@ def test_marketing_stats_api_does_not_require_account_id(self) -> None: assert client.marketing_stats_api.marketing_stats is not None + def test_subscription_topics_api_does_not_require_account_id(self) -> None: + client = self.get_client() + + assert client.subscription_topics_api.subscription_topics is not None + @pytest.mark.parametrize( "arguments, expected_url", [