Locust:如何通过API调用测试
我想通过一个API来启动Locust的负载测试,这样我就可以从持续集成工具(CI工具)中开始测试。
不过,我发现关于这种情况的文档不多,locust API文档里没有“Runner”或者类似的类。
我查看了在Windows安装后可以使用的“locust”命令。它是一个.exe文件,所以我不太确定它具体做了什么,以及它是如何真正启动测试的。
所以,我具体想问的是,是否有接口可以从另一个Python程序启动测试?
4 个回答
在命令行中使用curl命令来模拟你的浏览器请求:
curl 'http://localhost:8089/swarm' -H 'Cookie: l10n-locale=en_GB; l10n-submitter=; l10n-license-agreed=false; JSESSIONID.7094a8b9=16g03c8dktw4g1x8ag027nbvl5; screenResolution=1280x800' -H 'Origin: http://localhost:8089' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: en-US,en;q=0.8,tr;q=0.6' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36' -H 'Content-Type: application/x-www-form-urlencoded' -H 'Accept: */*' -H 'Referer: http://localhost:8089/' -H 'X-Requested-With: XMLHttpRequest' -H 'Connection: keep-alive' -H 'X-FirePHP-Version: 0.0.6' --data 'locust_count=5&hatch_rate=1' --compressed
{"message": "Swarming started", "success": true}ubuntu@ip-172-31-16-111:~$
要设置用户和生成速率,可以编辑数据:
--data 'locust_count=5&hatch_rate=1'
我喜欢上面timfeirg的回答。这个想法是,当我们使用locust的时候,已经安装了python,我们只需要运行一个python文件,这个主意很好。只是timfeirg的代码没有成功,所以我稍微修改了一下:
import requests
lc = 10
hr = 10
response = requests.post("http://127.0.0.1:8089/swarm", {"locust_count":lc, "hatch_rate":hr})
print(response.content)
你只需要在Locust的网页界面上做的事情,用Python代码来实现就可以了。
如果你在Locust的界面上监控网络流量,你会发现发起一个压力测试其实就是向 127.0.0.1:8089/swarm
发送一个GET请求,并且需要带上两个参数,分别是 locust_count
和 hatch_rate
。
为了回答你的问题,这里是你需要的API和一个示例:
import requests
payload = {
'locust_count': 12,
'hatch_rate': 22,
}
res = requests.get('http://127.0.0.1:8089/swarm', params=payload)
print(res.json())
我没有测试过这个,如果不管用请告诉我。
目前,控制Locust的方式只有命令行接口,没有正式的API文档。你可以通过命令行来启动负载测试,不过现在不能在没有网页用户界面的情况下运行Locust的分布式测试。
你也可以把网页用户界面当作一个API来用,只需要从你的程序里发送浏览器发送给网页用户界面的HTTP请求就可以了。
在Windows上创建的locust.exe文件(是通过Python的setuptools生成的),其实只是一个小工具,它会运行位于locust/main.py里的main()
函数。