美文网首页
locust2.0+教程:008 - 断言

locust2.0+教程:008 - 断言

作者: 玩转测试开发 | 来源:发表于2021-11-18 12:26 被阅读0次

简介:断言一般用于验证响应数据是否返回期望的结果,是验证测试是否预期的方法。对接口测试而言,断言既可以针对请求,也可以针对响应,大部分是对响应做断言。

本案例解析:

1、针对响应耗时断言。
2、针对响应状态码断言。

服务端源码:分别有3个接口:/hello、/new、/world,分别用作演示

1、不做断言。
2、耗时超出1800ms就抛出错误。
3、响应是200就抛出错误。


from sanic import Sanic
from sanic import response
import datetime

app = Sanic(__name__)


@app.get('/hello')
def handle_request(request):
    time = str(datetime.datetime.now())[:-7]
    return response.json({"hello time": time})


@app.get('/new')
def handle_request(request):
    time = str(datetime.datetime.now())[:-7]
    return response.json({"new": time})


@app.get('/world')
def handle_request(request):
    time = str(datetime.datetime.now())[:-7]
    return response.json({"world time": time, "sleep_time": sleep_time})


if __name__ == "__main__":
    app.run(host="127.0.0.1", port=3031, auto_reload=True)

客户端压测源码:

from locust import HttpUser, task, tag
import logging


class HelloWorldUser(HttpUser):

    @tag("tag1")
    @task
    def hello(self):
        self.client.get("/hello")

    @tag("tag2")
    @task
    def new(self):
        with self.client.get('/new', catch_response=True) as response:
            if response.elapsed.microseconds >= 1800:
                logging.info("new Failed!")
                response.failure('Failed!')
            else:
                logging.info("new success!")
                response.success()

    @tag("tag3")
    @task
    def world(self):
        with self.client.get('/world', catch_response=True) as response:
            if response.status_code == 200:
                logging.info("world Failed!")
                response.failure('Failed!')
            else:
                logging.info("world success!")
                response.success()


if __name__ == '__main__':
    import os
    os.system("locust -f my_locust --tags tag1")
    # os.system("locust -f my_locust --tags tag2")
    # os.system("locust -f my_locust --tags tag3")

启动服务端:

图片

压测执行tag1:普通不进行断言的场景

os.system("locust -f my_locust --tags tag1")

locust-web执行情况:执行发现,fails这栏基本就不会抛出错误。

图片

服务端响应的结果:

图片

压测执行tag2:断言耗时场景

os.system("locust -f my_locust --tags tag2")

locust-web执行情况:在遇到耗时较长的响应时,主动抛出错误。

image.gif

服务端响应的结果:

image.gif

压测执行tag3:断言状态码的场景

os.system("locust -f my_locust --tags tag3")

locust-web执行情况:因为服务端响应均为200,统计到全部抛出错误。

图片

服务端响应的结果:

图片

微信公众号:玩转测试开发
欢迎关注,共同进步,谢谢!

相关文章

网友评论

      本文标题:locust2.0+教程:008 - 断言

      本文链接:https://www.haomeiwen.com/subject/eewstrtx.html