python-mytnb 0.5.2__tar.gz → 0.5.4__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.
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/PKG-INFO +25 -14
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/README.md +24 -13
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/pyproject.toml +1 -1
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/src/mytnb/__init__.py +2 -0
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/src/mytnb/cli.py +37 -1
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/src/mytnb/client/client.py +80 -12
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/src/mytnb/client/legacy.py +20 -14
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/src/mytnb/client/rest.py +36 -15
- python_mytnb-0.5.4/src/mytnb/client/retry.py +92 -0
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/src/mytnb/exceptions.py +2 -0
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/src/mytnb/models.py +56 -3
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/tests/test_client.py +76 -0
- python_mytnb-0.5.4/tests/test_retry.py +106 -0
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/uv.lock +1 -1
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/.github/workflows/ci.yml +0 -0
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/.github/workflows/publish.yml +0 -0
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/.gitignore +0 -0
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/LICENSE +0 -0
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/src/mytnb/__main__.py +0 -0
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/src/mytnb/auth.py +0 -0
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/src/mytnb/client/__init__.py +0 -0
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/src/mytnb/client/auth.py +0 -0
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/src/mytnb/client/config.py +0 -0
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/src/mytnb/crypto.py +0 -0
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/tests/test_auth.py +0 -0
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/tests/test_cli.py +0 -0
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/tests/test_crypto.py +0 -0
- {python_mytnb-0.5.2 → python_mytnb-0.5.4}/tests/test_models.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: python-mytnb
|
|
3
|
-
Version: 0.5.
|
|
3
|
+
Version: 0.5.4
|
|
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
|
|
@@ -73,10 +73,17 @@ async def main():
|
|
|
73
73
|
for month in usage.by_month.months:
|
|
74
74
|
print(f"{month.month} {month.year}: {month.usage_total} kWh — RM {month.amount_total}")
|
|
75
75
|
|
|
76
|
-
# Bill history & due amount
|
|
76
|
+
# Bill history, payment history & due amount
|
|
77
77
|
history = await client.get_bill_history("220123456789")
|
|
78
|
+
payments = await client.get_payment_history("220123456789")
|
|
78
79
|
due = await client.get_account_due_amount("220123456789")
|
|
79
80
|
|
|
81
|
+
# Most account-scoped methods also accept a CustomerAccount directly
|
|
82
|
+
# (is_owner and account_type are derived automatically)
|
|
83
|
+
for acc in accounts:
|
|
84
|
+
if acc.is_smart_meter:
|
|
85
|
+
usage = await client.get_account_usage_smart(acc)
|
|
86
|
+
|
|
80
87
|
asyncio.run(main())
|
|
81
88
|
```
|
|
82
89
|
|
|
@@ -115,7 +122,8 @@ mytnb usage --daily <account> # Daily usage breakdown
|
|
|
115
122
|
mytnb usage --json <account> # Full usage data as JSON
|
|
116
123
|
mytnb current-usage <account> # Simplified current usage summary
|
|
117
124
|
mytnb due-amount <account> # Outstanding balance
|
|
118
|
-
mytnb bill-history <account> #
|
|
125
|
+
mytnb bill-history <account> # Bill history (bills issued)
|
|
126
|
+
mytnb payment-history <account> # Bill & payment history
|
|
119
127
|
```
|
|
120
128
|
|
|
121
129
|
Global options: `--debug` for full tracebacks, `--version`.
|
|
@@ -140,17 +148,20 @@ Request encryption for the ASMX API is automatic — just pass plaintext paramet
|
|
|
140
148
|
|
|
141
149
|
## Data Models
|
|
142
150
|
|
|
143
|
-
| Model
|
|
144
|
-
|
|
|
145
|
-
| `CustomerAccount`
|
|
146
|
-
| `AccountUsage`
|
|
147
|
-
| `UsageMetric`
|
|
148
|
-
| `CostMetric`
|
|
149
|
-
| `BillingMonth`
|
|
150
|
-
| `DailyUsage`
|
|
151
|
-
| `TariffBlock`
|
|
152
|
-
| `
|
|
153
|
-
| `
|
|
151
|
+
| Model | Description |
|
|
152
|
+
| --------------------- | ---------------------------------------------------- |
|
|
153
|
+
| `CustomerAccount` | Linked account: number, owner, address, SMR status |
|
|
154
|
+
| `AccountUsage` | Full usage response: metrics, monthly and daily data |
|
|
155
|
+
| `UsageMetric` | Current/average usage (kWh) |
|
|
156
|
+
| `CostMetric` | Current/projected cost (RM) |
|
|
157
|
+
| `BillingMonth` | Monthly billing record with tariff blocks |
|
|
158
|
+
| `DailyUsage` | Daily consumption and cost |
|
|
159
|
+
| `TariffBlock` | Tariff pricing block details |
|
|
160
|
+
| `BillHistoryEntry` | Single bill issued (date, amount, billing number) |
|
|
161
|
+
| `PaymentHistoryEntry` | Bill or payment entry with type, method, reference |
|
|
162
|
+
| `AccountDueAmount` | Outstanding balance and due date |
|
|
163
|
+
| `SMRAccount` | Smart Meter Reading eligibility status |
|
|
164
|
+
| `BREligibility` | Bill rendering opt-in status |
|
|
154
165
|
|
|
155
166
|
## Geographic Restrictions
|
|
156
167
|
|
|
@@ -39,10 +39,17 @@ async def main():
|
|
|
39
39
|
for month in usage.by_month.months:
|
|
40
40
|
print(f"{month.month} {month.year}: {month.usage_total} kWh — RM {month.amount_total}")
|
|
41
41
|
|
|
42
|
-
# Bill history & due amount
|
|
42
|
+
# Bill history, payment history & due amount
|
|
43
43
|
history = await client.get_bill_history("220123456789")
|
|
44
|
+
payments = await client.get_payment_history("220123456789")
|
|
44
45
|
due = await client.get_account_due_amount("220123456789")
|
|
45
46
|
|
|
47
|
+
# Most account-scoped methods also accept a CustomerAccount directly
|
|
48
|
+
# (is_owner and account_type are derived automatically)
|
|
49
|
+
for acc in accounts:
|
|
50
|
+
if acc.is_smart_meter:
|
|
51
|
+
usage = await client.get_account_usage_smart(acc)
|
|
52
|
+
|
|
46
53
|
asyncio.run(main())
|
|
47
54
|
```
|
|
48
55
|
|
|
@@ -81,7 +88,8 @@ mytnb usage --daily <account> # Daily usage breakdown
|
|
|
81
88
|
mytnb usage --json <account> # Full usage data as JSON
|
|
82
89
|
mytnb current-usage <account> # Simplified current usage summary
|
|
83
90
|
mytnb due-amount <account> # Outstanding balance
|
|
84
|
-
mytnb bill-history <account> #
|
|
91
|
+
mytnb bill-history <account> # Bill history (bills issued)
|
|
92
|
+
mytnb payment-history <account> # Bill & payment history
|
|
85
93
|
```
|
|
86
94
|
|
|
87
95
|
Global options: `--debug` for full tracebacks, `--version`.
|
|
@@ -106,17 +114,20 @@ Request encryption for the ASMX API is automatic — just pass plaintext paramet
|
|
|
106
114
|
|
|
107
115
|
## Data Models
|
|
108
116
|
|
|
109
|
-
| Model
|
|
110
|
-
|
|
|
111
|
-
| `CustomerAccount`
|
|
112
|
-
| `AccountUsage`
|
|
113
|
-
| `UsageMetric`
|
|
114
|
-
| `CostMetric`
|
|
115
|
-
| `BillingMonth`
|
|
116
|
-
| `DailyUsage`
|
|
117
|
-
| `TariffBlock`
|
|
118
|
-
| `
|
|
119
|
-
| `
|
|
117
|
+
| Model | Description |
|
|
118
|
+
| --------------------- | ---------------------------------------------------- |
|
|
119
|
+
| `CustomerAccount` | Linked account: number, owner, address, SMR status |
|
|
120
|
+
| `AccountUsage` | Full usage response: metrics, monthly and daily data |
|
|
121
|
+
| `UsageMetric` | Current/average usage (kWh) |
|
|
122
|
+
| `CostMetric` | Current/projected cost (RM) |
|
|
123
|
+
| `BillingMonth` | Monthly billing record with tariff blocks |
|
|
124
|
+
| `DailyUsage` | Daily consumption and cost |
|
|
125
|
+
| `TariffBlock` | Tariff pricing block details |
|
|
126
|
+
| `BillHistoryEntry` | Single bill issued (date, amount, billing number) |
|
|
127
|
+
| `PaymentHistoryEntry` | Bill or payment entry with type, method, reference |
|
|
128
|
+
| `AccountDueAmount` | Outstanding balance and due date |
|
|
129
|
+
| `SMRAccount` | Smart Meter Reading eligibility status |
|
|
130
|
+
| `BREligibility` | Bill rendering opt-in status |
|
|
120
131
|
|
|
121
132
|
## Geographic Restrictions
|
|
122
133
|
|
|
@@ -11,6 +11,7 @@ from mytnb.models import (
|
|
|
11
11
|
CustomerAccount,
|
|
12
12
|
DailyUsage,
|
|
13
13
|
Metric,
|
|
14
|
+
PaymentHistoryEntry,
|
|
14
15
|
TariffBlock,
|
|
15
16
|
TariffBlockLegendGroup,
|
|
16
17
|
TariffBlockLegendItem,
|
|
@@ -29,6 +30,7 @@ __all__ = [
|
|
|
29
30
|
"CustomerAccount",
|
|
30
31
|
"DailyUsage",
|
|
31
32
|
"Metric",
|
|
33
|
+
"PaymentHistoryEntry",
|
|
32
34
|
"TariffBlock",
|
|
33
35
|
"TariffBlockLegendGroup",
|
|
34
36
|
"TariffBlockLegendItem",
|
|
@@ -313,7 +313,7 @@ def due_amount(ctx, account, as_json):
|
|
|
313
313
|
@click.option("--json", "as_json", is_flag=True, help="Output full JSON.")
|
|
314
314
|
@click.pass_context
|
|
315
315
|
def bill_history(ctx, account, as_json):
|
|
316
|
-
"""Get bill
|
|
316
|
+
"""Get bill history (bills issued)."""
|
|
317
317
|
|
|
318
318
|
async def _history():
|
|
319
319
|
client = await _get_client(ctx)
|
|
@@ -340,6 +340,42 @@ def bill_history(ctx, account, as_json):
|
|
|
340
340
|
_run_async(_history())
|
|
341
341
|
|
|
342
342
|
|
|
343
|
+
@cli.command("payment-history")
|
|
344
|
+
@click.argument("account")
|
|
345
|
+
@click.option("--json", "as_json", is_flag=True, help="Output full JSON.")
|
|
346
|
+
@click.pass_context
|
|
347
|
+
def payment_history(ctx, account, as_json):
|
|
348
|
+
"""Get bill & payment history."""
|
|
349
|
+
|
|
350
|
+
async def _history():
|
|
351
|
+
client = await _get_client(ctx)
|
|
352
|
+
async with client:
|
|
353
|
+
with console.status("[bold green]Fetching..."):
|
|
354
|
+
result = await client.get_payment_history(account)
|
|
355
|
+
|
|
356
|
+
if as_json:
|
|
357
|
+
_print_json(result)
|
|
358
|
+
return
|
|
359
|
+
|
|
360
|
+
table = Table(title=f"Bill & Payment History — {account}")
|
|
361
|
+
table.add_column("Date", style="cyan")
|
|
362
|
+
table.add_column("Type")
|
|
363
|
+
table.add_column("Amount (RM)", justify="right", style="green")
|
|
364
|
+
table.add_column("Method / Ref")
|
|
365
|
+
for entry in result:
|
|
366
|
+
style = "green" if entry.is_payment else "red"
|
|
367
|
+
table.add_row(
|
|
368
|
+
entry.date.isoformat() if entry.date else "--",
|
|
369
|
+
entry.history_type_text or entry.history_type or "--",
|
|
370
|
+
f"[{style}]--[/{style}]" if entry.amount is None
|
|
371
|
+
else f"[{style}]{entry.amount:,.2f}[/{style}]",
|
|
372
|
+
entry.paid_via or entry.reference_number or "--",
|
|
373
|
+
)
|
|
374
|
+
console.print(table)
|
|
375
|
+
|
|
376
|
+
_run_async(_history())
|
|
377
|
+
|
|
378
|
+
|
|
343
379
|
@cli.command("init-config")
|
|
344
380
|
@click.option("-o", "--output", default="mytnb.json", help="Output path.")
|
|
345
381
|
def init_config(output):
|
|
@@ -21,12 +21,30 @@ from mytnb.models import (
|
|
|
21
21
|
BillHistoryEntry,
|
|
22
22
|
BREligibility,
|
|
23
23
|
CustomerAccount,
|
|
24
|
+
PaymentHistoryEntry,
|
|
24
25
|
SMRAccount,
|
|
25
26
|
)
|
|
26
27
|
|
|
27
28
|
logger = logging.getLogger(__name__)
|
|
28
29
|
|
|
29
30
|
|
|
31
|
+
def _resolve_account(
|
|
32
|
+
account: str | CustomerAccount,
|
|
33
|
+
is_owner: bool | None = None,
|
|
34
|
+
) -> tuple[str, bool, str]:
|
|
35
|
+
"""Resolve account identifier + metadata from a string or CustomerAccount.
|
|
36
|
+
|
|
37
|
+
Returns ``(account_number, is_owner, account_type)``.
|
|
38
|
+
"""
|
|
39
|
+
if isinstance(account, CustomerAccount):
|
|
40
|
+
return (
|
|
41
|
+
account.account_number,
|
|
42
|
+
is_owner if is_owner is not None else account.is_owned_bool,
|
|
43
|
+
"RE" if account.account_category_id == "2" else "UTIL",
|
|
44
|
+
)
|
|
45
|
+
return (account, is_owner if is_owner is not None else True, "UTIL")
|
|
46
|
+
|
|
47
|
+
|
|
30
48
|
class MyTNBClient:
|
|
31
49
|
"""Client for interacting with the myTNB API.
|
|
32
50
|
|
|
@@ -163,14 +181,15 @@ class MyTNBClient:
|
|
|
163
181
|
|
|
164
182
|
async def get_account_usage_smart(
|
|
165
183
|
self,
|
|
166
|
-
|
|
184
|
+
account: str | CustomerAccount,
|
|
167
185
|
*,
|
|
168
|
-
is_owner: bool =
|
|
186
|
+
is_owner: bool | None = None,
|
|
169
187
|
) -> AccountUsage:
|
|
170
188
|
"""Get smart meter account usage data."""
|
|
189
|
+
acc_no, owner, _ = _resolve_account(account, is_owner)
|
|
171
190
|
data = {
|
|
172
|
-
"contractAccount":
|
|
173
|
-
"isOwner": "true" if
|
|
191
|
+
"contractAccount": acc_no,
|
|
192
|
+
"isOwner": "true" if owner else "false",
|
|
174
193
|
"metercode": "",
|
|
175
194
|
"usrInf": self._legacy_transport.base_user_info(),
|
|
176
195
|
}
|
|
@@ -236,14 +255,15 @@ class MyTNBClient:
|
|
|
236
255
|
|
|
237
256
|
async def get_account_due_amount(
|
|
238
257
|
self,
|
|
239
|
-
|
|
258
|
+
account: str | CustomerAccount,
|
|
240
259
|
*,
|
|
241
|
-
is_owner: bool =
|
|
260
|
+
is_owner: bool | None = None,
|
|
242
261
|
) -> AccountDueAmount:
|
|
243
262
|
"""Get account due amount as a typed model."""
|
|
263
|
+
acc_no, owner, _ = _resolve_account(account, is_owner)
|
|
244
264
|
data = {
|
|
245
|
-
"contractAccount":
|
|
246
|
-
"isOwnedAccount": "true" if
|
|
265
|
+
"contractAccount": acc_no,
|
|
266
|
+
"isOwnedAccount": "true" if owner else "false",
|
|
247
267
|
"usrInf": self._legacy_transport.base_user_info(),
|
|
248
268
|
}
|
|
249
269
|
result = await self._legacy_transport.post("GetAccountDueAmount", data)
|
|
@@ -251,14 +271,15 @@ class MyTNBClient:
|
|
|
251
271
|
|
|
252
272
|
async def get_bill_history(
|
|
253
273
|
self,
|
|
254
|
-
|
|
274
|
+
account: str | CustomerAccount,
|
|
255
275
|
*,
|
|
256
|
-
is_owner: bool =
|
|
276
|
+
is_owner: bool | None = None,
|
|
257
277
|
) -> list[BillHistoryEntry]:
|
|
258
278
|
"""Get bill payment history as typed models (most recent first)."""
|
|
279
|
+
acc_no, owner, _ = _resolve_account(account, is_owner)
|
|
259
280
|
data = {
|
|
260
|
-
"contractAccount":
|
|
261
|
-
"isOwnedAccount": "true" if
|
|
281
|
+
"contractAccount": acc_no,
|
|
282
|
+
"isOwnedAccount": "true" if owner else "false",
|
|
262
283
|
"usrInf": self._legacy_transport.base_user_info(),
|
|
263
284
|
}
|
|
264
285
|
result = await self._legacy_transport.post("GetBillHistory", data)
|
|
@@ -279,6 +300,53 @@ class MyTNBClient:
|
|
|
279
300
|
)
|
|
280
301
|
return []
|
|
281
302
|
|
|
303
|
+
async def get_payment_history(
|
|
304
|
+
self,
|
|
305
|
+
account: str | CustomerAccount,
|
|
306
|
+
*,
|
|
307
|
+
is_owner: bool | None = None,
|
|
308
|
+
account_type: str | None = None,
|
|
309
|
+
) -> list[PaymentHistoryEntry]:
|
|
310
|
+
"""Get bill & payment history as typed models (most recent first).
|
|
311
|
+
|
|
312
|
+
Uses the GetAccountBillPayHistoryV4 endpoint which returns both bills
|
|
313
|
+
and payments. Each entry has a ``history_type`` field ("PAYMENT",
|
|
314
|
+
"BILL", or "ADVICE") so callers can filter as needed.
|
|
315
|
+
|
|
316
|
+
When ``account`` is a ``CustomerAccount``, ``is_owner`` and
|
|
317
|
+
``account_type`` are derived automatically (unless explicitly
|
|
318
|
+
overridden).
|
|
319
|
+
"""
|
|
320
|
+
acc_no, owner, derived_type = _resolve_account(account, is_owner)
|
|
321
|
+
if account_type is None:
|
|
322
|
+
account_type = derived_type
|
|
323
|
+
data = {
|
|
324
|
+
"contractAccount": acc_no,
|
|
325
|
+
"isOwnedAccount": owner,
|
|
326
|
+
"accountType": account_type,
|
|
327
|
+
"usrInf": self._legacy_transport.base_user_info(),
|
|
328
|
+
}
|
|
329
|
+
result = await self._legacy_transport.post(
|
|
330
|
+
"GetAccountBillPayHistoryV4", data
|
|
331
|
+
)
|
|
332
|
+
inner = result.get("data", result)
|
|
333
|
+
histories: list[PaymentHistoryEntry] = []
|
|
334
|
+
if isinstance(inner, dict):
|
|
335
|
+
for group in inner.get("BillPayHistories", []):
|
|
336
|
+
if not isinstance(group, dict):
|
|
337
|
+
continue
|
|
338
|
+
for item in group.get("BillPayHistoryData", []):
|
|
339
|
+
if isinstance(item, dict):
|
|
340
|
+
histories.append(PaymentHistoryEntry.model_validate(item))
|
|
341
|
+
elif isinstance(inner, list):
|
|
342
|
+
for group in inner:
|
|
343
|
+
if not isinstance(group, dict):
|
|
344
|
+
continue
|
|
345
|
+
for item in group.get("BillPayHistoryData", []):
|
|
346
|
+
if isinstance(item, dict):
|
|
347
|
+
histories.append(PaymentHistoryEntry.model_validate(item))
|
|
348
|
+
return histories
|
|
349
|
+
|
|
282
350
|
async def get_current_usage(self, account_number: str) -> dict:
|
|
283
351
|
"""Get a simplified summary of current usage."""
|
|
284
352
|
usage = await self.get_account_usage_smart(account_number)
|
|
@@ -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
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
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
|
-
|
|
108
|
+
_check_http_status(response.status_code, context="legacy API")
|
|
107
109
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
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
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
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
|
|
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import re
|
|
5
6
|
from datetime import date as date_cls
|
|
6
|
-
from datetime import datetime
|
|
7
|
+
from datetime import datetime, timezone
|
|
7
8
|
from typing import Any, Optional
|
|
8
9
|
|
|
9
10
|
from pydantic import AliasChoices, BaseModel, Field, field_validator
|
|
@@ -11,9 +12,12 @@ from pydantic import AliasChoices, BaseModel, Field, field_validator
|
|
|
11
12
|
# myTNB returns dates as DD/MM/YYYY; keep ISO variants as fallbacks.
|
|
12
13
|
_API_DATE_FORMATS = ("%d/%m/%Y", "%Y-%m-%d", "%d-%m-%Y")
|
|
13
14
|
|
|
15
|
+
# Microsoft JSON date format: /Date(1782921600000)/
|
|
16
|
+
_MS_DATE_RE = re.compile(r"/Date\((\d+)\)/")
|
|
17
|
+
|
|
14
18
|
|
|
15
19
|
def parse_api_date(value: Any) -> Optional[date_cls]:
|
|
16
|
-
"""Parse a myTNB date string (
|
|
20
|
+
"""Parse a myTNB date string (DD/MM/YYYY or /Date(ms)/) into a date.
|
|
17
21
|
|
|
18
22
|
Returns None for empty/None/unparseable input so a single bad field never
|
|
19
23
|
breaks an entire response.
|
|
@@ -24,6 +28,15 @@ def parse_api_date(value: Any) -> Optional[date_cls]:
|
|
|
24
28
|
return value
|
|
25
29
|
if not isinstance(value, str) or not value.strip():
|
|
26
30
|
return None
|
|
31
|
+
# Microsoft /Date(1782921600000)/ format (ms since epoch UTC)
|
|
32
|
+
ms_match = _MS_DATE_RE.fullmatch(value.strip())
|
|
33
|
+
if ms_match:
|
|
34
|
+
try:
|
|
35
|
+
return datetime.fromtimestamp(
|
|
36
|
+
int(ms_match.group(1)) / 1000, tz=timezone.utc
|
|
37
|
+
).date()
|
|
38
|
+
except (ValueError, OSError):
|
|
39
|
+
return None
|
|
27
40
|
for fmt in _API_DATE_FORMATS:
|
|
28
41
|
try:
|
|
29
42
|
return datetime.strptime(value.strip(), fmt).date()
|
|
@@ -436,7 +449,7 @@ class CustomerAccount(BaseModel):
|
|
|
436
449
|
|
|
437
450
|
|
|
438
451
|
class BillHistoryEntry(BaseModel):
|
|
439
|
-
"""A single bill
|
|
452
|
+
"""A single bill entry from GetBillHistory (bills *issued*, not payments).
|
|
440
453
|
|
|
441
454
|
Raw shape: {"DtBill": "31/05/2026", "AmPayable": "87.50", "BillingNo": "12345"}
|
|
442
455
|
"""
|
|
@@ -463,6 +476,46 @@ class BillHistoryEntry(BaseModel):
|
|
|
463
476
|
return "" if v is None else str(v)
|
|
464
477
|
|
|
465
478
|
|
|
479
|
+
class PaymentHistoryEntry(BaseModel):
|
|
480
|
+
"""A single payment-or-bill entry from GetAccountBillPayHistoryV4.
|
|
481
|
+
|
|
482
|
+
Raw shape:
|
|
483
|
+
{"BillOrPaymentDate":"15/01/2026","HistoryType":"Payment","Amount":"100.50",…}
|
|
484
|
+
"""
|
|
485
|
+
|
|
486
|
+
date: Optional[date_cls] = Field(default=None, alias="BillOrPaymentDate")
|
|
487
|
+
history_type: str = Field(default="", alias="HistoryType")
|
|
488
|
+
date_and_history_type: str = Field(default="", alias="DateAndHistoryType")
|
|
489
|
+
amount: Optional[float] = Field(default=None, alias="Amount")
|
|
490
|
+
reference_number: str = Field(default="", alias="DetailedInfoNumber")
|
|
491
|
+
paid_via: str = Field(default="", alias="PaidVia")
|
|
492
|
+
history_type_text: str = Field(default="", alias="HistoryTypeText")
|
|
493
|
+
is_payment_pending: bool = Field(default=False, alias="IsPaymentPending")
|
|
494
|
+
|
|
495
|
+
model_config = {"populate_by_name": True, "extra": "ignore"}
|
|
496
|
+
|
|
497
|
+
@field_validator("date", mode="before")
|
|
498
|
+
@classmethod
|
|
499
|
+
def _parse_date(cls, v: Any) -> Optional[date_cls]:
|
|
500
|
+
return parse_api_date(v)
|
|
501
|
+
|
|
502
|
+
@field_validator("amount", mode="before")
|
|
503
|
+
@classmethod
|
|
504
|
+
def _parse_amount(cls, v: Any) -> Optional[float]:
|
|
505
|
+
return _parse_optional_float(v)
|
|
506
|
+
|
|
507
|
+
@field_validator("history_type", "date_and_history_type", "reference_number",
|
|
508
|
+
"paid_via", "history_type_text", mode="before")
|
|
509
|
+
@classmethod
|
|
510
|
+
def _coerce_str(cls, v: Any) -> str:
|
|
511
|
+
return "" if v is None else str(v)
|
|
512
|
+
|
|
513
|
+
@property
|
|
514
|
+
def is_payment(self) -> bool:
|
|
515
|
+
"""True when this entry is a payment (not a bill or advice)."""
|
|
516
|
+
return self.history_type.upper() == "PAYMENT" # pylint: disable=no-member
|
|
517
|
+
|
|
518
|
+
|
|
466
519
|
class AccountDueAmount(BaseModel):
|
|
467
520
|
"""Outstanding balance for an account from GetAccountDueAmount.
|
|
468
521
|
|
|
@@ -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
|
|
|
@@ -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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|