-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_server.py
More file actions
273 lines (216 loc) · 8.7 KB
/
Copy pathtest_server.py
File metadata and controls
273 lines (216 loc) · 8.7 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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#!/usr/bin/env python3
# Test script for HTTP server assignment
# Tests GET, POST, security, and error handling
import requests
import json
import time
import threading
import os
from concurrent.futures import ThreadPoolExecutor
def test_basic_functionality():
# test basic server functionality
print("🧪 Testing Basic Functionality...")
base_url = "http://localhost:8080"
# Test GET requests
try:
# Test home page
response = requests.get(f"{base_url}/")
assert response.status_code == 200
assert "Multi-threaded HTTP Server" in response.text
print("✅ GET / - Home page served correctly")
# Test HTML files
response = requests.get(f"{base_url}/about.html")
assert response.status_code == 200
print("✅ GET /about.html - HTML file served correctly")
# Test text file download
response = requests.get(f"{base_url}/sample.txt")
assert response.status_code == 200
assert response.headers['content-type'] == 'application/octet-stream'
print("✅ GET /sample.txt - Text file download works")
# Test image files
response = requests.get(f"{base_url}/logo.png")
assert response.status_code == 200
assert response.headers['content-type'] == 'application/octet-stream'
print("✅ GET /logo.png - PNG file download works")
response = requests.get(f"{base_url}/photo.jpg")
assert response.status_code == 200
assert response.headers['content-type'] == 'application/octet-stream'
print("✅ GET /photo.jpg - JPEG file download works")
except Exception as e:
print(f"❌ Basic functionality test failed: {e}")
return False
return True
def test_post_functionality():
# test POST request functionality
print("\n🧪 Testing POST Functionality...")
base_url = "http://localhost:8080"
try:
# Test JSON upload
test_data = {
"name": "test_user",
"email": "test@example.com",
"message": "This is a test message",
"timestamp": "2024-03-15T10:30:00Z"
}
response = requests.post(
f"{base_url}/upload",
headers={'Content-Type': 'application/json'},
data=json.dumps(test_data)
)
assert response.status_code == 201
result = response.json()
assert result['status'] == 'success'
assert 'filepath' in result
print("✅ POST /upload - JSON upload works correctly")
# Test invalid JSON
response = requests.post(
f"{base_url}/upload",
headers={'Content-Type': 'application/json'},
data="invalid json"
)
assert response.status_code == 400
print("✅ POST /upload - Invalid JSON rejected correctly")
# Test non-JSON content
response = requests.post(
f"{base_url}/upload",
headers={'Content-Type': 'text/plain'},
data="plain text"
)
assert response.status_code == 415
print("✅ POST /upload - Non-JSON content rejected correctly")
except Exception as e:
print(f"❌ POST functionality test failed: {e}")
return False
return True
def test_security_features():
# test security features
print("\n🧪 Testing Security Features...")
base_url = "http://localhost:8080"
try:
# Test path traversal protection
response = requests.get(f"{base_url}/../etc/passwd")
assert response.status_code == 403
print("✅ Path traversal protection - ../etc/passwd blocked")
response = requests.get(f"{base_url}/./././../config")
assert response.status_code == 403
print("✅ Path traversal protection - ./././../config blocked")
# Test host validation
response = requests.get(f"{base_url}/", headers={'Host': 'evil.com'})
assert response.status_code == 403
print("✅ Host validation - evil.com blocked")
# Test missing host header
response = requests.get(f"{base_url}/", headers={'Host': ''})
assert response.status_code == 403
print("✅ Host validation - empty host blocked")
except Exception as e:
print(f"❌ Security features test failed: {e}")
return False
return True
def test_error_handling():
# test error handling
print("\n🧪 Testing Error Handling...")
base_url = "http://localhost:8080"
try:
# Test 404 Not Found
response = requests.get(f"{base_url}/nonexistent.html")
assert response.status_code == 404
print("✅ 404 Not Found - Non-existent file handled correctly")
# Test 405 Method Not Allowed
response = requests.put(f"{base_url}/index.html")
assert response.status_code == 405
print("✅ 405 Method Not Allowed - PUT method rejected")
response = requests.delete(f"{base_url}/index.html")
assert response.status_code == 405
print("✅ 405 Method Not Allowed - DELETE method rejected")
except Exception as e:
print(f"❌ Error handling test failed: {e}")
return False
return True
def test_concurrent_requests():
# test concurrent request handling
print("\n🧪 Testing Concurrent Requests...")
base_url = "http://localhost:8080"
def make_request():
try:
response = requests.get(f"{base_url}/sample.txt", timeout=10)
return response.status_code == 200
except:
return False
try:
# Test 10 concurrent requests
with ThreadPoolExecutor(max_workers=10) as executor:
futures = [executor.submit(make_request) for _ in range(10)]
results = [future.result() for future in futures]
success_count = sum(results)
print(f"✅ Concurrent requests - {success_count}/10 requests successful")
if success_count >= 8: # Allow for some failures
return True
else:
print("❌ Too many concurrent request failures")
return False
except Exception as e:
print(f"❌ Concurrent requests test failed: {e}")
return False
def test_binary_file_integrity():
# test binary file transfer integrity
print("\n🧪 Testing Binary File Integrity...")
base_url = "http://localhost:8080"
try:
# Test text file integrity
response = requests.get(f"{base_url}/sample.txt")
assert response.status_code == 200
# Check if content contains expected text
content = response.text
assert "Multi-threaded HTTP Server Test File" in content
assert "Binary file transfer" in content
print("✅ Text file integrity - Content preserved correctly")
# Test image file headers
response = requests.get(f"{base_url}/logo.png")
assert response.status_code == 200
assert 'content-disposition' in response.headers
assert 'attachment' in response.headers['content-disposition']
print("✅ Image file headers - Download headers set correctly")
except Exception as e:
print(f"❌ Binary file integrity test failed: {e}")
return False
return True
def main():
# run all tests
print("🚀 Starting HTTP Server Tests")
print("=" * 50)
# Check if server is running
try:
response = requests.get("http://localhost:8080/", timeout=5)
if response.status_code != 200:
print("❌ Server is not responding correctly")
return
except:
print("❌ Server is not running. Please start the server first:")
print(" python3 server.py")
return
print("✅ Server is running and responding")
# Run all tests
tests = [
test_basic_functionality,
test_post_functionality,
test_security_features,
test_error_handling,
test_concurrent_requests,
test_binary_file_integrity
]
passed = 0
total = len(tests)
for test in tests:
try:
if test():
passed += 1
except Exception as e:
print(f"❌ Test {test.__name__} failed with exception: {e}")
print("\n" + "=" * 50)
print(f"🏁 Test Results: {passed}/{total} tests passed")
if passed == total:
print("🎉 All tests passed! Server is working correctly.")
else:
print("⚠️ Some tests failed. Check the server implementation.")
if __name__ == "__main__":
main()