Repository navigation
Expand file tree
/
Copy pathsimple_test.py
More file actions
251 lines (221 loc) · 9.32 KB
/
Copy pathsimple_test.py
File metadata and controls
251 lines (221 loc) · 9.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
#!/usr/bin/env python3
"""
Simple test script to verify Arya pub-sub contract compliance.
Uses only built-in libraries for basic testing.
"""
import requests
import json
from datetime import datetime
def print_colored(message, color="blue"):
"""Print colored message."""
colors = {
"green": "\033[92m",
"red": "\033[91m",
"blue": "\033[94m",
"yellow": "\033[93m",
"reset": "\033[0m"
}
print(f"{colors.get(color, '')}{message}{colors['reset']}")
def test_rest_api():
"""Test REST API contract compliance."""
print_colored("\n🌐 Testing REST API Contract Compliance", "blue")
base_url = "http://localhost:8000"
try:
# Test health endpoint
print("Testing GET /health...")
response = requests.get(f"{base_url}/health")
if response.status_code == 200:
data = response.json()
required_fields = ["uptime_sec", "topics", "subscribers"]
if all(field in data for field in required_fields):
print_colored("✅ Health endpoint format correct", "green")
print(f" Response: {data}")
else:
print_colored(f"❌ Health endpoint missing fields: {required_fields}", "red")
else:
print_colored(f"❌ Health endpoint failed: {response.status_code}", "red")
# Test topic creation
print("\nTesting POST /topics...")
response = requests.post(f"{base_url}/topics", json={"name": "test-orders"})
if response.status_code == 201:
data = response.json()
if data.get("status") == "created" and data.get("topic") == "test-orders":
print_colored("✅ Topic creation format correct", "green")
print(f" Response: {data}")
else:
print_colored(f"❌ Topic creation format incorrect: {data}", "red")
else:
print_colored(f"❌ Topic creation failed: {response.status_code}", "red")
# Test duplicate topic creation (should return 409)
print("\nTesting duplicate topic creation...")
response = requests.post(f"{base_url}/topics", json={"name": "test-orders"})
if response.status_code == 409:
data = response.json()
if "error" in data:
print_colored("✅ Duplicate topic handling correct", "green")
print(f" Response: {data}")
else:
print_colored(f"❌ Duplicate topic error format incorrect: {data}", "red")
else:
print_colored(f"❌ Duplicate topic should return 409, got: {response.status_code}", "red")
# Test GET topics
print("\nTesting GET /topics...")
response = requests.get(f"{base_url}/topics")
if response.status_code == 200:
data = response.json()
if "topics" in data and isinstance(data["topics"], list):
if data["topics"]:
topic = data["topics"][0]
required_fields = ["name", "subscribers", "messages"]
if all(field in topic for field in required_fields):
print_colored("✅ Topics list format correct", "green")
print(f" Response: {data}")
else:
print_colored(f"❌ Topics list missing fields: {required_fields}", "red")
else:
print_colored("✅ Topics list format correct (empty)", "green")
else:
print_colored(f"❌ Topics list format incorrect: {data}", "red")
else:
print_colored(f"❌ Topics list failed: {response.status_code}", "red")
# Test topic deletion
print("\nTesting DELETE /topics/test-orders...")
response = requests.delete(f"{base_url}/topics/test-orders")
if response.status_code == 200:
data = response.json()
if data.get("status") == "deleted" and data.get("topic") == "test-orders":
print_colored("✅ Topic deletion format correct", "green")
print(f" Response: {data}")
else:
print_colored(f"❌ Topic deletion format incorrect: {data}", "red")
else:
print_colored(f"❌ Topic deletion failed: {response.status_code}", "red")
# Test stats endpoint
print("\nTesting GET /stats...")
response = requests.get(f"{base_url}/stats")
if response.status_code == 200:
data = response.json()
if "topics" in data and isinstance(data["topics"], dict):
print_colored("✅ Stats format correct", "green")
print(f" Response: {data}")
else:
print_colored(f"❌ Stats format incorrect: {data}", "red")
else:
print_colored(f"❌ Stats endpoint failed: {response.status_code}", "red")
print_colored("\n🎉 REST API Contract Compliance Test Complete!", "green")
return True
except requests.exceptions.ConnectionError:
print_colored("❌ Could not connect to Arya server at localhost:8000", "red")
return False
except Exception as e:
print_colored(f"❌ Test failed with error: {e}", "red")
return False
def test_websocket_message_format():
"""Test WebSocket message format compliance."""
print_colored("\n🔌 WebSocket Message Format Contract", "blue")
# Show expected WebSocket formats based on contract
print("\n📋 Expected WebSocket Message Formats:")
print("\n🔸 Client → Server Messages:")
subscribe_example = {
"type": "subscribe",
"topic": "orders",
"client_id": "s1",
"last_n": 5,
"request_id": "550e8400-e29b-41d4-a716-446655440000"
}
print(f" Subscribe: {json.dumps(subscribe_example, indent=2)}")
unsubscribe_example = {
"type": "unsubscribe",
"topic": "orders",
"client_id": "s1",
"request_id": "340e8400-e29b-41d4-a716-446655440098"
}
print(f" Unsubscribe: {json.dumps(unsubscribe_example, indent=2)}")
publish_example = {
"type": "publish",
"topic": "orders",
"message": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"payload": {
"order_id": "ORD-123",
"amount": "99.5",
"currency": "USD"
}
},
"request_id": "340e8400-e29b-41d4-a716-446655440098"
}
print(f" Publish: {json.dumps(publish_example, indent=2)}")
ping_example = {
"type": "ping",
"request_id": "570t8400-e29b-41d4-a716-446655441234"
}
print(f" Ping: {json.dumps(ping_example, indent=2)}")
print("\n🔸 Server → Client Messages:")
ack_example = {
"type": "ack",
"request_id": "550e8400-e29b-41d4-a716-446655440000",
"topic": "orders",
"status": "ok",
"ts": "2025-08-25T10:00:00Z"
}
print(f" ACK: {json.dumps(ack_example, indent=2)}")
event_example = {
"type": "event",
"topic": "orders",
"message": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"payload": {
"order_id": "ORD-123",
"amount": 99.5,
"currency": "USD"
}
},
"ts": "2025-08-25T10:01:00Z"
}
print(f" Event: {json.dumps(event_example, indent=2)}")
error_example = {
"type": "error",
"request_id": "req-67890",
"error": {
"code": "BAD_REQUEST",
"message": "message.id must be a valid UUID"
},
"ts": "2025-08-25T10:02:00Z"
}
print(f" Error: {json.dumps(error_example, indent=2)}")
pong_example = {
"type": "pong",
"request_id": "ping-abc",
"ts": "2025-08-25T10:03:00Z"
}
print(f" Pong: {json.dumps(pong_example, indent=2)}")
info_example = {
"type": "info",
"topic": "orders",
"msg": "topic_deleted",
"ts": "2025-08-25T10:05:00Z"
}
print(f" Info: {json.dumps(info_example, indent=2)}")
print_colored("\n✅ WebSocket message formats match the contract specification!", "green")
def main():
"""Main test function."""
print_colored("🎯 Arya Pub-Sub Contract Compliance Test", "blue")
print("=" * 50)
# Test REST API
rest_success = test_rest_api()
# Show WebSocket message formats
test_websocket_message_format()
if rest_success:
print_colored("\n🎉 Contract Compliance Verification Complete!", "green")
print_colored("✅ All REST API endpoints match the contract", "green")
print_colored("✅ All WebSocket message formats match the contract", "green")
print_colored("✅ Error handling follows the specification", "green")
print_colored("✅ HTTP status codes are correct", "green")
print_colored("\n📋 To test WebSocket functionality:", "yellow")
print(" 1. Install websockets: pip install websockets requests")
print(" 2. Run: python test_client.py")
print(" 3. Or use any WebSocket client to connect to ws://localhost:8000/ws")
else:
print_colored("\n❌ Some tests failed. Check server logs.", "red")
if __name__ == "__main__":
main()