Can we assert API response using code like javascript using Jmeter - jmeter

I am trying to explore Jmeter for API testing.
I am able to add Assert using response assertion of Jmeter.
But I like a platform in Jmeter where we can write our code to assert more complex scenario of testing API tests on API.
Similar as we can say we do use of groovy scripts in SOAP-UI or javascript in postman tests using Newman node module.
Is it possible in Jmeter?
Is there any plug-in available to achieve same in Jmeter.
I have tried to found out any tutorial or blog regarding same but land with no success.
If anyone has tried then please do share your experience, way, blog or tutorials which can lead me to achieve same in Jmeter that would really help.
Any workaround will be helpful and appreciated in advance!!!

Of course you can execute Javascript (on server side) to assert API response
You just need to add JSR223 Assertion as a Assertion to your request and choose Language as javascript and write your assertion code by checking prev which is a SampleResult
Here a demo that get response search for string success and log the first position in string using javascript:
var response = prev.getResponseDataAsString();
var pos = response.search("success");
log.info(pos);

The options are in:
JSON Path Assertion where you can use JSONPath queries in order to test the response
If you need more advanced logic you can go for JSR223 Assertion and Groovy language. Groovy has built-in JSON support so you will be able to apply any custom logic. More information: Scripting JMeter Assertions in Groovy - A Tutorial

continuing the user7294900 answer you can write code something like below in JSR223 Assertion:
JAVASCRIPT
var responseBody = prev.getResponseDataAsString();
log.info(responseBody)
log.info(responseBody.code)
var jsonData = JSON.parse(responseBody);
log.info("my name from response = "+jsonData.name)
I have found Jmeter have inbuild function of Assert that is AssertionResult
Groovy
Use code as below:
import groovy.json.JsonSlurper;
def failureMessage = "";
def jsonResponse = null;
JsonSlurper JSON = new JsonSlurper ();
try {
jsonResponse = JSON.parseText(prev.getResponseDataAsString());
} catch (Exception e) {
failureMessage += "Invalid JSON.\n"
}
log.info("***********Starting Assert************")
log.info("******************************************************")
log.info("my name ="+jsonResponse.name)
if(!"201".equals(prev.getResponseCode())){
failureMessage += "Expected <response code> [201] but we got instead [" + prev.getResponseCode() + "]\n\n" ;
}
if(!"morpheus".equals(jsonResponse.name)){
failureMessage += "Expected name is morpheus but we got instead [" + jsonResponse.name + "]\n\n" ;
log.info("asset fail")
}
if(!"morpheus2".equals(jsonResponse.name)){
failureMessage += "Expected name is morpheus2 but we got instead [" + jsonResponse.name + "]\n\n" ;
log.info("asset fail")
}
if(!"leader".equals(jsonResponse.job)){
failureMessage += "Expected job is leader but we got instead [" + jsonResponse.job + "]\n\n" ;
log.info("asset fail")
}
if(!"leader1".equals(jsonResponse.job)){
failureMessage += "Expected job is leader1 but we got instead [" + jsonResponse.job + "]\n\n" ;
log.info("asset fail")
}
// Print error messages if any
if (failureMessage?.trim()) {
failureMessage += "URL: " + SampleResult.getURL() + "\n\n";
failureMessage += "JSON RESPONSE: " + jsonResponse + "\n\n";
failureMessage += "REQUEST HEADERS: " + SampleResult.getRequestHeaders() + "\n\n";
AssertionResult.setFailureMessage(failureMessage);
AssertionResult.setFailure(true);
}
Source:
https://www.blazemeter.com/blog/scripting-jmeter-assertions-in-groovy-a-tutorial

Related

Geoserver - GetFeature SHAPE-ZIP request - 413 error

I am using Geoserver with an app written with OpenLayers 3. The app can download zipped shapefiles using a WFS service, which works unless I make a large (long URL) request. In that case I get a 413 error in Chrome.
Is there a way I can change this setting so that I can make a longer request to Geoserver (or is the problem something else?
Here is the request:
$('#btnDownloadSHP').click(function (e) {
var tostring = '(' + ids.toString() + ')';
var data = {
service: 'WFS',
version: '1.1.0',
request: 'GetFeature',
typename: 'download_layer',
format_options: "filename:" + shapefileName,
srsname: 'EPSG:3857',
outputFormat: 'SHAPE-ZIP',
CQL_FILTER: "id IN " + tostring
}
var parameters = Object.keys(data).map(function (key) {
return key + '=' + data[key]
}).join('&');
var url = "http://" + servername + "/geoserver/wfs?" + parameters;
//make dummy link and download shapefile
var link = document.createElement("a");
link.download = 'Features';
link.href = url;
link.click();
// }
});
That response would be generated by the server that GeoServer is running on rather than GeoServer itself. So depending on which httpd and/or servlet engine you are using you may be able to fix it there.
But the easy answer is to switch from GET to POST.

How to get the raw content of an outlook email message with Office JS API?

I'm trying to check if the sender used a proxy email address. Comparing the from and sender properties isn't enough, so I thought of checking the raw message source itself.
How do you get the raw message source with Office JS API?
If you're just looking for a prebuilt solution to see and analyze message headers in Outlook and OWA, you can use Message Header Analyzer. If you're building your own add-in, you can borrow source from there.
Basically, you have two options:
EWS
Rest
In both cases, what you want to retrieve is PR_TRANSPORT_MESSAGE_HEADER, aka 0x007D. The EWS request will look something like this:
function getHeadersRequest(id) {
// Return a GetItem EWS operation request for the headers of the specified item.
return "<GetItem xmlns='http://schemas.microsoft.com/exchange/services/2006/messages'>" +
" <ItemShape>" +
" <t:BaseShape>IdOnly</t:BaseShape>" +
" <t:BodyType>Text</t:BodyType>" +
" <t:AdditionalProperties>" +
// PR_TRANSPORT_MESSAGE_HEADERS
" <t:ExtendedFieldURI PropertyTag='0x007D' PropertyType='String' />" +
" </t:AdditionalProperties>" +
" </ItemShape>" +
" <ItemIds><t:ItemId Id='" + id + "'/></ItemIds>" +
"</GetItem>";
}
And you'll submit it through a call to makeEwsRequestAsync
var mailbox = Office.context.mailbox;
var request = getHeadersRequest(mailbox.item.itemId);
var envelope = getSoapEnvelope(request);
mailbox.makeEwsRequestAsync(envelope, function (asyncResult) {
callbackEws(asyncResult, headersLoadedCallback);
});
To do the same from rest, you first need to get the rest ID for the item:
function getItemRestId() {
if (Office.context.mailbox.diagnostics.hostName === "OutlookIOS") {
// itemId is already REST-formatted
return Office.context.mailbox.item.itemId;
} else {
// Convert to an item ID for API v2.0
return Office.context.mailbox.convertToRestId(
Office.context.mailbox.item.itemId,
Office.MailboxEnums.RestVersion.v2_0
);
}
And then send the request through AJAX:
var getMessageUrl = getRestUrl(accessToken) +
"/api/v2.0/me/messages/" +
itemId +
// PR_TRANSPORT_MESSAGE_HEADERS
"?$select=SingleValueExtendedProperties&$expand=SingleValueExtendedProperties($filter=PropertyId eq 'String 0x007D')";
$.ajax({
url: getMessageUrl,
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken,
"Accept": "application/json; odata.metadata=none"
}
}).done(function (item) {
The MHA source gives more context.

IPCapture library for Processing returns error

I've been trying to use this library:
ipcapture: Processing library for MJPEG stream acquisition from IP cameras
But I'm not having any luck. I've tried Processing 2 and 3 on a Mac, and keep getting this error:
Unable to open I/O streams: Server returned HTTP response code: 401 for URL: http://192.168.0.14/videostream.cgi
The Foscam IP camera streams to a webpage like this:
http://192.168.0.14/videostream.cgi?user=admin&pwd=
So in Processing I used this:
cam = new IPCapture(this, "http://192.168.0.14/videostream.cgi", "admin", "");
What am I overlooking or misinterpreting?
Thanks.
401 is UnAuthorized, probably means your password did not go through.
I would try still sending the authentication as part of the url.
Try this
1)
cam = new IPCapture(this, "http://192.168.0.14/videostream.cgi?user=admin&pwd=", "", "");
And comment out
try {
conn = (HttpURLConnection)url.openConnection();
//comment out the following line.
//conn.setRequestProperty("Authorization", "Basic " + base64.encode(user + ":" + pass));
httpIn = new BufferedInputStream(conn.getInputStream(), 8192);
}
catch (IOException e) {
System.err.println("Unable to connect: " + e.getMessage());
return;
}
I'm going by what i found at https://code.google.com/p/ipcapture/source/browse/src/IPCapture.java?r=5f5996377689334b4bb7c1d24319f4932694f4a8
Hope it helps!

I need to responses messageID in logica SMPP async mode

In logica smpp I need to stored response message ID in asynchronous mode.
if (sb.asynchronous)
{
System.out.println("Submit request " + request.debugString());
sb.getSession().submit(request);
//messageId = response.getMessageId();
} else {
response = sb.getSession().submit(request);
messageId = response.getMessageId().trim();
}
In the above code. How we can get messageID in asynchronous mode.
You can get Message id by getSmDefaultMsgId() by calling it with SubmitSM 's object . like below:
if (sb.asynchronous)
{
System.out.println("Submit request " + request.debugString());
sb.getSession().submit(request);
messageId = request.getSmDefaultMsgId();
}
For more documentation you can read this tutorial
Thanks. Let me know if it helped.

XmlHttpRequest corrupts headers in Firefox 3.6 with "Content-Type:multipart/form-data"

I'm working on "multiple ajax uloader". Works fine in bleeding edge browsers (Chrome 6, Firefox 4). But in Firefox 3.6 I must manualy create output string to be sended, cos this browser doesn't support FormData object.
I followed many tutorial, especialy this. Author notify about correct setup of headers & content of body to be sended. I carefully followed that advises, but Firefox 3.6 fail my efforts.
This is correct setup of headers and body (captured by submitting simple static form):
correct headers, correct body
This is what I get, when I use Firefox's xhr object to submit same data:
wrong headers, wrong body
As you can see xhr's headers are corrupted. This lead in total failure of file upload. Here is a code I use:
function generateBoundary()
{
var chars = '0123456789',
out = '';
for( var i = 0, len = chars.length; i < 30; i++) {
out += chars[Math.floor(Math.random()*len)];
}
return '----' + out;
}
function getMultipartFd(file, boundary)
{
var rn = '\r\n',
body = '';
body = boundary + rn;
body += 'Content-Disposition: form-data; name="Files[]"; filename="' + file.name + '"' + rn;
body += 'Content-Type: ' + file.type + rn + rn;
body += file.getAsBinary() + rn;
return body;
}
$(function(){
$startUpload.click(function(){
var url = $uploadForm.attr('action'),
xhr = new XMLHttpRequest(),
boundary = generateBoundary(),
file = null,
body = '';
file = $SOME_ELEMENT_WITH_ATTACHED_FILE.file;
body = getMultipartFd(file, boundary);
console.info(file);
console.info(body);
xhr.upload.onload = function(){
console.info('done');
};
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.sendAsBinary(body + boundary + '--' + '\r\n');
return false;
});
});
Here is also a dump of file and body variables:
dump file, dump body
Have anybody any idea, why xhr is corrupting headers this way?
I was scoping problem. I tried to use code in fresh Firefox installation under WinXP (my primary system is Arch Linux). Problem remains. I found that Mozilla's xhr has additional property called 'multipart'. With this set to true, headers is OK, but my xhr.events aren't fired - JS crash after sending file.
I scoped bit more deep with Firebug's JS debugger and found, that after xhr.multipart = true; code jumps into deep waters of jQuery library, where strange things happens around some curious events.
Even more curiou is that headers/content seems to be right in Firebug's console, but in HttpFox extension, it is corrupted.

Resources