forked from mathisonian/simple-testing-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimpletestingserver.py
More file actions
executable file
·92 lines (75 loc) · 2.96 KB
/
simpletestingserver.py
File metadata and controls
executable file
·92 lines (75 loc) · 2.96 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
#!/usr/bin/env python3
from http.server import BaseHTTPRequestHandler
from http.server import HTTPServer
import cgi
PORT = 8003
FILE_PREFIX = "."
if __name__ == "__main__":
try:
import argparse
parser = argparse.ArgumentParser(description = 'A simple fake server for testing your API client.')
parser.add_argument('-p', '--port', type = int, dest = "PORT",
help = 'the port to run the server on; defaults to 8003')
parser.add_argument('--path', type = str, dest = "PATH",
help = 'the folder to find the json files')
args = parser.parse_args()
if args.PORT:
PORT = args.PORT
if args.PATH:
FILE_PREFIX = args.PATH
except TypeError:
# Could not successfully import argparse or something
pass
class JSONRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
# send response code:
self.send_response(200)
# send headers:
self.send_header("Content-type", "application/json")
# send a blank line to end headers:
self.wfile.write("\n")
try:
output = open(FILE_PREFIX + "/" + self.path[1:] + ".json", 'r').read()
except IOError:
output = "{'error': 'Could not find file " + self.path[1:] + ".json'" + "}"
self.wfile.write(output)
def do_POST(self):
if self.path == "/success":
response_code = 200
elif self.path == "/error":
response_code = 500
else:
try:
response_code = int(self.path[1:])
except ValueError:
response_code = 201
try:
self.send_response(response_code)
self.wfile.write('Content-Type: application/json\n')
self.wfile.write('Client: %s\n' % str(self.client_address))
self.wfile.write('User-agent: %s\n' % str(self.headers['user-agent']))
self.wfile.write('Path: %s\n' % self.path)
self.end_headers()
form = cgi.FieldStorage(
fp = self.rfile,
headers = self.headers,
environ = {'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
self.wfile.write('{\n')
first_key = True
for field in form.keys():
if not first_key:
self.wfile.write(',\n')
else:
self.wfile.write('\n')
first_key = False
self.wfile.write('"%s":"%s"' % (field, form[field].value))
self.wfile.write('\n}')
except OSError as err:
print("OS error: {0}".format(err))
self.send_response(500)
else:
self.send_response(500)
server = HTTPServer(("localhost", PORT), JSONRequestHandler)
server.serve_forever()