python-mytnb 0.5.1__tar.gz → 0.5.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/PKG-INFO +1 -1
  2. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/pyproject.toml +1 -1
  3. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/src/mytnb/client/legacy.py +20 -14
  4. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/src/mytnb/client/rest.py +36 -15
  5. python_mytnb-0.5.3/src/mytnb/client/retry.py +92 -0
  6. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/src/mytnb/exceptions.py +2 -0
  7. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/src/mytnb/models.py +23 -4
  8. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/tests/test_client.py +76 -0
  9. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/tests/test_models.py +36 -5
  10. python_mytnb-0.5.3/tests/test_retry.py +106 -0
  11. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/uv.lock +1 -1
  12. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/.github/workflows/ci.yml +0 -0
  13. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/.github/workflows/publish.yml +0 -0
  14. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/.gitignore +0 -0
  15. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/LICENSE +0 -0
  16. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/README.md +0 -0
  17. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/src/mytnb/__init__.py +0 -0
  18. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/src/mytnb/__main__.py +0 -0
  19. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/src/mytnb/auth.py +0 -0
  20. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/src/mytnb/cli.py +0 -0
  21. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/src/mytnb/client/__init__.py +0 -0
  22. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/src/mytnb/client/auth.py +0 -0
  23. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/src/mytnb/client/client.py +0 -0
  24. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/src/mytnb/client/config.py +0 -0
  25. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/src/mytnb/crypto.py +0 -0
  26. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/tests/test_auth.py +0 -0
  27. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/tests/test_cli.py +0 -0
  28. {python_mytnb-0.5.1 → python_mytnb-0.5.3}/tests/test_crypto.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-mytnb
3
- Version: 0.5.1
3
+ Version: 0.5.3
4
4
  Summary: Python library to interface with the myTNB API (Tenaga Nasional Berhad)
5
5
  Project-URL: Repository, https://github.com/danieyal/python-mytnb
6
6
  License-Expression: MIT
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "python-mytnb"
7
- version = "0.5.1"
7
+ version = "0.5.3"
8
8
  description = "Python library to interface with the myTNB API (Tenaga Nasional Berhad)"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -16,6 +16,7 @@ from mytnb.client.config import (
16
16
  USER_AGENT,
17
17
  _check_http_status,
18
18
  )
19
+ from mytnb.client.retry import RETRYABLE_STATUS_CODES, with_retry
19
20
  from mytnb.crypto import encrypt_request
20
21
  from mytnb.exceptions import (
21
22
  APIError,
@@ -94,22 +95,27 @@ class _LegacyTransport:
94
95
  payload = encrypt_request(data, use_staging_key=self._use_staging_key)
95
96
  body = {"dt": payload.to_dict()}
96
97
 
97
- response = await asyncio.to_thread(
98
- self._session.post,
99
- url,
100
- headers=req_headers,
101
- json=body,
102
- timeout=int(self._timeout),
103
- )
104
- logger.debug("Legacy POST %s → %s", endpoint, response.status_code)
98
+ async def _send() -> Any:
99
+ response = await asyncio.to_thread(
100
+ self._session.post,
101
+ url,
102
+ headers=req_headers,
103
+ json=body,
104
+ timeout=int(self._timeout),
105
+ )
106
+ logger.debug("Legacy POST %s → %s", endpoint, response.status_code)
105
107
 
106
- _check_http_status(response.status_code, context="legacy API")
108
+ _check_http_status(response.status_code, context="legacy API")
107
109
 
108
- if response.status_code != 200:
109
- raise APIError(
110
- message=f"Legacy API request failed with status {response.status_code}",
111
- error_code=str(response.status_code),
112
- )
110
+ if response.status_code != 200:
111
+ raise APIError(
112
+ message=f"Legacy API request failed with status {response.status_code}",
113
+ error_code=str(response.status_code),
114
+ retryable=response.status_code in RETRYABLE_STATUS_CODES,
115
+ )
116
+ return response
117
+
118
+ response = await with_retry(_send, logger=logger)
113
119
 
114
120
  data = response.json()
115
121
 
@@ -10,6 +10,7 @@ import httpx
10
10
 
11
11
  from mytnb.auth import Credentials
12
12
  from mytnb.client.config import REST_BASE_URL, _check_http_status
13
+ from mytnb.client.retry import RETRYABLE_STATUS_CODES, with_retry
13
14
  from mytnb.exceptions import APIError
14
15
 
15
16
  logger = logging.getLogger(__name__)
@@ -70,16 +71,26 @@ class _RestTransport:
70
71
  if params is None:
71
72
  params = {"environment": "Prod"}
72
73
 
73
- response = await self._client.post(
74
- url,
75
- headers=req_headers,
76
- json=body or {},
77
- params=params,
78
- )
79
- logger.debug("REST POST %s → %s", path, response.status_code)
80
-
81
- _check_http_status(response.status_code)
82
- response.raise_for_status()
74
+ async def _send() -> httpx.Response:
75
+ response = await self._client.post(
76
+ url,
77
+ headers=req_headers,
78
+ json=body or {},
79
+ params=params,
80
+ )
81
+ logger.debug("REST POST %s → %s", path, response.status_code)
82
+
83
+ _check_http_status(response.status_code)
84
+ if response.status_code in RETRYABLE_STATUS_CODES:
85
+ raise APIError(
86
+ message=f"REST API request failed with status {response.status_code}",
87
+ error_code=str(response.status_code),
88
+ retryable=True,
89
+ )
90
+ response.raise_for_status()
91
+ return response
92
+
93
+ response = await with_retry(_send, logger=logger)
83
94
  data = response.json()
84
95
 
85
96
  status = data.get("statusDetail", {})
@@ -109,9 +120,19 @@ class _RestTransport:
109
120
  if params is None:
110
121
  params = {"environment": "Prod"}
111
122
 
112
- response = await self._client.get(url, headers=req_headers, params=params)
113
- logger.debug("REST GET %s → %s", path, response.status_code)
114
-
115
- _check_http_status(response.status_code)
116
- response.raise_for_status()
123
+ async def _send() -> httpx.Response:
124
+ response = await self._client.get(url, headers=req_headers, params=params)
125
+ logger.debug("REST GET %s → %s", path, response.status_code)
126
+
127
+ _check_http_status(response.status_code)
128
+ if response.status_code in RETRYABLE_STATUS_CODES:
129
+ raise APIError(
130
+ message=f"REST API request failed with status {response.status_code}",
131
+ error_code=str(response.status_code),
132
+ retryable=True,
133
+ )
134
+ response.raise_for_status()
135
+ return response
136
+
137
+ response = await with_retry(_send, logger=logger)
117
138
  return response.json()
@@ -0,0 +1,92 @@
1
+ """Bounded retry with exponential backoff for transient transport failures.
2
+
3
+ The myTNB APIs sit behind CloudFront/WAF and intermittently return transient
4
+ errors (a spurious 404, occasional 5xx, or a dropped connection) that succeed
5
+ on an immediate retry. This helper absorbs those blips inside a single call so
6
+ that a one-off failure does not surface as a hard error to callers.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import logging
13
+ import random
14
+ from typing import Awaitable, Callable, TypeVar
15
+
16
+ import httpx
17
+ from curl_cffi.requests.exceptions import RequestException as CurlRequestException
18
+
19
+ from mytnb.exceptions import MyTNBError
20
+
21
+ T = TypeVar("T")
22
+
23
+ # HTTP statuses treated as transient. 404 is unusual to retry, but for this
24
+ # WAF-fronted API it is a known intermittent edge failure, not a real
25
+ # "not found". 429 is deliberately excluded — retrying a rate limiter only
26
+ # makes it worse; let RateLimitError propagate.
27
+ RETRYABLE_STATUS_CODES = frozenset({404, 500, 502, 503, 504})
28
+
29
+ # Network/transport-level errors that are always safe to retry.
30
+ _RETRYABLE_EXCEPTIONS = (
31
+ httpx.TransportError,
32
+ httpx.TimeoutException,
33
+ CurlRequestException,
34
+ )
35
+
36
+ DEFAULT_MAX_ATTEMPTS = 3
37
+ DEFAULT_BASE_DELAY = 0.5
38
+
39
+
40
+ def _is_retryable(err: Exception) -> bool:
41
+ """Return True if the error is a transient failure worth retrying."""
42
+ if isinstance(err, _RETRYABLE_EXCEPTIONS):
43
+ return True
44
+ return isinstance(err, MyTNBError) and getattr(err, "retryable", False)
45
+
46
+
47
+ async def with_retry(
48
+ send: Callable[[], Awaitable[T]],
49
+ *,
50
+ attempts: int = DEFAULT_MAX_ATTEMPTS,
51
+ base_delay: float = DEFAULT_BASE_DELAY,
52
+ logger: logging.Logger | None = None,
53
+ ) -> T:
54
+ """Call ``send`` with exponential backoff on transient failures.
55
+
56
+ Args:
57
+ send: Zero-arg coroutine factory performing one request attempt.
58
+ attempts: Maximum number of attempts (including the first).
59
+ base_delay: Base backoff delay in seconds (with added jitter).
60
+ logger: Optional logger for debug messages between retries.
61
+
62
+ Returns:
63
+ Whatever ``send`` returns on the first successful attempt.
64
+
65
+ Raises:
66
+ ValueError: If ``attempts`` < 1 or ``base_delay`` < 0.
67
+ The last exception raised by ``send`` once attempts are exhausted, or
68
+ immediately for any non-retryable error.
69
+ """
70
+ if attempts < 1:
71
+ raise ValueError(f"attempts must be >= 1, got {attempts}")
72
+ if base_delay < 0:
73
+ raise ValueError(f"base_delay must be >= 0, got {base_delay}")
74
+
75
+ for attempt in range(attempts):
76
+ try:
77
+ return await send()
78
+ except Exception as err: # noqa: BLE001 - re-raised below unless retryable
79
+ if attempt >= attempts - 1 or not _is_retryable(err):
80
+ raise
81
+ delay = base_delay * 2**attempt + random.uniform(0, base_delay)
82
+ if logger is not None:
83
+ logger.debug(
84
+ "Transient request failure (attempt %d/%d), retrying in %.2fs: %s",
85
+ attempt + 1,
86
+ attempts,
87
+ delay,
88
+ err,
89
+ )
90
+ await asyncio.sleep(delay)
91
+ # Unreachable: the loop either returns or raises on the final attempt.
92
+ raise RuntimeError("with_retry exhausted attempts without returning")
@@ -23,8 +23,10 @@ class APIError(MyTNBError):
23
23
  message: str,
24
24
  error_code: str | None = None,
25
25
  display_message: str | None = None,
26
+ retryable: bool = False,
26
27
  ):
27
28
  self.display_message = display_message
29
+ self.retryable = retryable
28
30
  super().__init__(message, error_code)
29
31
 
30
32
 
@@ -269,10 +269,29 @@ class AccountUsage(BaseModel):
269
269
 
270
270
  @property
271
271
  def average_usage_kwh(self) -> Optional[float]:
272
- for m in self.usage_metrics:
273
- if m.key == "AVGUSAGE":
274
- return m.numeric_value
275
- return None
272
+ """Average daily consumption (kWh) across available daily readings.
273
+
274
+ Computed from ``by_day`` rather than a usage metric: the API's
275
+ ``AVERAGEUSAGE`` metric is a percentage comparison against the previous
276
+ bill period (e.g. "20% — More than the last bill period"), not a kWh
277
+ value. Days with no recorded consumption are excluded: both missing
278
+ readings and zero-usage days (such as the current, still-partial day).
279
+ Returns None when there is no usable daily data.
280
+ """
281
+ values: list[float] = []
282
+ for week in self.by_day:
283
+ for day in week.days:
284
+ if day.is_missing_reading:
285
+ continue
286
+ try:
287
+ consumption = day.consumption_kwh
288
+ except (ValueError, TypeError):
289
+ continue
290
+ if consumption > 0:
291
+ values.append(consumption)
292
+ if not values:
293
+ return None
294
+ return round(sum(values) / len(values), 2)
276
295
 
277
296
  @property
278
297
  def current_cost_rm(self) -> Optional[float]:
@@ -12,6 +12,7 @@ import pytest
12
12
  from mytnb.auth import Credentials, DeviceInfo, UserInfo
13
13
  from mytnb.client import MyTNBClient
14
14
  from mytnb.client.config import DEFAULT_API_KEY
15
+ from mytnb.client.retry import DEFAULT_MAX_ATTEMPTS
15
16
  from mytnb.exceptions import APIError, AuthenticationError, MyTNBError, RateLimitError
16
17
 
17
18
  # ── Fixtures ──────────────────────────────────────────────────────────────
@@ -168,6 +169,49 @@ class TestRestPost:
168
169
  with pytest.raises(APIError, match="Internal error"):
169
170
  await client._rest_transport.post("test/endpoint")
170
171
 
172
+ @pytest.mark.asyncio
173
+ async def test_post_retries_transient_503(self, monkeypatch):
174
+ """A transient HTTP 503 is retried and the eventual 200 succeeds."""
175
+ monkeypatch.setattr("mytnb.client.retry.asyncio.sleep", AsyncMock())
176
+ success = _mock_response(
177
+ {"statusDetail": {"code": "7200"}, "content": {"result": "ok"}}
178
+ )
179
+ async with MyTNBClient(_creds()) as client:
180
+ with patch.object(
181
+ client._client, "post", new_callable=AsyncMock,
182
+ side_effect=[_mock_response({}, status_code=503), success],
183
+ ) as mock_post:
184
+ result = await client._rest_transport.post("test/endpoint")
185
+ assert result["content"]["result"] == "ok"
186
+ assert mock_post.call_count == 2
187
+
188
+ @pytest.mark.asyncio
189
+ async def test_post_persistent_404_raises_after_attempts(self, monkeypatch):
190
+ """A persistent HTTP 404 raises APIError after exhausting attempts."""
191
+ monkeypatch.setattr("mytnb.client.retry.asyncio.sleep", AsyncMock())
192
+ async with MyTNBClient(_creds()) as client:
193
+ with patch.object(
194
+ client._client, "post", new_callable=AsyncMock,
195
+ return_value=_mock_response({}, status_code=404),
196
+ ) as mock_post:
197
+ with pytest.raises(APIError, match="status 404"):
198
+ await client._rest_transport.post("test/endpoint")
199
+ assert mock_post.call_count == DEFAULT_MAX_ATTEMPTS
200
+
201
+ @pytest.mark.asyncio
202
+ async def test_get_retries_transient_502(self, monkeypatch):
203
+ """REST GET retries a transient HTTP 502 then returns the payload."""
204
+ monkeypatch.setattr("mytnb.client.retry.asyncio.sleep", AsyncMock())
205
+ success = _mock_response({"content": {"result": "ok"}})
206
+ async with MyTNBClient(_creds()) as client:
207
+ with patch.object(
208
+ client._client, "get", new_callable=AsyncMock,
209
+ side_effect=[_mock_response({}, status_code=502), success],
210
+ ) as mock_get:
211
+ result = await client._rest_transport.get("test/endpoint")
212
+ assert result["content"]["result"] == "ok"
213
+ assert mock_get.call_count == 2
214
+
171
215
 
172
216
  # ── Legacy API ────────────────────────────────────────────────────────────
173
217
 
@@ -225,6 +269,38 @@ class TestLegacyPost:
225
269
  with pytest.raises(AuthenticationError):
226
270
  await client._legacy_transport.post("TestEndpoint", {})
227
271
 
272
+ @pytest.mark.asyncio
273
+ async def test_legacy_retries_transient_404(self, monkeypatch):
274
+ """A transient HTTP 404 is retried and the eventual 200 succeeds."""
275
+ monkeypatch.setattr("mytnb.client.retry.asyncio.sleep", AsyncMock())
276
+ success_data = {
277
+ "d": {"isError": "false", "ErrorCode": "7200", "data": {"result": "ok"}}
278
+ }
279
+ async with MyTNBClient(_creds()) as client:
280
+ mock_session = MagicMock()
281
+ mock_session.post.side_effect = [
282
+ _mock_tls_response({}, status_code=404),
283
+ _mock_tls_response(success_data),
284
+ ]
285
+ client._tls_session = mock_session
286
+
287
+ result = await client._legacy_transport.post("TestEndpoint", {})
288
+ assert result["data"]["result"] == "ok"
289
+ assert mock_session.post.call_count == 2
290
+
291
+ @pytest.mark.asyncio
292
+ async def test_legacy_persistent_404_raises_after_attempts(self, monkeypatch):
293
+ """A persistent HTTP 404 raises APIError after exhausting attempts."""
294
+ monkeypatch.setattr("mytnb.client.retry.asyncio.sleep", AsyncMock())
295
+ async with MyTNBClient(_creds()) as client:
296
+ mock_session = MagicMock()
297
+ mock_session.post.return_value = _mock_tls_response({}, status_code=404)
298
+ client._tls_session = mock_session
299
+
300
+ with pytest.raises(APIError, match="status 404"):
301
+ await client._legacy_transport.post("TestEndpoint", {})
302
+ assert mock_session.post.call_count == DEFAULT_MAX_ATTEMPTS
303
+
228
304
 
229
305
  # ── Endpoint methods ─────────────────────────────────────────────────────
230
306
 
@@ -88,12 +88,15 @@ FULL_API_RESPONSE = {
88
88
  "OtherUsageMetrics": {
89
89
  "Usage": [
90
90
  USAGE_METRIC_DATA,
91
+ # Real API shape: AVERAGEUSAGE is a percentage comparison vs the last
92
+ # bill period, not a kWh average (that's why average_usage_kwh is
93
+ # computed from by_day instead of read from this metric).
91
94
  {
92
- "Key": "AVGUSAGE",
95
+ "Key": "AVERAGEUSAGE",
93
96
  "Title": "Avg Usage",
94
- "SubTitle": "daily",
95
- "Value": "15.6",
96
- "ValueUnit": "kWh",
97
+ "SubTitle": "More than the last bill period",
98
+ "Value": "20%",
99
+ "ValueUnit": "",
97
100
  },
98
101
  ],
99
102
  "Cost": [
@@ -245,8 +248,36 @@ class TestAccountUsage:
245
248
  assert usage.current_usage_kwh == 234.5
246
249
 
247
250
  def test_average_usage_kwh(self):
251
+ # Computed from by_day (mean of daily consumption), not a usage metric.
248
252
  usage = AccountUsage.from_api_response(FULL_API_RESPONSE)
249
- assert usage.average_usage_kwh == 15.6
253
+ assert usage.average_usage_kwh == 8.5
254
+
255
+ def test_average_usage_kwh_multiple_days(self):
256
+ data = {
257
+ "ByDay": [
258
+ {
259
+ "Range": "Week 1",
260
+ "Days": [
261
+ # Two valid days that count toward the average.
262
+ {"Date": "2026-06-01", "Year": "2026", "Month": "06",
263
+ "Day": "01", "Consumption": "10", "Amount": "2.7"},
264
+ {"Date": "2026-06-02", "Year": "2026", "Month": "06",
265
+ "Day": "02", "Consumption": "20", "Amount": "5.4"},
266
+ # Excluded via the missing-reading flag (high value would
267
+ # skew the mean if the filter regressed).
268
+ {"Date": "2026-06-03", "Year": "2026", "Month": "06",
269
+ "Day": "03", "Consumption": "99", "Amount": "26.7",
270
+ "IsMissingReading": True},
271
+ # Excluded via zero consumption (the current partial day),
272
+ # independently of the missing-reading flag.
273
+ {"Date": "2026-06-04", "Year": "2026", "Month": "06",
274
+ "Day": "04", "Consumption": "0", "Amount": "0"},
275
+ ],
276
+ }
277
+ ],
278
+ }
279
+ usage = AccountUsage.from_api_response(data)
280
+ assert usage.average_usage_kwh == 15.0 # mean(10, 20)
250
281
 
251
282
  def test_current_cost_rm(self):
252
283
  usage = AccountUsage.from_api_response(FULL_API_RESPONSE)
@@ -0,0 +1,106 @@
1
+ """Tests for the transport retry helper."""
2
+
3
+ import httpx
4
+ import pytest
5
+
6
+ from mytnb.client.retry import RETRYABLE_STATUS_CODES, with_retry
7
+ from mytnb.exceptions import APIError, AuthenticationError
8
+
9
+
10
+ class _Counter:
11
+ """Callable that records how many times it was awaited."""
12
+
13
+ def __init__(self, side_effect):
14
+ self.calls = 0
15
+ self._side_effect = side_effect
16
+
17
+ async def __call__(self):
18
+ self.calls += 1
19
+ result = self._side_effect(self.calls)
20
+ if isinstance(result, Exception):
21
+ raise result
22
+ return result
23
+
24
+
25
+ @pytest.mark.asyncio
26
+ async def test_returns_on_first_success():
27
+ send = _Counter(lambda n: "ok")
28
+ result = await with_retry(send, base_delay=0)
29
+ assert result == "ok"
30
+ assert send.calls == 1
31
+
32
+
33
+ @pytest.mark.asyncio
34
+ async def test_retries_then_succeeds():
35
+ def effect(n):
36
+ if n < 3:
37
+ return APIError("transient", error_code="503", retryable=True)
38
+ return "ok"
39
+
40
+ send = _Counter(effect)
41
+ result = await with_retry(send, attempts=3, base_delay=0)
42
+ assert result == "ok"
43
+ assert send.calls == 3
44
+
45
+
46
+ @pytest.mark.asyncio
47
+ async def test_gives_up_after_attempts():
48
+ send = _Counter(lambda n: APIError("still failing", error_code="503", retryable=True))
49
+ with pytest.raises(APIError, match="still failing"):
50
+ await with_retry(send, attempts=3, base_delay=0)
51
+ assert send.calls == 3
52
+
53
+
54
+ @pytest.mark.asyncio
55
+ async def test_does_not_retry_non_retryable():
56
+ send = _Counter(lambda n: AuthenticationError("bad creds", error_code="401"))
57
+ with pytest.raises(AuthenticationError):
58
+ await with_retry(send, attempts=3, base_delay=0)
59
+ assert send.calls == 1
60
+
61
+
62
+ @pytest.mark.asyncio
63
+ async def test_non_retryable_api_error_not_retried():
64
+ # An APIError without retryable=True (e.g. a business error) is terminal.
65
+ send = _Counter(lambda n: APIError("business error", error_code="5000"))
66
+ with pytest.raises(APIError, match="business error"):
67
+ await with_retry(send, attempts=3, base_delay=0)
68
+ assert send.calls == 1
69
+
70
+
71
+ @pytest.mark.asyncio
72
+ async def test_network_error_is_retryable():
73
+ def effect(n):
74
+ if n < 2:
75
+ return httpx.ConnectError("connection reset")
76
+ return "ok"
77
+
78
+ send = _Counter(effect)
79
+ result = await with_retry(send, attempts=3, base_delay=0)
80
+ assert result == "ok"
81
+ assert send.calls == 2
82
+
83
+
84
+ @pytest.mark.asyncio
85
+ async def test_invalid_attempts_raises():
86
+ send = _Counter(lambda n: "ok")
87
+ with pytest.raises(ValueError, match="attempts must be >= 1"):
88
+ await with_retry(send, attempts=0, base_delay=0)
89
+ assert send.calls == 0
90
+
91
+
92
+ @pytest.mark.asyncio
93
+ async def test_invalid_base_delay_raises():
94
+ send = _Counter(lambda n: "ok")
95
+ with pytest.raises(ValueError, match="base_delay must be >= 0"):
96
+ await with_retry(send, base_delay=-1)
97
+ assert send.calls == 0
98
+
99
+
100
+ def test_retryable_status_codes():
101
+ assert 404 in RETRYABLE_STATUS_CODES
102
+ assert 503 in RETRYABLE_STATUS_CODES
103
+ # Auth / geoblock / rate-limit are handled separately, never retried here.
104
+ assert 401 not in RETRYABLE_STATUS_CODES
105
+ assert 403 not in RETRYABLE_STATUS_CODES
106
+ assert 429 not in RETRYABLE_STATUS_CODES
@@ -600,7 +600,7 @@ wheels = [
600
600
 
601
601
  [[package]]
602
602
  name = "python-mytnb"
603
- version = "0.4.0"
603
+ version = "0.5.3"
604
604
  source = { editable = "." }
605
605
  dependencies = [
606
606
  { name = "cryptography" },
File without changes
File without changes
File without changes