Is it possible to access the value of the response size in my postman test cases ?
While I am able to see the response size alongside the status code and the response time (both of which i can use in my test cases using responseCode.code and responseTime) I have not been able to use it in my tests. [I tried variables like responseSize and so forth to no success]
pm.response.responseSize will give you the response size of the body.
There is a possibility though not so straightforward:
The size you get in Postman is made of Body size and Headers size (just point on Size's value).
In your test area, you can recover Body size doing:
`
var size=0;
for (var count in responseBody) {
if(responseBody.hasOwnProperty(count))
size += 1;
}
console.log("BODY SIZE = " + size); // you'll see the correct value in the console for the body part
`
For headers I didn't manage to approach the value seen in postman.
In my case I always have the same response headers (I set them all in headers_id) and from these I do:
`
headers_id=["content-encoding","content-type","date","set-cookie","transfer-encoding","x-mbs-platform-state","x-representation-exclude"];
header_size = 0;
for (var i in headers_id)
{
myHeader=postman.getResponseHeader(headers_id[i]);
console.log("header " + myHeader);
console.log("- size " + myHeader.length);
console.log("- name's size " + headers_id[i].length);
header_size += myHeader.length; //+ headers_id[i].length; // uncomment this part if you want header content's size + header name's size
}
console.log("TOTAL HEADER SIZE = " + header_size);
`
Hope this helps
Alexandre
Adding an example to Sbaddam's excellent answer:
pm.test("response size", function () {
pm.expect(pm.response.responseSize).to.be.equal(1252184);
});
Related
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:
I am writing a client program and server program. On the server program, in order to write the result back to the client, I have to convert the string to const char* to put it in a const void* variable to use the write() function. The string itself is outputting the correct result when I checked, but when I use the c_str() function on the string, it is only outputting up until the first variable in the string. I am providing some code for reference (not sure if this is making any sense).
I have already tried all sorts of different ways to adjust the string, but nothing has worked yet.
Here are how the variables have been declared:
string final;
const void * fnlPrice;
carTable* table = new carTable[fileLength];
Here is the struct for the table:
struct carTable
{
string mm; // make and model
string hPrice; // high price
string lPrice; // low price
};
Here is a snipped of the code with the issue, starting with updating the string variable, final, with text as well as the resulting string variables:
final = "The high price for that car is $" + table[a].hPrice + "\nThe low
price for that car is $" + table[a].lPrice;;
if(found = true)
{
fnlPrice = final.c_str();
n = write(newsockfd,fnlPrice, 200);
if (n < 0)
{
error("ERROR writing to socket");
}
}
else
{
n = write(newsockfd, "That make and model is not in
the database. \n", 100);
if (n < 0)
{
error("ERROR writing to socket");
}
}
Unfortunately your code does not make any sense. And that may be your major problem. You should rewrite you code end eliminate the bugs.
Switch on all compiler warnings and eliminate the warnings.
Do not use new and pointers. Never
Do not use C-Style arrays. So, something with []. Never. Use STL containers
Always initialize all variables. Always. Even if you assign an other value in the next line
Do not use magic constants like 200 (The size of the string is final.size())
If an error happens then print the error text with strerror (or a compatible function)
Make sure that your array itself and the array values are initalized
To test your function, write to socket 1 (_write(1,fnlPrice,final.size()); 1 is equal to std::cout
There is no need to use the void pointer. You can use n = _write(newsockfd, final.c_str(), final.size()); directly
If you want a detailed answer here on SO then you need to post your compiled code. I have rewritten your function and tested it. It works for me and prints the complete string. So, there is a bug in an other part of your code that we cannot not see.
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'm trying to use the limit parameter in PrestaShop's WebService.
My problem is it's only half working, the number of entries to display is working fine, but the "starting point" is not.
For example:
http://example.com/api/combinations?display=[id,reference]&limit=[0,500]&sort=id_ASC&ws_key=WEBSERVICEKEY
AND
http://example.com/api/combinations?display=[id,reference]&limit=[500,500]&sort=id_ASC&ws_key=WEBSERVICEKEY
Returns exactly the same products (first 500).
I am using PS 1.6.1.17
I've updated the classes/webservice folder with the latest (from 1.6.1.18).
The code (classes/webservice/WebserviceRequest.php) - no override:
$sql_limit = '';
if (isset($this->urlFragments['limit'])) {
$limitArgs = explode(',', $this->urlFragments['limit']);
if (count($limitArgs) > 2) {
$this->setError(400, 'The "limit" value has to be formed as this example: "5,25" or "10"', 39);
return false;
} else {
$sql_limit .= ' LIMIT '.(int)($limitArgs[0]).(isset($limitArgs[1]) ? ', '.(int)($limitArgs[1]) : '')."\n";// LIMIT X|X, Y
}
}
The code looks fine, maybe it's SQL related? I'd like to print the generated query to test it but I couldn't fin a way...
I've found the problem.
The int cast wasn't working here.
$this->urlFragments['limit'] value is [500,500].
So after explode $limitArgs[0] is equal to [500 but the code (int)($limitArgs[0]) was always giving me 0 instead of 500 as result.
I replaced it with an ugly str_replace as follow:
$sql_limit .= ' LIMIT '.str_replace("[", "", $limitArgs[0]).(isset($limitArgs[1]) ? ','.(int)($limitArgs[1]) : '')."\n";// LIMIT X|X, Y
Not the best, but could be usefull if anyone faces this situation.
edit: I posted on the forge, the correct syntax for limit is limit=X,Y not limit=[X,Y].