From aaa78cf975f8869ab8faa07a355964827991f1cc Mon Sep 17 00:00:00 2001 From: Pavel Kuzmin Date: Fri, 20 Nov 2026 13:38:52 +0500 Subject: [PATCH] fix: align with the regenerated API spec (3.1.1) - wait_code: no KeyError on a getState operation without `response`; retries ApiError TRY_AGAIN_LATER / ERROR_UNDEFINED / INTERVAL_CONCURRENT_REQUESTS_ERROR until the deadline. - Types: Profile number int|None, country str|None; Operation.response optional; RentSms.code str|int (0 for notify, kept as sent); nullable free-list and payment-order fields; paylist kept when sent as a JSON array. - Error table: add "0", ACCOUNT_CLEANED, USER_NOT_ACTIVATED, ERROR_UNDEFINED, FORWARD_NOT_SUPPORTED; drop dead codes; NoNumberError only for NO_NUMBER. - MockOnlineSim mirrors the JS reference: revise/ok tzid rules, missing vs wrong key, rent reservation/confirmation, sum types, extend/close rules, webhook-log params, any scheme:// URL, payment forms/buttons, free list 44-first, count clamp, ISO created_at, ignore/content. - Docs, CHANGELOG, version 3.1.1. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 13 ++++ README.md | 2 +- docs/content/changelog.md | 6 ++ docs/content/index.md | 8 +- docs/content/numbers.md | 14 ++-- docs/content/rent.md | 14 ++-- docs/content/testing.md | 14 ++-- docs/content/user.md | 6 +- docs/content/webhooks.md | 8 +- onlinesimru/client.py | 5 +- onlinesimru/errors.py | 15 ++-- onlinesimru/mock/__init__.py | 9 ++- onlinesimru/mock/_handlers.py | 120 ++++++++++++++++++---------- onlinesimru/mock/_state.py | 45 ++++++++--- onlinesimru/models.py | 38 +++++---- onlinesimru/numbers.py | 3 +- onlinesimru/rent.py | 5 +- onlinesimru/user.py | 8 +- onlinesimru/wait.py | 22 ++++-- pyproject.toml | 2 +- tests/test_client.py | 18 +++-- tests/test_free.py | 6 ++ tests/test_integration.py | 4 +- tests/test_mock.py | 143 ++++++++++++++++++++++++++++------ tests/test_numbers.py | 23 ++++++ tests/test_rent.py | 26 +++++++ tests/test_user.py | 28 ++++++- tests/test_wait.py | 24 +++++- 28 files changed, 472 insertions(+), 157 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aea58cb..4db4bce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,19 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [3.1.1] + +Aligned with the regenerated backend API spec. + +### Fixed +- `numbers.wait_code` no longer crashes with `KeyError` on a getState operation without `response` (absent while no number is issued); it keeps polling. +- Types: `Profile["number"]` is `int | None` and `Profile["country"]` is `str | None` (they were swapped); `Operation["response"]` is optional; `RentSms["code"]` is `str | int` (the integer `0` for a `notify` SMS, returned as sent); `FreeCountry` `country_text`/`country_original`, `FreeNumber["country_original"]`, `PaymentOrder` `currency`/`form_text` accept `None`. +- `user.payment_history()` no longer drops `paylist` when the server sends it as a JSON array (ids 0, 1, 2…); it is returned as sent. +- `numbers.wait_code` retries `ApiError` `TRY_AGAIN_LATER` (HTTP 429 rate limit), `ERROR_UNDEFINED` and `INTERVAL_CONCURRENT_REQUESTS_ERROR` until its timeout instead of raising at once. +- Error messages: `"0"` (ban not applied, the operation already has an SMS), `ACCOUNT_CLEANED`, `USER_NOT_ACTIVATED`, `ERROR_UNDEFINED`, `FORWARD_NOT_SUPPORTED` added; `ERROR_NO_KEY`, `NO_NUMBER_FOR_FORWARD`, `ACCOUNT_IDENTIFICATION_REQUIRED`, `API_DISABLED` (no longer sent) removed; `NoNumberError` only for `NO_NUMBER`; `ERROR_WRONG_KEY` reads "Wrong or missing API key". +- `MockOnlineSim` follows the backend: `setOperationRevise` answers `{"tzid":"N","response":"1"}` and `ERROR_WRONG_TZID` / `ERROR_NO_TZID`; `setOperationOk` tzid `0` → `ERROR_NO_TZID`; a missing key is HTTP 200 `ERROR_WRONG_KEY` (456 only for a wrong key, also on public endpoints); `getNum` with `number` adds `title`, `response_text`, `guard_interval_remaining_seconds`. Rent: `getRentNum` reserves the price (`status` 0) and the first non-`notify` SMS confirms and charges it, unknown country → `UNDEFINED_COUNTRY`, `sum` a number in getRentNum/extendRentState and a string in getRentState, `guard_interval_remaining_seconds` with `number`; `extendRentState` refusals are all `TRY_AGAIN_LATER`; `closeRentNum` unknown tzid → `ERROR_NO_OPERATIONS`, releases the reservation of an unconfirmed rent. Webhook-log params: `code` `""` without a code, rent `number` in full digits, rent `time_left` in minutes, `time_start` per type. `profile.php` accepts any `scheme://…` URL. `getPaymentHistory` adds `forms`/`buttons`; `getFreeList` lists 44 first, clamps `count` to 10..500, sends ISO-8601 `created_at` and `ignore`/`content`. `MockRent` gained `initial_days` and `status`, `MockSms` gained `at`. +- Docs: rent reservation and `sum`, available = balance − max(zbalance, 0), `ban` answer `"0"`, webhook `number`/`time_left`/`time_start`, the `wait_code` retry policy, the mock's behaviour. + ## [3.1.0] ### Added diff --git a/README.md b/README.md index ae0dbcd..e58dbd6 100755 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ from onlinesimru import OnlineSim client = OnlineSim(os.environ["ONLINESIM_KEY"]) b = client.user.balance() -print(f"available: {b['balance'] - b['zbalance']} USD") +print(f"available: {b['balance'] - max(b['zbalance'], 0)} USD") order = client.numbers.get_with_number("google", 44) print(f"enter {order['number']} in the app") diff --git a/docs/content/changelog.md b/docs/content/changelog.md index 3acd9c2..721d195 100644 --- a/docs/content/changelog.md +++ b/docs/content/changelog.md @@ -7,6 +7,12 @@ navigation: The full history is in [CHANGELOG.md](https://github.com/s00d/onlinesim-python-api/blob/master/CHANGELOG.md). +## 3.1.1 + +- Fixed: `wait_code` no longer crashes on an operation without `response`; types against the current API (`Profile` `number`/`country`, optional `Operation["response"]`, `RentSms["code"]` `0` for `notify` SMS, nullable free-list and payment fields); `payment_history()["paylist"]` is kept when it arrives as a list. +- `wait_code` retries `TRY_AGAIN_LATER` (rate limit), `ERROR_UNDEFINED` and `INTERVAL_CONCURRENT_REQUESTS_ERROR`. +- `MockOnlineSim` follows the backend more closely: rent reservation and confirmation, `setOperationRevise` and `closeRentNum` answers, missing vs wrong key — see [Testing](/testing). + ## 3.1.0 - New: `MockOnlineSim`, an offline fake of the API for your tests — see [Testing](/testing). diff --git a/docs/content/index.md b/docs/content/index.md index 3ff9a5f..d235a36 100644 --- a/docs/content/index.md +++ b/docs/content/index.md @@ -29,7 +29,7 @@ from onlinesimru import OnlineSim client = OnlineSim(os.environ["ONLINESIM_KEY"]) b = client.user.balance() -print(f"available: {b['balance'] - b['zbalance']} USD") +print(f"available: {b['balance'] - max(b['zbalance'], 0)} USD") order = client.numbers.get_with_number("google", 44) print(f"enter {order['number']} in the app") @@ -60,7 +60,7 @@ client = OnlineSim("your-api-key", lang="en", timeout=15) Sections: [`client.numbers`](/numbers), [`client.rent`](/rent), [`client.user`](/user), [`client.free`](/free). Webhook bodies are parsed by the standalone [`parse_webhook`](/webhooks). -Returned dicts keep the server's snake_case field names. Two things are normalised: money that the server sends as a decimal string (`balance`, rent `sum`) becomes a number, and maps that arrive as an empty PHP array `[]` become `{}`. +Returned dicts keep the server's snake_case field names. Two things are normalised: money that the server sends as a decimal string (`balance`, rent `sum` in `rent.state`) becomes a number, and maps that arrive as an empty PHP array `[]` become `{}`. `payment_history()["paylist"]` is left as sent: a JSON array when its ids are 0, 1, 2… ### Transport @@ -82,8 +82,8 @@ Every error extends `OnlineSimError`. | Class | When | Attributes | |---|---|---| -| `ApiError` | The API answered with an error code (also a wrong key, HTTP 456). | `code`, `message` | -| `NoNumberError` | `NO_NUMBER` / `NO_NUMBER_FOR_FORWARD`: no number right now. Subclass of `ApiError`. | `code`, `message` | +| `ApiError` | The API answered with an error code (also a wrong key, HTTP 456, and the rate limit, HTTP 429 `TRY_AGAIN_LATER`). | `code`, `message` | +| `NoNumberError` | `NO_NUMBER`: no number right now. Subclass of `ApiError`. | `code`, `message` | | `TransportError` | Network error, request timeout, or a body that is not JSON. | `status` (`None` without a response), `body` (first 500 chars) | | `TimeoutError` | `wait_code` got no code within its `timeout`. Also a built-in `TimeoutError`. | — | diff --git a/docs/content/numbers.md b/docs/content/numbers.md index 004d52a..c7c6de0 100644 --- a/docs/content/numbers.md +++ b/docs/content/numbers.md @@ -77,12 +77,12 @@ def state(*, message_to_code: bool = True, order_by: Literal["asc", "desc"] = "a | `order_by` | `"asc" \| "desc"` | `"asc"` | Order of operations. | | `msg_list` | `bool` | `False` | `msg` is a list of all SMS (`list[OperationSms]`). | -`Operation`: `{tzid, response, number?, service?, country?, sum?, time?, msg?, guard_interval_remaining_seconds?, …}`. -`response` is the state: `TZ_INPOOL` (number being assigned), `TZ_NUM_WAIT` (waiting for SMS), `TZ_NUM_ANSWER` (SMS arrived), `TZ_OVER_OK` (finished), `ERROR_NO_ITEMS` (failed). `msg` is absent until the first SMS. The server caches answers for a few seconds. +`Operation`: `{tzid, response?, number?, service?, country?, sum?, time?, msg?, guard_interval_remaining_seconds?, …}`. +`response` is the state (absent when no number could be issued): `TZ_INPOOL` (number being assigned), `TZ_NUM_WAIT` (waiting for SMS), `TZ_NUM_ANSWER` (SMS arrived), `TZ_OVER_OK` (finished), `ERROR_NO_ITEMS` (failed). `msg` is absent until the first SMS. The server caches answers for a few seconds. ```python for op in client.numbers.state(order_by="desc"): - print(op["tzid"], op["response"], op.get("msg")) + print(op["tzid"], op.get("response"), op.get("msg")) ``` ## state_one @@ -95,7 +95,7 @@ def state_one(tzid: int, *, message_to_code: bool = True, msg_list: bool = False ```python op = client.numbers.state_one(tzid) -if op["response"] == "TZ_NUM_ANSWER": +if op.get("response") == "TZ_NUM_ANSWER": print(op.get("msg")) ``` @@ -120,7 +120,7 @@ def wait_code(tzid: int, *, interval: float = 5.0, timeout: float = 600.0, keep_ | `since` | `str \| None` | `None` | Ignore this value (the previous code). | | `sleep`, `clock` | callables | `time.sleep`, `time.monotonic` | Injectable for tests. | -A transient `TransportError` is retried until the timeout; any `ApiError` is raised at once. The same function is available standalone as `onlinesimru.wait_code(numbers, tzid, ...)`. +Transient errors are retried until the timeout: `TransportError`, and `ApiError` `TRY_AGAIN_LATER` (the HTTP 429 rate limit), `ERROR_UNDEFINED` and `INTERVAL_CONCURRENT_REQUESTS_ERROR`. Any other `ApiError` is raised at once. The same function is available standalone as `onlinesimru.wait_code(numbers, tzid, ...)`. ```python first = client.numbers.wait_code(tzid, keep_open=True) @@ -141,6 +141,8 @@ def next(tzid: int) -> bool client.numbers.next(tzid) ``` +Errors: `ApiError` `ERROR_WRONG_TZID` (not an operation of your account), `ERROR_NO_TZID`. + ## close Finish the operation. An operation without SMS can be closed only after its guard interval (`guard_interval_remaining_seconds`); every attempt locks the tzid for 5 s. @@ -167,7 +169,7 @@ def ban(tzid: int) -> bool client.numbers.ban(tzid) ``` -Errors: as `close`. +Errors: as `close`; `ApiError` with code `"0"` when the operation already has an SMS — nothing is changed then. ## tariffs diff --git a/docs/content/rent.md b/docs/content/rent.md index 9b36c43..fc7983e 100644 --- a/docs/content/rent.md +++ b/docs/content/rent.md @@ -7,14 +7,16 @@ navigation: A rent keeps a number for `days` days. Its SMS come in `RentItem["messages"]`, newest first. +`get` reserves the price (it shows in `zbalance`): the rent starts with `status` `0` and `checked` `False` and waits up to 20 minutes for its first SMS. The first SMS that is not a `notify` notice confirms it (`status` `1`) and charges the price; without one the rent closes and the reservation is released. Some countries (`confirm` in `tariffs`, e.g. US numbers) are confirmed and charged at once. + `RentItem`: `{tzid, status, number, country, sum, days, hours, time, time_seconds?, extension, extend, messages, start_time, stop_time, day_extend?, …}` — -`sum` is the price paid in USD (a number; the server sends a decimal string), `time` minutes left, `time_seconds` seconds left, +`sum` is the cost in USD incl. extensions (a number; `rent.state` gets it from the server as a decimal string), `time` minutes left, `time_seconds` seconds left, `extension` `0` not extendable / `1` extendable / `2` auto-extension, `extend` maps days to the extension price (`{}` when not extendable), -`messages` is `list[RentSms]`: `{id, service, text, code, created_at}`. +`messages` is `list[RentSms]`: `{id, service, text, code, created_at}` — `code` is `""` when no code was found and the integer `0` for a `notify` SMS (a prohibited sender). ## get -Rent a number and charge the balance. +Rent a number. The price is reserved; the first SMS charges it. ```python def get(country: int = 7, days: int = 1, extension: bool = True) -> RentItem @@ -62,7 +64,7 @@ Errors: `ApiError` `ERROR_NO_OPERATIONS` for an unknown tzid. ## extend -Extend a rent by `days` days and charge the balance. Only rents created with `extension=True`. +Extend a rent by `days` days and charge the balance at once. Only confirmed rents (`status` `1` or `4`) created with `extension=True`. ```python def extend(tzid: int, days: int = 1) -> RentItem @@ -73,11 +75,11 @@ rent = client.rent.extend(tzid, 3) print(rent["stop_time"]) ``` -Errors: `ApiError` `TRY_AGAIN_LATER` (not extendable, unknown tzid or period, a repeat within 10 s), `WARNING_LOW_BALANCE`. +Errors: `ApiError` `TRY_AGAIN_LATER` (unknown tzid, not confirmed yet or closed, not extendable, unknown period, a repeat within 10 s), `WARNING_LOW_BALANCE`. ## close -Return the number before the period ends. A rent that is not confirmed yet and has no SMS can be closed only after 120 s; US numbers cannot be closed early. +Return the number before the period ends. A rent that is not confirmed yet (`status` `0`) and has no SMS can be closed only after 120 s; then, or with only `notify` SMS, the reservation is released. With a real SMS the rent is confirmed (charged) and closed. A confirmed rent closes without a refund. US numbers cannot be closed early. ```python def close(tzid: int) -> bool diff --git a/docs/content/testing.md b/docs/content/testing.md index 4175470..c20f547 100644 --- a/docs/content/testing.md +++ b/docs/content/testing.md @@ -5,7 +5,7 @@ navigation: order: 6 --- -`MockOnlineSim` is an in-process fake of the OnlineSim API that ships with the package. It is a [transport](/#transport) that answers like the real backend — same shapes, same error codes, HTTP 456 for a wrong key — and keeps a balance, operations and rents. Your code talks to a normal `OnlineSim` client, so nothing in it changes for tests. It is deterministic: no randomness, no clock, numbers and ids come from a counter. +`MockOnlineSim` is an in-process fake of the OnlineSim API that ships with the package. It is a [transport](/#transport) that answers like the real backend — same shapes, same error codes, HTTP 456 for a wrong key and HTTP 200 `ERROR_WRONG_KEY` for a missing one — and keeps a balance, operations and rents. Your code talks to a normal `OnlineSim` client, so nothing in it changes for tests. It is deterministic: no randomness, no clock, numbers and ids come from a counter. ## Setup @@ -33,7 +33,7 @@ MockOnlineSim( | `balance` | `100` | Starting balance, USD. | | `prices` | `{7: {"vkcom": 0.5, "telegram": 1.2, "google": 0.3}, 44: {"google": 0.2, "vkcom": 0.36}}` | Number prices; replaces the defaults. Also feeds `numbers.tariffs()`. | | `rent_tariffs` | `{7: {"days": {1: 1.0, 3: 2.5, 7: 5.0}, "extend": 1}}` | Rent prices; `"extend": 0` makes rents of that country non-extendable. | -| `guard_interval` | `0` | `> 0`: an operation without SMS cannot be closed (`NO_COMPLETE_TZID`). | +| `guard_interval` | `0` | `> 0`: an operation without SMS, or an unconfirmed rent without any SMS, cannot be closed (`NO_COMPLETE_TZID`). | `mock.client(*, api_key, base_url, lang, dev_id, timeout)` takes the usual [client options](/#client-options) except `transport`. To build the client yourself, pass `mock.transport` as `transport`; any `base_url` works: @@ -94,7 +94,7 @@ def test_handles_a_missing_number_and_a_network_hiccup() -> None: assert client.user.balance()["balance"] == 100 # one-shot ``` -The state itself produces the real error codes too: `WARNING_LOW_BALANCE` when the balance is short, `NO_NUMBER` when `reject` matches the next number, `UNDEFINED_COUNTRY` / `ERROR_NO_SERVICE` for unknown prices, `ERROR_WRONG_TZID` for an unknown or closed operation, `TRY_AGAIN_LATER` when extending a non-extendable rent, `ERROR_WRONG_KEY` (HTTP 456) for a wrong key. +The state itself produces the real error codes too: `WARNING_LOW_BALANCE` when the balance is short, `NO_NUMBER` when `reject` matches the next number, `UNDEFINED_COUNTRY` / `ERROR_NO_SERVICE` for unknown prices, `ERROR_WRONG_TZID` for an unknown or closed operation (`next` too; `ERROR_NO_TZID` for tzid `0`), `UNDEFINED_COUNTRY` / `UNDEFINED_DAYS` for an unknown rent country or period, `TRY_AGAIN_LATER` for every refused `rent.extend`, `ERROR_NO_OPERATIONS` for an unknown rent in `rent.close`, `ERROR_WRONG_KEY` for a wrong key (HTTP 456) or no key (HTTP 200). ## Inspecting requests @@ -131,7 +131,7 @@ def test_sends_reject_as_a_comma_list() -> None: ## What the mock does - **Numbers**: `get` freezes the price; `close` after an SMS spends it, `close` without one refunds it; `ban` after an SMS answers `"0"`, like the server. Numbers are `+9000000NN`, ids count from 1. `next` switches to the following SMS. The operation's `time` stays at 1200 s — there is no clock. -- **Rent**: `get` charges at once and keeps the `extension` flag; `extend` charges again; `close` removes the rent. SMS appear in `messages`, newest first. -- **User**: `balance` (frozen part included), a fixed profile, `set_webhook_url` validates `http(s)` URLs (`VALIDATION_ERROR` otherwise), `webhook_logs` lists the deliveries the mock *recorded* when an SMS arrived while a webhook URL was set — it makes no HTTP call. `payment_history` is empty. -- **Free**: `free.list` returns two fixed countries with one number and a few SMS each. -- Not imitated: the server's 5 s lock after `setOperationOk` (`INTERVAL_CONCURRENT_REQUESTS_ERROR`) and anything else that needs real time. +- **Rent**: `get` reserves the price (`status` `0`, `checked` `False`) and keeps the `extension` flag; the first SMS that is not `notify` confirms the rent (`status` `1`) and charges it — `add_sms(tzid, text, service="notify")` adds a notice with `code` `0` that confirms nothing. `extend` works on a confirmed rent and charges at once. `close` releases the reservation of an unconfirmed rent and gives no refund for a confirmed one. `sum` is a number in `get`/`extend` and a decimal string on the wire of `state`, like the server. SMS appear in `messages`, newest first. +- **User**: `balance` (frozen part included), a fixed profile, `set_webhook_url` accepts any `scheme://…` URL (`VALIDATION_ERROR` otherwise), `webhook_logs` lists the deliveries the mock *recorded* when an SMS arrived while a webhook URL was set — it makes no HTTP call; their `params` follow the real payload (`code` `""` without a code, rent `number` in digits without `+`, rent `time_left` in minutes). `payment_history` has no orders. +- **Free**: `free.list` returns two fixed countries (44 first) with one number and a few SMS each. +- Not imitated: anything that needs real time — the 5 s lock after `setOperationOk` (`INTERVAL_CONCURRENT_REQUESTS_ERROR`), the 10 s lock of `rent.extend`, the 120 s before an unconfirmed rent may be closed and its 20-minute wait for the first SMS. `guard_interval > 0` stands in for "too early to close". diff --git a/docs/content/user.md b/docs/content/user.md index d19409c..1374d5e 100644 --- a/docs/content/user.md +++ b/docs/content/user.md @@ -13,11 +13,11 @@ Balance in USD. def balance() -> Balance # {"balance": float, "zbalance": float, "income"?: float} ``` -`balance` includes the sum frozen by numbers in progress (`zbalance`): available = `balance − zbalance`. `income` is the partner income. The server caches the answer for 60 s. +`balance` includes the sum frozen by numbers and unconfirmed rents in progress (`zbalance`, which may be negative): available = `balance − max(zbalance, 0)`. `income` is the partner income. The server caches the answer for 60 s. ```python b = client.user.balance() -available = b["balance"] - b["zbalance"] +available = b["balance"] - max(b["zbalance"], 0) ``` Errors: `ApiError` `ERROR_WRONG_KEY`, `ACCOUNT_BLOCKED`, `API_ACCESS_DISABLED`, `API_ACCESS_IP`. @@ -45,7 +45,7 @@ Top-up orders (paginated, newest first) and the available payment methods. def payment_history(page: int = 1) -> PaymentHistory ``` -`PaymentHistory`: `{orders, paylist, domains?, forms?, currency?, buttons?}` — `orders` is a paginator of `PaymentOrder`. `PaymentOrder["sum"]` stays a decimal string (`"89.00"`). +`PaymentHistory`: `{orders, paylist, domains?, forms?, currency?, buttons?}` — `orders` is a paginator of `PaymentOrder`. `PaymentOrder["sum"]` stays a decimal string (`"89.00"`); `currency` and `form_text` may be `None`. `paylist` maps a group id to its payment methods, or is a list when the ids are 0, 1, 2… (the server sends a JSON array then). ```python orders = client.user.payment_history()["orders"] diff --git a/docs/content/webhooks.md b/docs/content/webhooks.md index 0f24eaf..4b02c2b 100644 --- a/docs/content/webhooks.md +++ b/docs/content/webhooks.md @@ -45,9 +45,9 @@ HTTPServer(("", 8080), Hook).serve_forever() | `operation_id` | `int \| None` | `tzid` of the operation or rent. | | `user_id` | `int \| None` | Account id. | | `country_code` | `int \| None` | Country code of the number. | -| `number` | `str \| None` | The number, e.g. `+79001234567`. | +| `number` | `str \| None` | Numbers: `+` and the full number (`+79001234567`), or `hidden`. Rent: the full number in digits without `+` (`79001234567`). | | `sender` | `str \| None` | Sender of the SMS, e.g. `VK`. | | `message` | `str \| None` | Full SMS text. | -| `code` | `str \| None` | Code extracted from the SMS. | -| `time_start` | `str \| None` | Start of the operation. | -| `time_left` | `int \| None` | Time left. | +| `code` | `str \| None` | Code extracted from the SMS; `""` when none was found. | +| `time_start` | `str \| None` | Numbers: when the operation was ordered. Rent: when the SMS arrived. `YYYY-MM-DD HH:MM:SS`. | +| `time_left` | `int \| None` | Time left: seconds for numbers, minutes for rent. | diff --git a/onlinesimru/client.py b/onlinesimru/client.py index c8284a4..f4a1f65 100644 --- a/onlinesimru/client.py +++ b/onlinesimru/client.py @@ -155,7 +155,8 @@ def _request(self, endpoint: str, query: Optional[Mapping[str, QueryValue]] = No raise TransportError( f"HTTP {response.status}: response is not JSON", response.status, text[:_BODY_EXCERPT] ) from None - # The body is checked before the status: a wrong key is HTTP 456 with {"response":"ERROR_WRONG_KEY"}. + # The body is checked before the status: a wrong key is HTTP 456 with {"response":"ERROR_WRONG_KEY"}, + # the rate limit HTTP 429 with {"response":"TRY_AGAIN_LATER"}. if isinstance(payload, dict) and "response" in payload: return _unwrap(payload) if not 200 <= response.status < 300: @@ -177,7 +178,7 @@ def _unwrap(payload: Dict[str, Any]) -> Dict[str, Any]: # Debug backends echo the code as `message`; prefer the readable fallback then. message = rest.get("message") message = message if isinstance(message, str) and message != code else None - if code in ("NO_NUMBER", "NO_NUMBER_FOR_FORWARD"): + if code == "NO_NUMBER": raise NoNumberError(code, message) raise ApiError(code, message) diff --git a/onlinesimru/errors.py b/onlinesimru/errors.py index d447620..95cc4ce 100644 --- a/onlinesimru/errors.py +++ b/onlinesimru/errors.py @@ -21,7 +21,7 @@ def __init__(self, code: str, message: Optional[str] = None) -> None: class NoNumberError(ApiError): - """No number is available right now (``NO_NUMBER``, ``NO_NUMBER_FOR_FORWARD``).""" + """No number is available right now (``NO_NUMBER``).""" class TransportError(OnlineSimError): @@ -45,29 +45,30 @@ class TimeoutError(OnlineSimError, builtins.TimeoutError): # noqa: A001 ERROR_MESSAGES: Mapping[str, str] = { "ACCOUNT_BLOCKED": "Account is blocked", - "ERROR_WRONG_KEY": "Wrong API key", - "ERROR_NO_KEY": "API key is missing", + "ACCOUNT_CLEANED": "Account was deleted", + "USER_NOT_ACTIVATED": "Account email is not confirmed", + "ERROR_WRONG_KEY": "Wrong or missing API key", "ERROR_NO_SERVICE": "Service is not specified", "API_ACCESS_DISABLED": "API access is disabled in the profile", "API_ACCESS_IP": "API access from this IP is not allowed in the profile", "ERROR_NO_TZID": "tzid is not specified", "ERROR_WRONG_TZID": "Wrong tzid", "ERROR_NO_OPERATIONS": "No operations", + "ERROR_UNDEFINED": "Unexpected server error, try again", "NO_NUMBER": "No numbers available for this service right now", - "NO_NUMBER_FOR_FORWARD": "No numbers available for forwarding", "NO_COUNTRY": "Country not found", "UNDEFINED_COUNTRY": "Unknown country", "WARNING_LOW_BALANCE": "Not enough balance", "EXCEEDED_CONCURRENT_OPERATIONS": "Too many concurrent operations for this account", "INTERVAL_CONCURRENT_REQUESTS_ERROR": "Too many concurrent requests, try again in a few seconds", - "TRY_AGAIN_LATER": "Temporarily unable to perform the request, try again later", - "ACCOUNT_IDENTIFICATION_REQUIRED": "Account identification is required", + "TRY_AGAIN_LATER": "Rate limit exceeded or temporary error, try again later", + "FORWARD_NOT_SUPPORTED": "Number forwarding is no longer available", "ERROR_PARAMS": "Wrong parameters", - "API_DISABLED": "API is disabled", "NO_COMPLETE_TZID": "The operation cannot be closed yet", "NO_CLOSE_RENT_US": "US rent numbers cannot be closed early", "UNDEFINED_DAYS": "Unknown rent period", "VALIDATION_ERROR": "Validation failed", + "0": "Ban not applied: the operation already has an SMS", "TZ_OVER_OK": "Operation finished without a new code", "ERROR_NO_ITEMS": "Operation failed", } diff --git a/onlinesimru/mock/__init__.py b/onlinesimru/mock/__init__.py index 77ebbad..f9274fb 100644 --- a/onlinesimru/mock/__init__.py +++ b/onlinesimru/mock/__init__.py @@ -69,7 +69,8 @@ def __init__( :param balance: Starting balance, USD. :param prices: Number prices, country -> service -> USD; replaces the defaults. :param rent_tariffs: Rent tariffs, country -> ``{"days": {days: USD}, "extend": 0|1}``; replaces the defaults. - :param guard_interval: Seconds. ``> 0``: an operation without SMS cannot be closed (``NO_COMPLETE_TZID``). + :param guard_interval: Seconds. ``> 0``: an operation without SMS, or an unconfirmed rent without any SMS, + cannot be closed (``NO_COMPLETE_TZID``). """ self._state = MockState( api_key=api_key, balance=balance, prices=prices, rent_tariffs=rent_tariffs, guard_interval=guard_interval @@ -112,8 +113,12 @@ def transport(self, request: HttpRequest) -> HttpResponse: handler = ROUTES.get(req.path) if handler is None: return _text(404, "Not Found") - if req.path not in PUBLIC_PATHS and _authorization(request.headers) != f"Bearer {state.api_key}": + # A wrong key is HTTP 456 (public endpoints check a sent key too); no key at all is HTTP 200. + auth = _authorization(request.headers) + if auth is not None and auth != f"Bearer {state.api_key}": return _json({"response": "ERROR_WRONG_KEY"}, 456) + if auth is None and req.path not in PUBLIC_PATHS: + return _json({"response": "ERROR_WRONG_KEY"}) return _json(handler(state, req)) def add_sms(self, tzid: int, text: str, *, service: Optional[str] = None) -> None: diff --git a/onlinesimru/mock/_handlers.py b/onlinesimru/mock/_handlers.py index 11e2fa4..3932c7b 100644 --- a/onlinesimru/mock/_handlers.py +++ b/onlinesimru/mock/_handlers.py @@ -6,12 +6,14 @@ from __future__ import annotations -import urllib.parse +import re from typing import Any, Callable, Dict, List, Mapping, Sequence, Tuple from ._state import ( MOCK_USER_ID, + NOTIFY, OPERATION_TIME, + RENT_FIRST_SMS_MINUTES, MockOperation, MockRent, MockRequest, @@ -52,6 +54,11 @@ def _decimal(mills: int, digits: int = 3) -> str: return f"{from_mills(mills):.{digits}f}" +def _iso(seconds: int) -> str: + """``YYYY-MM-DDTHH:MM:SS.000000Z``, the ISO-8601 form getFreeList sends.""" + return stamp(seconds).replace(" ", "T") + ".000000Z" + + def _country_name(code: int) -> Tuple[str, str]: return _COUNTRY_NAMES.get(code, (f"country_{code}", f"Country {code}")) @@ -151,6 +158,9 @@ def _get_num(state: MockState, req: MockRequest) -> Any: "country": country, "time": OPERATION_TIME, "service": service, + "title": service, + "response_text": "Waiting for SMS", + "guard_interval_remaining_seconds": state.guard_interval, } @@ -170,16 +180,21 @@ def _get_state(state: MockState, req: MockRequest) -> Any: def _set_operation_revise(state: MockState, req: MockRequest) -> Any: tzid = _int(req, "tzid", 0) + if not tzid: + return _error("ERROR_NO_TZID") op = state.operations.get(tzid) - # Always succeeds, even for unknown tzids, like the backend. - if op is not None and op.status != "TZ_OVER_OK": + if op is None: + return _error("ERROR_WRONG_TZID") + if op.status != "TZ_OVER_OK": op.cursor = len(op.messages) op.status = "TZ_NUM_WAIT" - return {"response": 1, "tzid": tzid} + return {"tzid": str(tzid), "response": "1"} def _set_operation_ok(state: MockState, req: MockRequest) -> Any: tzid = _int(req, "tzid", 0) + if not tzid: + return _error("ERROR_NO_TZID") op = state.operations.get(tzid) if op is None or op.status == "TZ_OVER_OK": return _error("ERROR_WRONG_TZID") @@ -232,40 +247,52 @@ def _get_numbers_stats(state: MockState, req: MockRequest) -> Any: # ----- rent ----- -def _rent_item(state: MockState, rent: MockRent, req: MockRequest) -> Dict[str, Any]: +def _rent_item(state: MockState, rent: MockRent, req: MockRequest, string_sum: bool = False) -> Dict[str, Any]: + """A rent as the backend sends it. ``sum`` is a number in getRentNum/extendRentState and a 2-decimal string in + getRentState (``string_sum``). An unconfirmed rent (``status`` 0) waits 20 minutes for its first SMS.""" tariff = state.rent_tariffs.get(rent.country) days = dict(sorted(tariff["days"].items())) if tariff is not None else {} extendable = rent.extension and tariff is not None and tariff["extend"] == 1 + confirmed = rent.status == 1 start = rent.tzid + minutes = rent.days * 24 * 60 if confirmed else RENT_FIRST_SMS_MINUTES item: Dict[str, Any] = { - "status": 1, + "status": rent.status, "extension": 1 if rent.extension else 0, "messages": [ - {"id": m.id, "service": m.service, "text": m.text, "code": m.code or "", "created_at": m.created_at} + { + "id": m.id, + "service": m.service, + "text": m.text, + # A notice about a prohibited sender carries the integer 0, other SMS a string ("" without a code). + "code": 0 if m.service == NOTIFY else (m.code or ""), + "created_at": m.created_at, + } for m in reversed(rent.messages) ], "webhook_url": state.webhook_url, - "sum": _decimal(to_mills(rent.sum), 2), + "sum": _decimal(to_mills(rent.sum), 2) if string_sum else rent.sum, "country": rent.country, "start_time": stamp(start), - "stop_time": stamp(start + rent.days * 86_400), + "stop_time": stamp(start + minutes * 60), "checked_time": stamp(start), "number": rent.number, - "days_autoextend": 0, - "rent": 1, + "days_autoextend": rent.initial_days, + "rent": rent.days, "tzid": rent.tzid, - "time": rent.days * 24 * 60, - "days": rent.days, - "hours": rent.days * 24, + "time": minutes, + "days": rent.days if confirmed else 0, + "hours": rent.days * 24 if confirmed else 0, "extend": days if extendable else [], - "checked": True, - "reload": None, + "checked": confirmed, + "reload": 0 if rent.country == 7 else None, "day_extend": days.get(1, 0) if extendable else 0, "m_ext": False, "freeze": False, } if "number" in req.query: - item["time_seconds"] = rent.days * 86_400 + item["time_seconds"] = minutes * 60 + item["guard_interval_remaining_seconds"] = state.guard_interval if not confirmed and not rent.messages else 0 return item @@ -273,7 +300,7 @@ def _get_rent_num(state: MockState, req: MockRequest) -> Any: country = _int(req, "country", 7) tariff = state.rent_tariffs.get(country) if tariff is None: - return _error("NO_COUNTRY") + return _error("UNDEFINED_COUNTRY") days = _int(req, "days", 1) price = tariff["days"].get(days) if price is None: @@ -281,9 +308,10 @@ def _get_rent_num(state: MockState, req: MockRequest) -> Any: if state.available < to_mills(price): return _error("WARNING_LOW_BALANCE") tzid = state.next_id() - state.balance -= to_mills(price) + # Reserved, not charged: the first SMS that is not `notify` confirms the rent and charges it. + state.frozen += to_mills(price) # `extension` defaults to 1 on the server; `0` makes the rent non-extendable for good. - rent = MockRent(tzid, country, short_number(tzid), days, price, req.query.get("extension") != "0") + rent = MockRent(tzid, country, short_number(tzid), days, price, req.query.get("extension") != "0", days) state.rents[tzid] = rent return {"response": 1, "item": _rent_item(state, rent, req)} @@ -296,20 +324,19 @@ def _get_rent_state(state: MockState, req: MockRequest) -> Any: rents = list(state.rents.values()) for rent in rents: state.poll(rent.tzid) - return {"response": 1, "list": [_rent_item(state, r, req) for r in rents]} + return {"response": 1, "list": [_rent_item(state, r, req, string_sum=True) for r in rents]} def _extend_rent_state(state: MockState, req: MockRequest) -> Any: + # Every refusal is TRY_AGAIN_LATER, like the backend: unknown tzid, unconfirmed rent, not extendable, unknown days. rent = state.rents.get(_int(req, "tzid", 0)) - if rent is None: - return _error("ERROR_WRONG_TZID") - tariff = state.rent_tariffs.get(rent.country) - if not rent.extension or tariff is None or tariff["extend"] != 1: + tariff = None if rent is None else state.rent_tariffs.get(rent.country) + if rent is None or tariff is None or rent.status != 1 or not rent.extension or tariff["extend"] != 1: return _error("TRY_AGAIN_LATER") days = _int(req, "days", 1) price = tariff["days"].get(days) if price is None: - return _error("UNDEFINED_DAYS") + return _error("TRY_AGAIN_LATER") if state.available < to_mills(price): return _error("WARNING_LOW_BALANCE") state.balance -= to_mills(price) @@ -320,8 +347,17 @@ def _extend_rent_state(state: MockState, req: MockRequest) -> Any: def _close_rent_num(state: MockState, req: MockRequest) -> Any: tzid = _int(req, "tzid", 0) - if state.rents.pop(tzid, None) is None: - return _error("ERROR_WRONG_TZID") + rent = state.rents.get(tzid) + if rent is None: + return _error("ERROR_NO_OPERATIONS") + if rent.status == 0: + # `guard_interval` stands in for the backend's first 120 s, during which a rent without any SMS stays open. + if not rent.messages and state.guard_interval > 0: + return _error("NO_COMPLETE_TZID") + # Unconfirmed (no SMS or only `notify`): the reservation is released. + state.frozen -= to_mills(rent.sum) + # A confirmed rent closes without a refund. + del state.rents[tzid] state.scheduled.pop(tzid, None) return {"response": "1"} @@ -397,12 +433,8 @@ def _get_profile(state: MockState, req: MockRequest) -> Any: } -def _is_http_url(value: str) -> bool: - try: - url = urllib.parse.urlsplit(value) - return url.scheme in ("http", "https") and bool(url.hostname) - except ValueError: - return False +_URL = re.compile(r"[a-z][a-z0-9+.-]*://\S+", re.IGNORECASE) +"""The backend accepts any ``scheme://...`` URL.""" def _profile(state: MockState, req: MockRequest) -> Any: @@ -412,7 +444,7 @@ def _profile(state: MockState, req: MockRequest) -> Any: return _error("ERROR_PARAMS") if "webhook_url" in profile: url = profile["webhook_url"] - if url is not None and (not isinstance(url, str) or not _is_http_url(url)): + if url is not None and (not isinstance(url, str) or not _URL.fullmatch(url)): return {"response": {"webhook_url": ["The webhook url must be a valid URL."]}} state.webhook_url = url return {"response": "1", "user": {"id": MOCK_USER_ID, "webhook_url": state.webhook_url}} @@ -427,16 +459,20 @@ def _get_payment_history(state: MockState, req: MockRequest) -> Any: "response": "1", "orders": _paginate([], _int(req, "page", 1), 10, "getPaymentHistory.php"), "paylist": [], - "domains": [], + "domains": ["onlinesim.io"], + "forms": {"1": "Card"}, "currency": {"USD": 1}, + "buttons": {"USD": [5, 10, 20]}, } # ----- free ----- -# country -> (name, text, short number -> [(sender, text)]) +_FREE_IGNORE = "

Messages from these services are not shown:

1,2,3

" +"""``ignore`` of getFreeList: a note about prohibited services and their ids.""" + +# country -> (name, text, short number -> [(sender, text)]); country 44 first, like the backend's list. _FREE: Mapping[int, Tuple[str, str, Mapping[str, List[Tuple[str, str]]]]] = { - 7: ("russia", "Russia", {"9001234567": [("Telegram", "Telegram code: 51423")]}), 44: ( "united_kingdom", "United Kingdom", @@ -447,6 +483,7 @@ def _get_payment_history(state: MockState, req: MockRequest) -> Any: ] }, ), + 7: ("russia", "Russia", {"9001234567": [("Telegram", "Telegram code: 51423")]}), } @@ -473,18 +510,21 @@ def _get_free_list(state: MockState, req: MockRequest) -> Any: "text": text, "in_number": sender, "my_number": number, - "created_at": stamp(i), + "created_at": _iso(i), "data_humans": "1 day ago", "code": extract_code(text) or "-", } for i, (sender, text) in enumerate(by_number[number]) ] - page = _paginate(messages, _int(req, "page", 1), _int(req, "count", 10), "getFreeList") + count = min(500, max(10, _int(req, "count", 10))) + page = _paginate(messages, max(1, _int(req, "page", 1)), count, "getFreeList") return { "response": 1, "countries": [{"country": c, "country_text": _FREE[c][1], "country_original": _FREE[c][0]} for c in codes], "numbers": numbers, "messages": {**page, "number": number, "country": country}, + "ignore": _FREE_IGNORE, + "content": None, } diff --git a/onlinesimru/mock/_state.py b/onlinesimru/mock/_state.py index ad42659..934a5d5 100644 --- a/onlinesimru/mock/_state.py +++ b/onlinesimru/mock/_state.py @@ -32,6 +32,8 @@ class MockSms: text: str code: Optional[str] """Code extracted from ``text`` (first run of 4-8 digits), ``None`` when there is none.""" + at: int + """Seconds after the mock epoch when it arrived.""" @dataclass @@ -71,9 +73,14 @@ class MockRent: number: str """Number without the country code, as the backend sends it for rents.""" days: int + """Total rent days: the initial period plus extensions.""" sum: float - """Total paid, USD.""" + """Total cost incl. extensions, USD. Frozen while ``status`` is 0.""" extension: bool + initial_days: int + """The initial period (``days`` of getRentNum).""" + status: int = 0 + """``0``: reserved, waiting for the first SMS; ``1``: confirmed by an SMS that is not ``notify``, price charged.""" messages: List[MockRentSms] = field(default_factory=list) """Oldest first.""" @@ -120,6 +127,10 @@ class _ScheduledSms: MOCK_USER_ID = 1 OPERATION_TIME = 1200 """Seconds an operation stays open, as reported in ``time``. The mock has no clock, so it never runs down.""" +RENT_FIRST_SMS_MINUTES = 20 +"""Minutes an unconfirmed rent waits for its first SMS (``stop_time`` = start + this).""" +NOTIFY = "notify" +"""Sender of a rent SMS from a prohibited sender: it gets the integer ``code`` ``0`` and does not confirm the rent.""" _EPOCH = datetime(2026, 1, 1, tzinfo=timezone.utc) @@ -177,7 +188,7 @@ def __init__( self.balance = 0 """Total balance incl. the frozen part, mills.""" self.frozen = 0 - """Frozen by open operations, mills.""" + """Frozen by open operations and unconfirmed rents, mills.""" self.operations: Dict[int, MockOperation] = {} self.rents: Dict[int, MockRent] = {} self.webhook_url: Optional[str] = None @@ -226,17 +237,27 @@ def deliver(self, tzid: int, text: str, service: Optional[str] = None) -> bool: code = extract_code(text) op = self.operations.get(tzid) if op is not None and op.status != "TZ_OVER_OK": - sms = MockSms(op.service if service is None else service, text, code) + sms = MockSms(op.service if service is None else service, text, code, self.seq) op.messages.append(sms) op.status = "TZ_NUM_ANSWER" - self._webhook("receiving_sms", tzid, op.country, op.number, sms) + # Activation: `+`, seconds left, the order time. + self._webhook("receiving_sms", tzid, op.country, op.number, sms, OPERATION_TIME, stamp(op.tzid)) return True rent = self.rents.get(tzid) if rent is not None: id_ = self.next_id() - rent_sms = MockRentSms("other" if service is None else service, text, code, id_, stamp(id_)) + rent_sms = MockRentSms("other" if service is None else service, text, code, id_, id_, stamp(id_)) rent.messages.append(rent_sms) - self._webhook("rent_sms", tzid, rent.country, rent.number, rent_sms) + if rent.status == 0 and rent_sms.service != NOTIFY: + # The first real SMS confirms the rent: the reservation is charged. + cost = to_mills(rent.sum) + self.frozen -= cost + self.balance -= cost + rent.status = 1 + # Rent: full number in digits without `+`, minutes left, the SMS time. + minutes_left = rent.days * 24 * 60 if rent.status == 1 else RENT_FIRST_SMS_MINUTES + number = f"{rent.country}{rent.number}" + self._webhook("rent_sms", tzid, rent.country, number, rent_sms, minutes_left, stamp(id_)) return True return False @@ -260,11 +281,13 @@ def poll(self, tzid: int) -> None: for s in due: self.deliver(tzid, s.text, s.service) - def _webhook(self, type_: str, tzid: int, country: int, number: str, sms: MockSms) -> None: + def _webhook( + self, type_: str, tzid: int, country: int, number: str, sms: MockSms, time_left: int, time_start: str + ) -> None: """No HTTP call: the mock only records what the backend would have sent.""" if not self.webhook_url: return - time = stamp(self.seq) + time = stamp(sms.at) self.webhook_logs.append( { "id": len(self.webhook_logs) + 1, @@ -279,9 +302,9 @@ def _webhook(self, type_: str, tzid: int, country: int, number: str, sms: MockSm "number": number, "sender": sms.service, "message": sms.text, - "code": sms.code, - "time_start": time, - "time_left": OPERATION_TIME, + "code": sms.code or "", + "time_start": time_start, + "time_left": time_left, }, "status": "success", "error": None, diff --git a/onlinesimru/models.py b/onlinesimru/models.py index 933897b..4aab914 100644 --- a/onlinesimru/models.py +++ b/onlinesimru/models.py @@ -1,8 +1,9 @@ """Wire types. They mirror the schemas of the OnlineSim OpenAPI spec (snake_case field names as sent by the server), with these -client-side normalisations: decimal-string money (``balance``, rent ``sum``) becomes a number, and maps the server -may send as an empty PHP array ``[]`` become ``{}``. Keys of the ``total=False`` parts may be absent. +client-side normalisations: decimal-string money (``balance``, rent ``sum`` in ``rent.state``) becomes a number, and +maps the server may send as an empty PHP array ``[]`` become ``{}`` (``payment_history()["paylist"]`` is left as sent: +a JSON array when its ids are 0, 1, 2...). Keys of the ``total=False`` parts may be absent. """ from __future__ import annotations @@ -26,12 +27,13 @@ class OperationSms(TypedDict, total=False): class _OperationRequired(TypedDict): tzid: int - response: OperationStatus class Operation(_OperationRequired, total=False): """Number operation (getState item).""" + response: OperationStatus + """Absent when no number could be issued.""" number: str service: str country: int @@ -100,8 +102,11 @@ class CountryStat(_CountryStatRequired, total=False): class RentSms(TypedDict): id: int service: str + """Sender. ``notify``: a notice about a prohibited sender (does not confirm the rent); ``init``: record of a rent + confirmed at once.""" text: str - code: str + code: Union[str, int] + """Code found in the text, ``""`` when none; the integer ``0`` for a ``notify`` SMS.""" created_at: str @@ -111,7 +116,8 @@ class _RentItemRequired(TypedDict): number: str country: int sum: float - """Price paid, USD (parsed from the server's decimal string).""" + """Cost of the rent incl. extensions, USD (the server sends a number or a decimal string). Reserved while + ``status`` is 0, charged once confirmed.""" days: int hours: int time: int @@ -167,9 +173,9 @@ class RentTariff(_RentTariffRequired, total=False): class _BalanceRequired(TypedDict): balance: float - """Total balance, USD. Includes ``zbalance``: available = balance - zbalance.""" + """Total balance, USD. Includes ``zbalance``: available = balance - max(zbalance, 0).""" zbalance: float - """Sum frozen by numbers in progress.""" + """Sum frozen by numbers and rents in progress; may be negative.""" class Balance(_BalanceRequired, total=False): @@ -195,8 +201,8 @@ class Profile(_ProfileRequired, total=False): number_country: Optional[int] number_reject: Union[List[str], Dict[str, str], None] webhook_url: Optional[str] - number: Optional[str] - country: Optional[int] + number: Optional[int] + country: Optional[str] number_region: Optional[int] is_api: bool active: str @@ -243,9 +249,9 @@ class PaymentOrder(TypedDict, total=False): id: int sum: str """Decimal string, e.g. ``"89.00"``.""" - currency: str + currency: Optional[str] stat: int - form_text: str + form_text: Optional[str] status_text: str created_at: str @@ -256,8 +262,8 @@ class PaymentOrders(Paginator): class _PaymentHistoryRequired(TypedDict): orders: PaymentOrders - paylist: Dict[str, Any] - """Payment methods by list id.""" + paylist: Union[Dict[str, Any], List[Any]] + """Payment methods by group id; a list when the ids are 0, 1, 2... (the server sends a JSON array then).""" class PaymentHistory(_PaymentHistoryRequired, total=False): @@ -307,13 +313,13 @@ class WebhookLogs(Paginator): class FreeCountry(TypedDict): country: int - country_text: str - country_original: str + country_text: Optional[str] + country_original: Optional[str] class FreeNumber(TypedDict): country: int - country_original: str + country_original: Optional[str] full_number: str data_humans: str is_archive: bool diff --git a/onlinesimru/numbers.py b/onlinesimru/numbers.py index 791b701..fc429f6 100644 --- a/onlinesimru/numbers.py +++ b/onlinesimru/numbers.py @@ -67,7 +67,8 @@ def close(self, tzid: int) -> bool: return True def ban(self, tzid: int) -> bool: - """Finish the operation and report the number as bad (only before any SMS arrived).""" + """Finish the operation and report the number as bad. After an SMS arrived nothing changes and + ``ApiError("0")`` is raised.""" self._request("setOperationOk.php", {"tzid": tzid, "ban": True}) return True diff --git a/onlinesimru/rent.py b/onlinesimru/rent.py index 41a1581..c5ecb05 100644 --- a/onlinesimru/rent.py +++ b/onlinesimru/rent.py @@ -20,7 +20,8 @@ def __init__(self, request: RequestFn) -> None: self._request = request def get(self, country: int = 7, days: int = 1, extension: bool = True) -> RentItem: - """Rent a number for ``days`` days. ``extension=False`` makes the rent non-extendable for good.""" + """Rent a number for ``days`` days. The price is reserved; the first SMS that is not ``notify`` confirms the + rent and charges it. ``extension=False`` makes the rent non-extendable for good.""" res = self._request( "rent/getRentNum.php", {"country": country, "days": days, "extension": extension, **_DETAIL} ) @@ -39,7 +40,7 @@ def state_one(self, tzid: int) -> RentItem: return _rent_item(res["list"][0]) def extend(self, tzid: int, days: int = 1) -> RentItem: - """Extend a rent by ``days`` days (only rents created with ``extension=True``).""" + """Extend a rent by ``days`` days and charge at once (only confirmed rents created with ``extension=True``).""" res = self._request("rent/extendRentState.php", {"tzid": tzid, "days": days, **_DETAIL}) return _rent_item(res["item"]) diff --git a/onlinesimru/user.py b/onlinesimru/user.py index 06f3b80..f20b791 100644 --- a/onlinesimru/user.py +++ b/onlinesimru/user.py @@ -2,7 +2,7 @@ from typing import TYPE_CHECKING, cast -from ._normalize import as_map, num +from ._normalize import num from .models import Balance, PaymentHistory, Profile, WebhookLogs if TYPE_CHECKING: @@ -16,7 +16,7 @@ def __init__(self, request: RequestFn) -> None: self._request = request def balance(self) -> Balance: - """Balance in USD. ``balance`` includes the frozen ``zbalance``: available = balance - zbalance.""" + """Balance in USD. ``balance`` includes the frozen ``zbalance``: available = balance - max(zbalance, 0).""" res = self._request("getBalance.php", {"income": 1}) out: Balance = {"balance": num(res.get("balance")) or 0, "zbalance": num(res.get("zbalance")) or 0} income = num(res.get("income")) @@ -30,8 +30,8 @@ def profile(self) -> Profile: def payment_history(self, page: int = 1) -> PaymentHistory: """Top-up orders (paginated, newest first) and the available payment methods.""" - res = self._request("getPaymentHistory.php", {"page": page}) - return cast(PaymentHistory, {**res, "paylist": as_map(res.get("paylist"))}) + # `paylist` stays as sent: a non-empty JSON array is real data (ids 0..n), not PHP's empty map. + return cast(PaymentHistory, self._request("getPaymentHistory.php", {"page": page})) def set_webhook_url(self, url: str) -> bool: """Set the URL that receives SMS webhooks. Raises ``ApiError("VALIDATION_ERROR")`` for an invalid URL.""" diff --git a/onlinesimru/wait.py b/onlinesimru/wait.py index 60aaf66..b0de47e 100644 --- a/onlinesimru/wait.py +++ b/onlinesimru/wait.py @@ -1,12 +1,14 @@ from __future__ import annotations -import contextlib import time from typing import Callable, Optional, Protocol from .errors import ApiError, TimeoutError, TransportError from .models import Operation +_RETRYABLE = frozenset({"TRY_AGAIN_LATER", "ERROR_UNDEFINED", "INTERVAL_CONCURRENT_REQUESTS_ERROR"}) +"""Error codes that mean "try again": rate limit (HTTP 429), a transient server error, too many requests.""" + class _Numbers(Protocol): def state_one(self, tzid: int, *, message_to_code: bool = ..., msg_list: bool = ...) -> Operation: ... @@ -32,14 +34,21 @@ def wait_code( then ``close`` (or ``next`` with ``keep_open``) and return it. A finished operation (TZ_OVER_OK, ERROR_NO_ITEMS) without a new code raises ``ApiError`` with that state as the - code; running out of ``timeout`` seconds raises ``TimeoutError``. ``TransportError`` is retried until the - timeout; any ``ApiError`` is raised at once. ``sleep`` and ``clock`` are injectable for tests. + code; running out of ``timeout`` seconds raises ``TimeoutError``. ``TransportError`` and the transient + ``ApiError`` codes ``TRY_AGAIN_LATER``, ``ERROR_UNDEFINED`` and ``INTERVAL_CONCURRENT_REQUESTS_ERROR`` are + retried until the timeout; any other ``ApiError`` is raised at once. ``sleep`` and ``clock`` are injectable + for tests. """ deadline = clock() + timeout while True: op: Optional[Operation] = None - with contextlib.suppress(TransportError): # transient: retried until the timeout + try: op = numbers.state_one(tzid, message_to_code=not full_message) + except TransportError: + pass # transient: retried until the timeout + except ApiError as error: + if error.code not in _RETRYABLE: + raise if op is not None: msg = op.get("msg") @@ -49,8 +58,9 @@ def wait_code( else: numbers.close(tzid) return msg - if op["response"] in ("TZ_OVER_OK", "ERROR_NO_ITEMS"): - raise ApiError(op["response"]) + status = op.get("response") # absent while no number is issued + if status in ("TZ_OVER_OK", "ERROR_NO_ITEMS"): + raise ApiError(status) left = deadline - clock() if left <= 0: diff --git a/pyproject.toml b/pyproject.toml index 4fb30df..c299c05 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "onlinesimru" -version = "3.1.0" +version = "3.1.1" description = "Typed, zero-dependency Python client for the OnlineSim API: SMS numbers, rent, account and free numbers." readme = "README.md" license = "Apache-2.0" diff --git a/tests/test_client.py b/tests/test_client.py index a99ebc9..05df795 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -63,17 +63,25 @@ def test_no_number(self) -> None: assert info.value.message == "No numbers available for this service right now" assert str(info.value) == info.value.message - def test_no_number_for_forward(self) -> None: - client, _ = fake_client(Reply({"response": "NO_NUMBER_FOR_FORWARD"})) - with pytest.raises(NoNumberError): - client.numbers.get("google") + def test_http_429_try_again_later_is_api_error(self) -> None: + client, _ = fake_client(Reply({"response": "TRY_AGAIN_LATER"}, status=429)) + with pytest.raises(ApiError) as info: + client.numbers.state() + assert not isinstance(info.value, TransportError) + assert info.value.code == "TRY_AGAIN_LATER" + + def test_missing_key_http_200_wrong_key_is_api_error(self) -> None: + client, _ = fake_client(Reply({"response": "ERROR_WRONG_KEY"}), api_key=None) + with pytest.raises(ApiError) as info: + client.user.balance() + assert (info.value.code, info.value.message) == ("ERROR_WRONG_KEY", "Wrong or missing API key") def test_http_456_wrong_key_is_api_error(self) -> None: client, _ = fake_client(Reply({"response": "ERROR_WRONG_KEY"}, status=456)) with pytest.raises(ApiError) as info: client.user.balance() assert not isinstance(info.value, TransportError) - assert (info.value.code, info.value.message) == ("ERROR_WRONG_KEY", "Wrong API key") + assert (info.value.code, info.value.message) == ("ERROR_WRONG_KEY", "Wrong or missing API key") def test_server_message_unless_it_echoes_the_code(self) -> None: client, _ = fake_client( diff --git a/tests/test_free.py b/tests/test_free.py index 5a0a3f6..4173f25 100644 --- a/tests/test_free.py +++ b/tests/test_free.py @@ -17,3 +17,9 @@ def test_list_normalises_empty_numbers() -> None: client, fake = fake_client(Reply({"response": 1, "countries": [], "numbers": [], "messages": {"data": []}})) assert client.free.list()["numbers"] == {} assert fake.last().query == {} + + +def test_list_accepts_null_country_texts() -> None: + country = {"country": 999, "country_text": None, "country_original": None} + client, _ = fake_client(Reply({"response": 1, "countries": [country], "numbers": [], "messages": {"data": []}})) + assert client.free.list()["countries"] == [country] diff --git a/tests/test_integration.py b/tests/test_integration.py index d9aecbf..1365bd3 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -72,7 +72,7 @@ def test_rent_state(self, client: OnlineSim) -> None: def test_payment_history(self, client: OnlineSim) -> None: history = client.user.payment_history() assert isinstance(history["orders"]["data"], list) - assert isinstance(history["paylist"], dict) + assert isinstance(history["paylist"], (dict, list)) def test_webhook_logs(self, client: OnlineSim) -> None: assert isinstance(client.user.webhook_logs()["data"], list) @@ -112,7 +112,7 @@ def test_number_lifecycle(self, client: OnlineSim) -> None: ids = {op["tzid"] for op in client.numbers.state()} assert {tzid, order["tzid"]} <= ids - assert client.numbers.state_one(tzid)["response"].startswith("TZ_") + assert client.numbers.state_one(tzid).get("response", "TZ_").startswith("TZ_") # The test driver answers NO_NUMBER to any reject list: proves `reject` is sent. with pytest.raises(NoNumberError): diff --git a/tests/test_mock.py b/tests/test_mock.py index 6e5c768..bf741ea 100644 --- a/tests/test_mock.py +++ b/tests/test_mock.py @@ -2,13 +2,15 @@ from __future__ import annotations -from typing import Callable +import json +from typing import Any, Callable, Optional import pytest from onlinesimru import ( ApiError, HttpRequest, + HttpResponse, MockOnlineSim, MockRequest, NoNumberError, @@ -21,22 +23,37 @@ def no_sleep(_seconds: float) -> None: pass +def raw(mock: MockOnlineSim, path: str, key: Optional[str] = "mock-key") -> HttpResponse: + """One request straight to the mock transport, bypassing the client's parsing.""" + headers = {} if key is None else {"Authorization": f"Bearer {key}"} + return mock.transport(HttpRequest("GET", f"https://x.test/api/{path}", headers, None, 1)) + + +def body(res: HttpResponse) -> Any: + return json.loads(res.body) + + # ----- auth and transport ----- -def test_wrong_or_missing_key_is_http_456_mapped_to_api_error() -> None: +def test_wrong_key_is_http_456_missing_key_http_200_both_api_error() -> None: mock = MockOnlineSim() for api_key in ("nope", ""): with pytest.raises(ApiError) as error: mock.client(api_key=api_key).user.balance() assert error.value.code == "ERROR_WRONG_KEY" + missing = raw(mock, "getBalance.php", key=None) + assert (missing.status, body(missing)) == (200, {"response": "ERROR_WRONG_KEY"}) + assert raw(mock, "getBalance.php", key="nope").status == 456 -def test_tariffs_and_free_numbers_need_no_key() -> None: - client = MockOnlineSim().client(api_key="") +def test_tariffs_and_free_numbers_need_no_key_but_a_wrong_key_is_456() -> None: + mock = MockOnlineSim() + client = mock.client(api_key="") assert client.numbers.tariffs_one(44)["code"] == 44 assert client.rent.tariffs_one(7)["code"] == 7 assert client.free.list()["messages"]["country"] == 44 + assert code_of(mock.client(api_key="nope").free.list) == "ERROR_WRONG_KEY" def test_transport_of_a_hand_built_client_with_any_base_url() -> None: @@ -74,6 +91,9 @@ def test_get_freezes_the_price_and_numbers_are_deterministic() -> None: "country": 7, "time": 1200, "service": "vkcom", + "title": "vkcom", + "response_text": "Waiting for SMS", + "guard_interval_remaining_seconds": 0, } assert [r.query.get("number") for r in mock.requests] == [None, "1"] assert client.user.balance() == {"balance": 100, "zbalance": 0.7, "income": 0} @@ -148,7 +168,17 @@ def test_full_text_without_code_next_and_msg_list() -> None: {"service": "telegram", "msg": "Welcome!"}, {"service": "telegram", "msg": "98765"}, ] - assert client.numbers.next(424242) is True # always succeeds, like the backend + assert len([r for r in mock.requests if r.path == "setOperationRevise.php"]) == 1 + + +def test_next_answer_wrong_tzid_and_no_tzid() -> None: + mock = MockOnlineSim() + client = mock.client() + tzid = client.numbers.get("google", 44) + assert body(raw(mock, f"setOperationRevise.php?tzid={tzid}")) == {"tzid": str(tzid), "response": "1"} + assert code_of(lambda: client.numbers.next(424242)) == "ERROR_WRONG_TZID" + assert code_of(lambda: client.numbers.next(0)) == "ERROR_NO_TZID" + assert code_of(lambda: client.numbers.close(0)) == "ERROR_NO_TZID" def test_close_spends_or_refunds_and_ban_after_sms_answers_0() -> None: @@ -228,39 +258,73 @@ def test_tariffs_from_prices() -> None: # ----- rent ----- -def test_rent_get_state_extend_close() -> None: +def test_rent_get_reserves_first_sms_confirms_and_charges_extend_close() -> None: mock = MockOnlineSim(balance=10) client = mock.client() rent = client.rent.get(7, 3) - assert (rent["tzid"], rent["number"], rent["sum"], rent["days"]) == (1, "900000001", 2.5, 3) - assert (rent["time"], rent["extension"], rent["messages"]) == (3 * 1440, 1, []) - assert rent.get("time_seconds") == 3 * 86400 + assert (rent["tzid"], rent["number"], rent["status"], rent.get("checked")) == (1, "900000001", 0, False) + assert (rent["sum"], rent["days"], rent["time"], rent.get("time_seconds")) == (2.5, 0, 20, 1200) + assert (rent.get("rent"), rent.get("days_autoextend"), rent["extension"]) == (3, 3, 1) + assert (rent.get("guard_interval_remaining_seconds"), rent["messages"]) == (0, []) assert rent["extend"] == {"1": 1, "3": 2.5, "7": 5} - assert mock.balance() == 7.5 + # reserved: the total balance stays, the price is frozen + assert mock.balance() == 10 + assert client.user.balance() == {"balance": 10, "zbalance": 2.5, "income": 0} + assert code_of(lambda: client.rent.extend(rent["tzid"])) == "TRY_AGAIN_LATER" # not confirmed yet mock.add_sms(rent["tzid"], "Bank: 777 888", service="bank") mock.add_sms(rent["tzid"], "no code here") state = client.rent.state_one(rent["tzid"]) + assert (state["status"], state.get("checked"), state["days"], state["time"]) == (1, True, 3, 3 * 1440) + assert state.get("time_seconds") == 3 * 86400 assert [(m["service"], m["code"]) for m in state["messages"]] == [("other", ""), ("bank", "777888")] # newest first + assert mock.balance() == 7.5 + assert client.user.balance() == {"balance": 7.5, "zbalance": 0, "income": 0} extended = client.rent.extend(rent["tzid"], 1) - assert (extended["days"], extended["sum"]) == (4, 3.5) + assert (extended["days"], extended.get("rent"), extended.get("days_autoextend"), extended["sum"]) == (4, 4, 3, 3.5) assert mock.balance() == 6.5 + assert code_of(lambda: client.rent.extend(rent["tzid"], 2)) == "TRY_AGAIN_LATER" # unknown period + assert code_of(lambda: client.rent.extend(999)) == "TRY_AGAIN_LATER" # unknown tzid fixed = client.rent.get(7, 1, False) - assert (fixed["extension"], fixed["extend"]) == (0, {}) + mock.add_sms(fixed["tzid"], "1234") + fixed_state = client.rent.state_one(fixed["tzid"]) + assert (fixed_state["extension"], fixed_state["extend"]) == (0, {}) assert code_of(lambda: client.rent.extend(fixed["tzid"])) == "TRY_AGAIN_LATER" assert [r["tzid"] for r in client.rent.state()] == [rent["tzid"], fixed["tzid"]] - client.rent.close(fixed["tzid"]) + client.rent.close(fixed["tzid"]) # confirmed: no refund + assert mock.balance() == 5.5 assert [r.tzid for r in mock.rents()] == [rent["tzid"]] assert code_of(lambda: client.rent.state_one(fixed["tzid"])) == "ERROR_NO_OPERATIONS" - assert code_of(lambda: client.rent.close(fixed["tzid"])) == "ERROR_WRONG_TZID" + assert code_of(lambda: client.rent.close(fixed["tzid"])) == "ERROR_NO_OPERATIONS" + + +def test_rent_sum_number_in_get_string_in_state_on_the_wire() -> None: + mock = MockOnlineSim() + assert body(raw(mock, "rent/getRentNum.php?days=3"))["item"]["sum"] == 2.5 + assert body(raw(mock, "rent/getRentState.php"))["list"][0]["sum"] == "2.50" + + +def test_unconfirmed_rent_close_releases_notify_code_0_guard_interval() -> None: + mock = MockOnlineSim(balance=10, guard_interval=120) + client = mock.client() + rent = client.rent.get(7, 3) + assert rent.get("guard_interval_remaining_seconds") == 120 + assert code_of(lambda: client.rent.close(rent["tzid"])) == "NO_COMPLETE_TZID" + mock.add_sms(rent["tzid"], "Messages from this sender are not accepted", service="notify") + state = client.rent.state_one(rent["tzid"]) + assert (state["status"], state.get("checked"), state.get("guard_interval_remaining_seconds")) == (0, False, 0) + assert (state["messages"][0]["service"], state["messages"][0]["code"]) == ("notify", 0) + assert client.rent.close(rent["tzid"]) is True + assert mock.balance() == 10 # released, nothing charged + assert client.user.balance() == {"balance": 10, "zbalance": 0, "income": 0} def test_rent_errors() -> None: client = MockOnlineSim(balance=1.5).client() - assert code_of(lambda: client.rent.get(44)) == "NO_COUNTRY" + assert code_of(lambda: client.rent.get(44)) == "UNDEFINED_COUNTRY" assert code_of(lambda: client.rent.get(7, 2)) == "UNDEFINED_DAYS" assert code_of(lambda: client.rent.get(7, 3)) == "WARNING_LOW_BALANCE" @@ -271,8 +335,9 @@ def test_rent_add_sms_after_and_tariffs() -> None: tzid = client.rent.get()["tzid"] mock.add_sms_after(tzid, "6060", 1) assert client.rent.state_one(tzid)["messages"] == [] - message = client.rent.state()[0]["messages"][0] - assert (message["code"], message["service"]) == ("6060", "other") + listed = client.rent.state()[0] + assert listed["status"] == 1 + assert (listed["messages"][0]["code"], listed["messages"][0]["service"]) == ("6060", "other") count = {"1": 100, "3": 100, "7": 100} assert client.rent.tariffs() == { "7": { @@ -300,8 +365,9 @@ def test_profile_webhook_set_validate_clear_and_logs() -> None: profile = client.user.profile() assert (profile["id"], profile.get("apikey"), profile.get("webhook_url")) == (1, "secret", None) with pytest.raises(ApiError) as error: - client.user.set_webhook_url("ftp://x") + client.user.set_webhook_url("not a url") assert (error.value.code, error.value.message) == ("VALIDATION_ERROR", "The webhook url must be a valid URL.") + assert client.user.set_webhook_url("ftp://x") is True # any scheme://... URL client.user.set_webhook_url("https://example.com/hook") last = mock.requests[-1] assert (last.method, last.path) == ("POST", "profile.php") @@ -312,34 +378,63 @@ def test_profile_webhook_set_validate_clear_and_logs() -> None: mock.add_sms(tzid, "code 1234") rent = client.rent.get() mock.add_sms(rent["tzid"], "code 5678") + mock.add_sms(rent["tzid"], "no code") logs = client.user.webhook_logs() - assert (logs["total"], logs["current_page"], logs["per_page"]) == (2, 1, 10) + assert (logs["total"], logs["current_page"], logs["per_page"]) == (3, 1, 10) assert [(log["type"], log["params"]["operation_id"], log["params"]["code"]) for log in logs["data"]] == [ + ("rent_sms", rent["tzid"], ""), ("rent_sms", rent["tzid"], "5678"), ("receiving_sms", tzid, "1234"), ] + # activation: +number, seconds left, order time; rent: digits without +, minutes left, SMS time + activation, rent_log = logs["data"][2]["params"], logs["data"][1]["params"] + assert (activation["number"], activation["time_left"], activation["time_start"]) == ( + "+44900000001", + 1200, + "2026-01-01 00:00:01", + ) + assert (rent_log["number"], rent_log["time_left"], rent_log["time_start"]) == ( + "7900000002", + 1440, + "2026-01-01 00:00:03", + ) client.user.clear_webhook_url() assert client.user.profile().get("webhook_url") is None -def test_balance_includes_frozen_and_payment_history_is_empty() -> None: +def test_balance_includes_frozen_and_payment_history_has_no_orders() -> None: mock = MockOnlineSim(balance=3) client = mock.client() client.numbers.get("telegram") assert client.user.balance() == {"balance": 3, "zbalance": 1.2, "income": 0} history = client.user.payment_history() - assert history["paylist"] == {} + assert (history["paylist"], history.get("forms"), history.get("buttons")) == ( + [], + {"1": "Card"}, + {"USD": [5, 10, 20]}, + ) assert (history["orders"]["data"], history["orders"]["total"], history["orders"]["current_page"]) == ([], 0, 1) def test_free_list() -> None: client = MockOnlineSim().client() uk = client.free.list() - assert [c["country"] for c in uk["countries"]] == [7, 44] + assert [c["country"] for c in uk["countries"]] == [44, 7] assert list(uk["numbers"]) == ["7459608320"] - assert (uk["messages"]["number"], uk["messages"]["country"], uk["messages"]["total"]) == ("7459608320", 44, 2) - assert uk["messages"]["data"][0]["code"] == "195895" + messages = uk["messages"] + assert (messages["number"], messages["country"], messages["total"], messages["per_page"]) == ( + "7459608320", + 44, + 2, + 10, + ) + assert (messages["data"][0]["code"], messages["data"][0]["created_at"]) == ("195895", "2026-01-01T00:00:00.000000Z") + assert client.free.list(count=0)["messages"]["per_page"] == 10 # clamped to 10..500 + assert client.free.list(count=9999)["messages"]["per_page"] == 500 + assert client.free.list(country=999)["messages"]["country"] == 44 # unknown -> the first country + wire = body(raw(MockOnlineSim(), "getFreeList", key=None)) + assert (wire["response"], wire["content"], type(wire["ignore"])) == (1, None, str) ru = client.free.list(country=7) assert (ru["messages"]["data"][0]["code"], ru["messages"]["data"][0]["my_number"]) == ("51423", "9001234567") diff --git a/tests/test_numbers.py b/tests/test_numbers.py index c226533..b9d7cd7 100644 --- a/tests/test_numbers.py +++ b/tests/test_numbers.py @@ -124,3 +124,26 @@ def test_tariffs_one_no_country() -> None: with pytest.raises(ApiError) as info: client.numbers.tariffs_one(999) assert info.value.code == "NO_COUNTRY" + + +def test_ban_after_sms_answers_0() -> None: + client, _ = fake_client(Reply({"response": "0"})) + with pytest.raises(ApiError) as info: + client.numbers.ban(1520) + assert (info.value.code, info.value.message) == ("0", "Ban not applied: the operation already has an SMS") + + +def test_next_string_answer_and_wrong_tzid() -> None: + client, _ = fake_client(Reply({"tzid": "1520", "response": "1"}), Reply({"response": "ERROR_WRONG_TZID"})) + assert client.numbers.next(1520) is True + with pytest.raises(ApiError) as info: + client.numbers.next(1) + assert info.value.code == "ERROR_WRONG_TZID" + + +def test_state_one_without_response() -> None: + op = {"tzid": 5, "country": 7, "service": "vkcom", "sum": 0.5, "time": 900, "form": "index"} + client, _ = fake_client(Reply([op])) + got = client.numbers.state_one(5) + assert got["tzid"] == 5 + assert "response" not in got diff --git a/tests/test_rent.py b/tests/test_rent.py index a9f1352..3172c00 100644 --- a/tests/test_rent.py +++ b/tests/test_rent.py @@ -95,3 +95,29 @@ def test_close_no_close_rent_us() -> None: with pytest.raises(ApiError) as info: client.rent.close(1) assert info.value.code == "NO_CLOSE_RENT_US" + + +def test_spec_shapes_sum_number_or_string_and_notify_code_0() -> None: + item = { + **items()[0], + "status": 0, + "checked": False, + "sum": 1.5, + "messages": [ + { + "id": 2, + "service": "notify", + "text": "Sender not accepted", + "code": 0, + "created_at": "2026-11-19 10:01:12", + }, + {"id": 1, "service": "Google", "text": "G-070051", "code": "070051", "created_at": "2026-11-19 10:01:00"}, + ], + } + client, _ = fake_client( + Reply({"response": 1, "item": item}), Reply({"response": 1, "list": [{**item, "sum": "2.40"}]}) + ) + rent = client.rent.get(7, 3) + assert (rent["status"], rent.get("checked"), rent["sum"]) == (0, False, 1.5) + assert [m["code"] for m in rent["messages"]] == [0, "070051"] + assert client.rent.state_one(rent["tzid"])["sum"] == 2.4 diff --git a/tests/test_user.py b/tests/test_user.py index ae92631..e9f33b0 100644 --- a/tests/test_user.py +++ b/tests/test_user.py @@ -24,12 +24,36 @@ def test_profile() -> None: assert profile.get("number_reject") == ["333"] -def test_payment_history_normalises_empty_paylist() -> None: +def test_profile_number_int_and_country_string() -> None: + client, _ = fake_client(ok(profile={"id": 1, "number": 79001234567, "country": "RU"})) + profile = client.user.profile() + assert (profile.get("number"), profile.get("country")) == (79001234567, "RU") + + +def test_payment_history_keeps_list_paylist_and_nullable_order_fields() -> None: + body = fixture("getPaymentHistory") + order = { + "id": 1, + "sum": "10.00", + "currency": None, + "form_text": None, + "stat": 0, + "created_at": "2026-06-14 09:12:12", + } + paylist = [{"id": 0, "name": "Card"}, {"id": 1, "name": "Crypto"}] + client, _ = fake_client(Reply({**body, "paylist": paylist, "orders": {**body["orders"], "data": [order]}})) + history = client.user.payment_history() + assert history["paylist"] == paylist + first = history["orders"]["data"][0] + assert (first.get("currency"), first.get("form_text")) == (None, None) + + +def test_payment_history_keeps_empty_paylist() -> None: client, fake = fake_client(Reply(fixture("getPaymentHistory"))) history = client.user.payment_history(2) assert fake.last().path == "/api/getPaymentHistory.php" assert fake.last().query == {"page": "2"} - assert history["paylist"] == {} + assert history["paylist"] == [] order = history["orders"]["data"][0] assert (order.get("id"), order.get("sum")) == (9462, "89.00") diff --git a/tests/test_wait.py b/tests/test_wait.py index a178427..cf72734 100644 --- a/tests/test_wait.py +++ b/tests/test_wait.py @@ -27,6 +27,8 @@ def state_one(self, tzid: int, *, message_to_code: bool = True, msg_list: bool = raise step op: Operation = {"tzid": tzid, "response": "TZ_NUM_WAIT"} op.update(step) # type: ignore[typeddict-item] + if op.get("response") is None: # a step with `"response": None`: the key is absent + del op["response"] return op def close(self, tzid: int) -> bool: @@ -102,7 +104,27 @@ def test_retries_transient_transport_error() -> None: assert t.log == ["state 7 code=True", "sleep 5", "state 7 code=True", "close 7"] -def test_api_error_raised_at_once() -> None: +@pytest.mark.parametrize("code", ["TRY_AGAIN_LATER", "ERROR_UNDEFINED", "INTERVAL_CONCURRENT_REQUESTS_ERROR"]) +def test_retries_transient_api_error(code: str) -> None: + t = FakeNumbers([ApiError(code), {"msg": "42"}]) + assert t.wait() == "42" + assert t.log == ["state 7 code=True", "sleep 5", "state 7 code=True", "close 7"] + + +def test_retryable_api_error_still_times_out() -> None: + t = FakeNumbers([ApiError("TRY_AGAIN_LATER") for _ in range(10)]) + with pytest.raises(TimeoutError): + t.wait(interval=5, timeout=10) + assert t.now == 10 + + +def test_operation_without_response_keeps_polling() -> None: + t = FakeNumbers([{"response": None}, {"msg": "77"}]) + assert t.wait() == "77" + assert t.log == ["state 7 code=True", "sleep 5", "state 7 code=True", "close 7"] + + +def test_other_api_error_raised_at_once() -> None: t = FakeNumbers([ApiError("ERROR_NO_OPERATIONS")]) with pytest.raises(ApiError) as info: t.wait()