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 | import threading
import urllib
from django.core.servers import basehttp
from django.core.handlers.wsgi import WSGIHandler
class TestServerThread(threading.Thread):
"""
Thread for running a http server while tests are running.
Taken from: http://code.djangoproject.com/attachment/ticket/2879/django_live_server_r7936.diff
with some modifications to avoid patching django.
"""
def __init__(self, address, port):
self.address = address
self.port = port
self._started = threading.Event()
self._stopped = False
self._error = None
super(TestServerThread, self).__init__()
def start(self):
""" Start the server thread and wait for it to be ready """
super(TestServerThread, self).start()
self._started.wait()
if self._error:
raise self._error
def stop(self):
""" Stop the server """
self._stopped = True
# Send an http request to wake the server
url = urllib.urlopen('http://%s:%d/fake/request/' % (self.address, self.port))
url.read()
# Wait for server to finish
self.join(5)
if self._error:
raise self._error
def run(self):
""" Sets up test server and database and loops over handling http requests. """
try:
handler = basehttp.AdminMediaHandler(WSGIHandler())
server_address = (self.address, self.port)
httpd = basehttp.WSGIServer(server_address, basehttp.WSGIRequestHandler)
httpd.set_app(handler)
except basehttp.WSGIServerException, e:
self._error = e
finally:
self._started.set()
# Loop until we get a stop event.
while not self._stopped:
httpd.handle_request()
|
Comments
I've made a context manager to make even more easy use this snippet. It's at https://gist.github.com/1511536. With this, you can use:
#