locust-day3(Grpc脚本编写)

1.GRPC脚本编写,以公司查询短链接口为例

import unittest,ddt,grpc
import Center_ShortLink_pb2,Center_ShortLink_pb2_grpc
class Test(unittest.TestCase):
def setUp(self):
self.host = '121.40.175.176'
self.port = '10034'

def test(self):
conn = grpc.insecure_channel(self.host + ':' + self.port) # 监听频道
client = Center_ShortLink_pb2_grpc.CenterShortlinkStub(channel=conn)
response = client.GetTagDetail(Center_ShortLink_pb2.GetTagDetailRequest(
# name = "test标签1",
id = 1,
uid = "265802169",
userGroup = ['sl-admin']
))
print(response)
if __name__ == '__main__':
unittest.main()


2.Client端脚本编写,这个单独编程一个文件,供执行文件调用
import Center_ShortLink_pb2_grpc,Center_ShortLink_pb2
import time,grpc
from locust import User, task, between


class GrpcClient:

_locust_environment = None
# 对象初始化,调用对象的时候,必须传入host和port
def __init__(self, host, port):
# 调用对象,传入host和port
self.host = host
self.port = port
print('客户端初始化成功')

# 创建GRPC链接,通过host和port
def connect(self, host, port):
# 调用socket对象的创建链接
self.conn = grpc.insecure_channel(self.host + ':' + self.port) # 监听频道

# 连接服务,指定主机和端口
print('创建链接成功')

def send(self,id,uid,userGroup):
start_time = time.time()
try:
# print(conn)
self.sconnect = Center_ShortLink_pb2_grpc.CenterShortlinkStub(channel=self.conn)
self.sconnect.GetTagDetail(Center_ShortLink_pb2.GetTagDetailRequest(
# name = "test标签1",
id=1,
# username = "XXX",
uid="265802169",
userGroup=['sl-admin']
))

except Exception as e:
total_time = int((time.time() - start_time) * 1000)
self._locust_environment.events.request_failure.fire(request_type="grpc", name="Grpc请求",
response_time=total_time, response_length=0)
else:
total_time = int((time.time() - start_time) * 1000)
self._locust_environment.events.request_success.fire(request_type="grpc", name="Grpc请求",
response_time=total_time, response_length=0)

def close(self):
print("关闭连接")

class GrpcUser(User):
abstract = True
def __init__(self, *args, **kwargs):
super(GrpcUser, self).__init__(*args, **kwargs)
self.client = GrpcClient(self.host,self.port)
self.client._locust_environment = self.environment

Run文件代码编写,主要是调用Client方法里面的Grpcuser和GrpcClient方法

from QueryClient import GrpcClient,GrpcUser
from locust import between, TaskSet, task

class TcpTask(TaskSet):
#先进性创建链接,调用client方法
def on_start(self):
self.client.connect('121.40.175.176','10034')

def on_stop(self):
self.client.close()

@task #task标红之后可以点击红色按键
def tcp_start(self):
id = 1,
uid = "265802169",
userGroup = ['sl-admin']
self.client.send(id,uid,userGroup)

class TcoUser(GrpcUser):
#两种方式,要么定义任务类,要么在下面写任务标签
tasks = [TcpTask]
host = "121.40.175.176"
port = '10034'
wait_time = between(0.1, 1)


if __name__ == '__main__':
import os
os.system('locust -f QueryRun.py')

显示结果

 


 

 









posted @ 2020-11-23 19:23  *西西*  阅读(18)  评论(0编辑  收藏  举报