Finding the real error in a Webtest test failure
Asked Answered
O

2

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?

Oulu answered 22/11, 2012 at 4:10 Comment(1)
There will be error redirected to some file in WSGI config. You can check in that for getting error on some file.Johnsten
F
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))
Federative answered 5/4, 2017 at 23:33 Comment(2)
Thanks for this! I was failing to catch the other exceptions in my tests until I saw this expect_errors arg.Biggs
and you can also use status keyword args: testapp.get('/secure_page_url', status=403)Cartography
C
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.

Cutaway answered 16/6, 2015 at 9:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.