import os 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 PROBE_URL, acquire, mark_failed, page, probe, refresh_once, release from euniv.proxy_pool import _holds INITIAL_PASSWORD = os.environ["EUNIV_ADMIN_PASSWORD"] 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", "1.1.1.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://1.1.1.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", "4.4.4.4", 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"] == 2 assert payload["message"] == "" 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_old_dead_proxy_is_reprobed(monkeypatch) -> None: from datetime import datetime, timedelta, timezone _holds.clear() stale = _node("8.8.8.8", 88, status="dead") with SessionLocal() as db: node = db.get(ProxyNode, stale.id) assert node is not None node.last_checked_at = datetime.now(timezone.utc) - timedelta(hours=1) db.commit() monkeypatch.setattr( "euniv.proxy_pool.collect_all", lambda: [ProxyCandidate("http", "8.8.8.8", 88, "cn", "elite", "proxyhub")], ) called: list[str] = [] def fake_probe(scheme: str, host: str, port: int): called.append(host) return True, 20, "" monkeypatch.setattr("euniv.proxy_pool.probe", fake_probe) refresh_once() assert called == ["8.8.8.8"] with SessionLocal() as db: node = db.get(ProxyNode, stale.id) assert node is not None assert node.status == "alive" def test_probe_averages_euniv_related_sites(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("socks4", "10.0.0.9", 1080) assert ok is False assert latency == 8 assert reason == "无法连接" def test_admin_can_probe_one_and_all_proxies(monkeypatch) -> None: import euniv.api as api_module _holds.clear() one = _node("10.0.0.7", 8007) two = _node("10.0.0.8", 8008, status="new") monkeypatch.setattr("euniv.proxy_pool.probe", lambda scheme, host, port: (True, 321 if host.endswith("7") else 654, "")) client = TestClient(api_module.app) assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200 single = client.post(f"/api/admin/proxies/{one.id}/probe") assert single.status_code == 200 assert single.json()["latency_ms"] == 321 assert single.json()["status"] == "alive" bulk = client.post("/api/admin/proxies/probe", json={"ids": [two.id]}) assert bulk.status_code == 200 assert bulk.json()["running"] is True finished = {"running": True} for _ in range(40): finished = client.get("/api/admin/proxies/probe").json() if finished["running"] is False: break import time time.sleep(0.05) assert finished["running"] is False listed = client.get("/api/admin/proxies").json() probed = next(item for item in listed["items"] if item["id"] == two.id) assert probed["latency_ms"] == 654 missing = client.post("/api/admin/proxies/99999/probe") assert missing.status_code == 404 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_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/study-settings", 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(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