| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143 |
- import os
- import sys
- import time
- import unittest
- from unittest.mock import MagicMock, patch
- project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
- if project_root not in sys.path:
- sys.path.insert(0, project_root)
- from toolkit.proxy_manager import ProxyManager
- from core_types import Proxy, BizLogicError
- from toolkit.cloud_api import CloudApi
- class TestProxyManager(unittest.TestCase):
- def setUp(self):
- self.pm = ProxyManager.Instance()
- # 清理可能存在的隔离状态
- self.pm._quarantine.clear()
- self.pm._sliding_history.clear()
- self.pm._reputation_cache.clear()
- # Mock 掉耗时的真实外部探测与云端 HTTP 调用
- self.patcher_probe = patch.object(self.pm, "_async_probe_egress_ip", return_value=None)
- self.patcher_probe.start()
- self.patcher_rep = patch.object(CloudApi.Instance(), "get_proxy_reputation_map", return_value={})
- self.patcher_rep.start()
- self.patcher_report = patch.object(CloudApi.Instance(), "report_proxy_metric", return_value=True)
- self.patcher_report.start()
- def tearDown(self):
- self.patcher_probe.stop()
- self.patcher_rep.stop()
- self.patcher_report.stop()
- def test_local_proxy_single(self):
- # 测试 local 池 (单端口)
- res = self.pm.get_next_proxy(["local:local"])
- self.assertIsInstance(res, dict)
- self.assertEqual(res["ip"], "127.0.0.1")
- self.assertEqual(res["port"], 7897)
- proxy_obj = Proxy(**res)
- self.assertEqual(proxy_obj.port, 7897)
- def test_local_proxy_multi_pool(self):
- # 测试 local_multi_pool
- res = self.pm.get_next_proxy(["local:local_multi_pool"])
- self.assertIsInstance(res, dict)
- self.assertEqual(res["ip"], "127.0.0.1")
- self.assertTrue(res["port"] >= 10000)
- proxy_obj = Proxy(**res)
- self.assertTrue(proxy_obj.port >= 10000)
- def test_invalid_prefix(self):
- # 测试未带前缀的非法格式,必须抛出 BizLogicError
- with self.assertRaises(BizLogicError) as ctx:
- self.pm.get_next_proxy(["proxy-cheap"])
- self.assertIn("Must start with 'local:' or 'cloud:'", str(ctx.exception))
- def test_nonexistent_local_pool(self):
- # 测试不存在的本地池
- with self.assertRaises(BizLogicError) as ctx:
- self.pm.get_next_proxy(["local:non_existent_pool_12345"])
- self.assertIn("No proxies found in local pools", str(ctx.exception))
- def test_reputation_quarantine_and_revival(self):
- """测试专属 WAF 阻断进入隔离名单,以及成功后自愈复活"""
- plugin = "vfs_plugin"
- proxy = self.pm.get_next_proxy(["local:local_multi_pool"], plugin_name=plugin)
- port = proxy["port"]
- egress_ip = proxy["egress_ip"]
- # 模拟一次 403202 cf-mitigated 专属阻断
- self.pm.mark_proxy_result(
- proxy=proxy,
- plugin_name=plugin,
- action="spawn",
- success=False,
- http_code=403,
- error_type="cf-mitigated (403202)"
- )
- # 验证该 IP 已进入隔离名单
- self.assertIn(egress_ip, self.pm._quarantine.get(plugin, {}))
- # 模拟下一次该 IP 执行成功,验证自愈复活
- self.pm.mark_proxy_result(
- proxy=proxy,
- plugin_name=plugin,
- action="spawn",
- success=True,
- http_code=200
- )
- self.assertNotIn(egress_ip, self.pm._quarantine.get(plugin, {}))
- def test_site_outage_freeze(self):
- """测试 Layer 1: 全站故障时冻结扣分与隔离"""
- plugin = "vfs_plugin"
- # 构造跨多个不同 IP 的连续系统级故障 (502 / 503)
- for i in range(6):
- fake_proxy = {"port": 16000 + i, "egress_ip": f"104.28.1.{i}", "name": f"node_{i}"}
- self.pm.mark_proxy_result(
- proxy=fake_proxy,
- plugin_name=plugin,
- action="spawn",
- success=False,
- http_code=502,
- error_type="Bad Gateway"
- )
- # 此时全站故障已触发
- self.assertTrue(self.pm._is_site_outage(plugin))
- # 在全站故障状态下,即使有节点发生 WAF 阻断,也不会被拉黑隔离
- new_proxy = {"port": 16099, "egress_ip": "104.28.99.99", "name": "node_99"}
- self.pm.mark_proxy_result(
- proxy=new_proxy,
- plugin_name=plugin,
- action="spawn",
- success=False,
- http_code=403,
- error_type="cf-mitigated (403202)"
- )
- self.assertNotIn("104.28.99.99", self.pm._quarantine.get(plugin, {}))
- def test_minimum_viable_pool_anti_starvation(self):
- """测试 Layer 3: 最低可用保底池防雪崩,过度拉黑时强制重置隔离名单"""
- plugin = "test_plugin"
- # 人为把隔离名单填满
- self.pm._quarantine[plugin] = {
- f"port_{16000 + i}": time.time() + 1800 for i in range(1000)
- }
- # 获取下一个代理,不应该抛出异常,应该触发防雪崩重置并成功返回代理
- proxy = self.pm.get_next_proxy(["local:local_multi_pool"], plugin_name=plugin)
- self.assertIsInstance(proxy, dict)
- self.assertTrue(proxy["port"] >= 10000)
- if __name__ == "__main__":
- unittest.main()
|