This class runs a django test server in another thread. This is very useful for e.g. selenium integration. Simple to integrate into django test framework.
Usage:
server = TestServerThread("127.0.0.1", "8081")
server.start()
# Run tests e.g.
req = urllib.urlopen("http://127.0.0.1:8081")
contents = req.read()
server.stop()
ps. I don't actually double space my code :). Not sure whats up with that!
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()
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.