From bb71f8f8cb80babe97c61d773ccabe9bbe85cd9b Mon Sep 17 00:00:00 2001 From: Pavel Kuzmin Date: Thu, 19 Nov 2026 22:11:19 +0500 Subject: [PATCH] feat: MockOnlineSim, package linting and release workflow (3.1.0) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MockOnlineSim (offline fake API for users' tests), package linting, smoke from the built artifact, release.yml (tag → checks → publish → GitHub release). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 20 +- .github/workflows/docs.yml | 2 +- .github/workflows/publish.yml | 39 --- .github/workflows/release.yml | 65 +++++ CHANGELOG.md | 7 + README.md | 17 ++ docs/content/changelog.md | 6 +- docs/content/testing.md | 137 +++++++++ onlinesimru/__init__.py | 22 ++ onlinesimru/mock/__init__.py | 177 ++++++++++++ onlinesimru/mock/_handlers.py | 509 ++++++++++++++++++++++++++++++++++ onlinesimru/mock/_state.py | 291 +++++++++++++++++++ pyproject.toml | 2 +- tests/smoke_artifact.py | 72 +++++ tests/test_mock.py | 404 +++++++++++++++++++++++++++ 15 files changed, 1724 insertions(+), 46 deletions(-) delete mode 100644 .github/workflows/publish.yml create mode 100644 .github/workflows/release.yml create mode 100644 docs/content/testing.md create mode 100644 onlinesimru/mock/__init__.py create mode 100644 onlinesimru/mock/_handlers.py create mode 100644 onlinesimru/mock/_state.py create mode 100644 tests/smoke_artifact.py create mode 100644 tests/test_mock.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f58eb0c..f865d40 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,13 +38,25 @@ jobs: run: python -m pip install mypy - run: python -m pytest - build: - runs-on: ubuntu-latest + # Package linters on the built artifact, then the artifact itself installed into a fresh venv on the floor + # (3.9) and the latest Python, running the README "Testing" example against MockOnlineSim. + # ubuntu-22.04: setup-python has no 3.9 build for the newest ubuntu-latest image. + package: + runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: - python-version: '3.13' - - run: python -m pip install build twine + # The last one is the default `python`. + python-version: | + 3.9 + 3.13 + - run: python -m pip install build twine check-wheel-contents pyroma - run: python -m build - run: python -m twine check --strict dist/* + - run: check-wheel-contents dist/*.whl + - run: pyroma --min 10 dist/*.tar.gz + - name: smoke from artifact (python 3.13) + run: python tests/smoke_artifact.py dist + - name: smoke from artifact (python 3.9) + run: python3.9 tests/smoke_artifact.py dist diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 8aba159..e869732 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -39,7 +39,7 @@ jobs: run: npm run build - name: Add nojekyll - run: '> .output/public/.nojekyll' + run: touch .output/public/.nojekyll - name: Deploy to GitHub Pages uses: crazy-max/ghaction-github-pages@v4 diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml deleted file mode 100644 index 0bfc991..0000000 --- a/.github/workflows/publish.yml +++ /dev/null @@ -1,39 +0,0 @@ -name: Publish to PyPI - -on: - push: - tags: - - 'v*' - -jobs: - ci: - uses: ./.github/workflows/ci.yml - - publish: - needs: ci - runs-on: ubuntu-latest - environment: - name: pypi - url: https://pypi.org/p/onlinesimru - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-python@v5 - with: - python-version: '3.13' - - - name: Check the tag matches the package version - run: | - version=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])") - test "v${version}" = "${GITHUB_REF_NAME}" || { echo "tag ${GITHUB_REF_NAME} != v${version}"; exit 1; } - - - name: Build package - run: | - python -m pip install build - python -m build - - - name: Publish to PyPI - uses: pypa/gh-action-pypi-publish@release/v1 - with: - password: ${{ secrets.PYPI_API_TOKEN }} - skip-existing: true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..ec0a65a --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,65 @@ +name: release + +# Push a version tag (`vX.Y.Z`, equal to the version in pyproject.toml) to publish to PyPI and create the +# GitHub release. PyPI trusted publishing (OIDC): the PyPI project trusts this workflow file (`release.yml`) +# and the `release` environment; no API token is stored. + +on: + push: + tags: + - 'v*' + +permissions: + contents: read + +jobs: + ci: + uses: ./.github/workflows/ci.yml + + release: + needs: ci + runs-on: ubuntu-latest + environment: + name: release + url: https://pypi.org/p/onlinesimru + permissions: + contents: write # gh release create + id-token: write # PyPI trusted publishing + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: '3.13' + + - name: Check the tag matches the package version + id: version + run: | + version=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml', 'rb'))['project']['version'])") + test "v${version}" = "${GITHUB_REF_NAME}" || { echo "::error::tag ${GITHUB_REF_NAME} != v${version}"; exit 1; } + echo "version=${version}" >> "$GITHUB_OUTPUT" + + - name: Build + run: | + python -m pip install build + python -m build + + - name: Publish to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 + with: + skip-existing: true + + - name: GitHub release + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ steps.version.outputs.version }} + run: | + if gh release view "${GITHUB_REF_NAME}" > /dev/null 2>&1; then + echo "release ${GITHUB_REF_NAME} exists, skipped" + exit 0 + fi + # The CHANGELOG.md section of this version: from `## [X.Y.Z]` up to the next `## ` heading. + awk -v head="## [${VERSION}]" 'index($0, head) == 1 { found = 1; next } found && /^## / { exit } found' \ + CHANGELOG.md > "${RUNNER_TEMP}/notes.md" + test -s "${RUNNER_TEMP}/notes.md" || { echo "::error::no CHANGELOG.md section for ${VERSION}"; exit 1; } + gh release create "${GITHUB_REF_NAME}" --title "${GITHUB_REF_NAME}" --latest --notes-file "${RUNNER_TEMP}/notes.md" diff --git a/CHANGELOG.md b/CHANGELOG.md index b1c8488..aea58cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ 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.0] + +### Added +- `MockOnlineSim`: a built-in, in-process fake of the OnlineSim API for testing integrations offline — no network, key, money or clock. `mock.client()` returns a normal `OnlineSim` wired to it (`mock.transport` is the fake transport). It answers every endpoint the SDK calls like the real backend (HTTP 456 for a wrong key, string/int `response`, decimal-string money, `[]` for empty maps) and keeps balance, operations and rents. Test helpers: `add_sms`, `add_sms_after` (lets `wait_code` run with `interval=0`), `fail_next`, `fail_next_transport`, `set_balance`, `balance`, `operations`, `rents`, `requests`, `reset`. Part of the main package (`from onlinesimru import MockOnlineSim`). See the [testing guide](https://s00d.github.io/onlinesim-python-api/testing). +- Packaging checks in CI: `twine check --strict`, `check-wheel-contents`, `pyroma` (10/10), and a smoke test that installs the built wheel into a fresh venv and runs the README "Testing" example on Python 3.9 and 3.13. +- Releases are published by `.github/workflows/release.yml` with PyPI trusted publishing (OIDC, no API token) and get a GitHub release with the changelog section. + ## [3.0.0] A rewrite. The public API changed; see the [docs](https://s00d.github.io/onlinesim-python-api/). diff --git a/README.md b/README.md index b0364be..ae0dbcd 100755 --- a/README.md +++ b/README.md @@ -25,4 +25,21 @@ print(f"enter {order['number']} in the app") print("code:", client.numbers.wait_code(order["tzid"])) ``` +## Testing + +`MockOnlineSim` is a built-in offline fake of the API: test your integration without network, key or money. +More in the [testing guide](https://s00d.github.io/onlinesim-python-api/testing). + +```python +from onlinesimru import MockOnlineSim + +mock = MockOnlineSim(balance=10) +client = mock.client() + +tzid = client.numbers.get("google", 44) +mock.add_sms_after(tzid, "Your code: 123-456", 2) # arrives on the third poll +assert client.numbers.wait_code(tzid, interval=0) == "123456" +assert mock.balance() == 9.8 +``` + Documentation: **https://s00d.github.io/onlinesim-python-api/** · Changes: [CHANGELOG.md](CHANGELOG.md) · License: Apache-2.0 diff --git a/docs/content/changelog.md b/docs/content/changelog.md index e1dab9e..3acd9c2 100644 --- a/docs/content/changelog.md +++ b/docs/content/changelog.md @@ -2,11 +2,15 @@ title: Changelog description: Release notes of onlinesim-python-api (PyPI onlinesimru). navigation: - order: 6 + order: 7 --- The full history is in [CHANGELOG.md](https://github.com/s00d/onlinesim-python-api/blob/master/CHANGELOG.md). +## 3.1.0 + +- New: `MockOnlineSim`, an offline fake of the API for your tests — see [Testing](/testing). + ## 3.0.0 A rewrite with a new API; 2.x code does not run unchanged. diff --git a/docs/content/testing.md b/docs/content/testing.md new file mode 100644 index 0000000..4175470 --- /dev/null +++ b/docs/content/testing.md @@ -0,0 +1,137 @@ +--- +title: Testing +description: Test your integration offline with MockOnlineSim — no network, key or money. +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. + +## Setup + +```python +from onlinesimru import MockOnlineSim + +mock = MockOnlineSim(balance=10) +client = mock.client() # an OnlineSim wired to the mock +``` + +```python +MockOnlineSim( + *, + api_key: str = "mock-key", + balance: float = 100, # USD + prices: Mapping[int, Mapping[str, float]] | None = None, # country -> service -> USD + rent_tariffs: Mapping[int, MockRentTariff] | None = None, # country -> {"days": {days: USD}, "extend": 0 | 1} + guard_interval: int = 0, # seconds +) +``` + +| Option | Default | Description | +|---|---|---| +| `api_key` | `"mock-key"` | Key the mock accepts. `mock.client()` uses it; `mock.client(api_key="x")` tests a wrong key (`""` for none). | +| `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`). | + +`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: + +```python +from onlinesimru import MockOnlineSim, OnlineSim + +mock = MockOnlineSim() +client = OnlineSim("mock-key", transport=mock.transport) +``` + +## A full example + +Order a number, let an SMS arrive while `wait_code` polls, check the code and the money. `add_sms_after` delivers the SMS after a number of polls instead of after some time, so `wait_code` runs with `interval=0` and the test takes milliseconds. + +```python +from onlinesimru import MockOnlineSim + + +def test_receives_the_code() -> None: + mock = MockOnlineSim(balance=10) + client = mock.client() + + order = client.numbers.get_with_number("google", 44) + assert order["number"] == "+44900000001" + + mock.add_sms_after(order["tzid"], "Your Google code: 123-456", 2) # the third poll sees it + code = client.numbers.wait_code(order["tzid"], interval=0) + + assert code == "123456" + assert mock.operations()[0].status == "TZ_OVER_OK" # wait_code closed it + assert mock.balance() == 9.8 # the price is spent once an SMS arrived +``` + +The `msg` of an operation is the code by default: the first run of 4–8 digits, with spaces and dashes between digits removed (`123-456` → `123456`); a text without such a run comes back whole. `message_to_code=False` (or `full_message=True` in `wait_code`) gives the full text. + +## Errors + +`fail_next(code)` makes the next request answer `{"response": code}` — the client turns it into `ApiError` (or `NoNumberError`) exactly as for the real server. Pass `endpoint` to fail only that endpoint. `fail_next_transport()` makes the next request fail with a non-JSON HTTP 502 (`TransportError`). + +```python +import pytest + +from onlinesimru import MockOnlineSim, NoNumberError, TransportError + + +def test_handles_a_missing_number_and_a_network_hiccup() -> None: + mock = MockOnlineSim() + client = mock.client() + + mock.fail_next("NO_NUMBER", endpoint="getNum.php") + with pytest.raises(NoNumberError): + client.numbers.get("google") + + mock.fail_next_transport(status=503) + with pytest.raises(TransportError): + client.user.balance() + + 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. + +## Inspecting requests + +`mock.requests` lists every request received as `MockRequest(method, path, query, body)`, `path` relative to `/api/`. + +```python +from onlinesimru import MockOnlineSim, MockRequest + + +def test_sends_reject_as_a_comma_list() -> None: + mock = MockOnlineSim() + mock.client().numbers.get("google", 44, reject=["4470", "4471"]) + + assert mock.requests == [ + MockRequest("GET", "getNum.php", {"service": "google", "country": "44", "reject": "4470,4471", "lang": "en"}), + ] +``` + +## Control API + +| Member | Description | +|---|---| +| `client(**options)` | A normal `OnlineSim` wired to the mock. | +| `transport` | The fake transport (`Callable[[HttpRequest], HttpResponse]`). | +| `add_sms(tzid, text, *, service=None)` | An SMS arrives now at a number operation or a rent (detected by `tzid`). Raises `ValueError` for an unknown or closed one. | +| `add_sms_after(tzid, text, polls, *, service=None)` | The SMS arrives after `polls` state requests for `tzid` (`numbers.state`/`state_one`, `rent.state`/`state_one`). | +| `fail_next(code, *, endpoint=None)` | The next request (to `endpoint` only, e.g. `"getNum.php"`) answers `{"response": code}`. | +| `fail_next_transport(*, status=502, endpoint=None)` | The next request fails with a non-JSON body and HTTP `status`. | +| `set_balance(usd)` / `balance()` | Set / read the total balance, USD (it includes the part frozen by open operations, as `user.balance()` reports it). | +| `operations()` / `rents()` | Copies of the current number operations / open rents (`MockOperation` / `MockRent` dataclasses), for assertions. | +| `requests` | Log of the requests received (`list[MockRequest]`). | +| `reset()` | Back to the constructor's state. | + +## 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. diff --git a/onlinesimru/__init__.py b/onlinesimru/__init__.py index 35f1a16..7e00806 100644 --- a/onlinesimru/__init__.py +++ b/onlinesimru/__init__.py @@ -13,6 +13,18 @@ ) from .errors import ERROR_MESSAGES, ApiError, NoNumberError, OnlineSimError, TimeoutError, TransportError from .free import FreeApi +from .mock import ( + MOCK_BASE_URL, + MockOnlineSim, + MockOperation, + MockOperationStatus, + MockPrices, + MockRent, + MockRentSms, + MockRentTariff, + MockRequest, + MockSms, +) from .models import ( Balance, CountryStat, @@ -48,6 +60,7 @@ __all__ = [ "DEFAULT_BASE_URL", "ERROR_MESSAGES", + "MOCK_BASE_URL", "ApiError", "Balance", "CountryStat", @@ -59,6 +72,15 @@ "FreeNumber", "HttpRequest", "HttpResponse", + "MockOnlineSim", + "MockOperation", + "MockOperationStatus", + "MockPrices", + "MockRent", + "MockRentSms", + "MockRentTariff", + "MockRequest", + "MockSms", "NoNumberError", "NumberOrder", "NumbersApi", diff --git a/onlinesimru/mock/__init__.py b/onlinesimru/mock/__init__.py new file mode 100644 index 0000000..77ebbad --- /dev/null +++ b/onlinesimru/mock/__init__.py @@ -0,0 +1,177 @@ +"""In-process fake OnlineSim API for tests: :class:`MockOnlineSim`.""" + +from __future__ import annotations + +import copy +import json +from typing import Any, List, Mapping, Optional, Union +from urllib.parse import parse_qsl, urlsplit + +from ..client import DEFAULT_TIMEOUT, HttpRequest, HttpResponse, OnlineSim +from ._handlers import PUBLIC_PATHS, ROUTES +from ._state import ( + MockFailure, + MockOperation, + MockOperationStatus, + MockPrices, + MockRent, + MockRentSms, + MockRentTariff, + MockRequest, + MockSms, + MockState, + from_mills, + to_mills, +) + +__all__ = [ + "MOCK_BASE_URL", + "MockOnlineSim", + "MockOperation", + "MockOperationStatus", + "MockPrices", + "MockRent", + "MockRentSms", + "MockRentTariff", + "MockRequest", + "MockSms", +] + +MOCK_BASE_URL = "https://mock.onlinesim.invalid/api/" +"""Base URL of clients made by :meth:`MockOnlineSim.client`. Never contacted: the mock answers in-process.""" + + +class MockOnlineSim: + """In-process fake OnlineSim API for tests: no network, no key, no money, no clock. + + It is a transport (:attr:`transport`) that answers like the real backend; :meth:`client` returns a normal + :class:`~onlinesimru.OnlineSim` wired to it. Test helpers add SMS, queue failures and expose the state. + + >>> mock = MockOnlineSim(balance=10) + >>> client = mock.client() + >>> tzid = client.numbers.get("google", 44) + >>> mock.add_sms_after(tzid, "Your code: 123-456", 2) + >>> client.numbers.wait_code(tzid, interval=0) + '123456' + """ + + def __init__( + self, + *, + api_key: str = "mock-key", + balance: float = 100, + prices: Optional[Mapping[int, Mapping[str, float]]] = None, + rent_tariffs: Optional[Mapping[int, MockRentTariff]] = None, + guard_interval: int = 0, + ) -> None: + """ + :param api_key: Key the mock accepts as ``Authorization: Bearer ``. + :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``). + """ + self._state = MockState( + api_key=api_key, balance=balance, prices=prices, rent_tariffs=rent_tariffs, guard_interval=guard_interval + ) + + def client( + self, + *, + api_key: Optional[str] = None, + base_url: str = MOCK_BASE_URL, + lang: str = "en", + dev_id: Union[str, int, None] = None, + timeout: float = DEFAULT_TIMEOUT, + ) -> OnlineSim: + """A normal client wired to the mock. ``api_key`` defaults to the mock's key; pass another one (``""`` for + none) to test a wrong key.""" + key = self._state.api_key if api_key is None else api_key + return OnlineSim(key, base_url=base_url, lang=lang, dev_id=dev_id, timeout=timeout, transport=self.transport) + + def transport(self, request: HttpRequest) -> HttpResponse: + """The fake transport; pass ``transport=mock.transport`` when you build the client yourself. Any base URL + works.""" + url = urlsplit(request.url) + at = url.path.find("/api/") + req = MockRequest( + method=request.method.upper(), + path=url.path.lstrip("/") if at < 0 else url.path[at + 5 :], + query=dict(parse_qsl(url.query, keep_blank_values=True)), + body=None if request.body is None else json.loads(request.body), + ) + state = self._state + state.requests.append(req) + + failure = state.take_failure(req.path) + if failure is not None: + if failure.code is not None: + return _json({"response": failure.code}) + return _text(failure.status, "Mock transport failure") + + 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}": + return _json({"response": "ERROR_WRONG_KEY"}, 456) + return _json(handler(state, req)) + + def add_sms(self, tzid: int, text: str, *, service: Optional[str] = None) -> None: + """An SMS arrives now at number operation or rent ``tzid``. Raises ``ValueError`` when there is no open + operation or rent with that id.""" + if not self._state.deliver(tzid, text, service): + raise ValueError(f"MockOnlineSim: no open operation or rent {tzid}") + + def add_sms_after(self, tzid: int, text: str, polls: int, *, service: Optional[str] = None) -> None: + """The SMS arrives after ``polls`` state requests for ``tzid`` (getState / rent getRentState, listing it + alone or with others): with ``polls=2`` the third poll sees it. Lets ``wait_code`` run with + ``interval=0``.""" + if tzid not in self._state.operations and tzid not in self._state.rents: + raise ValueError(f"MockOnlineSim: no operation or rent {tzid}") + self._state.schedule(tzid, text, polls, service) + + def fail_next(self, code: str, *, endpoint: Optional[str] = None) -> None: + """The next request (to ``endpoint`` only, e.g. ``getNum.php``, when given) answers ``{"response": code}``.""" + self._state.failures.append(MockFailure(endpoint, code=code)) + + def fail_next_transport(self, *, status: int = 502, endpoint: Optional[str] = None) -> None: + """The next request (to ``endpoint`` only, when given) fails at transport level: a non-JSON body with HTTP + ``status``.""" + self._state.failures.append(MockFailure(endpoint, status=status)) + + def set_balance(self, usd: float) -> None: + """Set the total balance, USD.""" + self._state.balance = to_mills(usd) + + def balance(self) -> float: + """Total balance, USD, including the part frozen by open operations (as ``getBalance`` reports it).""" + return from_mills(self._state.balance) + + def operations(self) -> List[MockOperation]: + """Number operations, oldest first (copies).""" + return copy.deepcopy(list(self._state.operations.values())) + + def rents(self) -> List[MockRent]: + """Open rents, oldest first (copies).""" + return copy.deepcopy(list(self._state.rents.values())) + + @property + def requests(self) -> List[MockRequest]: + """Every request received, in order (a copy of the log).""" + return list(self._state.requests) + + def reset(self) -> None: + """Back to the constructor's state: balance, no operations, rents, logs, schedules or failures.""" + self._state.reset() + + +def _authorization(headers: Mapping[str, str]) -> Optional[str]: + return next((v for k, v in headers.items() if k.lower() == "authorization"), None) + + +def _json(body: Any, status: int = 200) -> HttpResponse: + return HttpResponse(status, json.dumps(body).encode()) + + +def _text(status: int, body: str) -> HttpResponse: + return HttpResponse(status, f"{status} {body}".encode()) diff --git a/onlinesimru/mock/_handlers.py b/onlinesimru/mock/_handlers.py new file mode 100644 index 0000000..11e2fa4 --- /dev/null +++ b/onlinesimru/mock/_handlers.py @@ -0,0 +1,509 @@ +"""The mock's routes: endpoint path (relative to ``/api/``) -> handler. A handler gets the state and the request +and returns the JSON body the real backend would send (HTTP 200). Shapes follow the OpenAPI spec and the live +captures: ``response`` as int or string per endpoint, decimal-string money, ``[]`` for empty maps. +Auth, queued failures, 456 and 404 are the transport's job (``MockOnlineSim``), not the handlers'. +""" + +from __future__ import annotations + +import urllib.parse +from typing import Any, Callable, Dict, List, Mapping, Sequence, Tuple + +from ._state import ( + MOCK_USER_ID, + OPERATION_TIME, + MockOperation, + MockRent, + MockRequest, + MockSms, + MockState, + extract_code, + from_mills, + short_number, + stamp, + to_mills, +) + +Handler = Callable[[MockState, MockRequest], Any] + +PUBLIC_PATHS = frozenset({"getNumbersStats.php", "rent/tariffsRent.php", "getFreeList"}) +"""Endpoints that answer without a key.""" + +_COUNTRY_NAMES: Mapping[int, Tuple[str, str]] = {7: ("russia", "Russia"), 44: ("united_kingdom", "United Kingdom")} + + +def _error(code: str) -> Dict[str, Any]: + return {"response": code} + + +def _flag(req: MockRequest, key: str) -> bool: + return req.query.get(key, "0") != "0" + + +def _int(req: MockRequest, key: str, fallback: int) -> int: + try: + return int(req.query[key]) + except (KeyError, ValueError): + return fallback + + +def _decimal(mills: int, digits: int = 3) -> str: + """USD with ``digits`` decimals, as the backend sends ``balance``.""" + return f"{from_mills(mills):.{digits}f}" + + +def _country_name(code: int) -> Tuple[str, str]: + return _COUNTRY_NAMES.get(code, (f"country_{code}", f"Country {code}")) + + +def _paginate(items: Sequence[Any], page: int, per_page: int, path: str) -> Dict[str, Any]: + """Laravel paginator over ``items``.""" + total = len(items) + last_page = max(1, -(-total // per_page)) + data = list(items[(page - 1) * per_page : page * per_page]) + + def url(p: int) -> str: + return f"https://onlinesim.host/api/{path}?page={p}" + + return { + "current_page": page, + "data": data, + "first_page_url": url(1), + "from": (page - 1) * per_page + 1 if data else None, + "last_page": last_page, + "last_page_url": url(last_page), + "links": [], + "next_page_url": url(page + 1) if page < last_page else None, + "path": f"https://onlinesim.host/api/{path}", + "per_page": per_page, + "prev_page_url": url(page - 1) if page > 1 else None, + "to": (page - 1) * per_page + len(data) if data else None, + "total": total, + } + + +# ----- numbers ----- + + +def _msg_of(sms: MockSms, to_code: bool) -> str: + return (sms.code or sms.text) if to_code else sms.text + + +def _operation_view(state: MockState, op: MockOperation, req: MockRequest) -> Dict[str, Any]: + to_code = _flag(req, "message_to_code") + is_open = op.status != "TZ_OVER_OK" + view: Dict[str, Any] = { + "country": op.country, + "sum": op.sum, + "service": op.service, + "number": op.number, + "subscription_package_id": None, + "webhook_url": state.webhook_url, + "response": op.status, + "tzid": op.tzid, + "time": OPERATION_TIME if is_open else 0, + "form": "index", + } + if _flag(req, "msg_list"): + if op.messages: + view["msg"] = [{"service": s.service, "msg": _msg_of(s, to_code)} for s in op.messages] + elif op.cursor < len(op.messages): + view["msg"] = _msg_of(op.messages[op.cursor], to_code) + if "number" in req.query: + view["guard_interval_remaining_seconds"] = state.guard_interval if is_open and not op.messages else 0 + return view + + +def _get_price(state: MockState, req: MockRequest) -> Any: + prices = state.prices.get(_int(req, "country", 7)) + if prices is None: + return _error("UNDEFINED_COUNTRY") + return {"response": "1", "price": prices.get(req.query.get("service", ""))} + + +def _get_num(state: MockState, req: MockRequest) -> Any: + country = _int(req, "country", 7) + service = req.query.get("service", "") + prices = state.prices.get(country) + if prices is None: + return _error("UNDEFINED_COUNTRY") + price = prices.get(service) + if price is None: + return _error("ERROR_NO_SERVICE") + cost = to_mills(price) + if state.available < cost: + return _error("WARNING_LOW_BALANCE") + + number = f"+{country}{short_number(state.peek_id())}" + reject = [p for p in req.query.get("reject", "").split(",") if p] + if any(number[1:].startswith(prefix) for prefix in reject): + return _error("NO_NUMBER") + + tzid = state.next_id() + state.frozen += cost + state.operations[tzid] = MockOperation(tzid, service, country, number, price, "TZ_NUM_WAIT") + if "number" not in req.query: + return {"response": 1, "tzid": tzid} + return { + "response": 1, + "tzid": tzid, + "number": number, + "country": country, + "time": OPERATION_TIME, + "service": service, + } + + +def _get_state(state: MockState, req: MockRequest) -> Any: + if "tzid" in req.query: + one = state.operations.get(_int(req, "tzid", -1)) + ops = [] if one is None else [one] + else: + ops = list(state.operations.values()) + for op in ops: + state.poll(op.tzid) + if not ops: + return _error("ERROR_NO_OPERATIONS") + ops.sort(key=lambda o: o.tzid, reverse=req.query.get("orderby") == "desc") + return [_operation_view(state, op, req) for op in ops] + + +def _set_operation_revise(state: MockState, req: MockRequest) -> Any: + tzid = _int(req, "tzid", 0) + 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": + op.cursor = len(op.messages) + op.status = "TZ_NUM_WAIT" + return {"response": 1, "tzid": tzid} + + +def _set_operation_ok(state: MockState, req: MockRequest) -> Any: + tzid = _int(req, "tzid", 0) + op = state.operations.get(tzid) + if op is None or op.status == "TZ_OVER_OK": + return _error("ERROR_WRONG_TZID") + received = bool(op.messages) + if _flag(req, "ban") and received: + return {"response": "0"} + if not received and state.guard_interval > 0: + return _error("NO_COMPLETE_TZID") + cost = to_mills(op.sum) + state.frozen -= cost + if received: + state.balance -= cost + op.status = "TZ_OVER_OK" + return {"response": 1, "tzid": tzid} + + +def _country_stat(state: MockState, code: int) -> Dict[str, Any]: + name, locale = _country_name(code) + services = { + f"service_{slug}": { + "count": 100, + "popular": False, + "code": code, + "price": price, + "id": i + 1, + "service": slug, + "slug": slug, + } + for i, (slug, price) in enumerate(state.prices.get(code, {}).items()) + } + return { + "name": name, + "position": code, + "code": code, + "other": False, + "new": False, + "enabled": True, + "services": services or [], + "locale_name": locale, + } + + +def _get_numbers_stats(state: MockState, req: MockRequest) -> Any: + if req.query.get("country") == "all": + return {str(code): _country_stat(state, code) for code in sorted(state.prices)} or [] + code = _int(req, "country", 7) + return _country_stat(state, code) if code in state.prices else _error("NO_COUNTRY") + + +# ----- rent ----- + + +def _rent_item(state: MockState, rent: MockRent, req: MockRequest) -> Dict[str, Any]: + 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 + start = rent.tzid + item: Dict[str, Any] = { + "status": 1, + "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} + for m in reversed(rent.messages) + ], + "webhook_url": state.webhook_url, + "sum": _decimal(to_mills(rent.sum), 2), + "country": rent.country, + "start_time": stamp(start), + "stop_time": stamp(start + rent.days * 86_400), + "checked_time": stamp(start), + "number": rent.number, + "days_autoextend": 0, + "rent": 1, + "tzid": rent.tzid, + "time": rent.days * 24 * 60, + "days": rent.days, + "hours": rent.days * 24, + "extend": days if extendable else [], + "checked": True, + "reload": 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 + return item + + +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") + days = _int(req, "days", 1) + price = tariff["days"].get(days) + if price is None: + return _error("UNDEFINED_DAYS") + if state.available < to_mills(price): + return _error("WARNING_LOW_BALANCE") + tzid = state.next_id() + state.balance -= 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") + state.rents[tzid] = rent + return {"response": 1, "item": _rent_item(state, rent, req)} + + +def _get_rent_state(state: MockState, req: MockRequest) -> Any: + if "tzid" in req.query: + one = state.rents.get(_int(req, "tzid", -1)) + rents = [] if one is None else [one] + else: + 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]} + + +def _extend_rent_state(state: MockState, req: MockRequest) -> Any: + 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: + return _error("TRY_AGAIN_LATER") + days = _int(req, "days", 1) + price = tariff["days"].get(days) + if price is None: + return _error("UNDEFINED_DAYS") + if state.available < to_mills(price): + return _error("WARNING_LOW_BALANCE") + state.balance -= to_mills(price) + rent.days += days + rent.sum = from_mills(to_mills(rent.sum) + to_mills(price)) + return {"response": 1, "item": _rent_item(state, rent, req)} + + +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") + state.scheduled.pop(tzid, None) + return {"response": "1"} + + +def _tariffs_rent(state: MockState, req: MockRequest) -> Any: + def tariff(code: int) -> Any: + t = state.rent_tariffs.get(code) + if t is None: + return [] + days = dict(sorted(t["days"].items())) + count = {d: 100 for d in days} + return { + "code": code, + "enabled": True, + "name": _country_name(code)[0], + "new": False, + "position": code, + "count": count, + "days": days, + "extend": t["extend"], + "confirm": False, + "ext_counts": count, + } + + if "country" in req.query: + return tariff(_int(req, "country", 0)) + return {str(code): tariff(code) for code in sorted(state.rent_tariffs)} or [] + + +# ----- user ----- + + +def _get_balance(state: MockState, req: MockRequest) -> Any: + res: Dict[str, Any] = {"response": "1", "balance": _decimal(state.balance), "zbalance": from_mills(state.frozen)} + if "income" in req.query: + res.update(income=0, income_usd="0.000") + return res + + +def _get_profile(state: MockState, req: MockRequest) -> Any: + return { + "response": "1", + "profile": { + "id": MOCK_USER_ID, + "hash_id": "mock", + "name": "mock@example.com", + "username": "mock@example.com", + "email": "mock@example.com", + "email_verified_at": stamp(), + "active": "true", + "apikey": state.api_key, + "api_access": True, + "is_api": True, + "number": None, + "country": None, + "locale": "en", + "currency": "USD", + "number_region": None, + "number_country": None, + "number_reject": [], + "ugroup": 1, + "verify": 0, + "block": 0, + "resetCount": None, + "created_at": stamp(), + "notification_at": None, + "first_login": False, + "sub": 0, + "disable": False, + "webhook_url": state.webhook_url, + "is_project_subscription": False, + }, + } + + +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 + + +def _profile(state: MockState, req: MockRequest) -> Any: + body = req.body + profile = body.get("profile") if isinstance(body, dict) else None + if req.method != "POST" or not isinstance(profile, dict): + 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)): + 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}} + + +def _webhook_logs(state: MockState, req: MockRequest) -> Any: + return {"response": "1", "data": _paginate(state.webhook_logs[::-1], _int(req, "page", 1), 10, "webhook-logs")} + + +def _get_payment_history(state: MockState, req: MockRequest) -> Any: + return { + "response": "1", + "orders": _paginate([], _int(req, "page", 1), 10, "getPaymentHistory.php"), + "paylist": [], + "domains": [], + "currency": {"USD": 1}, + } + + +# ----- free ----- + +# country -> (name, text, short number -> [(sender, text)]) +_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", + { + "7459608320": [ + ("Amazon", "Amazon: Use 195895 to reset your password."), + ("Microsoft", "Microsoft access code: 2991"), + ] + }, + ), +} + + +def _get_free_list(state: MockState, req: MockRequest) -> Any: + codes = list(_FREE) + wanted = _int(req, "country", 44) + country = wanted if wanted in _FREE else codes[0] + name, _text, by_number = _FREE[country] + numbers = { + n: { + "country": country, + "country_original": name, + "data_humans": "1 day ago", + "full_number": f"{country}{n}", + "is_archive": False, + } + for n in by_number + } + asked = req.query.get("number") + number = asked if asked is not None and asked in by_number else next(iter(by_number)) + messages = [ + { + "id": i + 1, + "text": text, + "in_number": sender, + "my_number": number, + "created_at": stamp(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") + 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}, + } + + +ROUTES: Mapping[str, Handler] = { + "getPrice.php": _get_price, + "getNum.php": _get_num, + "getState.php": _get_state, + "setOperationRevise.php": _set_operation_revise, + "setOperationOk.php": _set_operation_ok, + "getNumbersStats.php": _get_numbers_stats, + "rent/getRentNum.php": _get_rent_num, + "rent/getRentState.php": _get_rent_state, + "rent/extendRentState.php": _extend_rent_state, + "rent/closeRentNum.php": _close_rent_num, + "rent/tariffsRent.php": _tariffs_rent, + "getBalance.php": _get_balance, + "getProfile.php": _get_profile, + "profile.php": _profile, + "webhook-logs": _webhook_logs, + "getPaymentHistory.php": _get_payment_history, + "getFreeList": _get_free_list, +} diff --git a/onlinesimru/mock/_state.py b/onlinesimru/mock/_state.py new file mode 100644 index 0000000..ad42659 --- /dev/null +++ b/onlinesimru/mock/_state.py @@ -0,0 +1,291 @@ +"""State of the mock backend. :class:`MockState` is the single owner of everything the fake API remembers: +balance, operations, rents, the profile's webhook URL and its delivery log, scheduled SMS, the failure queue and +the request log. Handlers (``_handlers.py``) read and change it only through this object. + +Deterministic: ids and numbers come from a counter, timestamps from a fixed epoch plus that counter. +Money is kept in integer thousandths of a USD ("mills") so sums never drift. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field +from datetime import datetime, timedelta, timezone +from typing import Any, Dict, List, Literal, Mapping, Optional, TypedDict + +MockPrices = Dict[int, Dict[str, float]] +"""Prices of numbers: country code -> service slug -> USD.""" + + +class MockRentTariff(TypedDict): + """Rent tariff of one country: rent days -> USD, and whether rents can be extended (``1``) or not (``0``).""" + + days: Dict[int, float] + extend: int + + +@dataclass +class MockSms: + """One SMS received by an operation or a rent.""" + + service: str + text: str + code: Optional[str] + """Code extracted from ``text`` (first run of 4-8 digits), ``None`` when there is none.""" + + +@dataclass +class MockRentSms(MockSms): + """One SMS of a rent.""" + + id: int + created_at: str + + +MockOperationStatus = Literal["TZ_NUM_WAIT", "TZ_NUM_ANSWER", "TZ_OVER_OK"] + + +@dataclass +class MockOperation: + """A number operation as the mock stores it.""" + + tzid: int + service: str + country: int + number: str + """Full number with ``+``.""" + sum: float + """Price, USD. Frozen while open; spent on close after an SMS, refunded on close without one.""" + status: MockOperationStatus + messages: List[MockSms] = field(default_factory=list) + cursor: int = 0 + """Index of the SMS shown in ``msg``; ``next`` (setOperationRevise) moves it past the last one.""" + + +@dataclass +class MockRent: + """A rent as the mock stores it. Closed rents are removed.""" + + tzid: int + country: int + number: str + """Number without the country code, as the backend sends it for rents.""" + days: int + sum: float + """Total paid, USD.""" + extension: bool + messages: List[MockRentSms] = field(default_factory=list) + """Oldest first.""" + + +@dataclass(frozen=True) +class MockRequest: + """One request the mock received.""" + + method: str + path: str + """Path relative to ``/api/``, e.g. ``getNum.php``, ``rent/getRentNum.php``, ``getFreeList``.""" + query: Dict[str, str] + body: Any = None + """Parsed JSON body of a POST, ``None`` for GET.""" + + +@dataclass(frozen=True) +class MockFailure: + """A queued failure: the next matching request answers ``{"response": code}``, or (``code`` is ``None``) + a non-JSON HTTP ``status``.""" + + endpoint: Optional[str] + code: Optional[str] = None + status: int = 502 + + +@dataclass +class _ScheduledSms: + text: str + service: Optional[str] + polls: int + """getState/getRentState polls of this tzid still to pass before the SMS arrives.""" + + +DEFAULT_PRICES: Mapping[int, Mapping[str, float]] = { + 7: {"vkcom": 0.5, "telegram": 1.2, "google": 0.3}, + 44: {"google": 0.2, "vkcom": 0.36}, +} + +DEFAULT_RENT_TARIFFS: Mapping[int, MockRentTariff] = { + 7: {"days": {1: 1.0, 3: 2.5, 7: 5.0}, "extend": 1}, +} + +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.""" + +_EPOCH = datetime(2026, 1, 1, tzinfo=timezone.utc) + + +def stamp(seconds: int = 0) -> str: + """``YYYY-MM-DD HH:MM:SS`` at ``seconds`` after the fixed mock epoch.""" + return (_EPOCH + timedelta(seconds=seconds)).strftime("%Y-%m-%d %H:%M:%S") + + +_DIGIT_GAP = re.compile(r"([0-9])[\s-]+(?=[0-9])") +_CODE = re.compile(r"(? Optional[str]: + """The code rule shared by every SDK mock: dashes/spaces between digits are removed, then the first run of + 4-8 digits (not part of a longer run) is the code; ``None`` when there is none.""" + match = _CODE.search(_DIGIT_GAP.sub(r"\1", text)) + return match.group(0) if match else None + + +def to_mills(usd: float) -> int: + return round(usd * 1000) + + +def from_mills(mills: int) -> float: + return mills / 1000 + + +def short_number(id_: int) -> str: + """Short (country-less) number for an id: deterministic, 9 digits.""" + return str(900_000_000 + id_) + + +class MockState: + """Everything the fake backend remembers. One instance per :class:`~onlinesimru.MockOnlineSim`.""" + + def __init__( + self, + *, + api_key: str, + balance: float, + prices: Optional[Mapping[int, Mapping[str, float]]], + rent_tariffs: Optional[Mapping[int, MockRentTariff]], + guard_interval: int, + ) -> None: + self.api_key = api_key + self.guard_interval = guard_interval + self.prices: MockPrices = {c: dict(s) for c, s in (DEFAULT_PRICES if prices is None else prices).items()} + self.rent_tariffs: Dict[int, MockRentTariff] = { + c: {"days": dict(t["days"]), "extend": t["extend"]} + for c, t in (DEFAULT_RENT_TARIFFS if rent_tariffs is None else rent_tariffs).items() + } + self._start_balance = to_mills(balance) + + self.balance = 0 + """Total balance incl. the frozen part, mills.""" + self.frozen = 0 + """Frozen by open operations, mills.""" + self.operations: Dict[int, MockOperation] = {} + self.rents: Dict[int, MockRent] = {} + self.webhook_url: Optional[str] = None + self.webhook_logs: List[Dict[str, Any]] = [] + self.requests: List[MockRequest] = [] + self.failures: List[MockFailure] = [] + self.scheduled: Dict[int, List[_ScheduledSms]] = {} + self.seq = 0 + """Source of tzids, numbers, message ids and timestamps.""" + self.reset() + + def reset(self) -> None: + self.balance = self._start_balance + self.frozen = 0 + self.operations = {} + self.rents = {} + self.webhook_url = None + self.webhook_logs = [] + self.requests = [] + self.failures = [] + self.scheduled = {} + self.seq = 0 + + @property + def available(self) -> int: + """Available balance (total minus frozen), mills.""" + return self.balance - self.frozen + + def peek_id(self) -> int: + """The id the next operation/rent will get.""" + return self.seq + 1 + + def next_id(self) -> int: + self.seq += 1 + return self.seq + + def take_failure(self, path: str) -> Optional[MockFailure]: + """Remove and return the first queued failure that applies to ``path``.""" + for i, failure in enumerate(self.failures): + if failure.endpoint is None or failure.endpoint == path: + return self.failures.pop(i) + return None + + def deliver(self, tzid: int, text: str, service: Optional[str] = None) -> bool: + """An SMS arrives at operation or rent ``tzid`` now. Returns ``False`` when there is no open one.""" + 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) + op.messages.append(sms) + op.status = "TZ_NUM_ANSWER" + self._webhook("receiving_sms", tzid, op.country, op.number, sms) + 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.messages.append(rent_sms) + self._webhook("rent_sms", tzid, rent.country, rent.number, rent_sms) + return True + return False + + def schedule(self, tzid: int, text: str, polls: int, service: Optional[str] = None) -> None: + self.scheduled.setdefault(tzid, []).append(_ScheduledSms(text, service, polls)) + + def poll(self, tzid: int) -> None: + """One state poll of ``tzid``: delivers the scheduled SMS whose polls ran out, counts down the rest.""" + pending = self.scheduled.get(tzid) + if not pending: + return + due = [s for s in pending if s.polls <= 0] + rest = [s for s in pending if s.polls > 0] + for s in rest: + s.polls -= 1 + if rest: + self.scheduled[tzid] = rest + else: + del self.scheduled[tzid] + # Dropped silently when the operation was closed meanwhile: a real SMS would not arrive either. + 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: + """No HTTP call: the mock only records what the backend would have sent.""" + if not self.webhook_url: + return + time = stamp(self.seq) + self.webhook_logs.append( + { + "id": len(self.webhook_logs) + 1, + "user_id": MOCK_USER_ID, + "webhook_url": self.webhook_url, + "type": type_, + "params": { + "webhook_type": type_, + "operation_id": tzid, + "user_id": MOCK_USER_ID, + "country_code": country, + "number": number, + "sender": sms.service, + "message": sms.text, + "code": sms.code, + "time_start": time, + "time_left": OPERATION_TIME, + }, + "status": "success", + "error": None, + "created_at": time, + "updated_at": time, + } + ) diff --git a/pyproject.toml b/pyproject.toml index bae7aae..4fb30df 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "onlinesimru" -version = "3.0.0" +version = "3.1.0" 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/smoke_artifact.py b/tests/smoke_artifact.py new file mode 100644 index 0000000..4f35662 --- /dev/null +++ b/tests/smoke_artifact.py @@ -0,0 +1,72 @@ +"""Smoke test of the PUBLISHED artifact: check the built wheel holds only the package and its metadata, install it +into a fresh venv of the Python running this script (no index, no repo on the path) and run the README "Testing" +example (offline, against MockOnlineSim) taken from the wheel's own metadata. + +Build first (``python -m build``), then: ``python tests/smoke_artifact.py [dist-dir]``. CI runs it on the floor +Python and the latest one. +""" + +from __future__ import annotations + +import email +import os +import re +import subprocess +import sys +import tempfile +import zipfile +from pathlib import Path + + +def run(*args: str, cwd: Path) -> str: + return subprocess.run(args, cwd=cwd, check=True, text=True, stdout=subprocess.PIPE).stdout # noqa: S603 + + +def main(dist: Path) -> None: + wheels = sorted(dist.glob("onlinesimru-*-py3-none-any.whl")) + assert len(wheels) == 1, f"expected one wheel in {dist}, found {[w.name for w in wheels]}" + wheel = wheels[0].resolve() + version = wheel.name.split("-")[1] + info = f"onlinesimru-{version}.dist-info/" + + with zipfile.ZipFile(wheel) as z: + names = z.namelist() + readme = email.message_from_bytes(z.read(info + "METADATA")).get_payload() + stray = [n for n in names if not n.startswith(("onlinesimru/", info))] + assert not stray, f"wheel holds only the package and its metadata, got {stray}" + for required in ( + "onlinesimru/__init__.py", + "onlinesimru/py.typed", + "onlinesimru/mock/__init__.py", + info + "licenses/LICENSE", + ): + assert required in names, f"wheel contains {required}" + print(f"{wheel.name}: {len(names)} files") + + assert isinstance(readme, str) + match = re.search(r"^## Testing\n.*?```python\n(.*?)```", readme, re.S | re.M) + assert match, 'README has a "## Testing" section with a python example' + + with tempfile.TemporaryDirectory(prefix="onlinesim-smoke-") as tmp: + root = Path(tmp) + run(sys.executable, "-m", "venv", str(root / "venv"), cwd=root) + python = str(root / "venv" / ("Scripts" if os.name == "nt" else "bin") / "python") + run(python, "-m", "pip", "install", "--quiet", "--no-index", "--no-deps", str(wheel), cwd=root) + + app = root / "app" + app.mkdir() + (app / "readme_testing.py").write_text(match.group(1), "utf-8") + run(python, "-I", "readme_testing.py", cwd=app) + print('README "Testing" example: ok') + + check = ( + "import onlinesimru, pathlib, sys; " + f"assert onlinesimru.__version__ == {version!r}, onlinesimru.__version__; " + "assert (pathlib.Path(onlinesimru.__file__).parent / 'py.typed').is_file(); " + "print(sys.version.split()[0])" + ) + print(f"import, __version__ {version}, py.typed: ok (python {run(python, '-I', '-c', check, cwd=app).strip()})") + + +if __name__ == "__main__": + main(Path(sys.argv[1] if len(sys.argv) > 1 else Path(__file__).resolve().parent.parent / "dist")) diff --git a/tests/test_mock.py b/tests/test_mock.py new file mode 100644 index 0000000..6e5c768 --- /dev/null +++ b/tests/test_mock.py @@ -0,0 +1,404 @@ +"""MockOnlineSim through the real client: every endpoint, every control helper.""" + +from __future__ import annotations + +from typing import Callable + +import pytest + +from onlinesimru import ( + ApiError, + HttpRequest, + MockOnlineSim, + MockRequest, + NoNumberError, + OnlineSim, + TransportError, +) + + +def no_sleep(_seconds: float) -> None: + pass + + +# ----- auth and transport ----- + + +def test_wrong_or_missing_key_is_http_456_mapped_to_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" + + +def test_tariffs_and_free_numbers_need_no_key() -> None: + client = MockOnlineSim().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 + + +def test_transport_of_a_hand_built_client_with_any_base_url() -> None: + mock = MockOnlineSim(api_key="k", balance=5) + client = OnlineSim("k", transport=mock.transport) + assert client.user.balance() == {"balance": 5, "zbalance": 0, "income": 0} + assert mock.requests == [MockRequest("GET", "getBalance.php", {"income": "1", "lang": "en"}, None)] + + +def test_unknown_endpoint_is_a_non_json_404() -> None: + res = MockOnlineSim().transport(HttpRequest("GET", "https://x.test/api/nope.php", {}, None, 1)) + assert res.status == 404 + with pytest.raises(TransportError) as error: + MockOnlineSim().client()._request("nope.php") + assert error.value.status == 404 + + +# ----- numbers ----- + + +def test_price() -> None: + client = MockOnlineSim().client() + assert client.numbers.price("telegram", 7) == 1.2 + assert client.numbers.price("nope", 7) is None + assert code_of(lambda: client.numbers.price("google", 999)) == "UNDEFINED_COUNTRY" + + +def test_get_freezes_the_price_and_numbers_are_deterministic() -> None: + mock = MockOnlineSim() + client = mock.client() + assert client.numbers.get("google", 44) == 1 + assert client.numbers.get_with_number("vkcom") == { + "tzid": 2, + "number": "+7900000002", + "country": 7, + "time": 1200, + "service": "vkcom", + } + assert [r.query.get("number") for r in mock.requests] == [None, "1"] + assert client.user.balance() == {"balance": 100, "zbalance": 0.7, "income": 0} + assert [(o.tzid, o.number, o.status) for o in mock.operations()] == [ + (1, "+44900000001", "TZ_NUM_WAIT"), + (2, "+7900000002", "TZ_NUM_WAIT"), + ] + + +def code_of(call: Callable[[], object]) -> str: + """The ApiError code raised by ``call()``.""" + with pytest.raises(ApiError) as error: + call() + return error.value.code + + +def test_get_errors_unknown_country_service_low_balance_reject() -> None: + mock = MockOnlineSim(balance=0.25) + client = mock.client() + assert code_of(lambda: client.numbers.get("google", 999)) == "UNDEFINED_COUNTRY" + assert code_of(lambda: client.numbers.get("nope", 7)) == "ERROR_NO_SERVICE" + assert code_of(lambda: client.numbers.get("google", 7)) == "WARNING_LOW_BALANCE" + with pytest.raises(NoNumberError): + client.numbers.get("google", 44, reject=["4490", "7"]) + assert mock.requests[-1].query["reject"] == "4490,7" + # a non-matching reject passes; the rejected attempt did not consume a number + assert client.numbers.get_with_number("google", 44, reject=["4480"])["number"] == "+44900000001" + # 0.25 - 0.2 frozen = 0.05 available + assert code_of(lambda: client.numbers.get("google", 44)) == "WARNING_LOW_BALANCE" + + +def test_state_list_one_and_lifecycle() -> None: + mock = MockOnlineSim() + client = mock.client() + assert client.numbers.state() == [] + a = client.numbers.get("google", 44) + b = client.numbers.get("vkcom", 7) + one = client.numbers.state_one(a) + assert one["tzid"] == a + assert one["response"] == "TZ_NUM_WAIT" + assert one["number"] == "+44900000001" + assert one["sum"] == 0.2 + assert one["guard_interval_remaining_seconds"] == 0 + assert "msg" not in one + + mock.add_sms(a, "Your Google code is G-123 456. Do not share it.") + one = client.numbers.state_one(a) + assert (one["response"], one.get("msg")) == ("TZ_NUM_ANSWER", "123456") + full = client.numbers.state_one(a, message_to_code=False) + assert full.get("msg") == "Your Google code is G-123 456. Do not share it." + assert [o["tzid"] for o in client.numbers.state(order_by="desc")] == [b, a] + + client.numbers.close(a) + closed = client.numbers.state_one(a) + assert (closed["response"], closed.get("time")) == ("TZ_OVER_OK", 0) + assert code_of(lambda: client.numbers.state_one(999)) == "ERROR_NO_OPERATIONS" + + +def test_full_text_without_code_next_and_msg_list() -> None: + mock = MockOnlineSim() + client = mock.client() + tzid = client.numbers.get("telegram") + mock.add_sms(tzid, "Welcome!", service="telegram") + assert client.numbers.state_one(tzid).get("msg") == "Welcome!" + client.numbers.next(tzid) + waiting = client.numbers.state_one(tzid) + assert waiting["response"] == "TZ_NUM_WAIT" + assert "msg" not in waiting + mock.add_sms(tzid, "code 98765") + assert client.numbers.state_one(tzid).get("msg") == "98765" + assert client.numbers.state_one(tzid, msg_list=True).get("msg") == [ + {"service": "telegram", "msg": "Welcome!"}, + {"service": "telegram", "msg": "98765"}, + ] + assert client.numbers.next(424242) is True # always succeeds, like the backend + + +def test_close_spends_or_refunds_and_ban_after_sms_answers_0() -> None: + mock = MockOnlineSim(balance=10) + client = mock.client() + paid = client.numbers.get("telegram") + empty = client.numbers.get("telegram") + mock.add_sms(paid, "1111") + assert code_of(lambda: client.numbers.ban(paid)) == "0" + client.numbers.close(paid) + client.numbers.close(empty) + assert client.user.balance() == {"balance": 8.8, "zbalance": 0, "income": 0} + assert mock.balance() == 8.8 + assert code_of(lambda: client.numbers.close(paid)) == "ERROR_WRONG_TZID" + assert code_of(lambda: client.numbers.close(999)) == "ERROR_WRONG_TZID" + banned = client.numbers.get("google") + assert client.numbers.ban(banned) is True + assert next(o.status for o in mock.operations() if o.tzid == banned) == "TZ_OVER_OK" + + +def test_guard_interval_blocks_close_without_sms() -> None: + mock = MockOnlineSim(guard_interval=120) + client = mock.client() + tzid = client.numbers.get("google") + assert client.numbers.state_one(tzid).get("guard_interval_remaining_seconds") == 120 + assert code_of(lambda: client.numbers.close(tzid)) == "NO_COMPLETE_TZID" + mock.add_sms(tzid, "5555") + assert client.numbers.state_one(tzid).get("guard_interval_remaining_seconds") == 0 + assert client.numbers.close(tzid) is True + + +def test_wait_code_with_add_sms_after_and_zero_interval() -> None: + mock = MockOnlineSim() + client = mock.client() + tzid = client.numbers.get("google", 44) + mock.add_sms_after(tzid, "Your code: 4321", 2) + assert client.numbers.wait_code(tzid, interval=0, sleep=no_sleep) == "4321" + assert [r.path for r in mock.requests] == [ + "getNum.php", + "getState.php", + "getState.php", + "getState.php", + "setOperationOk.php", + ] + assert mock.operations()[0].status == "TZ_OVER_OK" + + +def test_wait_code_keep_open_and_since_polls_listing_all_count_too() -> None: + mock = MockOnlineSim() + client = mock.client() + tzid = client.numbers.get("google", 44) + mock.add_sms_after(tzid, "1111", 0) + first = client.numbers.wait_code(tzid, interval=0, sleep=no_sleep, keep_open=True) + mock.add_sms_after(tzid, "2222", 1) + client.numbers.state() # one poll of every operation + assert client.numbers.wait_code(tzid, interval=0, sleep=no_sleep, since=first) == "2222" + + +def test_tariffs_from_prices() -> None: + client = MockOnlineSim().client() + tariffs = client.numbers.tariffs() + assert list(tariffs) == ["7", "44"] + assert tariffs["44"]["services"]["service_vkcom"] == { + "count": 100, + "popular": False, + "code": 44, + "price": 0.36, + "id": 2, + "service": "vkcom", + "slug": "vkcom", + } + assert code_of(lambda: client.numbers.tariffs_one(1)) == "NO_COUNTRY" + empty = MockOnlineSim(prices={1: {}}).client() + assert empty.numbers.tariffs_one(1)["services"] == {} # `[]` on the wire + + +# ----- rent ----- + + +def test_rent_get_state_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["extend"] == {"1": 1, "3": 2.5, "7": 5} + assert mock.balance() == 7.5 + + 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 [(m["service"], m["code"]) for m in state["messages"]] == [("other", ""), ("bank", "777888")] # newest first + + extended = client.rent.extend(rent["tzid"], 1) + assert (extended["days"], extended["sum"]) == (4, 3.5) + assert mock.balance() == 6.5 + + fixed = client.rent.get(7, 1, False) + assert (fixed["extension"], fixed["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"]) + 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" + + +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(7, 2)) == "UNDEFINED_DAYS" + assert code_of(lambda: client.rent.get(7, 3)) == "WARNING_LOW_BALANCE" + + +def test_rent_add_sms_after_and_tariffs() -> None: + mock = MockOnlineSim() + client = mock.client() + 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") + count = {"1": 100, "3": 100, "7": 100} + assert client.rent.tariffs() == { + "7": { + "code": 7, + "enabled": True, + "name": "russia", + "new": False, + "position": 7, + "count": count, + "days": {"1": 1, "3": 2.5, "7": 5}, + "extend": 1, + "confirm": False, + "ext_counts": count, + } + } + assert code_of(lambda: client.rent.tariffs_one(44)) == "NO_COUNTRY" + + +# ----- user and free ----- + + +def test_profile_webhook_set_validate_clear_and_logs() -> None: + mock = MockOnlineSim(api_key="secret") + client = mock.client() + 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") + assert (error.value.code, error.value.message) == ("VALIDATION_ERROR", "The webhook url must be a valid URL.") + client.user.set_webhook_url("https://example.com/hook") + last = mock.requests[-1] + assert (last.method, last.path) == ("POST", "profile.php") + assert last.body == {"profile": {"webhook_url": "https://example.com/hook"}} + assert client.user.profile().get("webhook_url") == "https://example.com/hook" + + tzid = client.numbers.get("google", 44) + mock.add_sms(tzid, "code 1234") + rent = client.rent.get() + mock.add_sms(rent["tzid"], "code 5678") + logs = client.user.webhook_logs() + assert (logs["total"], logs["current_page"], logs["per_page"]) == (2, 1, 10) + assert [(log["type"], log["params"]["operation_id"], log["params"]["code"]) for log in logs["data"]] == [ + ("rent_sms", rent["tzid"], "5678"), + ("receiving_sms", tzid, "1234"), + ] + + 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: + 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["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 list(uk["numbers"]) == ["7459608320"] + assert (uk["messages"]["number"], uk["messages"]["country"], uk["messages"]["total"]) == ("7459608320", 44, 2) + assert uk["messages"]["data"][0]["code"] == "195895" + ru = client.free.list(country=7) + assert (ru["messages"]["data"][0]["code"], ru["messages"]["data"][0]["my_number"]) == ("51423", "9001234567") + + +# ----- control API ----- + + +def test_fail_next_once_optionally_for_one_endpoint() -> None: + mock = MockOnlineSim() + client = mock.client() + mock.fail_next("NO_NUMBER", endpoint="getNum.php") + assert client.user.balance()["balance"] == 100 # other endpoint: untouched + with pytest.raises(NoNumberError): + client.numbers.get("google") + assert client.numbers.get("google") == 1 + mock.fail_next("TRY_AGAIN_LATER") + assert code_of(client.user.profile) == "TRY_AGAIN_LATER" + + +def test_fail_next_transport_once_and_wait_code_retries_it() -> None: + mock = MockOnlineSim() + client = mock.client() + mock.fail_next_transport() + with pytest.raises(TransportError) as error: + client.user.balance() + assert error.value.status == 502 + + tzid = client.numbers.get("google") + mock.add_sms(tzid, "3030") + mock.fail_next_transport(status=503, endpoint="getState.php") + assert client.numbers.wait_code(tzid, interval=0, sleep=no_sleep) == "3030" + + +def test_unknown_ids_set_balance_requests_log_and_reset() -> None: + mock = MockOnlineSim(balance=1) + client = mock.client(lang="ru") + with pytest.raises(ValueError, match="no open operation or rent 5"): + mock.add_sms(5, "x") + with pytest.raises(ValueError, match="no operation or rent 5"): + mock.add_sms_after(5, "x", 1) + mock.set_balance(50) + assert mock.balance() == 50 + tzid = client.numbers.get("telegram") + client.numbers.close(tzid) + with pytest.raises(ValueError): + mock.add_sms(tzid, "late") # closed + assert mock.requests[0] == MockRequest("GET", "getNum.php", {"service": "telegram", "country": "7", "lang": "ru"}) + + mock.fail_next("NO_NUMBER") + mock.reset() + assert mock.balance() == 1 + assert mock.operations() == [] + assert mock.rents() == [] + assert mock.requests == [] + assert client.numbers.get("google", 44) == 1 # ids restart, failure queue cleared + + +def test_operations_returns_copies() -> None: + mock = MockOnlineSim() + mock.client().numbers.get("google") + mock.operations()[0].status = "TZ_OVER_OK" + assert mock.operations()[0].status == "TZ_NUM_WAIT"