feat: add recommendation command and expand test coverage

This commit is contained in:
luofengyuan committed 2026-05-18 19:27:41 +08:00
1 parent 702280a416
commit f9267352cc
9 files changed
+684 -4

No files matched your search

+15
View File
@@ -72,3 +72,18 @@ Read the provider reference that matches the requested service before answering
- [5SIM](references/5sim.md)
- [GrizzlySMS](references/grizzlysms.md)
- [Local auth example](references/auth.example.md)
## Recommend (price-first shortlist)
The unified CLI now supports a `recommend` command for price-driven shortlist generation:
- For `smsvn`: uses `getServicesAndCostWithStatistics` for a specific `--country`.
- For `5sim`: uses `guest_products/{country}/{operator}`.
- Supports filters: `--service`, `--max-price`, `--min-qty`, `--top-n`.
Examples:
```bash
python3 scripts/sms_activation.py --provider smsvn recommend --country 12 --max-price 0.2 --top-n 10
python3 scripts/sms_activation.py --provider 5sim recommend --country usa --operator any --service amazon --top-n 5
```
+9 -2
View File
@@ -69,7 +69,9 @@ def read_state(path: str) -> Dict[str, Any]:
def write_state(path: str, state: Dict[str, Any]) -> None:
os.makedirs(os.path.dirname(path), exist_ok=True)
dirname = os.path.dirname(path)
if dirname:
os.makedirs(dirname, exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
json.dump(state, f, ensure_ascii=False, indent=2)
@@ -103,12 +105,17 @@ def normalize_status(provider: str, status_raw: Any, payload: Any = None) -> str
if provider in {"smsvn", "grizzly"}:
if s.startswith("STATUS_WAIT_CODE") or s in {"WAIT_CODE", "WAITING"}:
return "waiting"
if s.startswith("STATUS_OK") or "CODE" in s:
if s.startswith("STATUS_OK:") or s == "STATUS_OK":
return "code_received"
if "CANCEL" in s:
return "canceled"
if "ACCESS_ACTIVATION" in s or "FINISH" in s:
return "completed"
if "TIMEOUT" in s or "EXPIRED" in s:
return "timeout"
if "BANNED" in s:
return "banned"
return "error"
if provider == "5sim":
m = {
"PENDING": "waiting",
+103 -1
View File
@@ -83,6 +83,95 @@ def do_ban(client, args):
return {"provider": args.provider, "error": "ban_not_supported_by_default"}
def _to_float(v: Any, default: float = 0.0) -> float:
try:
return float(v)
except Exception:
return default
def recommend_smsvn(client, args):
if not args.country:
raise RuntimeError("recommend for smsvn requires --country")
data = client.services(int(args.country))
if not isinstance(data, list):
raise RuntimeError("unexpected smsvn services response")
items = []
for row in data:
if not isinstance(row, dict):
continue
sid = str(row.get("id", "")).strip()
if args.service and sid != args.service:
continue
price = _to_float(row.get("price"), default=1e18)
qty = int(_to_float(row.get("quantity"), default=0))
deliverability = _to_float(row.get("deliverability"), default=0.0)
if qty < args.min_qty:
continue
if args.max_price is not None and price > args.max_price:
continue
items.append(
{
"service": sid,
"name": row.get("name"),
"price": price,
"quantity": qty,
"deliverability": deliverability,
"country": int(args.country),
"provider": "smsvn",
}
)
items.sort(key=lambda x: (x["price"], -x["quantity"], -x["deliverability"], x["service"]))
return {"provider": "smsvn", "recommendations": items[: args.top_n], "total_candidates": len(items)}
def recommend_5sim(client, args):
if not args.country:
raise RuntimeError("recommend for 5sim requires --country")
raw = client.guest_products(args.country, args.operator)
if not isinstance(raw, dict):
raise RuntimeError("unexpected 5sim products response")
items = []
for service, row in raw.items():
if args.service and service != args.service:
continue
if not isinstance(row, dict):
continue
price = _to_float(row.get("Price"), default=1e18)
qty = int(_to_float(row.get("Qty"), default=0))
if qty < args.min_qty:
continue
if args.max_price is not None and price > args.max_price:
continue
items.append(
{
"service": service,
"category": row.get("Category"),
"price": price,
"quantity": qty,
"country": args.country,
"operator": args.operator,
"provider": "5sim",
}
)
items.sort(key=lambda x: (x["price"], -x["quantity"], x["service"]))
return {"provider": "5sim", "recommendations": items[: args.top_n], "total_candidates": len(items)}
def do_recommend(client, args):
if args.provider == "smsvn":
return recommend_smsvn(client, args)
if args.provider == "5sim":
return recommend_5sim(client, args)
return {
"provider": "grizzly",
"error": "recommend_not_supported",
"note": "grizzly public activation API does not provide a stable full discovery table here",
}
def main() -> int:
ap = argparse.ArgumentParser(description="SMS activation unified operator")
ap.add_argument("--provider", choices=["smsvn", "5sim", "grizzly"], required=True)
@@ -98,6 +187,14 @@ def main() -> int:
p_cov.add_argument("--operator", default="any")
p_cov.add_argument("--service")
p_rec = sub.add_parser("recommend")
p_rec.add_argument("--country")
p_rec.add_argument("--operator", default="any")
p_rec.add_argument("--service")
p_rec.add_argument("--max-price", type=float)
p_rec.add_argument("--min-qty", type=int, default=1)
p_rec.add_argument("--top-n", type=int, default=10)
p_buy = sub.add_parser("buy")
p_buy.add_argument("--country", required=True)
p_buy.add_argument("--operator", default="any")
@@ -123,10 +220,13 @@ def main() -> int:
args = ap.parse_args()
state = read_state(args.state_file)
exit_code = 0
try:
client = get_client(args.provider)
if args.cmd == "balance":
out = do_balance(client, args.provider)
elif args.cmd == "recommend":
out = do_recommend(client, args)
elif args.cmd == "discover":
if args.provider == "smsvn":
if not args.country:
@@ -171,14 +271,16 @@ def main() -> int:
out = {"ok": False, "provider": e.provider, "error_code": e.code, "error": e.message}
if args.debug_errors and e.payload is not None:
out["payload"] = e.payload
exit_code = 1
except Exception as e:
out = {"ok": False, "error": str(e)}
exit_code = 2
if args.raw:
print(json.dumps(out, ensure_ascii=False, indent=2, default=str))
else:
print(json.dumps(out, ensure_ascii=False, default=str))
return 0
return exit_code
if __name__ == "__main__":
+89
View File
@@ -0,0 +1,89 @@
from __future__ import annotations
import io
import json
import sys
import contextlib
import importlib
def _run(mod, argv):
old = sys.argv[:]
try:
sys.argv = argv
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
rc = mod.main()
return rc, json.loads(buf.getvalue())
finally:
sys.argv = old
def test_discover_smsvn_country_and_price_branch(monkeypatch):
mod = importlib.import_module("scripts.sms_activation")
class FakeClient:
def _call(self, action, **kwargs):
if action == "getPrices":
return {"ok": True, "branch": "prices"}
return {"ok": True}
def services(self, country):
return {"ok": True, "branch": "services", "country": country}
def countries(self):
return [{"id": 1}]
monkeypatch.setattr(mod, "get_client", lambda provider: FakeClient())
monkeypatch.setattr(mod, "read_state", lambda path: {})
rc, out = _run(mod, ["sms_activation.py", "--provider", "smsvn", "discover"])
assert rc == 0 and out[0]["id"] == 1
rc, out = _run(mod, ["sms_activation.py", "--provider", "smsvn", "discover", "--country", "12"])
assert rc == 0 and out["branch"] == "services"
rc, out = _run(
mod,
["sms_activation.py", "--provider", "smsvn", "discover", "--country", "12", "--service", "am"],
)
assert rc == 0 and out["branch"] == "prices"
def test_buy_writes_state(monkeypatch):
mod = importlib.import_module("scripts.sms_activation")
captured = {}
class FakeClient:
def get_number(self, **kwargs):
return {"activationId": "100", "phoneNumber": "15550000000"}
def fake_write(path, state):
captured["path"] = path
captured["state"] = state
monkeypatch.setattr(mod, "get_client", lambda provider: FakeClient())
monkeypatch.setattr(mod, "read_state", lambda path: {})
monkeypatch.setattr(mod, "write_state", fake_write)
rc, out = _run(
mod,
[
"sms_activation.py",
"--provider",
"smsvn",
"--state-file",
"x.json",
"buy",
"--country",
"12",
"--operator",
"any",
"--service",
"am",
],
)
assert rc == 0
assert out["activationId"] == "100"
assert captured["path"] == "x.json"
assert captured["state"]["smsvn"]["order_id"] == "100"
+94
View File
@@ -0,0 +1,94 @@
from __future__ import annotations
import io
import json
import sys
import contextlib
import importlib
def _run(mod, argv):
old = sys.argv[:]
try:
sys.argv = argv
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
rc = mod.main()
return rc, json.loads(buf.getvalue())
finally:
sys.argv = old
def test_discover_5sim_and_grizzly_branches(monkeypatch):
mod = importlib.import_module("scripts.sms_activation")
class FakeClient:
def _get(self, path):
assert path == "/v1/guest/countries"
return {"branch": "countries"}
def guest_products(self, country, operator):
return {"branch": "products", "country": country, "operator": operator}
def guest_prices(self, country, service):
return {"branch": "prices", "country": country, "service": service}
monkeypatch.setattr(mod, "get_client", lambda provider: FakeClient())
monkeypatch.setattr(mod, "read_state", lambda path: {})
rc, out = _run(mod, ["sms_activation.py", "--provider", "5sim", "discover"])
assert rc == 0 and out["branch"] == "countries"
rc, out = _run(
mod,
["sms_activation.py", "--provider", "5sim", "discover", "--country", "usa", "--operator", "any"],
)
assert rc == 0 and out["branch"] == "products"
rc, out = _run(
mod,
["sms_activation.py", "--provider", "5sim", "discover", "--country", "usa", "--service", "amazon"],
)
assert rc == 0 and out["branch"] == "prices"
# grizzly discover is note-style fallback branch
rc, out = _run(mod, ["sms_activation.py", "--provider", "grizzly", "discover"])
assert rc == 0
assert out["provider"] == "grizzly"
assert "limited" in out["note"]
def test_finish_cancel_ban_branches(monkeypatch):
mod = importlib.import_module("scripts.sms_activation")
class FiveClient:
def finish(self, order_id):
return {"op": "finish", "order_id": order_id}
def cancel(self, order_id):
return {"op": "cancel", "order_id": order_id}
def ban(self, order_id):
return {"op": "ban", "order_id": order_id}
class SmsClient:
def set_status(self, order_id, status):
return {"op": "set_status", "order_id": order_id, "status": status}
monkeypatch.setattr(mod, "read_state", lambda path: {})
monkeypatch.setattr(mod, "get_client", lambda provider: FiveClient())
rc, out = _run(mod, ["sms_activation.py", "--provider", "5sim", "finish", "--order-id", "1"])
assert rc == 0 and out["op"] == "finish"
rc, out = _run(mod, ["sms_activation.py", "--provider", "5sim", "cancel", "--order-id", "1"])
assert rc == 0 and out["op"] == "cancel"
rc, out = _run(mod, ["sms_activation.py", "--provider", "5sim", "ban", "--order-id", "1"])
assert rc == 0 and out["op"] == "ban"
monkeypatch.setattr(mod, "get_client", lambda provider: SmsClient())
rc, out = _run(mod, ["sms_activation.py", "--provider", "smsvn", "finish", "--order-id", "9"])
assert rc == 0 and out["status"] == 6
rc, out = _run(mod, ["sms_activation.py", "--provider", "smsvn", "cancel", "--order-id", "9"])
assert rc == 0 and out["status"] == 8
rc, out = _run(mod, ["sms_activation.py", "--provider", "smsvn", "ban", "--order-id", "9"])
assert rc == 0 and out["error"] == "ban_not_supported_by_default"
+90
View File
@@ -0,0 +1,90 @@
from __future__ import annotations
import json
import requests
from protocols.fivesim import FiveSimClient
from protocols.grizzly import GrizzlyClient
from protocols.smsvn import SmsVnClient
class DummyResp:
def __init__(self, status_code=200, text="", headers=None, json_data=None, url="https://x.test/api"):
self.status_code = status_code
self.text = text
self.headers = headers or {"content-type": "application/json"}
self._json_data = json_data
self.url = url
def json(self):
if self._json_data is not None:
return self._json_data
return json.loads(self.text)
def raise_for_status(self):
if self.status_code >= 400:
e = requests.HTTPError(f"{self.status_code} error")
req = requests.Request("GET", self.url).prepare()
e.request = req
e.response = self
raise e
def test_smsvn_get_number_string_response(monkeypatch):
def fake_get(url, params=None, timeout=20):
return DummyResp(status_code=200, text="ACCESS_NUMBER:123:15550001111", headers={"content-type": "text/plain"})
monkeypatch.setattr(requests, "get", fake_get)
c = SmsVnClient(api_key="k")
out = c.get_number(service="am", country=12, operator="any")
assert out["activationId"] == "123"
assert out["phoneNumber"] == "15550001111"
def test_smsvn_request_error_redacts_query_key(monkeypatch):
def fake_get(url, params=None, timeout=20):
req = requests.Request("GET", "https://x.test/stubs/handler_api?api_key=SECRET123&action=getBalance").prepare()
resp = DummyResp(status_code=500, text="boom", headers={"content-type": "text/plain"}, url=req.url)
err = requests.HTTPError("500 error")
err.request = req
err.response = resp
raise err
monkeypatch.setattr(requests, "get", fake_get)
c = SmsVnClient(api_key="k")
try:
c.balance()
assert False, "expected error"
except Exception as e:
assert "SECRET123" not in str(getattr(e, "payload", ""))
def test_fivesim_check_extracts_sms_code(monkeypatch):
class FakeSession:
headers = {}
def get(self, url, params=None, timeout=25):
payload = {
"id": 1,
"status": "RECEIVED",
"sms": [{"text": "code 667788", "code": "667788"}],
}
return DummyResp(status_code=200, json_data=payload)
monkeypatch.setattr(requests, "Session", lambda: FakeSession())
c = FiveSimClient(token="t")
out = c.check("1")
assert out["status"] == "code_received"
assert out["sms_code"] == "667788"
def test_grizzly_get_number_v1_string(monkeypatch):
def fake_get(url, params=None, timeout=20):
return DummyResp(status_code=200, text="ACCESS_NUMBER:9:13330000000", headers={"content-type": "text/plain"})
monkeypatch.setattr(requests, "get", fake_get)
c = GrizzlyClient(api_key="k")
out = c.get_number(service="tg", country=187, v2=False)
assert out["activationId"] == "9"
assert out["phoneNumber"] == "13330000000"
+67
View File
@@ -0,0 +1,67 @@
from __future__ import annotations
import json
import requests
from protocols.fivesim import FiveSimClient
from protocols._common import parse_json_or_text
class DummyResp:
def __init__(self, status_code=200, text="", headers=None, json_data=None, url="https://x.test/api"):
self.status_code = status_code
self.text = text
self.headers = headers or {"content-type": "application/json"}
self._json_data = json_data
self.url = url
def json(self):
if self._json_data is not None:
return self._json_data
return json.loads(self.text)
def raise_for_status(self):
if self.status_code >= 400:
e = requests.HTTPError(f"{self.status_code} error")
req = requests.Request("GET", self.url).prepare()
e.request = req
e.response = self
raise e
def test_parse_json_or_text_fallback_text():
r = DummyResp(status_code=200, text="PLAIN_OK", headers={"content-type": "text/plain"})
assert parse_json_or_text(r) == "PLAIN_OK"
def test_fivesim_auth_error(monkeypatch):
class FakeSession:
headers = {}
def get(self, url, params=None, timeout=25):
return DummyResp(status_code=401, text="unauthorized", headers={"content-type": "text/plain"})
monkeypatch.setattr(requests, "Session", lambda: FakeSession())
c = FiveSimClient(token="x")
try:
c.profile()
assert False, "expected auth error"
except Exception as e:
assert "AUTH" in str(e)
def test_fivesim_http_error(monkeypatch):
class FakeSession:
headers = {}
def get(self, url, params=None, timeout=25):
return DummyResp(status_code=500, text="server error", headers={"content-type": "text/plain"})
monkeypatch.setattr(requests, "Session", lambda: FakeSession())
c = FiveSimClient(token="x")
try:
c.profile()
assert False, "expected http error"
except Exception as e:
assert "HTTP" in str(e)
+112
View File
@@ -0,0 +1,112 @@
from __future__ import annotations
import io
import json
import sys
import contextlib
import importlib
def _run(mod, argv):
old = sys.argv[:]
try:
sys.argv = argv
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
rc = mod.main()
return rc, json.loads(buf.getvalue())
finally:
sys.argv = old
def test_recommend_smsvn_filters_and_sorts(monkeypatch):
mod = importlib.import_module("scripts.sms_activation")
class FakeClient:
def services(self, country):
assert country == 12
return [
{"id": "am", "name": "Amazon", "price": 0.16, "quantity": 100, "deliverability": 50},
{"id": "go", "name": "Google", "price": 0.04, "quantity": 200, "deliverability": 12},
{"id": "tg", "name": "Telegram", "price": 0.74, "quantity": 1000, "deliverability": 95},
{"id": "xx", "name": "LowQty", "price": 0.01, "quantity": 0, "deliverability": 99},
]
monkeypatch.setattr(mod, "get_client", lambda provider: FakeClient())
monkeypatch.setattr(mod, "read_state", lambda path: {})
rc, out = _run(
mod,
[
"sms_activation.py",
"--provider",
"smsvn",
"recommend",
"--country",
"12",
"--max-price",
"0.2",
"--min-qty",
"1",
"--top-n",
"2",
],
)
assert rc == 0
recs = out["recommendations"]
assert len(recs) == 2
assert recs[0]["service"] == "go"
assert recs[1]["service"] == "am"
def test_recommend_5sim_filters_and_service(monkeypatch):
mod = importlib.import_module("scripts.sms_activation")
class FakeClient:
def guest_products(self, country, operator):
assert country == "usa"
assert operator == "any"
return {
"amazon": {"Category": "activation", "Qty": 100, "Price": 0.13},
"telegram": {"Category": "activation", "Qty": 2, "Price": 0.74},
"bad": {"Category": "activation", "Qty": 0, "Price": 0.01},
}
monkeypatch.setattr(mod, "get_client", lambda provider: FakeClient())
monkeypatch.setattr(mod, "read_state", lambda path: {})
rc, out = _run(
mod,
[
"sms_activation.py",
"--provider",
"5sim",
"recommend",
"--country",
"usa",
"--operator",
"any",
"--service",
"amazon",
"--min-qty",
"10",
],
)
assert rc == 0
recs = out["recommendations"]
assert len(recs) == 1
assert recs[0]["service"] == "amazon"
def test_recommend_grizzly_not_supported(monkeypatch):
mod = importlib.import_module("scripts.sms_activation")
class FakeClient:
pass
monkeypatch.setattr(mod, "get_client", lambda provider: FakeClient())
monkeypatch.setattr(mod, "read_state", lambda path: {})
rc, out = _run(mod, ["sms_activation.py", "--provider", "grizzly", "recommend"])
assert rc == 0
assert out["error"] == "recommend_not_supported"
+105 -1
View File
@@ -1,4 +1,12 @@
from protocols._common import extract_code, normalize_status, redact_url_secrets
import io
import json
import os
import sys
import contextlib
import importlib
from pathlib import Path
from protocols._common import extract_code, normalize_status, redact_url_secrets, write_state, read_state
def test_extract_code():
@@ -9,6 +17,7 @@ def test_extract_code():
def test_normalize_smsvn():
assert normalize_status("smsvn", "STATUS_WAIT_CODE") == "waiting"
assert normalize_status("smsvn", "STATUS_OK:8888") == "code_received"
assert normalize_status("smsvn", "NO_CODE_YET") == "error"
def test_normalize_5sim():
@@ -23,3 +32,98 @@ def test_redact_url_secrets():
assert "ABC" not in redacted
assert "api_key=%2A%2A%2A" in redacted
assert "token=%2A%2A%2A" in redacted
def test_write_state_supports_bare_filename(tmp_path):
prev = Path.cwd()
try:
os.chdir(tmp_path)
write_state("state.json", {"a": 1})
assert read_state("state.json") == {"a": 1}
write_state("nested/state.json", {"b": 2})
assert read_state("nested/state.json") == {"b": 2}
finally:
os.chdir(prev)
def test_cli_returns_nonzero_on_provider_error(monkeypatch):
mod = importlib.import_module("scripts.sms_activation")
class FakeClient:
def balance(self):
raise mod.ProviderError("smsvn", "BAD_KEY", "bad key", payload={"debug": "x"})
monkeypatch.setattr(mod, "get_client", lambda provider: FakeClient())
monkeypatch.setattr(mod, "read_state", lambda path: {})
monkeypatch.setattr(sys, "argv", ["sms_activation.py", "--provider", "smsvn", "balance"])
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
rc = mod.main()
out = json.loads(buf.getvalue())
assert rc == 1
assert out["ok"] is False
assert out["error_code"] == "BAD_KEY"
assert "payload" not in out
def test_cli_debug_errors_includes_payload(monkeypatch):
mod = importlib.import_module("scripts.sms_activation")
class FakeClient:
def balance(self):
raise mod.ProviderError("smsvn", "HTTP_500", "req failed", payload={"url": "https://a.test?k=%2A%2A%2A"})
monkeypatch.setattr(mod, "get_client", lambda provider: FakeClient())
monkeypatch.setattr(mod, "read_state", lambda path: {})
monkeypatch.setattr(sys, "argv", ["sms_activation.py", "--provider", "smsvn", "--debug-errors", "balance"])
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
rc = mod.main()
out = json.loads(buf.getvalue())
assert rc == 1
assert out["ok"] is False
assert out["payload"]["url"].startswith("https://")
def test_poll_stops_on_terminal_state(monkeypatch):
mod = importlib.import_module("scripts.sms_activation")
calls = {"n": 0}
class FakeClient:
def get_status(self, order_id):
calls["n"] += 1
if calls["n"] == 1:
return {"status": "waiting"}
return {"status": "code_received", "sms_code": "1234"}
monkeypatch.setattr(mod, "get_client", lambda provider: FakeClient())
monkeypatch.setattr(mod, "read_state", lambda path: {})
monkeypatch.setattr(mod, "sleep_with_backoff", lambda *a, **k: None)
monkeypatch.setattr(
sys,
"argv",
[
"sms_activation.py",
"--provider",
"smsvn",
"poll",
"--order-id",
"1",
"--attempts",
"10",
"--interval",
"0.01",
"--backoff",
"1.0",
],
)
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
rc = mod.main()
out = json.loads(buf.getvalue())
assert rc == 0
assert calls["n"] == 2
assert out["status"] == "code_received"