Jmeter BeanShell - compare between int to counter - jmeter

I'm trying to compare int (parse from string) to counter in BeanShell assertion.
my code:
int i = Integer.parseInt(vars.get("count_2"));
counter = vars.get("counter");
if (i != counter)
{
Failure = true;
FailureMessage = "failed";
} else {
Failure = false;
}
On debug sampler I can see that both "count_2" and "counter" have the same values in all loop runs, but the assertion fails.
What went wrong?

Option 1: use integers everywhere
Change this line:
counter = vars.get("counter");
To:
int counter = Integer.parseInt(vars.get("counter"));
Option 2: use strings everywhere
String i = vars.get("count_2");
String counter = vars.get("counter");
if (!i.equals(counter))
...
JMeterVariables can be either Strings or Objects, so you need to cast them to the types you need to work with.
See How to use BeanShell: JMeter's favorite built-in component guide for essential information on scripting in JMeter and some form of cookbook.

Related

Java Palindrome always returns true

I tried to create a palindrome java program with JOptionPane by using for loop, but it ends up returning true all the time no matter the input is really a palindrome or not. Can guys please help if you guys know what's wrong with the code below, thanks.
public class program {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
JOptionPane.showMessageDialog(null, "Welcome to The Palindrome!", "Hello", JOptionPane.INFORMATION_MESSAGE);
String str = JOptionPane.showInputDialog("Please input a string");
int len = str.length();
int j = len - 1;
int i = 0;
boolean result;
for(i = 0; i <= (len - 1)/2; i++);
{
if(str.charAt(i) != str.charAt(j))
result = false;
j--;
}
if(result = true)
JOptionPane.showMessageDialog(null, str + " is a palindrome.", "ByeBye", JOptionPane.INFORMATION_MESSAGE);
if(result = false)
JOptionPane.showMessageDialog(null, str + " is not a palindrome.", "ByeBye", JOptionPane.INFORMATION_MESSAGE);
}
Instead of using traditional way to check palindrome, just use the smart way. Here you go
boolean result = str.equalsIgnoreCase(new StringBuffer(str).reverse().toString());
When you check for the value of result, you are using =, which assigns that value to the result variable, and always evaluates to true.
To correct your code, you can either remove the equal sign, or use result == true (usually you use the former, as it is more concise).
However, this may result in an error, as you are not initialising the value of result. I recommend setting it's value to true as the default value.

How to use variable from JSR223 in MQTT request

I have following script in JSR223:
setStrictJava (true);
int a = 0; // Creating a Variable
int b = 1; // Creating a Variable
int S = a - b; //
log.info(S + " - Subtraction Operation");
vars.put("T1", S)
Added, I have MQTT request, where i need to use the T1 output (-1) but it doesn't return anything.
Sure i am missing few basic. pls any help.
I don't think you can save an Integer using vars.put() function as it takes 2 Strings as the parameters, so my expectation is that you need to explicitly convert your S variable to String like:
vars.put("T1", S as String)
If you need the variable as the Integer in your MQTT logic you can use vars.putObject() function instead like:
vars.putObject("T1", S)
More information: Top 8 JMeter Java Classes You Should Be Using with Groovy

Assert if the JMeter variable has incremented from the previous iteration

In JMeter I'm doing a get request to check activeMQ queue size.
This request is made inside a Loop Controller that runs lets say 4 times.
In each iteration I'm extracting the value of outQueueCount into a JMeter variable.
How to do an assertion to verify that the current count value is greater than the previous iteration?
if you have 2 JMeter variables with numbers you can check the difference between them with __intSum function
${__intSum(${outQueueCount},-${currentCount},difference)}
difference will be a new JMeter variable with the result, then you can check if difference is 1 for example:
${__jexl3("${difference}" == "1")}
Add JSR223 Assertion as a child of the request which returns this outQueueCount
Put the following code into "Script" area:
def previousValue = vars.get('previousValue')
if (previousValue == null) {
vars.put('previousValue', vars.get('outQueueCount'))
}
else {
long previous = previousValue as long
long current = vars.get('outQueueCount') as long
if (previous >= current) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('Queue size not incremented: previous value: ' + previous + ', current value: ' + current)
}
}
If previous value will be greater than or equal to the new one - you will get an error message and the sampler will get failed:
More information: Scripting JMeter Assertions in Groovy - A Tutorial
1) Add a Counter as a child of your loop controller just before your request with the below configurations:
Start: 1
Increment: 1
Reference Name: Counter
2) Add a BeanShell PostProcessor as a child of your request after your regular expression extractor with the below script in the script area:
String Counter = vars.get("Counter");
vars.put("MyVar_" + Counter, vars.get("MyVar"));// MyVar is the name of your regular expression extractor.
3) Add a BeanShell Assertion after the above BeanShell PostProcessor with the below script in the script area:
int Counter = Integer.parseInt(vars.get("Counter"));
if(Counter > 1){
int Prev = Counter - 1;
int CurrentCount = Integer.parseInt(vars.get("MyVar_" + Counter));
int PrevCount = Integer.parseInt(vars.get("MyVar_" + Prev));
if(CurrentCount < PrevCount){
Failure = true;
FailureMessage = "CurrentCount = " + CurrentCount + " is less than " + "PrevCount = " + PrevCount;}}

Is it possible to generate UUID v1 with JMeter?

I read JMeter's manual and saw that there is __uuid() function for JMeter. It allows to generate UUID type 4 for JMeter tests. Is it possible to generate UUIDv1 in JMeter or maybe some plugin exists.
I would recommend taking the following steps:
Download Jug library (for example from here) and drop the .jar somewhere to JMeter Classpath
Restart JMeter to pick the .jar up
Once done you should be able to generate UUIDv1 using JSR223 Test Elements and Groovy language like:
import com.fasterxml.uuid.EthernetAddress
import com.fasterxml.uuid.Generators
import com.fasterxml.uuid.impl.TimeBasedGenerator
def addr = EthernetAddress.fromInterface()
def gen = Generators.timeBasedGenerator(addr)
def v1uuid = gen.generate()
log.info(v1uuid.toString())
Demo:
References:
Generating version 1 UUIDs
Groovy is the New Black
In jmeter you can add JSR 223 Sampler choose Java language and execute java code for UUID version 1:
String timeuuid = com.datastax.driver.core.utils.UUIDs.timeBased().toString();
And then add it to Jmeter variable:
vars.put("myUUID", timeuuid);
First, we'll generate the 64 least and most significant bits as long values:
private static long get64LeastSignificantBitsForVersion1() {
Random random = new Random();
long random63BitLong = random.nextLong() & 0x3FFFFFFFFFFFFFFFL;
long variant3BitFlag = 0x8000000000000000L;
return random63BitLong + variant3BitFlag;
}
private static long get64MostSignificantBitsForVersion1() {
LocalDateTime start = LocalDateTime.of(1582, 10, 15, 0, 0, 0);
Duration duration = Duration.between(start, LocalDateTime.now());
long seconds = duration.getSeconds();
long nanos = duration.getNano();
long timeForUuidIn100Nanos = seconds * 10000000 + nanos * 100;
long least12SignificatBitOfTime = (timeForUuidIn100Nanos & 0x000000000000FFFFL) >> 4;
long version = 1 << 12;
return
(timeForUuidIn100Nanos & 0xFFFFFFFFFFFF0000L) + version + least12SignificatBitOfTime;
}
We can then pass these two values to the constructor of the UUID:
public static UUID generateType1UUID() {
long most64SigBits = get64MostSignificantBitsForVersion1();
long least64SigBits = get64LeastSignificantBitsForVersion1();
return new UUID(most64SigBits, least64SigBits);
}

C++ Ensuring that user input value is int only [duplicate]

This question already has answers here:
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
Closed 8 years ago.
I am a little new to C++ and would really appreciate any input or suggestions! So with our intro course projects I have been looking for a way to ensure that when the prog. is asking for int values it correctly responds! That is it states its invalid in cases of both a double as well as string being entered! So if cin >> intVariable ... intVariable will not accept cin entry of "abdf" or 20.01.
So to achieve this I wrote the following function...It works but I am looking for your thoughts on how this process can be further improved!
void getIntegerOnly(int& intVariable, string coutStatement)
{
bool isInteger; // Check if value entered by user is int form or not
string tmpValue; // Variable to store temp value enetered by user
cout << coutStatement; // Output the msg for the cin statement
do
{
cin >> tmpValue; // Ask user to input their value
try // Use try to catch any exception caused by what user enetered
{
/* Ex. if user enters 20.01 then the if statement converts the
string to a form of int anf float to compare. that is int value
will be 20 and float will be 20.01. And if values do not match
then user input is not integer else it is. Keep looping untill
user enters a proper int value. Exception is 20 = 20.00 */
if (stoi(tmpValue) != stof(tmpValue))
{
isInteger = false; // Set to false!
clear_response(); // Clear response to state invalid
}
else
{
isInteger = true; //Set to true!
clear_cin(); // Clear cin to ignore all text and space in cin!
}
}
catch (...) // If the exception is trigured!
{
isInteger = false; // Set to false!
clear_response(); // Clear response to state invalid
}
} while (!isInteger); //Request user to input untill int clause met
//Store the int value to the variable passed by reference
intVariable = stoi(tmpValue);
}
This is simply an example of getting users age and age is greater than zero when running a Win32 console based application! Thank you for the feedback :)
One way would be something like the following:
std::string str;
std::cin >> str;
bool are_digits = std::all_of(
str.begin(), str.end(),
[](char c) { return isdigit(static_cast<unsigned char>(c)); }
);
return are_digits ? std::stoi(str) : throw std::invalid_argument{"Invalid input"};
and catch the exceptions on the calling side (stoi can also throw std::out_of_range).
You can leverage the second parameter of stoi().
string tmpValue;
size_t readChars;
stoi(tmpValue, &readChars);
if(readChars == tmpValue.length())
{
// input was integer
}
EDIT: this will not work for strings containing "." (for example integers passed in scientific notation).
This is not my work, but the answer to this question is what you want. Pass the string to it as a reference. It will return true is your string is an integer.
How do I check if a C++ string is an int?

Resources