This repository has been archived by the owner on Nov 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
mock_httpd.py
executable file
·73 lines (54 loc) · 1.95 KB
/
mock_httpd.py
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
#!/usr/bin/env python
# Using BaseHTTPServer for mocking servers
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from threading import Thread
from time import sleep, time
from urllib import urlopen
import httplib
import re
def wait_for_server(url, timeout=5):
'''Wait for server to become available.'''
start = time()
while time() - start < timeout:
try:
urlopen(url)
return
except IOError:
sleep(0.1)
raise ValueError('no server at {}'.format(url))
def run_server(config, port=0, ctype='application/json'):
'''Run HTTP server, return server object.
Config is a dictionary path -> data
If port is 0, a random free port will be selected (you can access the port
from server.server_port, or the base url in server.url)
ctype is the Content-Type header returned by the server
'''
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
# Normalize path
path = re.sub('/+', '/', self.path)
if path not in config:
self.send_error(httplib.NOT_FOUND, self.path + ' not found')
return
self.send_response(httplib.OK)
self.send_header('Content-Type', ctype)
self.end_headers()
self.wfile.write(config[path])
def log_message(self, *args):
'''Be quiet'''
pass
server = HTTPServer(('', port), Handler)
server.url = 'http://localhost:{}'.format(server.server_port)
t = Thread(target=server.serve_forever)
t.daemon = True
t.start()
wait_for_server('{}/{}'.format(server.url, config.keys()[0]))
return server
def _test():
'''Example on how to use'''
path, payload = '/hello', 'hello there'
server = run_server({path: payload})
data = urlopen('{}/{}'.format(server.url, path)).read()
assert data == payload, '{} != {}'.format(data, payload)
if __name__ == '__main__':
_test()