-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadditional_tests.py
More file actions
212 lines (177 loc) Β· 8.52 KB
/
additional_tests.py
File metadata and controls
212 lines (177 loc) Β· 8.52 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
#!/usr/bin/env python3
"""
Additional BitTorrent Protocol Compliance Tests
"""
import asyncio
import aiohttp
import json
import time
import hashlib
import random
import bencode
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv('/app/frontend/.env')
BASE_URL = os.getenv('REACT_APP_BACKEND_URL', 'http://localhost:8001')
API_BASE = f"{BASE_URL}/api"
async def test_malformed_requests():
"""Test error handling for malformed requests"""
print("π Testing malformed request handling...")
async with aiohttp.ClientSession() as session:
# Test missing required parameters
test_cases = [
{"name": "Missing info_hash", "params": {"peer_id": "test", "port": 6881}},
{"name": "Missing peer_id", "params": {"info_hash": "a" * 40, "port": 6881}},
{"name": "Missing port", "params": {"info_hash": "a" * 40, "peer_id": "test"}},
{"name": "Invalid port", "params": {"info_hash": "a" * 40, "peer_id": "test", "port": "invalid"}},
{"name": "Invalid info_hash length", "params": {"info_hash": "short", "peer_id": "test", "port": 6881}},
]
for test_case in test_cases:
try:
async with session.get(f"{API_BASE}/announce", params=test_case["params"]) as response:
if response.status == 500:
content = await response.read()
try:
decoded = bencode.decode(content)
if "failure reason" in decoded:
print(f"β
{test_case['name']}: Proper error handling")
else:
print(f"β {test_case['name']}: No failure reason in response")
except:
print(f"β {test_case['name']}: Invalid bencoded error response")
else:
print(f"β {test_case['name']}: Expected error but got status {response.status}")
except Exception as e:
print(f"β {test_case['name']}: Exception - {e}")
async def test_peer_aggregation():
"""Test cross-protocol peer aggregation"""
print("\nπ Testing cross-protocol peer aggregation...")
info_hash = hashlib.sha1(b"test_aggregation").hexdigest()
async with aiohttp.ClientSession() as session:
# Add peers via HTTP
http_peers = []
for i in range(3):
peer_id = f"-HTTP-{i:012d}"
port = 6881 + i
params = {
'info_hash': info_hash,
'peer_id': peer_id,
'port': port,
'uploaded': 0,
'downloaded': 0,
'left': 1000000,
'event': 'started'
}
async with session.get(f"{API_BASE}/announce", params=params) as response:
if response.status == 200:
http_peers.append({"peer_id": peer_id, "port": port})
# Check swarm stats
async with session.get(f"{API_BASE}/swarms") as response:
if response.status == 200:
data = await response.json()
swarms = data.get('swarms', [])
target_swarm = next((s for s in swarms if s['info_hash'] == info_hash), None)
if target_swarm:
print(f"β
Peer aggregation: {target_swarm['total_peers']} peers in swarm")
print(f" Seeders: {target_swarm['seeders']}, Leechers: {target_swarm['leechers']}")
else:
print("β Peer aggregation: Swarm not found")
async def test_bep3_compliance():
"""Test BEP-3 (BitTorrent Protocol) compliance"""
print("\nπ Testing BEP-3 compliance...")
info_hash = hashlib.sha1(b"bep3_test").hexdigest()
peer_id = "-BEP3-" + "0" * 14
async with aiohttp.ClientSession() as session:
params = {
'info_hash': info_hash,
'peer_id': peer_id,
'port': 6881,
'uploaded': 0,
'downloaded': 0,
'left': 1073741824,
'event': 'started',
'numwant': 50,
'compact': 1 # Request compact format
}
async with session.get(f"{API_BASE}/announce", params=params) as response:
if response.status == 200:
content = await response.read()
try:
decoded = bencode.decode(content)
# Check BEP-3 required fields
required_fields = ['interval', 'complete', 'incomplete']
optional_fields = ['min interval', 'peers', 'tracker id']
missing_required = [f for f in required_fields if f not in decoded]
present_optional = [f for f in optional_fields if f in decoded]
if not missing_required:
print(f"β
BEP-3 compliance: All required fields present")
print(f" Optional fields: {present_optional}")
# Check interval values
interval = decoded.get('interval', 0)
min_interval = decoded.get('min interval', 0)
if interval > 0:
print(f"β
Valid interval: {interval} seconds")
else:
print(f"β Invalid interval: {interval}")
if min_interval > 0:
print(f"β
Valid min interval: {min_interval} seconds")
else:
print(f"β BEP-3 compliance: Missing required fields: {missing_required}")
except Exception as e:
print(f"β BEP-3 compliance: Failed to decode response - {e}")
else:
print(f"β BEP-3 compliance: HTTP {response.status}")
async def test_performance_under_load():
"""Test performance under concurrent load"""
print("\nβ‘ Testing performance under load...")
info_hash = hashlib.sha1(b"load_test").hexdigest()
async def make_request(session, peer_num):
peer_id = f"-LOAD-{peer_num:010d}"
port = 6881 + (peer_num % 1000)
params = {
'info_hash': info_hash,
'peer_id': peer_id,
'port': port,
'uploaded': random.randint(0, 1000000),
'downloaded': random.randint(0, 1000000),
'left': random.randint(0, 1000000),
'event': random.choice(['started', 'completed', 'stopped'])
}
start_time = time.time()
try:
async with session.get(f"{API_BASE}/announce", params=params) as response:
response_time = time.time() - start_time
return response.status == 200, response_time
except:
return False, time.time() - start_time
async with aiohttp.ClientSession() as session:
# Test with 50 concurrent requests
start_time = time.time()
tasks = [make_request(session, i) for i in range(50)]
results = await asyncio.gather(*tasks, return_exceptions=True)
total_time = time.time() - start_time
successful = sum(1 for result in results if isinstance(result, tuple) and result[0])
response_times = [result[1] for result in results if isinstance(result, tuple)]
if response_times:
avg_response_time = sum(response_times) / len(response_times)
max_response_time = max(response_times)
print(f"β
Load test: {successful}/50 requests successful")
print(f" Total time: {total_time:.3f}s")
print(f" Avg response time: {avg_response_time:.3f}s")
print(f" Max response time: {max_response_time:.3f}s")
print(f" Requests/second: {50/total_time:.1f}")
else:
print("β Load test: No successful requests")
async def main():
"""Run additional tests"""
print("π§ͺ Running Additional BitTorrent Protocol Tests")
print("=" * 60)
await test_malformed_requests()
await test_peer_aggregation()
await test_bep3_compliance()
await test_performance_under_load()
print("\n" + "=" * 60)
print("β
Additional tests completed")
if __name__ == "__main__":
asyncio.run(main())