| 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()
- # Clear potential quarantine state
- self.pm._quarantine.clear()
- self.pm._sliding_history.clear()
- self.pm._reputation_cache.clear()
- # Mock out time-consuming external probe and cloud HTTP calls
- 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):
- # Test local pool (single port)
- 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):
- # Test 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):
- # Test invalid prefix format without local: or cloud:, must raise 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):
- # Test non-existent local pool
- 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):
- """Tests WAF block enters quarantine list, and revives on success."""
- plugin = "vfs_plugin"
- proxy = self.pm.get_next_proxy(["local:local_multi_pool"], plugin_name=plugin)
- port = proxy["port"]
- egress_ip = proxy["egress_ip"]
- # Simulate a 403202 cf-mitigated block
- self.pm.mark_proxy_result(
- proxy=proxy,
- plugin_name=plugin,
- action="spawn",
- success=False,
- http_code=403,
- error_type="cf-mitigated (403202)"
- )
- # Verify that IP entered quarantine
- self.assertIn(egress_ip, self.pm._quarantine.get(plugin, {}))
- # Simulate subsequent success on the IP, verifying half-open revival
- 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):
- """Tests Layer 1: Site-wide outage freezes penalty and quarantine."""
- plugin = "vfs_plugin"
- # Construct continuous server errors (502/503) across multiple distinct IPs
- 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"
- )
- # Site-wide outage triggered
- self.assertTrue(self.pm._is_site_outage(plugin))
- # Under site outage, nodes with WAF blocks should not be quarantined
- 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):
- """Tests Layer 3: Anti-avalanche floor guarantee resets quarantine when over-filtered."""
- plugin = "test_plugin"
- # Artificially fill quarantine list
- self.pm._quarantine[plugin] = {
- f"port_{16000 + i}": time.time() + 1800 for i in range(1000)
- }
- # Should not raise exception; triggers anti-avalanche reset and returns proxy
- 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()
|