Last Updated: February 25, 2016
·
620
· __imom0

WSGI at a Glance by Fixing my Unittests

Nowadays, I started on a new project and tried a lot of things that I was not familar with before, like plim, stylus, coffee and sqlalchemy.But what stuck me was that I cannot set up my unittests at first.

We used to run webtests with paste, treating it as the default testapp.We can login as a user by passing extra_environ={'REMOTE_USER': 'imom0'} to it.For example, we tested a django form this way before:

app = TestApp(extra_environ={'REMOTE_USER': 'imom0'}) 
resp = app.get('/my/precious/')
csrf_token = resp.form['csrfmiddlewaretoken'].value
resp = app.post('/my/precious/', {'csrfmiddlewaretoken': csrf_token, ...}, extra_environ=...)

So twisted, isn't it?

We cannot use django testapp for that extra auth infomation handled by our customized paste testapp.On the other hand, when using paste testapp to test flask and wtforms(flask-wtf), the flag WTF_CSRF_ENABLED seems to be True forever, you can get nothing but 403s.

I think I'd better use flask's testapp or django's testapp instead, so the problem turns to how to set extra environ to them.

After I viewed the source code of encapsulated paste testapp, the functionality was added by:

from appengine.utils import set_environ
# in __call__ of the wsgi application
set_environ(environ)

Briefly, I regard WSGI applications as things callable who take (environ, callback) as inputs and always return something iterable.

First, I patched werkzeug._internel._get_environ with adding set_environ function after the original.But better practice is wrapping the wsgi application with middleware.