285 lines
9.4 KiB
Python
285 lines
9.4 KiB
Python
import httpx
|
|
from fastapi.testclient import TestClient
|
|
|
|
from euniv.collectors import ProxyCandidate, collect_all, is_china, parse_proxyhub_result
|
|
from euniv.crypto import encrypt_secret
|
|
from euniv.db import SessionLocal
|
|
from euniv.models import Account, ProxyNode
|
|
from euniv.proxy import apply as apply_proxy
|
|
from euniv.proxy import bind_url, is_proxy_failure, view_of
|
|
from euniv.proxy_pool import acquire, mark_failed, page, refresh_once, release
|
|
from euniv.proxy_pool import _holds
|
|
|
|
INITIAL_PASSWORD = "242520"
|
|
|
|
|
|
def _node(host: str, port: int, status: str = "alive", scheme: str = "http", assigns: int = 0) -> ProxyNode:
|
|
node = ProxyNode(
|
|
scheme=scheme,
|
|
host=host,
|
|
port=port,
|
|
country="cn",
|
|
anonymity="elite",
|
|
source="proxyhub",
|
|
status=status,
|
|
latency_ms=200 if status == "alive" else None,
|
|
assigns=assigns,
|
|
)
|
|
with SessionLocal() as db:
|
|
db.add(node)
|
|
db.commit()
|
|
db.refresh(node)
|
|
return node
|
|
|
|
|
|
def _account(employee_id: str) -> None:
|
|
with SessionLocal() as db:
|
|
db.add(
|
|
Account(
|
|
employee_id=employee_id,
|
|
password_cipher=encrypt_secret("secret"),
|
|
credential_cipher="",
|
|
)
|
|
)
|
|
db.commit()
|
|
|
|
|
|
def test_parse_proxyhub_keeps_structured_rows() -> None:
|
|
payload = {
|
|
"jsonrpc": "2.0",
|
|
"id": 1,
|
|
"result": {
|
|
"isError": False,
|
|
"structuredContent": {
|
|
"proxies": [
|
|
{"ip": "1.1.1.1", "port": 8080, "country": "cn", "type": "http", "anonymity": "elite"},
|
|
{"ip": "2.2.2.2", "port": 1080, "country": "cn", "type": "socks5", "anonymity": "anonymous"},
|
|
],
|
|
"count": 2,
|
|
},
|
|
},
|
|
}
|
|
rows = parse_proxyhub_result(payload)
|
|
assert [(item.scheme, item.host, item.port, item.source) for item in rows] == [
|
|
("http", "1.1.1.1", 8080, "proxyhub"),
|
|
("socks5", "2.2.2.2", 1080, "proxyhub"),
|
|
]
|
|
|
|
|
|
def test_china_filter_and_collect_all(monkeypatch) -> None:
|
|
assert is_china("cn")
|
|
assert is_china("中国")
|
|
assert not is_china("us")
|
|
|
|
class Dummy:
|
|
name = "dummy"
|
|
|
|
def collect(self):
|
|
return [
|
|
ProxyCandidate("http", "1.1.1.1", 80, "cn", "elite", "dummy"),
|
|
ProxyCandidate("http", "8.8.8.8", 80, "us", "elite", "dummy"),
|
|
]
|
|
|
|
monkeypatch.setattr("euniv.collectors.collectors", lambda: [Dummy()])
|
|
items = collect_all()
|
|
assert [(item.host, item.country) for item in items] == [("1.1.1.1", "cn")]
|
|
|
|
|
|
def test_acquire_spreads_accounts_and_skips_dead() -> None:
|
|
_holds.clear()
|
|
first = _node("10.0.0.1", 8001)
|
|
second = _node("10.0.0.2", 8002)
|
|
_node("10.0.0.3", 8003, status="dead")
|
|
a = acquire("u1")
|
|
b = acquire("u2")
|
|
assert {a, b} == {"http://10.0.0.1:8001", "http://10.0.0.2:8002"}
|
|
c = acquire("u3")
|
|
assert c in {a, b}
|
|
mark_failed("u1", a, "无法连接")
|
|
again = acquire("u1")
|
|
assert again == b
|
|
with SessionLocal() as db:
|
|
dead_id = first.id if a.endswith(":8001") else second.id
|
|
dead = db.get(ProxyNode, dead_id)
|
|
assert dead is not None
|
|
assert dead.status == "dead"
|
|
assert acquire("u1") == again
|
|
release("u1")
|
|
release("u2")
|
|
release("u3")
|
|
|
|
|
|
def test_empty_pool_returns_direct() -> None:
|
|
_holds.clear()
|
|
_node("10.0.0.9", 9, status="dead")
|
|
assert acquire("nobody") is None
|
|
|
|
|
|
def test_bind_url_uses_pool_or_manual() -> None:
|
|
_holds.clear()
|
|
_node("10.0.0.4", 8004)
|
|
_account("pool-user")
|
|
_account("manual-user")
|
|
with SessionLocal() as db:
|
|
pool_user = db.get(Account, "pool-user")
|
|
manual_user = db.get(Account, "manual-user")
|
|
assert pool_user is not None and manual_user is not None
|
|
apply_proxy(pool_user, "pool")
|
|
apply_proxy(manual_user, "http", "127.0.0.1", 7890)
|
|
db.commit()
|
|
db.refresh(pool_user)
|
|
db.refresh(manual_user)
|
|
assert view_of(pool_user)["scheme"] == "pool"
|
|
assert bind_url(pool_user) == "http://10.0.0.4:8004"
|
|
assert bind_url(manual_user) == "http://127.0.0.1:7890"
|
|
apply_proxy(pool_user, "off")
|
|
db.commit()
|
|
db.refresh(pool_user)
|
|
assert bind_url(pool_user) is None
|
|
|
|
|
|
def test_refresh_marks_slow_and_keeps_fast(monkeypatch) -> None:
|
|
_holds.clear()
|
|
monkeypatch.setattr(
|
|
"euniv.proxy_pool.collect_all",
|
|
lambda: [
|
|
ProxyCandidate("http", "1.1.1.1", 80, "cn", "elite", "proxyhub"),
|
|
ProxyCandidate("http", "2.2.2.2", 80, "cn", "elite", "proxyhub"),
|
|
ProxyCandidate("http", "3.3.3.3", 80, "us", "elite", "proxyhub"),
|
|
],
|
|
)
|
|
|
|
def fake_probe(scheme: str, host: str, port: int):
|
|
if host == "1.1.1.1":
|
|
return True, 800, ""
|
|
return False, 4000, "超时"
|
|
|
|
monkeypatch.setattr("euniv.proxy_pool.probe", fake_probe)
|
|
payload = refresh_once()
|
|
assert payload["alive"] == 1
|
|
assert payload["dead"] == 1
|
|
with SessionLocal() as db:
|
|
listed = page(db)
|
|
hosts = {item["host"]: item for item in listed["items"]}
|
|
assert hosts["1.1.1.1"]["status"] == "alive"
|
|
assert hosts["1.1.1.1"]["latency_ms"] == 800
|
|
assert hosts["2.2.2.2"]["status"] == "dead"
|
|
assert "3.3.3.3" not in hosts
|
|
|
|
|
|
def test_failed_proxy_is_not_reprobed(monkeypatch) -> None:
|
|
_holds.clear()
|
|
dead = _node("9.9.9.9", 99, status="dead")
|
|
monkeypatch.setattr(
|
|
"euniv.proxy_pool.collect_all",
|
|
lambda: [ProxyCandidate("http", "9.9.9.9", 99, "cn", "elite", "proxyhub")],
|
|
)
|
|
called = []
|
|
|
|
def fake_probe(scheme: str, host: str, port: int):
|
|
called.append(host)
|
|
return True, 10, ""
|
|
|
|
monkeypatch.setattr("euniv.proxy_pool.probe", fake_probe)
|
|
refresh_once()
|
|
assert called == []
|
|
with SessionLocal() as db:
|
|
node = db.get(ProxyNode, dead.id)
|
|
assert node is not None
|
|
assert node.status == "dead"
|
|
|
|
|
|
def test_is_proxy_failure_detects_connect_errors() -> None:
|
|
assert is_proxy_failure(httpx.ConnectError("boom"))
|
|
assert is_proxy_failure(httpx.ConnectTimeout("late"))
|
|
assert not is_proxy_failure(RuntimeError("登录需要重新验证"))
|
|
|
|
|
|
def test_admin_proxy_page_and_pool_assignment() -> None:
|
|
import euniv.api as api_module
|
|
|
|
_holds.clear()
|
|
_node("10.0.0.5", 8005)
|
|
_account("a-user")
|
|
_account("b-user")
|
|
client = TestClient(api_module.app)
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
listed = client.get("/api/admin/proxies")
|
|
assert listed.status_code == 200
|
|
body = listed.json()
|
|
assert body["alive"] == 1
|
|
assert body["items"][0]["host"] == "10.0.0.5"
|
|
assert body["items"][0]["status_text"] == "可用"
|
|
saved = client.put(
|
|
"/api/admin/users/proxy",
|
|
json={"employee_ids": ["a-user", "b-user"], "scheme": "pool"},
|
|
)
|
|
assert saved.status_code == 200
|
|
users = client.get("/api/admin/users").json()
|
|
one = next(item for item in users if item["employee_id"] == "a-user")
|
|
two = next(item for item in users if item["employee_id"] == "b-user")
|
|
assert one["has_proxy"] is True
|
|
assert one["proxy"] == "自动"
|
|
assert two["proxy"] == "自动"
|
|
detail = client.get("/api/admin/users/a-user/proxy")
|
|
assert detail.json()["scheme"] == "pool"
|
|
assert detail.json()["enabled"] is True
|
|
|
|
|
|
def test_user_can_enable_pool_proxy() -> None:
|
|
import euniv.api as api_module
|
|
import euniv.service as service_module
|
|
|
|
class FakeClient:
|
|
def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None:
|
|
self.login_name = login_name
|
|
self.password = password
|
|
self.proxy = proxy
|
|
self._profile = {
|
|
"token": "ucs-1",
|
|
"accountId": login_name,
|
|
"userId": "u1",
|
|
"ssoinfo": "sso",
|
|
"unionId": "",
|
|
}
|
|
self._token = "yxt-1"
|
|
|
|
def close(self) -> None:
|
|
return None
|
|
|
|
def login(self, manual: bool = False, auto_attempts: int = 3) -> dict:
|
|
return dict(self._profile)
|
|
|
|
def authorize(self, profile: dict) -> None:
|
|
return None
|
|
|
|
def export_credential(self) -> dict:
|
|
return {
|
|
"ucs_token": "ucs-1",
|
|
"ucs_account_id": self.login_name,
|
|
"ucs_user_id": "u1",
|
|
"ucs_ssoinfo": "sso",
|
|
"ucs_union_id": "",
|
|
"yxt_token": "yxt-1",
|
|
}
|
|
|
|
def restore(self, credential: dict) -> None:
|
|
return None
|
|
|
|
def credential_alive(self) -> bool:
|
|
return True
|
|
|
|
api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store(
|
|
db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts
|
|
)
|
|
client = TestClient(api_module.app)
|
|
assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200
|
|
saved = client.put("/api/settings/proxy", json={"scheme": "pool"})
|
|
assert saved.status_code == 200
|
|
assert saved.json()["scheme"] == "pool"
|
|
assert saved.json()["enabled"] is True
|
|
with SessionLocal() as db:
|
|
account = db.get(Account, "6650000146")
|
|
assert account is not None
|
|
assert account.use_proxy_pool is True
|