Skip to content

Commit 8da73a7

Browse files
Make it possible to set a custom user agent
1 parent 8821498 commit 8da73a7

2 files changed

Lines changed: 17 additions & 6 deletions

File tree

mailtrap/client.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import importlib.metadata
12
import warnings
23
from typing import Optional
34
from typing import Union
@@ -34,6 +35,10 @@ class MailtrapClient:
3435
DEFAULT_PORT = 443
3536
BULK_HOST = BULK_HOST
3637
SANDBOX_HOST = SANDBOX_HOST
38+
DEFAULT_USER_AGENT = (
39+
f"mailtrap-python/{importlib.metadata.version('mailtrap')} "
40+
"(https://github.com/railsware/mailtrap-python)"
41+
)
3742

3843
def __init__(
3944
self,
@@ -44,6 +49,7 @@ def __init__(
4449
sandbox: bool = False,
4550
account_id: Optional[str] = None,
4651
inbox_id: Optional[str] = None,
52+
user_agent: Optional[str] = None,
4753
) -> None:
4854
self.token = token
4955
self.api_host = api_host
@@ -52,6 +58,9 @@ def __init__(
5258
self.sandbox = sandbox
5359
self.account_id = account_id
5460
self.inbox_id = inbox_id
61+
self._user_agent = (
62+
user_agent if user_agent is not None else self.DEFAULT_USER_AGENT
63+
)
5564

5665
self._validate_itself()
5766

@@ -147,9 +156,7 @@ def headers(self) -> dict[str, str]:
147156
return {
148157
"Authorization": f"Bearer {self.token}",
149158
"Content-Type": "application/json",
150-
"User-Agent": (
151-
"mailtrap-python (https://github.com/railsware/mailtrap-python)"
152-
),
159+
"User-Agent": self._user_agent,
153160
}
154161

155162
@property

tests/unit/test_client.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,11 @@ def test_headers_should_return_appropriate_dict(self) -> None:
8686
assert client.headers == {
8787
"Authorization": "Bearer fake_token",
8888
"Content-Type": "application/json",
89-
"User-Agent": (
90-
"mailtrap-python (https://github.com/railsware/mailtrap-python)"
91-
),
89+
"User-Agent": mt.MailtrapClient.DEFAULT_USER_AGENT,
9290
}
91+
92+
def test_headers_should_use_custom_user_agent_when_provided(self) -> None:
93+
custom_ua = "MyApp/1.0 (custom)"
94+
client = self.get_client(user_agent=custom_ua)
95+
96+
assert client.headers["User-Agent"] == custom_ua

0 commit comments

Comments
 (0)