So, I wanted to do some very simple functional tests using a real-ish webserver, but I didn’t want to have to depend on twisted.web or an external setup. So I did this:
from wsgiref.simple_server import make_server
from multiprocessing import Process, Queue
class TestPosting(unittest.TestCase):
# FIXME: THIS IS TERROBLE
def setUp(self):
self.q = Queue()
self.p = Process(target=self.serve, args=(self.q,))
self.p.start()
self.port = self.q.get()
def serve(self, q):
httpd = make_server('', 0, simple_app_maker(q))
port = httpd.server_port
q.put(port)
httpd.serve_forever()
def tearDown(self):
self.p.terminate()
def test_something(self):
url = "http://locahost:%s/whatever" % self.port
...
result = self.queue.get()
# make some assertions on the results
def simple_app_maker(queue):
def simple_app(environ, start_response):
post_env = environ.copy()
post_env['QUERY_STRING'] = ''
post = cgi.FieldStorage(
fp=environ['wsgi.input'],
environ=post_env,
keep_blank_values=True
)
q.put(...) # put the relevant stuff in the queue
status = '200 OK'
response_headers = [('Content-type','text/plain')]
start_response(status, response_headers)
return ['Hello world!\n']
return simple_app
just have the simple_app function put whatever you want to check in the queue, and your tests pull it out and make some assertions. Super nasty, but it actually works!