Well, I think I've succeeded in writing the world's most trivial middleware. :-) Once I got into this, I realized that I didn't want to re-issue a request just to dump the environ. Instead, I save off the environ on every request and access it as needed.
<br><br>One issue that comes up with this approach is EnvPrinter will have to be the last middleware in the stack or the environ won't be complete; the test author will just have to know this requirement. Of course, it's possible someone might want to dump the environ from the middle of the stack, too, so maybe this is more of a feature than a bug.
<br><br>A working example is below. I'm including everything in one script as a demo, with a namespace hack to show where I'd put things in a finished product. <br><br>If you don't see any design flaws in this, I can work on patches for a finished product if you'd like.
<br><br>thanks,<br>-Ken<br><br><br><br>import twill<br>import twill.extensions<br><br>try:<br> import wsgi_intercept<br>except ImportError:<br> from twill import wsgi_intercept<br><br># Hack up a psuedo-module for twill_wsgi namespace,
<br># to show where I'd be putting things eventually.<br>class X(object): pass<br>twill.extensions.twill_wsgi = X()<br><br>def print_env(env_var):<br> return wsgi_intercept.last_request_environ[env_var]<br>twill.extensions.twill_wsgi.print_environ
= print_env<br><br><br>wsgi_intercept.last_request_environ = None<br>class EnvPrinter:<br> """Super simple middleware to save off the request's wsgi environ."""<br><br> def __init__(self, app):
<br> self.wrapped_app = app<br><br> def __call__(self, environ, start_response):<br> global last_request_environ<br> wsgi_intercept.last_request_environ = environ<br><br> return self.wrapped_app
(environ, start_response)<br>wsgi_intercept.EnvPrinter = EnvPrinter<br><br><br>###########<br># Test it.<br>###########<br>def simple_app(environ, start_response):<br> """Simplest possible application object"""
<br> status = '200 OK'<br> response_headers = [('Content-type','text/plain')]<br> environ['simple_app.myval'] = True<br> start_response(status, response_headers)<br><br> return ['WSGI intercept successful!\n']
<br><br>def test_print_environ():<br> """ Test access to the wsgi environment with wsgi_intercept. """<br> app_fn = wsgi_intercept.EnvPrinter(simple_app)<br> twill.add_wsgi_intercept
('localhost', 80, lambda: app_fn)<br><br> print 'go'<br> twill.commands.go('<a href="http://localhost:80/'">http://localhost:80/'</a>)<br><br> print 'print_environ'<br> val =
twill.extensions.twill_wsgi.print_environ('simple_app.myval')<br> assert val == True, val<br><br> print 'remove'<br> twill.remove_wsgi_intercept('localhost', 80)<br><br><br># TODO: Implement twill script, python api access. script example:
<br>#>> extend_with twill_wsgi<br>#>> print_environ foo_name env_variable_to_print<br><br><br>