I'm new at postman an im trying to generate a random string with letters(A-Z) and numbers(0-9). The string should have 20 points. I don't know how to set the Body and the pre req. I know that the Request must be POST. I have no idea how to start.
You can add scripts to the Pre-request Script to create this value.
This function will create the random value from the characters in the dataset and it will be 20 characters in length - The length can be adjusted when calling the function with your desired min and max values.
function randomString(minValue, maxValue, dataSet = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ') {
if (!minValue) {
minValue = 20;
maxValue = 20;
}
if (!maxValue) {
maxValue = minValue;
}
let length = _.random(minValue, maxValue),
randomString = "";
for (let i = 0; i < length; i++)
randomString += dataSet.charAt(Math.floor(Math.random() * dataSet.length));
return randomString;
}
pm.variables.set('randomString', randomString());
Adding a basic body like this is how you can use the randomly generated value:
{
"randomValue": "{{randomString}}"
}
When the request is sent, it will execute the function in the Pre-request Scripts tab and set the value as a local variable, this will then be used in the body of the request:
Per postman's docs you should be able to use {{$randomAlphaNumeric}} to generate a single character. $randomPassword seems to just generate 15 random alpha numeric characters so something like:
{{$randomPassword}}{{$randomAlphaNumeric}}{{$randomAlphaNumeric}}{{$randomAlphaNumeric}}{{$randomAlphaNumeric}}{{$randomAlphaNumeric}}
should give you 20 random characters without writing much code. This is a little terse, you could also just use the $randomAlphaNumberic selector 20 times.
Code for your Pre-request Script tab in Request:
function randomString(length=1) {
let randomString = "";
for (let i = 0; i < length; i++){
randomString += pm.variables.replaceIn("{{$randomAlphaNumeric}}");
}
return randomString;
}
STRING_LEN = 1000
pm.variables.set('randomString', randomString(STRING_LEN));
Just set the STRING_LEN to desired value.
Test it by using expression {{randomString}} i.e. in URL:
https://httpbin.org/anything?string={{randomString}}
Result:
Related
I am using postman to get response header value like below:
var data = postman.getResponseHeader("Location") . //value is "http://aaa/bbb" for example
I can print the value via console.log(data) easily.
However, what I really want is "bbb". So I need some substring() type of function. And apparently 'data' is not a javascript string type, because data.substring(10) for example always return null.
Does anyone what i need to do in this case?
If any postman API doc existing that explains this?
You can set an environment variable in postman. try something like
var data = JSON.parse(postman.getResponseHeader("Location"));
postman.setEnvironmentVariable("dataObj", data.href.substring(10));
You have the full flexibility of JavaScript at your fingertips here, so just split the String and use the part after the last /:
var data = pm.response.headers.get("Location").split("/").pop());
See W3 school's documentation of split and pop if you need more in depth examples of JavaScript internals.
Some initial thought - I needed a specific part of the "Location" header like the OP, but I had to also get a specific value from that specific part.
My header would look something like this
https://example.com?code_challenge_method=S256&redirect_uri=https://localhost:8080&response_type=code&state=vi8qPxcvv7I&nonce=uq95j99qBCGgJvrHjGoFtJiBoo
And I need the "state" value to pass on to the next request as a variable
var location_header = pm.response.headers.get("Location");
var attributes = location_header.split('&');
console.log(attributes);
var len = attributes.length;
var state_attribute_value = ""
var j = 0;
for (var i = 0; i < len; i++) {
attribute_key = attributes[i].split('=')[0];
if (attribute_key == "state") {
state_attribute_value = attributes[i].split('=')[1];
}
j = j + 1;
}
console.log(state_attribute_value);
pm.environment.set("state", state_attribute_value);
Might you get the point here, "split" is the choice to give you some array of values.
If the text you are splitting is always giving the same array length it should be easy to catch the correct number
I was trying to hit Myntra's home page and search for puma in the search box using JMeter. Using the regEx extractor I extracted few values from the response as shown below:
JMeterVariables:
JMeterThread.last_sample_ok=true
JMeterThread.pack=org.apache.jmeter.threads.SamplePackage#1589f854
START.HMS=122825
START.MS=1532069905949
START.YMD=20180720
TESTSTART.MS=1532073140645
__jmeter.USER_TOKEN__=Thread Group 1-1
outValue=puma?f=gender:men::categories:Tshirts
value_1=puma?f=gender:men::categories:Tshirts
value_1_g=1
value_1_g0="value":"puma?f=gender:men::categories:Tshirts"
value_1_g1=puma?f=gender:men::categories:Tshirts
value_2=puma?f=gender:men::categories:Casual Shoes
value_2_g=1
value_2_g0="value":"puma?f=gender:men::categories:Casual Shoes"
value_2_g1=puma?f=gender:men::categories:Casual Shoes
value_3=puma?f=gender:men::categories:Sports Shoes
value_3_g=1
value_3_g0="value":"puma?f=gender:men::categories:Sports Shoes"
value_3_g1=puma?f=gender:men::categories:Sports Shoes
value_matchNr=3
Now using For Each Controller I can pass these values to my next HTTP request and iterate through them once as shown below:
But I want to do the same thing using a BeanShell preprocessor and am new to scripting, so I need help on this that how I can do the same using a BeanShell preprocessor and pass the values to my next HTTP request.
Suggestions are welcomed.
Use value_matchNr to find out how many instance of the variable you have. Then loop: build an appropriate variable name, and get its value using vars.get(name):
// First, use the value of 'value_matchNr' to identify how many variables of type 'value_...' we have
int count = 0;
try {
count = Integer.parseInt(vars.get("value_matchNr"));
} catch(NumberFormatException e) { log.error("Variable 'value_matchNr' was not found. There won't be any looping"); }
// Next, loop through variables (if there's at least 1 to loop through)
for(int i = 1; i <= count; i++) {
String name = "value_" + i; // build variable name, e.g. value_1, value_2, etc
String value = vars.get(name); // get variable value
// at this point you can do whatever you want with the value. For example print it out:
log.info("Variable '" + name + "' has value '" + value + "'");
}
I am new to Jmeter BeanShell Scripting/Java and currently facing issue using script below.
Using Regular Expression Extractor I am able to pull array of all possible values. For example: 10 date values, and the variable is defined as ${RegExValue_All} (Template: $1$; Match: -1)
Sample Value:
01/01/2017
01/01/2017
01/01/2017
04/01/2017
05/01/2017
07/01/2017
07/01/2017
08/01/2017
10/01/2017
10/01/2017
Now I am trying to write a BeanShell script to match specific date and pull out its ordinal/index/iteration number and save it to a user defined variable ${Matched_Iteration_Value} which is currently blank.
When I am using the code below, I am able to compare the correct required values as I have set for loop count as 10 but unable to save the ordinal/index/iteration number and getting various errors.
Also I want code to stop execution as soon as 1st match is obtained and its iteration number to be saved in a variable which I need to use in subsequent requests.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
matches = (vars.get("RegExValue _All"));
for (int i=1; i<=20; i++) {
if (vars.get("cPIGValueDate_All_" + i).equals("07/01/2017")) {
log.info("Variable: cPIGValueDate_All_" + i + " is the Correct PIG");
vars.putobject("Matched_Iteration_Value ",i);
}
}
Your script and explanation are a bit inconsistent, so I have to assume some things:
That regex extractor is configured with Reference Name: RegExValue. So with Match: -1, when it finds more than 1 date, it will save them as variables with names RegExValue_1, RegExValue_2
That you don't care about RegExValue _All, since you are retrieving it, but not using it anywhere, and it's not part of your question
That you want to compare dates as dates (and not as strings), since you imported various date-related classes
That your date is in format dd/MM/yyyy
So
First of all, the loop itself should be based on variable called RegExValue_matchNr, which is automatically created by JMeter when regex has more than one match. This is better than hard-coding loop to 20.
You can convert both, expected and actual dates from string to Date using SimpleDateFormat.
Then you compare them as dates
And finally, save variable and exit the loop if dates are the same
Here's the code:
import java.lang.Integer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
// 1.
int count = 0;
try {
count = Integer.parseInt(vars.get("RegExValue_matchNr"));
}
catch(Exception e) { }
// 2.
DateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);
Date expectedDate = format.parse("07/01/2017");
for(int i = 1; i <= count; i++)
{
Date actualDate = null;
try {
actualDate = format.parse(vars.get("RegExValue_" + i));
}
catch(Exception e) { }
// 3.
if(actualDate != null && expectedDate.compareTo(actualDate) == 0) {
log.info("Variable: RegExValue_" + i + " is the Correct PIG");
// 4.
vars.put("Matched_Iteration_Value", "" + i);
return;
}
}
I have written a program in which I save an image during a loop, with this command
writeimagefile("f:\\chkng\\otp.bmp",0,0,scn,scn);
This command is from graphics.h, which writes the image file in the given location. How should I save the image every loop with a different name? i.e otp1.bmp, otp2.bmp, otp3.bmp.
for (int i = start; i != end; ++i )
{
char filename[100];
sprintf(filename, "f:\\chkng\\otp%d.bmp", i);
writeimagefile(filename,0,0,scn,scn);
}
For this, I'm assuming that your loop is index based (counts from 0 to a max). I'm also assuming that you've included string.
int max = 1; //example
for(int i=0;i<max;i++){
std::string filename = "f:\\chkng\\otp" + std::to_string(i) + ".bmp";
writeimagefile(filename.c_str(),0,0,scn,scn);
}
Explanation:
What I'm doing here is using a loop, building a string with a number in the filename as requested, and calling your function with the c_str version (what your function wants) of the filename we just built.
For loops work well for counting things, and in many languages the example you're showing can be done by concatenating the count into the filename string. Try something like the following:
for (int count = startingNumber; count <= endingNumber; count++)
{
writeimagefile("f:\\chkng\\otp" + count + ".bmp",0,0,scn,scn);
}
I have a couchdb database with 156 json documents. I want to find the max of a certain value in the documents and then emit the whole document that contains that maximun value. I used this code but it doesnt seem to work. This may help you understand what i mean.
function(doc) {
var i,m;
for (i = 0; i < doc.watchers.length; i++)
m = Math.max(m,doc.watchers[i]);
for (i = 0; i < doc.watchers.length; i++)
if (m = doc.watchers[i])
emit(doc.watchers[i], doc.watchers);
}
I would also like to select the 2 top documents, that have the max value.
Just using a map function won't work because the way map/reduce works doesn't make available the complete set of keys and values to the map function at the same time.
I would use a reduce function for that. Something like this:
Map function
function(doc) {
var i,m;
for (i = 0; i < doc.watchers.length; i++) {
emit([doc._id, doc.watchers[i]], doc.watchers);
}
}
Reduce function
function(keys, values) {
var top=0;
var index=0;
for (i=0;i<keys.length;i++) {
if (keys[i][1] > top) {
top = keys[i][1];
index = i;
}
}
return({keys[index], values[index]})
}
For this strategy to work you need to query using group_level=1, so that couch passes the results grouped by document id to the map function.
I haven't tested this solution and it doesn't solve your second question yet. I can refine it if you think it goes the right way.