Files
EnuivTools/backend/tests/test_proxy_pool.py
T

292 lines
9.0 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_PROTOCOL,
_fetch_batch,
_fetches,
_holds,
acquire,
force_direct,
probe,
release,
reset_budget,
)
def _clear() -> None:
_holds.clear()
_fetches.clear()
def test_fetch_batch_asks_for_eight_chinese_https_proxies(monkeypatch) -> None:
seen: dict = {}
class FakeResponse:
def json(self) -> dict:
return {
"code": 200,
"message": "success",
"data": {
"proxies": ["1.2.3.4:8080", "10.0.0.1:3128", "bad", "8.8.8.8:9"],
"count": 4,
},
}
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):
seen["url"] = url
seen["params"] = params
return FakeResponse()
monkeypatch.setattr("euniv.proxy_pool.httpx.Client", FakeClient)
assert _fetch_batch() == [("1.2.3.4", 8080), ("8.8.8.8", 9)]
assert seen["url"].endswith("/api/get_proxy.php")
assert seen["params"] == {"protocol": SOURCE_PROTOCOL, "count": BATCH_SIZE, "country_code": "CN"}
def test_acquire_stops_at_the_first_usable_proxy(monkeypatch) -> None:
_clear()
batches = [[("1.1.1.1", 1), ("2.2.2.2", 2), ("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(host)
return host == "2.2.2.2", 10, ""
monkeypatch.setattr("euniv.proxy_pool.probe", fake_probe)
assert acquire("u1") == "http://2.2.2.2:2"
assert probed == ["1.1.1.1", "2.2.2.2"]
assert acquire("u1") == "http://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 [(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 [(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: [("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