Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion .github/workflows/docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
39 changes: 0 additions & 39 deletions .github/workflows/publish.yml

This file was deleted.

65 changes: 65 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -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"
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/).
Expand Down
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
6 changes: 5 additions & 1 deletion docs/content/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
137 changes: 137 additions & 0 deletions docs/content/testing.md
Original file line number Diff line number Diff line change
@@ -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 `+<country>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.
22 changes: 22 additions & 0 deletions onlinesimru/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -48,6 +60,7 @@
__all__ = [
"DEFAULT_BASE_URL",
"ERROR_MESSAGES",
"MOCK_BASE_URL",
"ApiError",
"Balance",
"CountryStat",
Expand All @@ -59,6 +72,15 @@
"FreeNumber",
"HttpRequest",
"HttpResponse",
"MockOnlineSim",
"MockOperation",
"MockOperationStatus",
"MockPrices",
"MockRent",
"MockRentSms",
"MockRentTariff",
"MockRequest",
"MockSms",
"NoNumberError",
"NumberOrder",
"NumbersApi",
Expand Down
Loading
Loading