我正在使用Python和Webtest来测试WSGI应用程序。我发现处理程序代码中引发的异常往往被Webtest吞噬,然后引发了泛型:
AppError: Bad response: 500 Internal Server Error
如何告诉它引发或打印导致此错误的原始错误?
答案 0 :(得分:3)
您的WSGI框架和服务器包含处理异常并执行某些操作的处理程序(在正文中呈现堆栈跟踪,将回溯记录到日志文件等)。默认情况下,Webtest不显示实际响应,如果您的框架在正文中呈现堆栈跟踪,这可能很有用。当我需要查看响应的主体时,我将以下扩展用于Webtest:
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)
更多地控制异常发生的情况取决于您使用的框架和服务器。对于内置的wsgiref
模块,您可以覆盖error_output以实现您想要的效果。
答案 1 :(得分:3)
虽然clj的答案肯定有效,但您可能仍希望在测试用例中访问响应。为此,您可以在向TestApp发出请求时使用expect_errors=True
(来自webtest documentation),这样就不会引发AppError。这是一个我期待403错误的例子:
# 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))