我们今天来看看Locust如何自定义客户端测试系统的 ,
由于基础内容,在第一章节,已经介绍完。
所以本章内容,就是实例展示!!
Locust以HTTP为主要目标构建。但是,通过编写触发request_success 和request_failure事件的自定义客户端,可以轻松扩展对任何基于请求/响应的系统进行负载测试。
我们使用User类XmlRpcUser的示例,来看看XmlRpcUser如何发送请求。
老规矩,上代码
# -*- coding:utf-8 -*- # @Time : 2022-05-29 # @Author : Carl_奕然 import time from xmlrpc.client import ServerProxy, Fault from locust import User, task, between class XmlRpcClient(ServerProxy): """ Simple, sample XML RPC client implementation that wraps xmlrpclib.ServerProxy and fires locust events on request_success and request_failure, so that all requests gets tracked in locust's statistics. """ _locust_environment = None def __getattr__(self, name): func = ServerProxy.__getattr__(self, name) def wrapper(*args, **kwargs): start_time = time.time() try: result = func(*args, **kwargs) except Fault as e: total_time = int((time.time() - start_time) * 1000) self._locust_environment.events.request_failure.fire( request_type="xmlrpc", name=name, response_time=total_time, exception=e ) else: total_time = int((time.time() - start_time) * 1000) self._locust_environment.events.request_success.fire( request_type="xmlrpc", name=name, response_time=total_time, response_length=0 ) # In this example, I've hardcoded response_length=0. If we would want the response length to be # reported correctly in the statistics, we would probably need to hook in at a lower level return wrapper class XmlRpcUser(User): """ This is the abstract User class which should be subclassed. It provides an XML-RPC client that can be used to make XML-RPC requests that will be tracked in Locust's statistics. """ abstract = True def __init__(self, *args, **kwargs): super(XmlRpcUser, self).__init__(*args, **kwargs) self.client = XmlRpcClient(self.host) self.client._locust_environment = self.environment class ApiUser(XmlRpcUser): host = "http://127.0.0.1:8877/" wait_time = between(0.1, 1) @task(10) def get_time(self): self.client.get_time() @task(5) def get_random_number(self): self.client.get_random_number(0, 100)
这段示例,也是没有什么难度,如果 通过Locust编写过测试脚本或者进行过测试,那么就很容易理解。
但是,在这里,小鱼还是强调一次,
在这段代码中:
①你可以认识到ApiUser的类,这是一个普通的类,只是声明了几个任务;
②ApiUser继承自XmlRpcUser ,这个可以在ApiUser类上看到;
③abstract = True,则标记为Locust不会尝试从该类创建模拟用户(仅扩展该类的类)。
④ XmlRpcUser在客户端属性下提供XmlRpcClient的实例。
这是XML-RPC服务器的实现,该服务器可用作客户端代码的服务器。
代码展示:
# -*- coding:utf-8 -*- # @Time : 2022-05-29 # @Author : Carl_奕然 import time from xmlrpc.server import SimpleXMLRPCServer def get_time(): time.sleep(random.random()) return time.time() def get_random_number(low, high): time.sleep(random.random()) return random.randint(low, high) server = SimpleXMLRPCServer(("localhost", 8877)) print("Listening on port 8877...") server.register_function(get_time, "get_time") server.register_function(get_random_number, "get_random_number") server.serve_forever()
今天的代码,就分享到这里,代码很简单,希望熟练掌握。