feat: add recommendation command and expand test coverage
This commit is contained in:
1 parent
702280a416
commit
f9267352cc
9 files changed
+684
-4
No files matched your search
@@ -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"
|
||||
@@ -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"
|
||||
@@ -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"
|
||||
@@ -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)
|
||||
@@ -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"
|
||||
@@ -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"
|
||||
Reference in new issue
Block a user