22

I'm using Python and Webtest to test a WSGI application. I found that exceptions raised in the handler code tend to be swallowed by Webtest, which then raises a generic:

AppError: Bad response: 500 Internal Server Error

How do I tell it to raise or print the original error that caused this?

Sudhir Jonathan
  • 16,998
  • 13
  • 66
  • 90
  • There will be `error` redirected to some file in WSGI config. You can check in that for getting error on some file. – Nilesh Nov 22 '12 at 05:53

2 Answers2

6

While clj's answer certainly works, you may still want to access the response in your test case. To do this, you can use expect_errors=True (from the webtest documentation) when you make your request to the TestApp, and that way no AppError will be raised. Here is an example where I am expecting a 403 error:

# attempt to access secure page without logging in
response = testapp.get('/secure_page_url', expect_errors=True)

# now you can assert an expected http code, 
# and print the response if the code doesn't match
self.assertEqual(403, response.status_int, msg=str(response))
Brendan Goggin
  • 2,061
  • 14
  • 14
4

Your WSGI framework and server contains handlers which catch exceptions and performs some action (render a stacktrace in the body, log the backtrace to a logfile, etc). Webtest, by default, does not show the actual response, which might be useful if your framework renders a stacktrace in the body. I use the following extension to Webtest when I need to look at the body of the response:

class BetterTestApp(webtest.TestApp):

    """A testapp that prints the body when status does not match."""

    def _check_status(self, status, res):
        if status is not None and status != res.status_int:
            raise webtest.AppError(
                "Bad response: %s (not %s)\n%s", res.status, status, res)
        super(BetterTestApp, self)._check_status(status, res)

Getting more control over what happens to the exception depends on what framework and server you are using. For the built in wsgiref module you might be able to override error_output to achieve what you want.

clj
  • 481
  • 2
  • 8