Skip to content

Commit f9f8f4c

Browse files
committed
AI test successful
1 parent 5debb33 commit f9f8f4c

File tree

8 files changed

+494
-25
lines changed

8 files changed

+494
-25
lines changed

anp_proxy/examples/simple_test.py

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
"""Simple test to verify basic Gateway functionality without Receiver."""
2+
3+
import asyncio
4+
5+
import httpx
6+
7+
from anp_proxy.common.config import AuthConfig, GatewayConfig
8+
from anp_proxy.gateway import GatewayServer
9+
10+
11+
async def test_gateway_only():
12+
"""Test Gateway in standalone mode."""
13+
print("🧪 Testing Gateway standalone functionality")
14+
15+
# Configure Gateway with auth disabled
16+
config = GatewayConfig(
17+
host="127.0.0.1",
18+
port=9080,
19+
wss_host="127.0.0.1",
20+
wss_port=9765,
21+
auth=AuthConfig(enabled=False),
22+
max_connections=10,
23+
timeout=30.0
24+
)
25+
26+
gateway = GatewayServer(config)
27+
28+
try:
29+
# Start Gateway
30+
print("🚀 Starting Gateway...")
31+
await gateway.start()
32+
await asyncio.sleep(2) # Give time to start
33+
34+
print("✅ Gateway started successfully")
35+
36+
# Test health endpoint (this should work even without receiver)
37+
print("📡 Testing Gateway health endpoint...")
38+
try:
39+
# Clear any proxy settings
40+
async with httpx.AsyncClient(
41+
timeout=10.0,
42+
proxy=None, # No proxy
43+
trust_env=False # Don't trust environment proxy settings
44+
) as client:
45+
response = await client.get("http://127.0.0.1:9080/health")
46+
print(f"✅ Health check - Status: {response.status_code}")
47+
if response.status_code == 200:
48+
print(f" Response: {response.json()}")
49+
else:
50+
print(f" Response: {response.text}")
51+
52+
except Exception as e:
53+
print(f"❌ Health check failed: {e}")
54+
55+
# Test other endpoint (should timeout since no receiver)
56+
print("📡 Testing Gateway root endpoint (should timeout)...")
57+
try:
58+
async with httpx.AsyncClient(
59+
timeout=5.0, # Short timeout
60+
proxy=None,
61+
trust_env=False
62+
) as client:
63+
response = await client.get("http://127.0.0.1:9080/")
64+
print(f"🤔 Unexpected success - Status: {response.status_code}")
65+
66+
except httpx.TimeoutException:
67+
print("✅ Expected timeout (no receiver connected)")
68+
except Exception as e:
69+
print(f"❌ Unexpected error: {e}")
70+
71+
finally:
72+
print("🛑 Stopping Gateway...")
73+
await gateway.stop()
74+
print("✅ Gateway stopped")
75+
76+
77+
if __name__ == "__main__":
78+
asyncio.run(test_gateway_only())
Lines changed: 308 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,308 @@
1+
"""Comprehensive test script for Gateway and Receiver functionality."""
2+
3+
import asyncio
4+
import time
5+
6+
import httpx
7+
8+
# Note: websockets import removed as it's not needed for this test
9+
from anp_proxy.common.config import (
10+
AuthConfig,
11+
GatewayConfig,
12+
ReceiverConfig,
13+
TLSConfig,
14+
)
15+
from anp_proxy.examples.simple_fastapi_app import app as test_app
16+
from anp_proxy.gateway import GatewayServer
17+
from anp_proxy.receiver import ReceiverClient
18+
19+
20+
class ANPProxyTester:
21+
"""Comprehensive tester for ANP Proxy functionality."""
22+
23+
def __init__(self):
24+
self.gateway_port = 9080
25+
self.wss_port = 9765
26+
self.gateway = None
27+
self.receiver = None
28+
self.gateway_task = None
29+
self.receiver_task = None
30+
31+
async def setup_components(self):
32+
"""Setup Gateway and Receiver components with auth disabled."""
33+
print("🔧 Setting up components...")
34+
35+
# Create configuration with auth and TLS disabled for testing
36+
gateway_config = GatewayConfig(
37+
host="127.0.0.1",
38+
port=self.gateway_port,
39+
wss_host="127.0.0.1",
40+
wss_port=self.wss_port,
41+
auth=AuthConfig(enabled=False), # Disable authentication
42+
tls=TLSConfig(enabled=False), # Disable TLS for testing
43+
max_connections=10,
44+
timeout=30.0
45+
)
46+
47+
receiver_config = ReceiverConfig(
48+
gateway_url=f"ws://127.0.0.1:{self.wss_port}", # Use ws for testing
49+
auth=AuthConfig(enabled=False), # Disable authentication
50+
tls=TLSConfig(enabled=False), # Disable TLS for testing
51+
reconnect_delay=1.0,
52+
max_reconnect_attempts=3
53+
)
54+
55+
# Create components
56+
self.gateway = GatewayServer(gateway_config)
57+
self.receiver = ReceiverClient(receiver_config, test_app)
58+
59+
print("✅ Components configured (auth disabled)")
60+
61+
async def start_components(self):
62+
"""Start Gateway and Receiver asynchronously."""
63+
print("🚀 Starting Gateway and Receiver...")
64+
65+
# Start Gateway first
66+
self.gateway_task = asyncio.create_task(self.gateway.start())
67+
await asyncio.sleep(1) # Give gateway time to start
68+
69+
# Start Receiver
70+
self.receiver_task = asyncio.create_task(self.receiver.start())
71+
await asyncio.sleep(2) # Give receiver time to connect
72+
73+
print("✅ Both components started")
74+
75+
async def stop_components(self):
76+
"""Stop Gateway and Receiver."""
77+
print("🛑 Stopping components...")
78+
79+
tasks = []
80+
if self.receiver:
81+
tasks.append(asyncio.create_task(self.receiver.stop()))
82+
if self.gateway:
83+
tasks.append(asyncio.create_task(self.gateway.stop()))
84+
85+
if tasks:
86+
await asyncio.gather(*tasks, return_exceptions=True)
87+
88+
# Cancel running tasks
89+
for task in [self.gateway_task, self.receiver_task]:
90+
if task and not task.done():
91+
task.cancel()
92+
try:
93+
await task
94+
except asyncio.CancelledError:
95+
pass
96+
97+
print("✅ Components stopped")
98+
99+
async def test_basic_get_request(self):
100+
"""Test basic GET request through the proxy."""
101+
print("\n📡 Testing basic GET request...")
102+
103+
try:
104+
async with httpx.AsyncClient(timeout=10.0, proxy=None, trust_env=False) as client:
105+
response = await client.get(f"http://127.0.0.1:{self.gateway_port}/")
106+
107+
assert response.status_code == 200
108+
data = response.json()
109+
assert "message" in data
110+
assert "timestamp" in data
111+
112+
print(f"✅ GET / - Status: {response.status_code}")
113+
print(f" Response: {data}")
114+
return True
115+
116+
except Exception as e:
117+
print(f"❌ GET request failed: {e}")
118+
return False
119+
120+
async def test_health_check(self):
121+
"""Test health check endpoint."""
122+
print("\n🩺 Testing health check...")
123+
124+
try:
125+
async with httpx.AsyncClient(timeout=10.0, proxy=None, trust_env=False) as client:
126+
response = await client.get(f"http://127.0.0.1:{self.gateway_port}/health")
127+
128+
assert response.status_code == 200
129+
data = response.json()
130+
assert data["status"] == "healthy"
131+
132+
print(f"✅ GET /health - Status: {response.status_code}")
133+
print(f" Response: {data}")
134+
return True
135+
136+
except Exception as e:
137+
print(f"❌ Health check failed: {e}")
138+
return False
139+
140+
async def test_path_parameters(self):
141+
"""Test path parameters."""
142+
print("\n🛤️ Testing path parameters...")
143+
144+
try:
145+
async with httpx.AsyncClient(timeout=10.0, proxy=None, trust_env=False) as client:
146+
response = await client.get(f"http://127.0.0.1:{self.gateway_port}/echo/test-item?q=test-query")
147+
148+
assert response.status_code == 200
149+
data = response.json()
150+
assert data["item"] == "test-item"
151+
assert data["query"] == "test-query"
152+
153+
print(f"✅ GET /echo/test-item?q=test-query - Status: {response.status_code}")
154+
print(f" Response: {data}")
155+
return True
156+
157+
except Exception as e:
158+
print(f"❌ Path parameters test failed: {e}")
159+
return False
160+
161+
async def test_post_request(self):
162+
"""Test POST request with JSON body."""
163+
print("\n📮 Testing POST request...")
164+
165+
try:
166+
test_data = {"name": "ANP Proxy", "version": "1.0", "test": True}
167+
168+
async with httpx.AsyncClient(timeout=10.0, proxy=None, trust_env=False) as client:
169+
response = await client.post(
170+
f"http://127.0.0.1:{self.gateway_port}/echo",
171+
json=test_data
172+
)
173+
174+
assert response.status_code == 200
175+
data = response.json()
176+
assert data["method"] == "POST"
177+
assert "body" in data
178+
179+
print(f"✅ POST /echo - Status: {response.status_code}")
180+
print(f" Method: {data['method']}")
181+
print(f" Body received: {data['body'] is not None}")
182+
return True
183+
184+
except Exception as e:
185+
print(f"❌ POST request failed: {e}")
186+
return False
187+
188+
189+
190+
async def test_slow_response(self):
191+
"""Test slow response to verify timeout handling."""
192+
print("\n🐌 Testing slow response...")
193+
194+
try:
195+
async with httpx.AsyncClient(timeout=15.0, proxy=None, trust_env=False) as client:
196+
start_time = time.time()
197+
response = await client.get(f"http://127.0.0.1:{self.gateway_port}/slow-response")
198+
elapsed = time.time() - start_time
199+
200+
assert response.status_code == 200
201+
data = response.json()
202+
assert "message" in data
203+
assert elapsed >= 2.0 # Should take at least 2 seconds
204+
205+
print(f"✅ GET /slow-response - Status: {response.status_code}")
206+
print(f" Elapsed time: {elapsed:.2f}s")
207+
print(f" Response: {data['message']}")
208+
return True
209+
210+
except Exception as e:
211+
print(f"❌ Slow response test failed: {e}")
212+
return False
213+
214+
async def test_connection_status(self):
215+
"""Test that receiver is properly connected to gateway."""
216+
print("\n🔌 Testing receiver connection status...")
217+
218+
try:
219+
# Check if receiver is connected by trying to access gateway internals
220+
if self.gateway and self.receiver:
221+
print("✅ Gateway and Receiver components are running")
222+
# Additional check: see if we can make requests successfully
223+
await asyncio.sleep(1) # Give time for connection
224+
return True
225+
else:
226+
print("❌ Components not properly initialized")
227+
return False
228+
229+
except Exception as e:
230+
print(f"❌ Connection status test failed: {e}")
231+
return False
232+
233+
async def run_all_tests(self):
234+
"""Run comprehensive test suite."""
235+
print("🧪 Starting ANP Proxy comprehensive test suite")
236+
print("=" * 50)
237+
238+
# Setup and start components
239+
await self.setup_components()
240+
await self.start_components()
241+
242+
# Wait a bit for everything to stabilize
243+
await asyncio.sleep(3)
244+
245+
# Run tests
246+
tests = [
247+
("Basic GET Request", self.test_basic_get_request),
248+
("Health Check", self.test_health_check),
249+
("Path Parameters", self.test_path_parameters),
250+
("POST Request", self.test_post_request),
251+
("Slow Response (Timeout)", self.test_slow_response),
252+
("Connection Status", self.test_connection_status),
253+
]
254+
255+
results = []
256+
for test_name, test_func in tests:
257+
try:
258+
result = await test_func()
259+
results.append((test_name, result))
260+
except Exception as e:
261+
print(f"❌ {test_name} failed with exception: {e}")
262+
results.append((test_name, False))
263+
264+
# Print summary
265+
print("\n" + "=" * 50)
266+
print("📊 Test Results Summary:")
267+
passed = 0
268+
for test_name, result in results:
269+
status = "✅ PASS" if result else "❌ FAIL"
270+
print(f" {status} - {test_name}")
271+
if result:
272+
passed += 1
273+
274+
print(f"\n🎯 Overall: {passed}/{len(results)} tests passed")
275+
276+
# Cleanup
277+
await self.stop_components()
278+
279+
return passed == len(results)
280+
281+
282+
async def main():
283+
"""Main test function."""
284+
tester = ANPProxyTester()
285+
286+
try:
287+
success = await tester.run_all_tests()
288+
if success:
289+
print("\n🎉 All tests passed! Gateway and Receiver are working correctly.")
290+
return 0
291+
else:
292+
print("\n💥 Some tests failed. Check the logs above for details.")
293+
return 1
294+
295+
except KeyboardInterrupt:
296+
print("\n⏹️ Test interrupted by user")
297+
await tester.stop_components()
298+
return 1
299+
300+
except Exception as e:
301+
print(f"\n💥 Test suite failed with error: {e}")
302+
await tester.stop_components()
303+
return 1
304+
305+
306+
if __name__ == "__main__":
307+
exit_code = asyncio.run(main())
308+
exit(exit_code)

0 commit comments

Comments
 (0)