如何用Locust测试FastAPI API端点?解决运行报错问题
问题修复方案
错误原因
你的Locust测试代码中,WebsiteUser类的属性名拼写错误——需要使用复数形式的tasks,而非单数的task。Locust框架只会识别tasks属性来绑定任务集合,单数的task无法被正确识别,因此触发了"未定义任务"的报错。
修复后的完整代码
from locust import HttpUser, TaskSet, task import json class UserBehavior(TaskSet): @task(1) def create_post(self): headers = {'content-type': 'application/json','Accept-Encoding':'gzip'} self.client.post( "/predictions", data=json.dumps({"text": "I am tired"}), headers=headers, name="Create a new post" ) class WebsiteUser(HttpUser): tasks = [UserBehavior] # 修正为复数形式的tasks
额外优化建议
- 可以直接使用
json参数替代data=json.dumps(...),Locust的client.post方法支持自动序列化JSON数据,同时会自动设置content-type: application/json请求头,代码更简洁:self.client.post( "/predictions", json={"text": "I am tired"}, headers={'Accept-Encoding':'gzip'}, name="Create a new post" ) - 运行Locust时,记得通过
--host参数指定API的基础地址,避免在请求路径中重复写完整URL:locust -f your_test_file.py --host=http://127.0.0.1:8000
内容的提问来源于stack exchange,提问作者math_guy_shy
相关产品推荐
相关产品推荐

