What is the best way to run functional tests of a WSGI application?
I am writing a couple of simple WSGI applications to get a feel for the standard, and I am to the point where I want to test if my applications are working as expected. Now I am trying to find the best way to start and stop the server that hosts these applications.
My first thought was to run SimpleServer
from wsgiref
in a method setUp
and close it in tearDown
. Since the serve_forever
blocks, I did it in a separate Thread
. Unfortunately, if I use serve_forever
to start the server, the secondary thread never dies and it turns out that there is threading
no way to kill Thread
.
I am now considering using something like this as my run
server implementation Thread
:
while keep_going:
httpd.handle_request()
where keep_going
is the variable I set in True
in mine setUp
and set in False
in mine tearDown
.
Is there a better way? I was hoping to write these applications and tests using only the standard library - it is better to understand what I am abstracting when I use lib / framework, but that seems like a terrible problem.
Thanks.
a source to share
The best way to test WSGI applications is WebTest , which removes the need to run test servers for your application. Instead, it allows you to make HTTP requests to your WSGI application as method calls on an object TestApp
:
>>> from webtest import TestApp
>>> from myapp import my_wsgi_app
>>> app = TestApp(my_wsgi_app)
>>> res = app.get('/')
>>> res.status
'200 OK'
>>> res.status_int
200
>>> params = {'email': 'foo@example.com', 'password': 'foo', }
>>> res = app.post('/login/', params)
>>> res.status_int
302
I usually have a base test class that will add an attribute self.app
to my test cases that points to an instance TestApp
for the WSGI application I'm testing. So my test methods look something like this:
def test_index_page(self):
res = self.app.get('/')
self.failUnlessEqual(res.status_int, 200)
a source to share