当前位置: 首页 > 科技观察

Locustfile中的User类和HttpUser类

时间:2023-03-16 10:13:31 科技观察

本文转载自微信公众号“东方儿”,作者东方儿。转载本文请联系东方儿公众号。什么是蝗虫文件?Locustfile是Locust性能测试工具的用户脚本,用于描述单个用户的行为。locustfile是一个普通的Python模块。如果写成locustfile.py,则路径切换到文件所在目录,直接执行命令:$locust如果改名,只能通过-f指定文件名运行参数:$locust-flocust_files/my_locust_file.py和一般Python模块的区别在于locustfile必须至少定义一个类,并且继承自User类。User类User类代表性能测试的模拟用户,Locust会在运行时创建User类的实例。wait_time属性设置等待时间,默认值不等待,立即执行。Locust支持4种方式来设置wait_time属性。为了便于理解实际含义,我在下面贴出源码。常量函数constant,任??务执行完后等待X秒开始下一个任务。defconstant(wait_time):"""返回一个函数,它只返回wait_time参数指定的数字Example::classMyUser(User):wait_time=constant(3)"""returnlambdainstance:wait_timebetweenfunction,intervalrandomvalue,waitforX-Yseconds(中间的随机值)任务执行完后开始下一个任务Task。defbetween(min_wait,max_wait):"""Returnanfunctionthatwillreturnarandomnumberbetweenmin_waitandmax_wait.Example::classMyUser(User):#waitbetween3.0and10.5secondsaftereachtaskwait_time=between(3.0,10.5)"""returnlambdainstance:min_wait_random*(wait_rand))constant_pacing函数,自适应,如果任务耗时超过这个时间,则任务结束后立即执行下一个任务;如果任务没有超过这个时间,到时间后会执行下一个任务。defconstant_pacing(wait_time):"""Returnsafunctionthatwilltracktheruntimeofthetasks,andforeachtimeit'scalleditwillreturnawaittimethatwilltrytomakethetotaltimebetweentaskexecutionequaltothetimespecifiedbythewait_timeargument.Inthefollowingexamplethetaskwillalwaysbeexecutedonceeverysecond,nomatterthetaskexecutiontime::classMyUser(User):wait_time=constant_pacing(1)@taskdefmy_task(self):time.sleep(random.random())Ifataskexecutionexceedsthespecifiedwait_time,thewaitwillbe0beforestartingthenexttask."""defwait_time_func(self):ifnothasattr(self,"_cp_last_run"):self._cp_last_wait_time=wait_timeself._cp_last_run=time()returnwait_timeelse:run_time=time()-self._cp_last_run-self._cp_last_wait_timeself._cp_last_wait_time=max(0,wait_time-run_time)self._cp_last_run=time()returnsself._cp_last_wait_timereturnwait_time_func自定义wait_time方法,比如每次等待时间1秒2秒3秒递增:classMyUser(User):last_wait_time=0defwait_time(self_ti.last_wait)me+=1returnsself.last_wait_time...weight属性设置创建类实例的权重。默认情况下,每个类创建相同数量的实例。locustfile中可以有多个继承User类的类。命令行可以指定运行哪些类:$locust-flocust_file.pyWebUserMobileUser允许类通过weight属性创建更大概率的实例,例如:classWebUser(User):weight=3...classMobileUser(User):weight=1...WebUser类创建实例的可能性是MobileUser类的三倍。host属性设置URL前缀。通常,在Locust的WebUI或命令行中,通过--host指定URL前缀。如果不通过--host指定,类中设置了host属性,则类的host属性生效。环境属性是指用户的运行环境。例如在task方法中,使用environment属性终止运行:self.environment.runner.quit()注意单机会终止所有运行,分布式只会终止单个worker节点。on_start和on_stop方法在测试前初始化并在测试后清理。HttpUser类开篇的示例脚本并没有继承User类,而是继承了它的子类HttpUser:它比User类更常用,因为它增加了一个client属性来发送HTTP请求。client属性/HttpSessionHttpUser类的client属性是HttpSession类的实例:HttpSession是requests.Session的子类,requests是接口测试常用的requests库:HttpSession不对requests.Session做任何改动,主要是通过requests的结果给Locust,比如成功/失败,响应时间,响应长度,名称。示例:response=self.client.post("/login",{"username":"testuser","password":"secret"})print("Responsestatuscode:",response.status_code)print("Responsetext:",response.text)response=self.client.get("/my-profile")由于requests.Session会临时保存cookies,所以可以在示例中的/login请求登录后继续请求/my-profile。断言响应结果可以使用with语句和catch_response参数断言响应结果:withself.client.get("/",catch_response=True)asresponse:ifresponse.text=="Success":response.success()elifresponse。文本!="Success":response.failure("Gotwrongresponse")elifresponse.elapsed.total_seconds()>0.5:response.failure("Requesttoooktoolong")或者直接抛异常:fromlocust.exceptionimportRescheduleTask...withself.client.get("/does_not_exist/",catch_response=True)asresponse:ifresponse.status_code==404:raiseRescheduleTask()name参数name参数用于统计同组不同API,例如:foriinrange(10):self.client.get("/blog?id=%i"%i,name="/blog?id=[id]")会根据/blog/?id=[id]统计1条数据,而不是分成10条数据块。HTTP代理Locust默认将requests.Session的trust_env设置为False,不搜索代理以提高运行性能。如果需要,将locust_instance.client.trust_env设置为True。示例代码请求RESTAPI并断言:fromjsonimportJSONDecodeError...withself.client.post("/",json={"foo":42,"bar":None},catch_response=True)asresponse:try:ifresponse.json()["greeting"]!="hello":response.failure("Didnotgetexpectedvalueingreeting")exceptJSONDecodeError:response.failure("ResponsecouldnotbedecodedasJSON")exceptKeyError:response.failure("Responsedidnotcontainexpectedkey'greeting'")必须继承User类或其子类HttpUser等本文介绍了User类和HttpUser类的属性和方法,并使用它们编写用户脚本进行性能测试。locustfile还有一个重要的组成部分,@task。