Locust入门

环境
  1. python:3.7
  2. locust:1.3.2
# -*- coding: utf-8 -*-
# @Author  : Lee
# @File    : demo.py

import os
import sys
# 将当前项目根目录添加到运行环境中,目的是引用自定义包
sys.path.append(os.path.join(os.getcwd(), "../.."))  # 需根据当前文件所在目录层级调整

from pathlib import Path
from locust.runners import MasterRunner # 设置主从运行时导入
from locust import HttpUser, task, between, tag, events # Locust框架相关

class LocustDemo(HttpUser):
    wait_time = between(1, 5)

    # 每启动一个用户调用一次
    def on_start(self):
        print("on_start")

    def on_stop(self):
        print("on_stop")
  
    @task
    @tag("tag", "tag1")
    def task_demo_tag1(self):
        response = self.client.post(url, params=params, data=data, catch_response=True)
        # 执行成功
        response.success()
        # 执行失败
        response.failure(“error message”)

    @task
    @tag("tag2")
    def task_demo_tag2(self):
        response = self.client.post(url, params=params, data=data, catch_response=True)
        # 执行成功
        response.success()
        # 执行失败
        response.failure(“error message”)

    @task
    @tag("tag3")
    def task_demo_tag3(self):
        response = self.client.get(url, params=params, catch_response=True)
        # 执行成功
        response.success()
        # 执行失败
        response.failure(“error message”)

    @task
    @tag("tag4")
    def task_demo_tag4(self):
        response = self.client.get(url, params=params, catch_response=True)
        # 执行成功
        response.success()
        # 执行失败
        response.failure(“error message”)

     # 测试开始前执行,只执行一次
     @events.test_start.add_listener
     def on_test_start(**kwargs):
         print("A new test is starting")
    
     # 测试结束后执行
     @events.test_stop.add_listener
     def on_test_stop(**kwargs):
         print("A new test is ending")
    
     # 设置主从时在主机上执行
     @events.init.add_listener
     def on_locust_init(environment, **kwargs):
         if isinstance(environment.runner, MasterRunner):
             print("I'm on master node")
         else:
             print("I'm on a worker or standalone node")


if __name__ == '__main__':
    res = os.system("locust -f {} --host={} --tags tag4 tag1".format(Path(__file__).name, configr.cp.get("api", "pre_url")))


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、性能测试定义 在一定的负载情况下,系统的响应时间等待特性是否满足特定的性能需求,较广泛的的概念(关注 CPU ...
    sofiiii阅读 3,907评论 1 0
  • 安装 一般直接通过 pip 就可以安装: 注意:Locust 1.x 版本与之前的设计有很大的颠覆,所以你看到的很...
    樱井咲夜阅读 13,784评论 1 4
  • 简介与功能 Locust 是基于Gevent协程实现,可以轻量高效地单机模拟较高并发请求。 主要功能: 基于Web...
    击石小记阅读 3,089评论 0 0
  • 什么是Locust 本文Locust版本0.7.5 原文地址:http://docs.locust.io/en/l...
    Yuan_Jie阅读 5,843评论 0 2
  • 性能测试中负载测试大多数用JMeter。今天说的Locust是基于Python开发的一个开源框架。 JMeter和...
    ljZhang416阅读 7,319评论 0 1