Skip to content

Commit 8fe4303

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

File tree

2 files changed

+17
-6
lines changed

2 files changed

+17
-6
lines changed

mailtrap/client.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
import warnings
2+
3+
import importlib.metadata
4+
25
from typing import Optional
36
from typing import Union
47
from typing import cast
@@ -34,6 +37,10 @@ class MailtrapClient:
3437
DEFAULT_PORT = 443
3538
BULK_HOST = BULK_HOST
3639
SANDBOX_HOST = SANDBOX_HOST
40+
DEFAULT_USER_AGENT = (
41+
f"mailtrap-python/{importlib.metadata.version('mailtrap')} "
42+
"(https://github.com/railsware/mailtrap-python)"
43+
)
3744

3845
def __init__(
3946
self,
@@ -44,6 +51,7 @@ def __init__(
4451
sandbox: bool = False,
4552
account_id: Optional[str] = None,
4653
inbox_id: Optional[str] = None,
54+
user_agent: Optional[str] = None,
4755
) -> None:
4856
self.token = token
4957
self.api_host = api_host
@@ -52,6 +60,7 @@ def __init__(
5260
self.sandbox = sandbox
5361
self.account_id = account_id
5462
self.inbox_id = inbox_id
63+
self._user_agent = user_agent if user_agent is not None else self.DEFAULT_USER_AGENT
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)