Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the real error in a Webtest test failure

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?

like image 989
Sudhir Jonathan Avatar asked Nov 22 '12 04:11

Sudhir Jonathan


2 Answers

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))
like image 57
Brendan Goggin Avatar answered Oct 17 '22 16:10

Brendan Goggin


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.

like image 22
clj Avatar answered Oct 17 '22 16:10

clj