locustfile中的User类和HttpUser类

locustfile中的User类和HttpUser类

 

locustfile是什么?

locustfile是Locust特性检测工具的用户脚本,叙述了单独客户的个人行为。

locustfile是个一般的Python控制模块,假如创作locustfile.py,那麼途径转换到文档所属文件目录,立即运行命令就能运作:

$ locust

假如换一个名称,那麼只有根据-f主要参数特定文件夹名称运作:

$ locust -f locust_files/my_locust_file.py

与一般Python控制模块不一样的是:locustfile务必最少界定一个类,且承继自User类。

User类

User类表明功能测试的仿真模拟客户,Locust会在运作时建立User类的案例

wait_time特性

设定等待的时间,初始值不等候,立即执行。

Locust适用4种方法设定wait_time特性

为了更好地有利于了解现实意义,我将源代码贴在了下边。

  • constant涵数,变量定义,每日任务实行结束等候X秒逐渐下一每日任务。

    def constant(wait_time):
        """
        Returns a function that just returns the number specified by the wait_time argument
    
        Example::
    
            class MyUser(User):
                wait_time = constant(3)
        """
        return lambda instance: wait_time
    
  • between涵数,区段任意值,每日任务实行结束等候X-Y秒(正中间任意赋值)逐渐下一每日任务。

    def between(min_wait, max_wait):
        """
        Returns a function that will return a random number between min_wait and max_wait.
    
        Example::
    
            class MyUser(User):
                # wait between 3.0 and 10.5 seconds after each task
                wait_time = between(3.0, 10.5)
        """
        return lambda instance: min_wait   random.random() * (max_wait - min_wait)
    
  • constant_pacing涵数,响应式,若每日任务用时超出该時间,则每日任务完毕后立即执行下一每日任务;若每日任务用时不超过该時间,则等候做到该時间后实行下一每日任务。

    def constant_pacing(wait_time):
        """
        Returns a function that will track the run time of the tasks, and for each time it's
        called it will return a wait time that will try to make the total time between task
        execution equal to the time specified by the wait_time argument.
    
        In the following example the task will always be executed once every second, no matter
        the task execution time::
    
            class MyUser(User):
                wait_time = constant_pacing(1)
                @task
                def my_task(self):
                    time.sleep(random.random())
    
        If a task execution exceeds the specified wait_time, the wait will be 0 before starting
        the next task.
        """
    
        def wait_time_func(self):
            if not hasattr(self, "_cp_last_run"):
                self._cp_last_wait_time = wait_time
                self._cp_last_run = time()
                return wait_time
            else:
                run_time = time() - self._cp_last_run - self._cp_last_wait_time
                self._cp_last_wait_time = max(0, wait_time - run_time)
                self._cp_last_run = time()
                return self._cp_last_wait_time
    
        return wait_time_func
    
  • 自定wait_time方式,例如每一次等待的时间一秒2秒3秒增长:

    class MyUser(User):
        last_wait_time = 0
    
        def wait_time(self):
            self.last_wait_time  = 1
            return self.last_wait_time
    
        ...
    

weight特性

设定建立类案例的权重值,默认设置每一个类建立同样总数的案例。

locustfile中能够有好几个承继了User类的类

cmd能够特定运作什么类:

$ locust -f locust_file.py WebUser MobileUser

根据weight特性能够让类更大概率建立案例,例如:

class WebUser(User):
    weight = 3
    ...

class MobileUser(User):
    weight = 1
    ...

WebUser对比MobileUser类多三倍几率建立案例。

host特性

设定URL作为前缀。

一般是在Locust的Web UI或是cmd,根据--host特定URL作为前缀。要是没有根据--host特定,而且类中设定了host特性,那麼类的host特性才会起效。

environment特性

对客户软件环境的引入。

例如在task方式中根据environment特性停止运作:

self.environment.runner.quit()

留意,单机遇停止全部运作,分布式系统总是停止单独worker连接点。

on_start和on_stop方式

检测前复位和检测后清除。

HttpUser类

开场文章内容的实例脚本制作,沒有承继User类,只是承继了它的派生类HttpUser:

image-20210507203533924

它比User类更常见,因为它加上了一个client特性,用于推送HTTP要求

client特性/HttpSession

HttpUser类的client特性是HttpSession类的一个案例:

image-20210510100543452

HttpSession是requests.Session的派生类,requests便是常见来做接口测试的那一个requests库:

image-20210510161237184

HttpSession沒有对requests.Session干什么修改,主要是传送要求結果给Locust,例如success/fail,response time,response length,name。

实例:

response = self.client.post("/login", {"username":"testuser", "password":"secret"})
print("Response status code:", response.status_code)
print("Response text:", response.text)
response = self.client.get("/my-profile")

因为requests.Session会储存cookie,因此实例中登陆/login要求后能够再次要求/my-profile

肯定回应結果

能够应用with句子和catch_response主要参数对回应結果开展肯定:

with self.client.get("/", catch_response=True) as response:
    if response.text == "Success":
        response.success()
    elif response.text != "Success":
        response.failure("Got wrong response")
    elif response.elapsed.total_seconds() > 0.5:
        response.failure("Request took too long")

或是立即抛出异常:

from locust.exception import RescheduleTask
...
with self.client.get("/does_not_exist/", catch_response=True) as response:
    if response.status_code == 404:
        raise RescheduleTask()

name主要参数

name主要参数用以把不一样api按同一排序开展统计分析,例如:

for i in range(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。

实例编码

要求REST API并肯定:

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

总结

locustfile是个一般Python控制模块,务必承继User类或他的儿子类HttpUser等。文中对User类和HttpUser类的特性和方式开展了详细介绍,应用他们能够撰写功能测试的用户脚本。locustfile也有此外一个关键构成原素,@task

参考文献:

https://docs.locust.io/en/stable/writing-a-locustfile.html

https://blog.csdn.net/Orangesir/article/details/114914969



    自动化技术编码艺术美学  

评论(0条)

刀客源码 游客评论