-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtests.py
More file actions
370 lines (323 loc) · 13.4 KB
/
Copy pathtests.py
File metadata and controls
370 lines (323 loc) · 13.4 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import mimetypes
import os
import socket
import unittest
CRLF = '\r\n'
KNOWN_TYPES = set(mimetypes.types_map.values())
class ResponseOkTestCase(unittest.TestCase):
"""unit tests for the response_ok method in our server
Becase this is a unit test case, it does not require the server to be
running.
"""
def call_function_under_test(self, body="", mimetype="text/plain"):
"""call the `response_ok` function from our http_server module"""
from http_server import response_ok
return response_ok(body=body, mimetype=mimetype)
def test_response_code(self):
ok = self.call_function_under_test()
expected = "200 OK"
actual = ok.split(CRLF)[0].split(' ', 1)[1].strip()
self.assertEqual(expected, actual)
def test_response_method(self):
ok = self.call_function_under_test()
expected = 'HTTP/1.1'
actual = ok.split(CRLF)[0].split(' ', 1)[0].strip()
self.assertEqual(expected, actual)
def test_response_has_content_type_header(self):
ok = self.call_function_under_test()
headers = ok.split(CRLF+CRLF, 1)[0].split(CRLF)[1:]
expected_name = 'content-type'
has_header = False
for header in headers:
name, value = header.split(':')
actual_name = name.strip().lower()
if actual_name == expected_name:
has_header = True
break
self.assertTrue(has_header)
def test_response_has_legitimate_content_type(self):
ok = self.call_function_under_test()
headers = ok.split(CRLF+CRLF, 1)[0].split(CRLF)[1:]
expected_name = 'content-type'
for header in headers:
name, value = header.split(':')
actual_name = name.strip().lower()
if actual_name == expected_name:
self.assertTrue(value.strip() in KNOWN_TYPES)
return
self.fail('no content type header found')
def test_passed_mimetype_in_response(self):
mimetypes = [
'image/jpeg', 'text/html', 'text/x-python',
]
header_name = 'content-type'
for expected in mimetypes:
ok = self.call_function_under_test(mimetype=expected)
headers = ok.split(CRLF+CRLF, 1)[0].split(CRLF)[1:]
for header in headers:
name, value = header.split(':')
if header_name == name.strip().lower():
actual = value.strip()
self.assertEqual(
expected,
actual,
"expected {0}, got {1}".format(expected, actual)
)
def test_passed_body_in_response(self):
bodies = [
"a body",
"a longer body\nwith two lines",
open("webroot/sample.txt", 'r').read(),
]
for expected in bodies:
ok = self.call_function_under_test(body=expected)
actual = ok.split(CRLF+CRLF, 1)[1]
self.assertEqual(
expected,
actual,
"expected {0}, got {1}".format(expected, actual))
class ResponseMethodNotAllowedTestCase(unittest.TestCase):
"""unit tests for the response_method_not_allowed function"""
def call_function_under_test(self):
"""call the `response_method_not_allowed` function"""
from http_server import response_method_not_allowed
return response_method_not_allowed()
def test_response_code(self):
resp = self.call_function_under_test()
expected = "405 Method Not Allowed"
actual = resp.split(CRLF)[0].split(' ', 1)[1].strip()
self.assertEqual(expected, actual)
def test_response_method(self):
resp = self.call_function_under_test()
expected = 'HTTP/1.1'
actual = resp.split(CRLF)[0].split(' ', 1)[0].strip()
self.assertEqual(expected, actual)
class ResponseNotFoundTestCase(unittest.TestCase):
"""unit tests for the response_not_found function"""
def call_function_under_test(self):
"""call the 'response_not_found' function"""
from http_server import response_not_found
return response_not_found()
def test_response_code(self):
resp = self.call_function_under_test()
expected = "404 Not Found"
actual = resp.split(CRLF)[0].split(' ', 1)[1].strip()
self.assertEqual(expected, actual)
def test_response_method(self):
resp = self.call_function_under_test()
expected = 'HTTP/1.1'
actual = resp.split(CRLF)[0].split(' ', 1)[0].strip()
self.assertEqual(expected, actual)
class ParseRequestTestCase(unittest.TestCase):
"""unit tests for the parse_request method"""
def call_function_under_test(self, request):
"""call the `parse_request` function"""
from http_server import parse_request
return parse_request(request)
def test_get_method(self):
"""verify that GET HTTP requests do not raise an error"""
request = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"
try:
self.call_function_under_test(request)
except (NotImplementedError, Exception), e:
self.fail('GET method raises an error {0}'.format(str(e)))
def test_bad_http_methods(self):
"""verify that non-GET HTTP methods raise a NotImplementedError"""
methods = ['POST', 'PUT', 'DELETE', 'HEAD']
request_template = "{0} / HTTP/1.1\r\nHost: example.com\r\n\r\n"
for method in methods:
request = request_template.format(method)
self.assertRaises(
NotImplementedError, self.call_function_under_test, request
)
def test_uri_returned(self):
"""verify that the parse_request function returns a URI"""
URIs = [
'/', '/a_web_page.html', '/sample.txt', '/images/sample_1.png',
]
request_tmplt = "GET {0} HTTP/1.1"
for expected in URIs:
request = request_tmplt.format(expected)
actual = self.call_function_under_test(request)
self.assertEqual(
expected,
actual,
"expected {0}, got {1}".format(expected, actual)
)
class ResolveURITestCase(unittest.TestCase):
"""unit tests for the resolve_uri function"""
def call_function_under_test(self, uri):
"""call the resolve_uri function"""
from http_server import resolve_uri
return resolve_uri(uri)
def test_directory_resource(self):
uri = '/'
expected_names = [
'a_web_page.html', 'images', 'make_time.py', 'sample.txt',
]
expected_mimetype = "text/plain"
actual_body, actual_mimetype = self.call_function_under_test(uri)
self.assertEqual(
expected_mimetype,
actual_mimetype,
'expected {0} got {1}'.format(expected_mimetype, actual_mimetype)
)
for expected in expected_names:
self.assertTrue(
expected in actual_body,
'"{0}" not in "{1}"'.format(expected, actual_body)
)
def test_file_resource(self):
uris_types = {
'/a_web_page.html': 'text/html',
'/make_time.py': 'text/x-python',
'/sample.txt': 'text/plain',
}
for uri, expected_mimetype in uris_types.items():
path = "webroot{0}".format(uri)
expected_body = open(path, 'rb').read()
actual_body, actual_mimetype = self.call_function_under_test(uri)
self.assertEqual(
expected_mimetype,
actual_mimetype,
'expected {0} got {1}'.format(
expected_mimetype, actual_mimetype
)
)
self.assertEqual(
expected_body,
actual_body,
'expected {0} got {1}'.format(
expected_mimetype, actual_mimetype
)
)
def test_image_resource(self):
names_types = {
'JPEG_example.jpg': 'image/jpeg',
'sample_1.png': 'image/png',
}
for filename, expected_mimetype in names_types.items():
uri = "/images/{0}".format(filename)
path = "webroot{0}".format(uri)
expected_body = open(path, 'rb').read()
actual_body, actual_mimetype = self.call_function_under_test(uri)
self.assertEqual(
expected_mimetype,
actual_mimetype,
'expected {0} got {1}'.format(
expected_mimetype, actual_mimetype
)
)
self.assertEqual(
expected_body,
actual_body,
'expected {0} got {1}'.format(
expected_mimetype, actual_mimetype
)
)
def test_missing_resource(self):
uri = "/missing.html"
self.assertRaises(ValueError, self.call_function_under_test, uri)
class HTTPServerFunctionalTestCase(unittest.TestCase):
"""functional tests of the HTTP Server
This test case interacts with the http server, and as such requires it to
be running in order for the tests to pass
"""
def send_message(self, message):
"""Attempt to send a message using the client and the test buffer
In case of a socket error, fail and report the problem
"""
from simple_client import client
response = ''
try:
response = client(message)
except socket.error, e:
if e.errno == 61:
msg = "Error: {0}, is the server running?"
self.fail(msg.format(e.strerror))
else:
self.fail("Unexpected Error: {0}".format(str(e)))
return response
def test_get_request(self):
message = CRLF.join(['GET / HTTP/1.1', 'Host: example.com', ''])
expected = '200 OK'
actual = self.send_message(message)
self.assertTrue(
expected in actual, '"{0}" not in "{1}"'.format(expected, actual)
)
def test_post_request(self):
message = CRLF.join(['POST / HTTP/1.1', 'Host: example.com', ''])
expected = '405 Method Not Allowed'
actual = self.send_message(message)
self.assertTrue(
expected in actual, '"{0}" not in "{1}"'.format(expected, actual)
)
def test_webroot_directory_resources(self):
"""verify that directory uris are properly served"""
message_tmpl = CRLF.join(['GET {0} HTTP/1.1', 'Host: example.com', ''])
root = "webroot"
for directory, directories, files in os.walk(root):
directory_uri = "/{0}".format(directory[len(root):])
message = message_tmpl.format(directory_uri)
actual = self.send_message(message)
# verify that directory listings are correct
self.assertTrue(
"200 OK" in actual,
"request for {0} did not result in OK".format(directory_uri))
for expected in directories + files:
self.assertTrue(
expected in actual,
'"{0}" not in "{1}"'.format(expected, actual)
)
def test_webroot_file_uris(self):
"""verify that file uris are properly served"""
message_tmpl = CRLF.join(['GET {0} HTTP/1.1', 'Host: example.com', ''])
root = "webroot"
for directory, directories, files in os.walk(root):
directory_uri = "/{0}".format(directory[len(root):])
# verify that all files are delivered correctly
for filename in files:
# file as local resource and as web URI
file_path = os.path.sep.join([directory, filename])
if directory_uri != '/':
file_uri = '/'.join([directory_uri, filename])
else:
file_uri = '/{0}'.format(filename)
# set up expectations for this file
expected_body = open(file_path, 'rb').read()
expected_mimetype = mimetypes.types_map[
os.path.splitext(filename)[1]
]
# make a request for this file as a uri
message = message_tmpl.format(file_uri)
actual = self.send_message(message)
# verify that request is OK
self.assertTrue(
"200 OK" in actual,
"request for {0} did not result in OK".format(
directory_uri
)
)
self.assertTrue(
expected_mimetype in actual,
"mimetype {0} not in response for {1}".format(
expected_mimetype, file_uri
)
)
self.assertTrue(
expected_body in actual,
"body of {0} not in response for {1}".format(
file_path, file_uri
)
)
def test_missing_resource(self):
message = CRLF.join(
['GET /missing.html HTTP/1.1', 'Host: example.com', '']
)
expected = '404 Not Found'
actual = self.send_message(message)
self.assertTrue(
expected in actual, '"{0}" not in "{1}"'.format(expected, actual)
)
if __name__ == '__main__':
unittest.main()