性能工具之 nGrinder 关联脚本编写

简介: 【5月更文挑战第5天】性能工具之 nGrinder 关联脚本编写

2000元阿里云代金券免费领取,2核4G云服务器仅664元/3年,新老用户都有优惠,立即抢购>>>


阿里云采购季(云主机223元/3年)活动入口:请点击进入>>>,


阿里云学生服务器(9.5元/月)购买入口:请点击进入>>>,

一、前言

在做性能测试,脚本的关联是一个比较棘手的问题,nGrinder 脚本是怎么关联,其实也是比较简单的,简单前提条件是自己具备一定的代码基础、http 协议、网络等基础知识,这样才能顺利开展工作。

二、什么是关联?

  • 关联的目的是后面请求需要,如果不需要就不需要关联。
  • 关联获取结果做断言
  • 想了解更多、更详细关联知识请查找相关资料。

常见的获取请求结果方法有:

  • 通过正则表达方式获取结果
  • 通过 xpath 方式获取相关结果
  • 通过 json 解析获取相关结果

    在编写 nGrinder 脚本之前请学习下 groovy 语法这样方便写脚本,脚本编写建议在 idea 中上写脚本与调试脚本,这样有语法提示能很快写出脚本与调试脚本,写完脚本后直接复制到线上脚本中在微调验证就能使用。

三、如何编写脚本?

这里脚本编写与调试需要解析 JSON 所以需要引入 fastjson 包

仓库地址为:https://mvnrepository.com/artifact/com.alibaba/fastjson

1、线上直接写脚本

需要上传 jar 包,在脚本页面的脚本文件夹中新建 lib 文件夹,之后再 lib 文件中上传相关的jar包,如下图:
image.png

点击文件夹:
image.png

image.png

注意:

一定在脚本文件相关的地方新建 lib 文件夹,并且在 lib 下中上传 jar 包

线上调试:
image.png

2、IDE 中写脚本

如果是 idea 中写代码与调试脚本,需要在脚本文件中新建 lib 文件夹之后在把 jar 包加入工程。
image.png

该工程下载后需要处理下才可以使用:
image.png

再次选择:
image.png

idea 中调试并且测试:

image.png

四、示例脚本

import HTTPClient.Cookie
import HTTPClient.CookieModule
import HTTPClient.HTTPResponse
import HTTPClient.NVPair
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import groovy.json.JsonParser
import groovy.json.JsonSlurper
import net.grinder.plugin.http.HTTPPluginControl
import net.grinder.plugin.http.HTTPRequest
import net.grinder.script.GTest
import net.grinder.scriptengine.groovy.junit.GrinderRunner
import net.grinder.scriptengine.groovy.junit.annotation.BeforeProcess
import net.grinder.scriptengine.groovy.junit.annotation.BeforeThread
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;

import static com.alibaba.fastjson.JSON.parse
import static net.grinder.script.Grinder.grinder
import static org.hamcrest.Matchers.is


// import static net.grinder.util.GrinderUtils.* // You can use this if you're using nGrinder after 3.2.3

import static org.junit.Assert.assertThat

/**
 * @Title: OneAndTwo
 * @author 7d
 * @date 2019/10/27 / 11:00
 */
@RunWith(GrinderRunner)
class OneAndTwo {
   
   

    public static GTest test
    // 定义 HTTPRequest 静态变量 request,用于发送 HTTP 请求
    public static HTTPRequest request
    // 定义 NVPair 数组 headers ,用于存放通用的请求头数据
    public static NVPair[] headers = []
    // 定义 NVPair 数组 params ,用于存放请求参数数据
    public static NVPair[] params = []
    // 定义 Cookie 数组 cookies ,用于存放通用的 cookie 数据
    public static Cookie[] cookies = []

    //存储第一个请求得参数
    def paramName = new ArrayList()


    @BeforeProcess
    public static void beforeProcess() {
   
   
        // 设置请求响应超时时间(ms)
        HTTPPluginControl.getConnectionDefaults().timeout = 6000
        // 创建GTest对象,第一个参数1代表有多个请求/事务时的执行顺序ID,
        // 第二个参数是请求/事务的名称,会显示在summary结果中,有多个请求/事务时,要创建多个GTest对象
        test = new GTest(1, "User_find_01")
        //创建 HTTPRequest 对象,用于发起 HTTP 请求
        request = new HTTPRequest()
        // Set header datas
        List<NVPair> headerList = new ArrayList<NVPair>()
        headerList.add(new NVPair("Content-Type", "application/x-www-form-urlencoded"))
        headerList.add(new NVPair("Connection", "keep-alive"))
        headers = headerList.toArray()
        // Set param datas

//        List<Cookie> cookieList = new ArrayList<Cookie>()
//        cookieList.add(new Cookie("Cookie", "null", "localhost:8888", "", new Date(), true))
//        cookies = cookieList.toArray()
        grinder.logger.info("before process.");

    }

    @BeforeThread
    public void beforeThread() {
   
   
//        注册事件,启动test,第二个参数要与@Test注解的方法名保持一致,有多个请求/事务时,要注册多个事件
        test.record(this, "test")

        //配置延迟报告统计结果
        grinder.statistics.delayReports = true;
        grinder.logger.info("before thread.");
    }

    @Before
    public void before() {
   
   
        //在这里可以添加headers属性和cookies
//        request.setHeaders(headers)
        cookies.each {
   
    CookieModule.addCookie(it, HTTPPluginControl.getThreadHTTPClientContext()) }
        grinder.logger.info("before thread. init headers and cookies");

    }

    @Test
    public void test() {
   
   
        getUserFind()
        getItem()
    }


    public void getUserFind() {
   
   
        // 发送GET请求
        HTTPResponse resu = request.GET("http://localhost:8888/userfind")
        def text1 = resu.getText()
        JSONObject jsonObject = JSONObject.parseObject(text1);
        JSONObject object = jsonObject.getJSONObject("extend")
        JSONArray array = object.getJSONArray("info")
        for (int i = 0; i < array.size(); i++) {
   
   
            JSONObject object1 = JSONObject.parseObject(array.get(i).toString())
            Object name = object1.get("userName");
            grinder.logger.info("这是获取得名字--->" + name)
            paramName.add(String.valueOf(name))
        }
        grinder.logger.info("这是第一个请求:" + text1)
        assertThat(resu.statusCode, is(200))
    }

    public void getItem() {
   
   
        List<NVPair> paramList = new ArrayList<NVPair>()
        //获取参数的第一个值
        paramList.add(new NVPair("userName", paramName.get(0)))
        params = paramList.toArray()
        // Set cookie datas
        HTTPResponse result = request.GET("http://localhost:8888/findName", params)
        def text = result.getText()

        grinder.logger.info("这是第二请求" + text)
        // 断言HTTP请求状态码
        assertThat(result.statusCode, is(200))
    }
}

测试结果显示:
image.png

image.png

源码地址:

目录
相关文章
|
4天前
|
IDE 测试技术 开发工具
性能工具之 nGrinder 参数化脚本编写
【5月更文挑战第6天】性能工具之 nGrinder 参数化脚本编写
23 5
性能工具之 nGrinder 参数化脚本编写
|
4天前
|
SQL JSON Java
性能工具之 nGrinder Get 请求脚本编写
【5月更文挑战第3天】性能工具之 nGrinder Get 请求脚本编写
28 8
|
4天前
|
缓存 人工智能 算法
编写高效的Python脚本:性能优化的策略与技巧
编写高效的Python脚本需要综合考虑多个方面,包括代码结构、数据结构和算法选择等。本文将探讨在Python编程中提高脚本性能的方法,包括优化数据结构、选择合适的算法、使用Python内置函数以及通过并行和异步编程提升效率。这些技巧旨在帮助开发者在不同应用场景中编写出高性能的Python代码。
|
4天前
|
JSON 测试技术 数据格式
性能工具之Jmeter关联入门
【4月更文挑战第4天】关联是每个性能测试人员必须掌握的技能,是解决性能脚本中的"金钥匙"。
27 2
性能工具之Jmeter关联入门
|
5月前
|
程序员 API 开发者
自动化脚本如何编写?打算写个自动发布文章的脚本教程
作为一名程序员/开发者,我们经常需要处理重复性的任务,比如发布文章到多个媒体平台。为了提高效率,我们可以编写自动化脚本来完成这些任务。本文将介绍如何使用万媒易发多平台内容同步助手来自动发布文章。
|
6月前
|
数据采集 监控 数据处理
Python自动化与脚本编写:提升效率与简化工作流程
Python自动化与脚本编写:提升效率与简化工作流程
|
XML SQL 前端开发
loadrunner 脚本优化-关联设置
loadrunner 脚本优化-关联设置
166 0
|
SQL 关系型数据库 MySQL
Loadrunner脚本优化-参数化之关联MySQL数据库获取数据
Loadrunner脚本优化-参数化之关联MySQL数据库获取数据
69 0
|
Linux 程序员
自己编写高负荷测试的工具
在第一轮测试时,我们通过在LINUX操作系统上,用压缩和解压缩的方法去占用CPU,这样的方法有个弊端,就是比较耗时而且不可控。
EMQ
|
Java 测试技术 Linux
JMeter 扩展开发:BeanShell 数据模拟实现及性能探讨
本文是开源测试工具JMeter扩展性开发教程第三期,讲解如何采用JMeter内置功能BeanShell实现动态生成测试数据,并探讨其与Java扩展JMeter的实现方式对比。
EMQ
145 0
JMeter 扩展开发:BeanShell 数据模拟实现及性能探讨
http://www.vxiaotou.com