Files

297 lines
9.5 KiB
Python

import httpx
from fastapi.testclient import TestClient
from euniv.crypto import encrypt_secret
from euniv.db import SessionLocal
from euniv.models import Account
from euniv.proxy import is_proxy_failure
from euniv.proxy_pool import (
BATCH_SIZE,
MAX_FETCHES,
PROBE_URL,
SOURCE_PROTOCOLS,
_fetch_batch,
_fetches,
_holds,
acquire,
force_direct,
probe,
release,
reset_budget,
)
def _clear() -> None:
_holds.clear()
_fetches.clear()
def test_fetch_batch_asks_for_socks5_then_http_then_https(monkeypatch) -> None:
calls: list[dict] = []
class FakeResponse:
def __init__(self, protocol: str) -> None:
self.protocol = protocol
def json(self) -> dict:
proxies = {
"socks5": ["1.2.3.4:1080"],
"http": ["9.9.9.9:8080"],
"https": ["1.2.3.4:1080", "8.8.8.8:8080", "10.0.0.1:1"],
}[self.protocol]
return {"code": 200, "message": "success", "data": {"proxies": proxies, "count": len(proxies)}}
class FakeClient:
def __init__(self, *_args, **_kwargs) -> None:
return None
def __enter__(self):
return self
def __exit__(self, *_args) -> bool:
return False
def get(self, url: str, params: dict | None = None):
calls.append({"url": url, "params": params or {}})
return FakeResponse(str((params or {}).get("protocol")))
monkeypatch.setattr("euniv.proxy_pool.httpx.Client", FakeClient)
assert _fetch_batch() == [
("socks5", "1.2.3.4", 1080),
("http", "9.9.9.9", 8080),
("http", "8.8.8.8", 8080),
]
assert [item["params"]["protocol"] for item in calls] == [protocol for protocol, _scheme in SOURCE_PROTOCOLS]
assert all(item["url"].endswith("/api/get_proxy.php") for item in calls)
assert all(item["params"]["count"] == BATCH_SIZE and item["params"]["country_code"] == "CN" for item in calls)
def test_acquire_stops_at_the_first_usable_proxy(monkeypatch) -> None:
_clear()
batches = [[("socks5", "1.1.1.1", 1), ("socks5", "2.2.2.2", 2), ("http", "3.3.3.3", 3)]]
probed: list[str] = []
monkeypatch.setattr("euniv.proxy_pool._fetch_batch", lambda: list(batches.pop(0)))
def fake_probe(scheme: str, host: str, _port: int):
probed.append(f"{scheme}:{host}")
return host == "2.2.2.2", 10, ""
monkeypatch.setattr("euniv.proxy_pool.probe", fake_probe)
assert acquire("u1") == "socks5://2.2.2.2:2"
assert probed == ["socks5:1.1.1.1", "socks5:2.2.2.2"]
assert acquire("u1") == "socks5://2.2.2.2:2"
assert batches == []
def test_acquire_uses_eight_batches_then_direct(monkeypatch) -> None:
_clear()
calls = {"n": 0}
def fetch() -> list[tuple[str, int]]:
calls["n"] += 1
return [("http", f"1.2.3.{calls['n']}", 8000)]
monkeypatch.setattr("euniv.proxy_pool._fetch_batch", fetch)
monkeypatch.setattr("euniv.proxy_pool.probe", lambda *_args: (False, 8, "无法连接"))
assert acquire("u1") is None
assert calls["n"] == MAX_FETCHES
assert acquire("u1") is None
assert calls["n"] == MAX_FETCHES
def test_failed_proxy_fetches_the_next_batch_until_budget(monkeypatch) -> None:
_clear()
calls = {"n": 0}
def fetch() -> list[tuple[str, int]]:
calls["n"] += 1
return [("http", f"1.2.3.{calls['n']}", 8000)]
monkeypatch.setattr("euniv.proxy_pool._fetch_batch", fetch)
monkeypatch.setattr("euniv.proxy_pool.probe", lambda *_args: (True, 20, ""))
first = acquire("u1")
assert first == "http://1.2.3.1:8000"
force_direct("u1")
assert acquire("u1") is None
assert calls["n"] == 1
reset_budget("u1")
assert acquire("u1") == "http://1.2.3.2:8000"
def test_direct_recheck_keeps_valid_credential_without_login(monkeypatch) -> None:
from euniv.autostudy import _continue_direct
class Fake:
login_called = False
def __init__(self, employee_id: str, password: str, proxy: str | None = None) -> None:
assert proxy is None
self.client = self
self.cookies = self
self.jar: list = []
self._profile = {"userId": "u", "accountId": employee_id}
def restore(self, credential: dict) -> None:
assert credential["yxt_token"] == "saved"
def credential_alive(self) -> bool:
return True
def _ensure_site(self) -> str:
return ""
def session_token(self) -> str:
return "saved"
def login(self, manual: bool = False) -> dict:
Fake.login_called = True
raise AssertionError("凭据仍有效,不应重新登录")
def close(self) -> None:
return None
monkeypatch.setattr("euniv.autostudy.EunivClient", Fake)
monkeypatch.setattr("euniv.autostudy._stored_credential", lambda _employee_id: {"yxt_token": "saved"})
monkeypatch.setattr("euniv.proxy_pool.force_direct", lambda _employee_id: None)
token, _user_id, _org_id, _cookies, proxy, reason = _continue_direct("100", "pw")
assert token == "saved"
assert proxy is None
assert reason == ""
assert Fake.login_called is False
def test_release_lets_the_next_task_fetch_again(monkeypatch) -> None:
_clear()
monkeypatch.setattr("euniv.proxy_pool._fetch_batch", lambda: [("http", "8.8.4.4", 8080)])
monkeypatch.setattr("euniv.proxy_pool.probe", lambda *_args: (True, 15, ""))
assert acquire("u1") == "http://8.8.4.4:8080"
release("u1")
assert "u1" not in _holds
assert "u1" not in _fetches
def test_probe_reaches_euniv_home(monkeypatch) -> None:
seen: list[str] = []
class FakeResponse:
status_code = 200
class FakeClient:
def __init__(self, *_args, **_kwargs) -> None:
return None
def __enter__(self):
return self
def __exit__(self, *_args) -> bool:
return False
def get(self, url: str):
seen.append(url)
return FakeResponse()
ticks = iter([0.0, 0.12])
monkeypatch.setattr("euniv.proxy_pool.sync_httpx_client", FakeClient)
monkeypatch.setattr("euniv.proxy_pool.time.perf_counter", lambda: next(ticks))
ok, latency, reason = probe("http", "1.1.1.1", 8080)
assert seen == [PROBE_URL]
assert ok is True
assert latency == 120
assert reason == ""
def test_probe_instant_connect_error_keeps_elapsed_latency(monkeypatch) -> None:
class FakeClient:
def __init__(self, *_args, **_kwargs) -> None:
return None
def __enter__(self):
return self
def __exit__(self, *_args) -> bool:
return False
def get(self, _url: str):
raise httpx.ConnectError("boom")
ticks = iter([0.0, 0.008])
monkeypatch.setattr("euniv.proxy_pool.sync_httpx_client", FakeClient)
monkeypatch.setattr("euniv.proxy_pool.time.perf_counter", lambda: next(ticks))
ok, latency, reason = probe("http", "1.1.1.1", 8080)
assert ok is False
assert latency == 8
assert reason == "无法连接"
def test_is_proxy_failure_detects_connect_errors() -> None:
assert is_proxy_failure(httpx.ConnectError("boom"))
assert is_proxy_failure(httpx.ConnectTimeout("late"))
assert is_proxy_failure(httpx.ReadTimeout("slow"))
assert is_proxy_failure(httpx.ReadError("reset"))
assert is_proxy_failure(httpx.RemoteProtocolError("bad"))
assert not is_proxy_failure(RuntimeError("登录需要重新验证"))
def test_user_can_enable_pool_proxy(monkeypatch) -> 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
monkeypatch.setattr(
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