Sud*_*han 18 python unit-testing webtest
我正在使用Python和Webtest来测试WSGI应用程序.我发现处理程序代码中引发的异常往往被Webtest吞噬,然后引发泛型:
AppError: Bad response: 500 Internal Server Error
如何告诉它引发或打印导致此错误的原始错误?
虽然 clj 的答案确实有效,但您可能仍想访问测试用例中的响应。为此,您可以在向 TestApp 提出请求时使用expect_errors=True(来自webtest 文档),这样就不会引发 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))
小智 4
您的 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来实现您想要的。
| 归档时间: | 
 | 
| 查看次数: | 1610 次 | 
| 最近记录: |