在web.py应用中测试400错误与粘贴

13 投票
1 回答
3411 浏览
提问于 2025-04-16 23:39

我正在使用paste来对我在web.py应用中的“控制器”进行一些功能测试。在一个案例中,我想测试当向一个API接口发送格式错误的请求时,是否会返回400的错误响应。以下是我的测试代码:

def test_api_users_index_post_malformed(self):
    r = self.testApp.post('/api/users', params={})
    assert r.header('Content-Type') == 'application/json'
    assert r.status == 400

但是我遇到了以下异常:

AppError: Bad response: 400 Bad Request (not 200 OK or 3xx redirect for /api/users)

我看到paste有一个HttpException中间件,但我找不到任何关于如何使用它的例子,也不确定这是否是正确的方法。有没有什么建议?还是说我这样做本身就是错的?

1 个回答

33

我知道我来得有点晚,但我在找同样问题的答案时碰到了这个。要让TestApp能够返回非2xx或3xx的响应,你需要告诉请求允许“错误”。

def test_api_users_index_post_malformed(self):
    r = self.testApp.post('/api/users', params={}, expect_errors=True)
    assert r.header('Content-Type') == 'application/json'
    assert r.status == 400

祝你编程愉快!

撰写回答