码迷,mamicode.com
首页 > 系统相关 > 详细

Testing Complex Logic with JMeter Beanshell

时间:2019-01-13 19:10:31      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:current   The   测试数据   从服务器   nes   gettime   rac   detail   情况   

BeanShell是最先进的JMeter内置组件之一。JMeter具有丰富的内置插件,可满足性能测试的许多需求。例如,在编写一些复杂的测试时,您可能需要一些额外的脚本。在这种情况下,值得使用Beanshell。在这篇文章中,我们将讨论使用JMeter Beanshell和常见用例测试复杂逻辑。Beanshell具有运行Java代码的功能,并且可以访问JMeter API和在JMeter类路径中加载的外部类。

JMeter具有以下启用Beanshell的组件:

  1. Beanshell采样器
  2. Beanshell预处理器
  3. Beanshell PostProcessor
  4. __BeanShell函数。
  5. Beanshell断言

以下是向Beanshell公开的JMeter API类。如果查看Beanshell的底部,您将看到为脚本定义的变量列表。

技术分享图片

SampleResult

您可以在Beanshell中访问SampleResult的成员变量和方法

例如,您可以分别使用setThreadName()getThreadName()方法设置和获取线程名称

技术分享图片

ResponseCode

此类允许您手动设置响应代码。在某些情况下,您可能需要根据从服务器获得的响应来设置响应代码。
这是一个用例示例:

if(condition){ 
  ResponseCode =“200”; 
} 
else { 
  ResponseCode =“500”; 
}

ResponseMessage

此类允许您手动设置响应消息。示例用例与for的用例相同ResponseCode

IsSuccess:

IsSuccessBoolean反映采样器是否成功的反映。如果设置为true,则认为采样器已“通过”。否则,它将被标记为“失败”。

if(condition){ 
  IsSuccess = true; 
} 
else { 
  IsSuccess = false; 
}

CTX

ctx是暴露给BeanShell的最强大的变量。它代表JMeterContext类,它本身就是JMeter。它提供对底层JMeter引擎,采样器及其结果以及变量/属性的读/写访问。

以下代码演示了ctx变量的用法:

log.info(“Current Sampler class is:”+ ctx.getCurrentSampler()); 
log.info(“JMeter Engine类是:”+ ctx.getEngine()); 

log.info(“上一个响应消息是:”+ ctx.getPreviousResult()。getResponseMessage()); 
log.info(“上一个响应代码是:”+ ctx.getPreviousResult()。getResponseCode()); 
log.info(“Previous Response URL is:”+ ctx.getPreviousResult()。getURL()); 
log.info(“Previous Response Time is:”+ ctx.getPreviousResult()。getTime()); 

log.info(“Previous Domain is:”+ ctx.getPreviousSampler()。getDomain()); 
log.info(“Previous Protocol is:”+ ctx.getPreviousSampler()。getProtocol()); 
log.info(“Previous Port is:”+ ctx.getPreviousSampler()。getPort());
log.info(“Previous Method is:”+ ctx.getPreviousSampler()。getMethod()); 

log.info(“Thread Name is:”+ ctx.getThread()。getThreadName()); 
log.info(“Thread Start Time is:”+ ctx.getThread()。getStartTime()); 
log.info(“Thread End Time is:”+ ctx.getThread()。getEndTime()); 
log.info(“在错误时启动下一个线程循环:”+ ctx.getThreadGroup()。getOnErrorStartNextLoop()); 
log.info(“Stop Test on Error:”+ ctx.getThreadGroup()。getOnErrorStopTest());

技术分享图片

另一个用例是,如果要将所有断言错误写入HTML文件,以便可以查看哪个断言不起作用。您可以ctx在Beanshell断言中使用变量来遍历当前上下文中的所有采样器,并将失败写入html文件中。

添加Beanshell断言并复制以下代码以将所有断言写入html文件:

import org.apache.jmeter.services.FileServer; 
f = new FileOutputStream(“C:\\ apache-jmeter-4.0 \\ bin \\ result.html”,true); 
pt = new PrintStream(f); 
pt.println( “<HTML> <BODY>”); 
for(a:SampleResult.getAssertionResults()){ 
  if(a.isError()|| a.isFailure()){ 
    log.error(“URL:”+ ctx.getCurrentSampler()。toString()); 
    log.error(Thread.currentThread()。getName()+“:”+ SampleLabel +“:响应失败:”+ new String((byte [])ResponseData)); 
    pt.println(“URL:”+ ctx.getCurrentSampler()。toString()); 
    pt.println(Thread.currentThread()。getName()+“:”+ SampleLabel +“:响应断言失败:”+ new String((byte [])ResponseData));
  pt.println( “</ BODY> </ HTML>”); 
  pt.close(); 
  f.close(); 
}

瓦尔

它是JMeterVariables的一个实例,提供对当前变量的读/写访问,能够枚举/更改现有变量,创建新变量以及获取嵌套属性。所有JMeter变量都是Java字符串。如果您需要将其他内容添加到JMeter变量中,则需要先将其强制转换为字符串。以下代码段演示了如何将以前的采样器响应数据保存到JMeter变量中:

vars.put(“ResponceData”,prev.getResponseDataAsString()); 
log.info(vars.get( “ResponceData”));

技术分享图片

道具

基本上,这与vars相同,但它公开了JMeter属性。有关java.util.Properties更多信息,请参阅有关JMeter属性的JavaDoc on 和JMeter文档。的主要区别之间props并且vars是道具有一个“全局”范围,而范围vars是有限的,以当前线程组。

日志

log表示Logger类,可用于将消息附加到jmeter.log文件中。以下是示例用例:

log.info(“使用INFO级别测试消息”); 
log.error(“使用ERROR级别测试消息”);

Beanshell的一些常见用例

在JMeter中编写自定义请求。

在某些情况下,您可能希望根据响应添加参数。您可以使用Beanshell预处理器执行此操作。

sampler.addArgument()方法允许您在手动访问服务器之前添加参数。

更改JMeter变量。

如前所述,您可以使用Beanshell动态更新JMeter变量。假设您有一个名为“counter”的用户定义变量,其值为“1”。假设您希望每次在while循环中执行采样器时将此计数器值递增1。以下代码段将计数器值递增1并更新相同的值:

int counter = Integer.parseInt(vars.get(“counter”))+ 1; 
vars.put( “计数器”,Integer.toString(计数器));

在Beanshell采样器中使用自定义Jar。

假设您需要调用用户创建的类中存在的方法之一。您可以使用Beanshell调用用户创建的JAR文件中存在的方法。

  1. 将用户创建的Jar文件放在lib/extJMeter的文件夹中。
  2. 重新启动JMeter以选择.jar。
  3. 将Beanshell采样器添加到测试计划中,并像在Java中一样从.jar文件中调用该方法。

例如 :

鉴于您有以下课程:

package timeStampPack; 
import java.text.SimpleDateFormat; 
import java.util.Calendar; 
public class TimeStampConversion 
{ 
  public TimeStampConversion(){} 
  public static String getTimeStamps(int count)
  { 
    String dates =“”; 
    for(int i = 1; i <= count; i ++)
    { 
      try { 
        Thread.sleep(1L); 
      } catch(InterruptedException e){ 
        e.printStackTrace(); 
      } 
      dates = dates +“TimeStamp”+ i +“==>”+ getCurrentDateTime()+“\ n”; 
    } 
    返回日期; 
  } 
}

在上面的类中,getTimeStamps()方法返回timestamp,将其打包为timeStamp.jar并将文件复制到lib/extJMeter安装文件夹中。

将Beanshell Sampler添加到测试计划中,并将以下代码放入“脚本”区域。

导入timeStampPack。*; 
var time = TimeStampConversion.getTimeStamps(1); 
log.info(时间);

上面的代码将调用getTimeStamps()方法并记录该值。

技术分享图片

您还可以使用Beanshell使用CSV文件参数化测试数据。查看此文章以查看详细信息。

RedLine13如何增强JMeter负载测试

JMeter是数千名开发人员使用的优秀开源负载测试工具。如果您是其中之一,则可能需要加载测试。JMeter可用于负载测试。使用RedLine13,您可以在10分钟内使用任何移动应用程序,Web应用程序或API的JMX脚本运行JMeter负载测试

BeanShell is one of the most advanced JMeter built-in components. JMeter has rich built-in plugins which cover many needs of a performance test. For example, you might need some additional scripting while writing some complex tests. In such cases, it’s worth using Beanshell. In this post, we are going to be talking about testing complex logic with JMeter Beanshell and common use cases. Beanshell has the functionality to run java code and has access to JMeter APIs and external classes that are loaded in the JMeter classpath.

JMeter has the following Beanshell enabled components:

  1. Beanshell Sampler.
  2. Beanshell PreProcessor.
  3. Beanshell PostProcessor.
  4. __BeanShell function.
  5. Beanshell Assertion.

Below are the JMeter API classes exposed to Beanshell. If you look at the bottom of Beanshell, you’ll see the list of variables defined for the script.

技术分享图片

SampleResult

You can access the member variables and methods of the SampleResult Class in Beanshell.

For example, you can set and get the thread name using setThreadName() and getThreadName() methods respectively.

技术分享图片

ResponseCode

This class allows you to set response code manually. In some situations, you may need to set the response code based on the response that you get from server.
Here is a sample use-case:

if (condition) {
  ResponseCode = "200";
}
else {
  ResponseCode = "500";
}

ResponseMessage

This class allows you to set the response message manually. The sample use case is the same as the one for ResponseCode.

IsSuccess:

IsSuccess is a Boolean that reflects whether the sampler succeeded. If it’s set to true, the sampler is considered to have “passed.” Otherwise, it will be marked as “failed”.

if (condition) {
  IsSuccess = true;
}
else {
  IsSuccess = false;
}

ctx

ctx is the most powerful variable exposed to BeanShell. It represents the JMeterContext class, which is virtually JMeter itself. It provides read/write access to the underlying JMeter engine, samplers, and their results as well as variables/properties.

The following code demonstrates the usage of ctx variable:

log.info("Current Sampler class is: " + ctx.getCurrentSampler());
log.info("JMeter Engine class is: " + ctx.getEngine());

log.info("Previous Response Message is: " + ctx.getPreviousResult().getResponseMessage());
log.info("Previous Response Code is: " + ctx.getPreviousResult().getResponseCode());
log.info("Previous Response URL is: " + ctx.getPreviousResult().getURL());
log.info("Previous Response Time is: " + ctx.getPreviousResult().getTime());

log.info("Previous Domain is: " + ctx.getPreviousSampler().getDomain());
log.info("Previous Protocol is: " + ctx.getPreviousSampler().getProtocol());
log.info("Previous Port is: " + ctx.getPreviousSampler().getPort());
log.info("Previous Method is: " + ctx.getPreviousSampler().getMethod());

log.info("Thread Name is: " + ctx.getThread().getThreadName());
log.info("Thread Start Time is: " + ctx.getThread().getStartTime());
log.info("Thread End Time is: " + ctx.getThread().getEndTime());
log.info("Start Next Thread Loop on Error: " + ctx.getThreadGroup().getOnErrorStartNextLoop());
log.info("Stop Test on Error: " + ctx.getThreadGroup().getOnErrorStopTest());

技术分享图片

Another use case is if you want to write all Assertions error to an HTML file so you can see which assertion is not working. You can use ctx variable in Beanshell assertion to iterate through all samplers in the current context and write the failures in an html file.

Add a Beanshell assertion and copy the following code to write all the assertions to a html file:

import org.apache.jmeter.services.FileServer;
f = new FileOutputStream("C:\\apache-jmeter-4.0\\bin\\result.html", true);
pt = new PrintStream(f);
pt.println("<html><body>");
for (a: SampleResult.getAssertionResults()) {
  if (a.isError() || a.isFailure()) {
    log.error("URL :"+ ctx.getCurrentSampler().toString());
    log.error(Thread.currentThread().getName()+": "+SampleLabel+": Assertion failed for response: " + new String((byte[]) ResponseData));
    pt.println("URL :"+ ctx.getCurrentSampler().toString());
    pt.println(Thread.currentThread().getName()+": "+SampleLabel+": Assertion failed for response: " + new String((byte[]) ResponseData)); // update here what you want to write
  }
  pt.println("</body></html>");
  pt.close();
  f.close();
}

vars

It’s an instance of the JMeterVariables class and provides read/write access to current variables, is capable of enumerating/changing existing variables, creating new variables, and obtaining nested properties. All JMeter variables are Java strings. If you need to put something else to a JMeter variable, you’ll need to cast it to a string first. The following code snippet demonstrates how to save previous sampler response data into a JMeter variable:

vars.put("ResponceData", prev.getResponseDataAsString());
log.info(vars.get("ResponceData"));

技术分享图片

props

Basically, this is the same as vars, but it exposes JMeter properties instead. See JavaDoc on java.util.Properties and JMeter documentation on JMeter properties for more information. The primary distinction between props and vars is that props have a “global” scope, whereas the scope of vars is limited to the current thread group.

log

log represents the Logger class and can be used to append a message into jmeter.log file. The following is the sample use case:

log.info("Test Message with INFO level");
log.error("Test Message with ERROR level");

Some Common Use Cases of Beanshell

Writing custom requests in JMeter.

In some cases, you might want to add parameters based on the response. You can do this using the Beanshell preprocessor.

The sampler.addArgument() method allows you to add arguments before hitting the server manually.

Changing JMeter Variables.

As mentioned earlier, you can update JMeter variables on the fly using Beanshell. Assume that you have a user defined variable called “counter” with the value of “1”. Let’s say you want to increment this counter value by one every time it executes a sampler in while loop. The following code snippet increments the counter value by one and updates the same:

int counter = Integer.parseInt(vars.get("counter")) +1;
vars.put("counter",Integer.toString(counter));

Using a Custom Jar in the Beanshell Sampler.

Assume that you have a requirement to call one of the methods which is present in a user created class. You can call the methods present in user created JAR file using Beanshell.

  1. Place your User created Jar file in lib/ext folder of JMeter.
  2. Restart JMeter to pick the .jar.
  3. Add a Beanshell sampler to your Test Plan and call the method from .jar file as you would do in Java.

For Example :

Given you have the following class:

package timeStampPack;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class TimeStampConversion
{
  public TimeStampConversion() {}
  public static String getTimeStamps(int count)
  {
    String dates = "";
    for (int i = 1; i <= count; i++)
    {
      try {
        Thread.sleep(1L);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      dates = dates + "TimeStamp" + i + "==>" + getCurrentDateTime() + "\n";
    }
    return dates;
  }
}

In above class, getTimeStamps() method returns timestamp, packages it as timeStamp.jar and copies the file to the lib/ext folder of your JMeter installation.

Add Beanshell Sampler to your Test Plan and put the following code into the “Script” area.

Import timeStampPack.*;
var time=TimeStampConversion.getTimeStamps(1);
log.info(time);

The above code will call getTimeStamps() method and logs the value.

技术分享图片

You can also use Beanshell to parameterize test data using CSV file. Check this article to see details.

How RedLine13 Enhances JMeter Load Testing

JMeter is an excellent open source load testing tool used by thousands of developers. If you’re one of them, you may want to load test. JMeter can be used for load testing. With RedLine13, you can run a JMeter Load Test with your JMX script of any mobile application, web application, or API in 10 minutes.

 

Testing Complex Logic with JMeter Beanshell

标签:current   The   测试数据   从服务器   nes   gettime   rac   detail   情况   

原文地址:https://www.cnblogs.com/a00ium/p/10263503.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!