Retrieve request data information's using JSR223 post processer in JMeter - jmeter

I am using the following payload as post request to one of my test servers, and I want to retrieve the size of the payload, uniquid from the payload. I am using JSR223 post processer for this any help to get these information
Sample Payload:
POST https://test.eventgrid.azure.net/api/events
POST data:
[
{
"subject": "audit",
"id": "6aca5990-713b-47d1-be81-ed228bd81735",
"eventType": "test.audit",
"eventTime": "2020-08-31T05:02:02.462Z",
"data": {
"version": "1.0",
"application": {
"id": "PI0001",
"name": "PLMAS",
"component": {
"id": "PLMAS01",
"name": "SingleFileImporter",
"type": "LogicApp"
}
},
"audit": {
"id": "168999807c4c46af908ce7a455a5e5eb",
"timestamp": "2020-08-31T05:02:02.462Z",
"type": "input",
"entry": "File retrieved, validated and processed successfully",
"message": {
"headers": "J9SGinwTz0SSrEHrBrhMS3wquHlWu",
"payload": "00=SfsDZ0LESTLZ6VpCmIEDT5nqOPqlwUJknCSIQuAIBM8wKj",
"type": "csv",
"protocol": ""
},
"keys": [
{
"name": "file-archive-location",
"value": "Performance Test From Jmeter"
}
]
},
"context": {
"transactionId": "65174971-62d6-44da-9ecd-537b8d636464",
"messageId": "04cb206c-25dd-4385-bed7-42f770c67cb8",
"customerId": "FANSOI",
"studyId": "FANSOI1234"
}
},
"dataVersion": "1.0",
"metadataVersion": "1"
}
]
Is there any default method like sampler.getUrl() to get the request url and sampler.getArguments().getArgument(0).getValue() to get the request body.

This should do what you want:
import java.util.List;
def size = prev.getBodySizeAsLong() + prev.getHeadersSize();
List<String> list = com.jayway.jsonpath.JsonPath.read( prev.getQueryString(), "$..id");
String uniqueId = list.get(0).toString();
log.info("size:{}, uniqueId:{}", size, uniqueId);

You can use the same functions but instead of sampler go for ctx.getCurrentSampler(), something like:
def data = ctx.getCurrentSampler().getArguments().getArgument(0).getValue()
def size = data.length()
def id = new groovy.json.JsonSlurper().parseText(data)[0].id
log.info('Size: ' + size)
log.info('Id: ' + id)
Demo:
More information:
Apache Groovy - Parsing and producing JSON
Top 8 JMeter Java Classes You Should Be Using with Groovy

Related

YouTube Data API Get Channel by Handle

Introducing handles: A new way to identify your YouTube channel
Does the YouTube Data API support querying for a channel by it's #handle? This does not seem to be supported.
ex: https://www.youtube.com/#lionsgatemovies
forUsername param
GET https://www.googleapis.com/youtube/v3/channels?part=id,snippet&forUsername=#lionsgatemovies
{
"kind": "youtube#channelListResponse",
"etag": "RuuXzTIr0OoDqI4S0RU6n4FqKEM",
"pageInfo": {
"totalResults": 0,
"resultsPerPage": 5
}
}
id param
GET https://www.googleapis.com/youtube/v3/channels?part=id,snippet&id=#lionsgatemovies
{
"kind": "youtube#channelListResponse",
"etag": "RuuXzTIr0OoDqI4S0RU6n4FqKEM",
"pageInfo": {
"totalResults": 0,
"resultsPerPage": 5
}
}
None of the supported filter params seem to be appropriate:
{
"error": {
"code": 400,
"message": "No filter selected. Expected one of: mySubscribers, forUsername, mine, managedByMe, categoryId, id",
"errors": [
{
"message": "No filter selected. Expected one of: mySubscribers, forUsername, mine, managedByMe, categoryId, id",
"domain": "youtube.parameter",
"reason": "missingRequiredParameter",
"location": "parameters.",
"locationType": "other"
}
]
}
}
You can use Search API with q parameter set to #handle
curl \
'https://youtube.googleapis.com/youtube/v3/search?part=snippet&maxResults=25&q=%40kevinrooke&type=channel&key=[YOUR_API_KEY]'
{
"kind": "youtube#searchListResponse",
"etag": "AYlro9VG2vMtdew4OQiWoQM8Rs0",
"regionCode": "LT",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "ls9E_ctoa-RLsqznJwxWlHHIE1s",
"id": {
"kind": "youtube#channel",
"channelId": "UCTdxV_ItCZMayyzGkw7P_qQ"
},
"snippet": {
"publishedAt": "2017-05-27T03:56:38Z",
"channelId": "UCTdxV_ItCZMayyzGkw7P_qQ",
"title": "Kevin Rooke",
"description": "Interviews with the builders bringing the Lightning Network to life. ⚡kerooke#fountain.fm.",
"thumbnails": {
"default": {
"url": "https://yt3.ggpht.com/ytc/AMLnZu-SpmaNjx7KOMqs5Cr7ZthU60BaQApzt89_dHOlcg=s88-c-k-c0xffffffff-no-rj-mo"
},
"medium": {
"url": "https://yt3.ggpht.com/ytc/AMLnZu-SpmaNjx7KOMqs5Cr7ZthU60BaQApzt89_dHOlcg=s240-c-k-c0xffffffff-no-rj-mo"
},
"high": {
"url": "https://yt3.ggpht.com/ytc/AMLnZu-SpmaNjx7KOMqs5Cr7ZthU60BaQApzt89_dHOlcg=s800-c-k-c0xffffffff-no-rj-mo"
}
},
"channelTitle": "Kevin Rooke",
"liveBroadcastContent": "none",
"publishTime": "2017-05-27T03:56:38Z"
}
}
]
}
As of this moment (17th Nov 2022), YouTube has yet to update the Data API with #handle support.
The channelId was scattered around in the Html. You can easily parse them after fetching the url with the handle.
const html = await(await fetch(url)).text()
const channelId = html.match(/(?<=channelId(":"|"\scontent="))[^"]+/g)[0];
Following is the python snippet while we are waiting for YouTube API's official support. This is inspired by goodhyun's wonderful thoughts.
import requests
import re
# return YouTube channel id via handle or False if failed
def scraping_get_channel_id_from_handle(handle:str):
if handle.find('#') == -1:
handle = '#' + handle
url = 'https://www.youtube.com/' + handle
resp = requests.get(url)
if resp.status_code == 200:
found = re.findall('"channelId":"([^"]*)","title"', resp.text)
return found[0]
else:
return False

How to extract multiple json values from a Json response

I am trying to extract multiple values from a JSON response on my jmeter script. Below is sample of my response:
{
"startDate": "2018-12-10T15:36:34.400+0000",
"userId": "7211111-2fa90",
"createdBy": "TEST",
"note": {
"content": "Application Submitted "
},
"Type": "SUBMITTED"
},
"currentEventState": "CLOSED",
{
"Xxxx": "test",
"Loc": null,
"Zipcode": [],
"Locality": 82,
"Address": {
"Add": 12302,
"Add2": "place",
"Zip": {
"Phone": "home",
"Email": "test#test.com"
}
},
"state": "MD",
"Cost": "E "
},
"AppID": "cd8d98e6-c2a79",
"Status": "CLOSED",
}
I am trying to extract userid and AppID for the case if the TYPE is Submitted and Status is Closed.I tried using the Json extractor with $.[?(#.Type=="SUBMITTED")].[*].?(#.Status=="CLOSED").userid,APPID, but couldn't get the expected result. Could anyone guide me on this.
You need to use an inline predicate to combine 2 clausees and a semicolon in order to store results into 2 separate JMeter Variables.
Add JSON Extractor as a child of the request which returns above JSON
Configure it as follows:
Names of created variables: userid;appid
JSON Path Expressions: $..[?(#.Type=='SUBMITTED' && #.Status == 'CLOSED')].userId; $..[?(#.Type=='SUBMITTED' && #.Status == 'CLOSED')].AppID
Default values: NA;NA
Here is the demo of single expression working fine:
And here are extracted values reported by the Debug Sampler:

Require help in creating JSR223 request for getting csv data & parsing to Jmeter

I have a HTTP request whose body data(which is in Json) is given below
{
"$ct": false,
"Source": [
"DFT"
],
"Type": "View",
"Apply": "Filter",
"Format": "PDF",
"validationFactors": {
"Expand": "attributes",
"FilterConstraints": [{
"type": "articles",
"Apply": "All",
"CreatedUpdated": [{
"title": "UN",
"FirstName": "Alia",
"MiddleName": "",
"LastName": "Stve",
"Datatype": "string",
"Encode": "Pswd",
"Local": "project",
"Id": "146FG"
}]
},
{
"type": "articles",
"Apply": "All",
"CreatedUpdated": [{
"title": "UA",
"FirstName": "ABC",
"MiddleName": "XYZ",
"LastName": "TFG",
"Datatype": "string",
"Encode": "title",
"Local": "project",
"Id": "ST6879GIGOYGO790"
}]
}
]
}
}
In above Json,I have paratermize below attributes, these values are stored in csv ."title": "${title}","FirstName": "${FirstName}","MiddleName": "${MiddleName}","LastName": "${LastName}","Datatype": "${Datatype}","Encode": "${Encode}","Local": "${Local}","Id": "${Id}"
Problem : I have created a JSR223 below my http request, but in script area how to get data from csv and parametrize it? Thanks in advance
You ain't need JSR223 PreProcessor for this, just placing JSON Payload into "Body data" tab of the HTTP Request sampler should be sufficient, just replace hard-coded values with the JMeter Variables from the CSV Data Set Config reference names.
You might also need to add a HTTP Header Manager and configure it to send Content-Type header with the value of application/json

How to simulate multiple child elements with different values in the same Jmeter POST request body?

The below request being the base request,
[
{
"name": "Test1",
"description": "testings",
"unitname": simple,
"ID": 02,
"val": "item"
},
{
"name": "Test2",
"description": "testing",
"unitname": simple3,
"ID": 23,
"val": "item"
}
]
I want to simulate this with multiple (1000) 'child' sections like the below in a single JMeter request:
It should create 1000 data set(name,description,unitname,ID,val) with unique values and then post the request. Instead of manually creating multiple tags, can i automate it or create a script to generate this automatically ?
[
{
"name": "Test1",
"description": "testings",
"unitname": simple,
"ID": 02,
"val": "item"
},
{
"name": "Test2",
"description": "testing",
"unitname": simple3,
"ID": 23,
"val": "item"
}
{
"name": "Test3",
"description": "testing",
"unitname": simple4,
"ID": 23,
"val": "item"
}
{
"name": "Test4",
"description": "testing",
"unitname": simple6,
"ID": 23,
"val": "item"
}
]
Any help please?
Add JSR223 PreProcessor as a child of your request where you need to send the generated JSON
Put the following code into "Script" area:
import groovy.json.JsonBuilder
import groovy.json.internal.LazyMap
import org.apache.commons.lang3.RandomStringUtils
def data = new ArrayList()
1.upto(1000, {
def entry = new LazyMap()
entry.put('name', 'test' + it)
entry.put('description', RandomStringUtils.randomAlphabetic(10))
entry.put('unitname', 'simple')
entry.put('ID', it)
entry.put('val', 'item')
data.add(entry)
})
def builder = new JsonBuilder()
builder(
data.collect {
[
name : it.get('name'),
descrtiption: it.get('description'),
unitname : it.get('unitname'),
ID : it.get('ID'),
val : it.get('val')
]
}
)
sampler.setPostBodyRaw(true)
sampler.addNonEncodedArgument("", builder.toPrettyString(), "")
Tick Cache compiled script if available box
Make sure groovy is selected in "Language" dropdown
That's it, the above script will generate a JSON Array and set it as the HTTP Request sampler's body.
More information:
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

json deserializing coming back empty

I took suggestions from here and tried to create a class with objects for the parts I need to parse from my json feed. I then tried to deserialize it before mapping the field contents to my objects but the deserialization returns nothing.
Here is the json feed content:
"data": [
{
"id": "17xxxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxx",
"from": {
"name": "Lxxxxxx",
"category": "Sports league",
"id": "17xxxxxxxxxxxxx"
},
"picture": "http://external.ak.fbcdn.net/safe_image.php?d=AQB4GscSy-2RHY_0&w=130&h=130&url=http\u00253A\u00252F\u00252Fwww.ligabbva.com\u00252Fquiz\u00252Farchivos\u00252Fbenzema-quiz-facebook.png",
"link": "http://www.xxxxxva.com/quiz/index.php?qid=34",
"source": "http://www.lxxxxva.com/modulos/redirectQuiz.php?name=benzema&q=34&time=1312827103",
"name": "DEMUESTRA CU\u00c1NTO SABES SOBRE... BENZEMA",
"caption": "www.xxxxxva.com",
"description": "Demuestra cu\u00e1nto sabes sobre Karim Benzema, delantero del Real Madrid.",
"icon": "http://static.ak.fbcdn.net/rsrc.php/v1/yj/r/v2OnaTyTQZE.gif",
"type": "video",
"created_time": "2011-08-08T18:11:54+0000",
"updated_time": "2011-08-08T18:11:54+0000",
"likes": {
"data": [
{
"name": "Jhona Arancibia",
"id": "100000851276736"
},
{
"name": "Luis To\u00f1o",
"id": "100000735350531"
},
{
"name": "Manuel Raul Guerrero Cumbicos",
"id": "100001485973224"
},
{
"name": "Emmanuel Gutierrez",
"id": "100000995038988"
}
],
"count": 127
},
"comments": {
"count": 33
}
},
{
"id": "17xxxxxxxxxxxxxxxx_xxxxxxxxxxxxx",
"from": {
"name"
and here is the code I am trying. I tried to also use the jsontextreader and loop through each tokentype and check each one and then read the value but this looks like it will turn out to be tedious.
....
//fetch the content
responsedata = reader.readtoend()
......
dim pp as facedata = JsonConvert.DeserializeObject(of faceData)(responsedata)
console.writeline(pp.id.tostring)
and the class objects
Public Class faceData
Public Property id() as string
Get
Return f_id
End Get
Set(ByVal value as string)
f_id =value
End Set
End Property
Private f_id as string
......
any response appreciated.
Does anyone have links to full code where it actually works using vb.net.

Resources