我正在使用Python和Webtest来测试WSGI应用程序。我发现,在处理程序代码引起的异常往往被WebTest的被吞噬,然后提出了一个通用的:在Webtest测试失败中找到真正的错误
AppError: Bad response: 500 Internal Server Error
我怎么告诉它提高或打印导致原来这个错误?
我正在使用Python和Webtest来测试WSGI应用程序。我发现,在处理程序代码引起的异常往往被WebTest的被吞噬,然后提出了一个通用的:在Webtest测试失败中找到真正的错误
AppError: Bad response: 500 Internal Server Error
我怎么告诉它提高或打印导致原来这个错误?
您的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以实现您想要的效果。
报告上游:https://github.com/Pylons/webtest/issues/176 –
尽管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))
感谢您的支持!我没有在我的测试中捕获其他异常,直到看到expect_errors arg。 –
在WSGI配置中会有'error'重定向到某个文件。您可以检查某些文件是否有错误。 – Nilesh