Locust 性能测试 - Assertion 断言 Status Code 为 0 的问题

背景

性能测试过程中,往往会遇到很多问题,稳定性就是一个重要的考量指标。高并发时,会有很多异常情况发生,怎么能捕获到这些异常,脚本的断言显得太重要了。不同的测试工具,默认对请求 PASS 的标准会有所不同,作为脚本开发阶段,必须熟悉所使用工具的默认设置,不然怎么有足够充分的理由去说服开发人员呢

本文以 Locust 为例,也是经过痛苦推理,反复实践才悟出来的。发现异常时,要是 server log 不全的情况下,开发人员首先会质疑你的工具,明明 server 没有任何异常的 log,怎么断定是异常呢。

Locust 断言

根据 Locust 官方文档 ,当 HTTP Status Code 小于 400 时,认为 Request 均是 PASS,这在实际测试中是不现实的。

Requests are considered successful if the HTTP response code is OK (<400)

所以我们要根据被测接口实际情况,加一些额外的断言,确保性能测试过程中能捕捉到任何异常现象。这里就要用到 catch_response 参数 和 with 语句。

例如:除了 status code 断言,还需要对 response body 断言

from json import JSONDecodeError
with self.client.post("/", json={
    
    "foo": 42, "bar": None}, catch_response=True) as response:
    if response.status_code != 200:		
        response.failure("Did not get expected status code")
	try:
        if response.json()["status"] != "Success":
            response.failure("Did not get expected value in status")
    except JSONDecodeError:
            response.failure("Response could not be decoded as JSON")
    except KeyError:
            response.failure("Response did not contain expected key 'status'")

Locust status code 0 的情况

在性能测试过程中,偶尔会发现 status code 为 0 的情况, 有时出现,有时没有,server log 里也发现不了任何线索,这让人困惑,是个什么问题呢。

测试过程中的现象:

  1. 5 个并发有时出现
  2. 30 个并发有时不出现
  3. 某一时间段出现的频率高
  4. 观察 CPU, Memory 也没有异常,诡异得很
  5. 换成 Jmeter,有时也能出现 None Status Code 返回

经过规律性观察发现,两组人在同一时间段测试高并发,出现这种异常的概率大大提高,所以有足够的理由相信 Locust 是没有问题的。

Locust 文档中有这样描述:

HttpSession catches any requests.RequestException thrown by Session (caused by connection errors, timeouts or similar), instead returning a dummy Response object with status_code set to 0 and content set to None.

这是 Locust 安全模式处理,为防止引发异常,将这一类 connection error, timeouts 等问题统统处理成一个虚设的 response 返回, 这个 response 的 status code 为 0, content 为 None。

所以高并发时出现这种情况概率比较大,低并发时不会出现,这是个性能问题,server 没法处理所有请求,应该引起重视,不然造成一些请求丢失处理

猜你喜欢

转载自blog.csdn.net/wumingxiaoyao/article/details/121301512