5-响应数据断言

断言请求是否符合自己预期

  • 默认情况下响应的response.status_code<400,就会被判定为success,因此我们应该对response结果进行断言
  • locust>clients>HttpSession(requests.Session)中重写了request方法,其中定义的catch_response参数的说明: catch_response:(可选)布尔参数,如果设置,可用于使请求返回上下文管理器作为with语句的参数。这将允许根据响应的内容将请求标记为失败,即使响应代码是ok (2xx)。反之也可以,可以使用catch_response来捕获请求,然后将其标记为成功,即使响应代码不是(即500或404)。
  • 因此如果要对响应进行断言,在使用self.client.get时必须带一个catch_response=True参数,否则无法对请求断言,并且必须使用with-block的写法
# 测试
from locust import task, HttpUser


class TestUser(HttpUser):
    host = 'https://yourhost.com'

    @task
    def test_task(self):
        resp1 = self.client.get('yourtestapi', name='resp1')
        # 程序报错 TypeError: _failure() takes 1 positional argument but 2 were given
        # resp1.failure('标记测试失败')
        '''
        resp2、resp3调用failure()报错
        locust.exception.LocustError: Tried to set status on a request that has not yet been made. Make sure you use a with-block, like this:
        with self.client.request(..., catch_response=True) as response:
            response.failure(...)
        '''
        # resp2 = self.client.get('yourtestapi', name='resp2', catch_response=True)
        # resp2.failure('resp2标记测试失败')
        # with self.client.get('yourtestapi', name='resp3') as resp2:
        #     resp2.failure('resp3标记测试失败')
        with self.client.get('yourtestapi', name='resp4', catch_response=True) as resp2:
            resp2.failure('resp4标记测试失败')
  • 最终执行测试结果报告如下

  • 获取相应结果,对字段判断,修改下代码如下
...省略...
 with self.client.get('yourtestapi', name='resp4', catch_response=True) as resp2:
            if resp2.json()['state'] == 200:
                resp2.success()
            else:
                resp2.failure(f'resp4预期state是200,实际是:{resp2.json()["state"]}')

小结

  1. 对locust的请求断言必须使用with-block,并且必须传入catch_response=True参数
  2. 断言成功使用response.success(),断言失败使用response.failure('自定义错误信息')
posted @ 2023-07-28 15:45  威力Kami  阅读(105)  评论(0编辑  收藏  举报