diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 9f2ba00..4ee979f 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -13,6 +13,15 @@ repos: - id: ruff args: ['--fix'] - id: ruff-format + - repo: local + hooks: + - id: mypy + name: mypy + entry: poetry run mypy + language: system + types: [python] + pass_filenames: false + args: ["src"] - repo: https://github.com/igorshubovych/markdownlint-cli rev: v0.44.0 hooks: diff --git a/pyproject.toml b/pyproject.toml index 6442c3d..c7be108 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -97,3 +97,7 @@ warn_unused_configs = true namespace_packages = true explicit_package_bases = true mypy_path = "src" + +[[tool.mypy.overrides]] +module = "customerio.*" +ignore_missing_imports = true diff --git a/src/altissimo/customerio/client.py b/src/altissimo/customerio/client.py index 7c8c8d2..163f86a 100644 --- a/src/altissimo/customerio/client.py +++ b/src/altissimo/customerio/client.py @@ -7,7 +7,7 @@ import random import re import time -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, TypedDict, Unpack, cast from altissimo.customerio.exceptions import CustomerIOImportError from altissimo.customerio.models import EmailAddress, SendResult @@ -41,6 +41,21 @@ __all__ = ["CustomerIOClient"] +class _RequestOptions(TypedDict, total=False): + """Per-send fields forwarded unchanged to ``SendEmailRequest``. + + A field set to ``None`` is left off the request. ``False`` is kept, since it + is a meaningful value distinct from "let the transactional message decide". + Adding a field here and to the public send methods is all a new one needs. + """ + + preheader: str | None + headers: dict[str, str] | None + send_to_unsubscribed: bool | None + tracked: bool | None + disable_message_retention: bool | None + + def _get_regions_class() -> type[Regions]: """Lazily import the Customer.io ``Regions`` enum. @@ -52,7 +67,7 @@ def _get_regions_class() -> type[Regions]: except ImportError: raise CustomerIOImportError from None - return _Regions + return cast("type[Regions]", _Regions) def _get_api_client(app_api_key: str, region: Any) -> APIClient: @@ -438,11 +453,7 @@ def _build_email_request( identifiers: dict[str, str] | None = None, reply_to: str | None = None, bcc: list[str] | None = None, - preheader: str | None = None, - headers: dict[str, str] | None = None, - send_to_unsubscribed: bool | None = None, - tracked: bool | None = None, - disable_message_retention: bool | None = None, + **options: Unpack[_RequestOptions], ) -> Any: """Build a ``SendEmailRequest`` from the given parameters. @@ -454,54 +465,26 @@ def _build_email_request( except ImportError: raise CustomerIOImportError from None - # Build identifiers — default to recipient email if not provided - if identifiers is None: - identifiers = {"email": to} - + fields: dict[str, Any] = { + "transactional_message_id": transactional_message_id, + "_from": from_email, + "subject": subject, + "body": body, + "message_data": message_data, + "reply_to": reply_to, + "bcc": bcc, + **options, + } + # ``is not None`` rather than truthy: ``False`` is a meaningful value the + # caller may want to send, distinct from "leave it unset and let the + # transactional message's own configuration decide". kwargs: dict[str, Any] = { "to": to, - "identifiers": identifiers, + # Default to the recipient's email if no identifiers were given. + "identifiers": identifiers if identifiers is not None else {"email": to}, + **{key: value for key, value in fields.items() if value is not None}, } - if transactional_message_id is not None: - kwargs["transactional_message_id"] = transactional_message_id - - if from_email is not None: - kwargs["_from"] = from_email - - if subject is not None: - kwargs["subject"] = subject - - if body is not None: - kwargs["body"] = body - - if message_data is not None: - kwargs["message_data"] = message_data - - if reply_to is not None: - kwargs["reply_to"] = reply_to - - if bcc is not None: - kwargs["bcc"] = bcc - - if preheader is not None: - kwargs["preheader"] = preheader - - if headers is not None: - kwargs["headers"] = headers - - # Explicitly ``is not None`` rather than truthy: ``False`` is a meaningful - # value the caller may want to send, distinct from "leave it unset and let - # the transactional message's own configuration decide". - if send_to_unsubscribed is not None: - kwargs["send_to_unsubscribed"] = send_to_unsubscribed - - if tracked is not None: - kwargs["tracked"] = tracked - - if disable_message_retention is not None: - kwargs["disable_message_retention"] = disable_message_retention - return SendEmailRequest(**kwargs) # ------------------------------------------------------------------ @@ -756,11 +739,7 @@ def _send_inline( reply_to: EmailAddressLike | None = None, bcc: EmailRecipients | None = None, identifiers: dict[str, str] | None = None, - preheader: str | None = None, - headers: dict[str, str] | None = None, - send_to_unsubscribed: bool | None = None, - tracked: bool | None = None, - disable_message_retention: bool | None = None, + **options: Unpack[_RequestOptions], ) -> SendResult: """Internal method to send inline-content transactional emails.""" client = self.client # Resolve eagerly — config/import errors must not be retried. @@ -781,11 +760,7 @@ def _send_inline( identifiers=identifiers, reply_to=reply_to_str, bcc=bcc_list, - preheader=preheader, - headers=headers, - send_to_unsubscribed=send_to_unsubscribed, - tracked=tracked, - disable_message_retention=disable_message_retention, + **options, ) context = f"to={to_str} subject={subject!r}" diff --git a/tests/test_client.py b/tests/test_client.py index b75a766..17583be 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -700,18 +700,26 @@ def test_forwarded_on_template_send( assert getattr(request, field) is value @pytest.mark.parametrize("method", ["send_text", "send_html"]) - def test_forwarded_on_inline_send(self, client_with_mock: Any, fake_api_client: MagicMock, method: str) -> None: + @pytest.mark.parametrize("field", ["tracked", "disable_message_retention"]) + @pytest.mark.parametrize("value", [True, False]) + def test_forwarded_on_inline_send( + self, client_with_mock: Any, fake_api_client: MagicMock, method: str, field: str, value: bool + ) -> None: content = {"body": "Text"} if method == "send_text" else {"html": "
Text
"} - getattr(client_with_mock, method)( - to="recipient@example.com", - subject="Hello", - tracked=False, - disable_message_retention=True, - **content, - ) + getattr(client_with_mock, method)(to="recipient@example.com", subject="Hello", **content, **{field: value}) request = fake_api_client.send_email.call_args[0][0] - assert request.tracked is False - assert request.disable_message_retention is True + assert getattr(request, field) is value + + @pytest.mark.parametrize("method", ["send_text", "send_html"]) + def test_omitted_on_inline_send_when_not_given( + self, client_with_mock: Any, fake_api_client: MagicMock, method: str + ) -> None: + """Unset stays off an inline request too, leaving Customer.io's own default.""" + content = {"body": "Text"} if method == "send_text" else {"html": "Text
"} + getattr(client_with_mock, method)(to="recipient@example.com", subject="Hello", **content) + payload = fake_api_client.send_email.call_args[0][0]._to_dict() + assert "tracked" not in payload + assert "disable_message_retention" not in payload def test_on_the_wire(self, client_with_mock: Any, fake_api_client: MagicMock) -> None: client_with_mock.send_email(