Getting error in Postman request as TypeError Cannot read property 'xyz' of undefined - postman-collection-runner

Getting error while running the script in Postman(on newman as well) request as TypeError Cannot read property 'xyz' of undefined.
In my request, i have test script as :
var jsonData = JSON.parse(responseBody);
tests["Response has data value"] = jsonData.from.xyz === dataAuth.auth;
dataAuth is my data file in json is as below :
[{
"path": "auth",
"id": "test11",
"desc": "test11",
"fk": "None",
}]

This means that a variable is undefined in your tests.

Related

Defining an array of json docs in Elasticsearch Painless Lab

I'm trying to define some docs in ES Painless Lab, to test some logic in Painless Lab, before running it on the actual index, but can't figure out how to do it, and the docs are not helping either. There is very little documentation on the actual syntax and it's not much help for someone with no Java background.
If I try to define a doc like this:
def docs = [{ "id": 1, "name": "Apple" }];
I get an error:
Unhandled Exception illegal_argument_exception
invalid sequence of tokens near ['{'].
Stack:
[
"def docs = [{ \"id\": 1, \"name\": \"Apple ...",
" ^---- HERE"
]
If I want to do it the Java way:
String message;
JSONObject json = new JSONObject();
json.put("test1", "value1");
message = json.toString();
I'm also getting an error:
Unhandled Exception illegal_argument_exception
invalid declaration: cannot resolve type [JSONObject]
Stack:
[
"... ring message;\nJSONObject json = new JSONObject();\n ...",
" ^---- HERE"
]
So what's the proper way to define an array of json objects to play with in Painless Lab?
After more experimenting, I found out that the docs can be passed in the parameters tab as:
{
"docs": [
{ "id": 1, "name": "Apple" },
{ "id": 2, "name": "Pear" },
{ "id": 3, "name": "Pineapple" }
]
}
and then access it from the code as
def doc = params.docs[1];
return doc["name"];
I'd be still interested how to define an object or array in the code itself.

How to iterate through the contents of a Json object

On the JSR223 assertion in Jmeter, I need to validate only the inner part of the JSON returned.
I followed this thread to get an idea on the validation.
​How can I write JSON schema validation for JMeter run in TeamCity
Basically my Jmeter sampler returns the json as follows. On my schema, the validation should be for items, service and requestId. No validation should be performed for "payload".
{
"payload": [
{
"items": [
{
"code": "487482378",
"description": "Alpha Co",
"valid": true
},
{
"code": "92901128365",
"description": "Beta Co",
"valid": true
}
],
"service": "entities",
"requestId": "d190219"
}
]
}
This is my current code in the js223 sampler:
var schemaPath = '/path/entities-schema.json'
var rawSchema = new org.json.JSONObject(new org.json.JSONTokener(org.apache.commons.io.FileUtils.readFileToString(new java.io.File(schemaPath), 'UTF-8')))
var schema = org.everit.json.schema.loader.SchemaLoader.load(rawSchema)
schema.validate(new org.json.JSONObject(prev.getResponseDataAsString()))
You can remove the "unwanted" part of the response using JSR223 PostProcessor like:
def before = prev.getResponseDataAsString()
log.info('Before: ' + before)
def response = new groovy.json.JsonSlurper().parseText(before)
def after = new groovy.json.JsonBuilder(response.payload.items).toPrettyString()
log.info('After: ' + after)
prev.setResponseData(after, 'UTF-8')
Once done you can use your JSON Schema validation approach against the new content without elements you don't need.
References:
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

MailChimp API 3.0 batch request returns 400 Invalid Resource error

I've been trying to use the batch endpoint of MailChimp API (version 3.0) to subscribe new users to a list, but can't make it work.
Here is the request:
POST /3.0/batches
{
"operations": [
{
"method" : "POST",
"path" : "lists/c852ce5c86/members",
"body": "{\"email_address\":\"email#domain.tld\", \"status\":\"subscribed\"}"
}
]
}
The request seems ok cause I get a 200 response:
{
"id": "49abca6ef3",
"status": "finished",
"total_operations": 1,
"finished_operations": 1,
"errored_operations": 1,
"submitted_at": "2015-09-21T18:11:16+00:00",
"completed_at": "2015-09-21T18:11:23+00:00",
"response_body_url": "https://mailchimp-api-batch.s3.amazonaws.com/49abca6ef3-response.tar.gz?..."
}
However, as you can see, the only operation in my batch is errored.
Here is the response_body_url for this operation:
[{
"status_code":400,
"operation_id":null,
"response":"{
\"type\":\"http://kb.mailchimp.com/api/error-docs/400-invalid-resource\",
\"title\":\"Invalid Resource\",
\"status\":400,
\"detail\":\"The resource submitted could not be validated. For field-specific details, see the 'errors' array.\",
\"instance\":\"\",
\"errors\":[{
\"field\":\"\",
\"message\":\"Schema describes object, NULL found instead\"
}]
}"
}]
which is not very helpful :(
Note that if I directly hit POST lists/c852ce5c86/members with {"email_address":"email#domain.tld", "status":"subscribed"} payload, it's working properly.
That was actually a bug in the mailchimp API. After reaching them they quickly fixed it.

Parsing request JSON in Sinatra app

I am having some difficulty with parsing the JSON from a request to my Sinatra application:
response = JSON.pretty_generate(request.env)
reply = response["rack.request.form_hash"]
results in reply just returning:
rack.request.form_hash
as a string rather than just the relevant part of the response:
{...
"rack.request.form_hash": {
"token": "token",
"team_id": "team",
"team_domain": "teamname",
"service_id": "service",
"channel_id": "channel",
"channel_name": "testing-webhooks",
"timestamp": "1424480976.000910",
"user_id": "U029W1WF2",
"user_name": "myusername",
"text": "checkeverything",
"trigger_word": "checkeverything"
},
...}
which is within the JSON request object I'm trying to parse. When I use:
response["rack.request.form_hash"]["user_name"]
there is nothing returned. The following is returned in my log:
App 1662 stdout:
App 1640 stderr: JSON::ParserError - 746: unexpected token at 'No text specified':
So it looks like it's not iterating properly, or perhaps can't access it.
I've looked through other documentation and other posts, but found nothing that worked for me, but I am definitely overlooking something, but I'm not sure what.
What is the best way to parse this nested array in a request to Sinatra?
This should fix it :
res = JSON.parse( JSON.generate(request.env) )
res.class
# => Hash
res["rack.url_scheme"]
# => http
The reason is that the JSON.generate only generates JSON syntax for objects and arrays in a string. Then you need to parse the generated JSON string into a hash in Ruby with JSON.parse.

Fancytree complains Ajax request returned a string using Cherrypy

Hi I am very new to use cherrypy as backend with fanytree as front end.
here is my fanytree side of the code:
source: {
url : '/test_data'
},
on the cherrypy side, I implemented function called test_data
#cherrypy.expose
#cherrypy.tools.json_out()
def test_data(self, **kwargs):
cherrypy.response.headers["Content-Type"] = "application/json"
return '[ {"title":"abc", "folder": true, "key": "1", "children":[ {"title":"b","key":"2"}] }]'
So I see the request comes to cherrypy as
'GET /test_data?_=some number...
On browser I see my return object back but it failed on check:
if (typeof data === "string") {
$.error("Ajax request returned a string (did you get the JSON dataType wrong?).");
}
I read somewhere that you need content-type to be json but I already have. What am I missing?
CherryPy JSON output tool, cherrypy.tools.json_out, takes care of MIME and turning your data into a JSON string. So if you use it the method should look like:
#cherrypy.expose
#cherrypy.tools.json_out()
def test_data(self, **kwargs):
return [{
"title" : "abc",
"folder" : True,
"key" : 1,
"children" : [{"title": "b", "key": 2}]
}]
Otherwise if you want to do it yourself it'll be:
import json
#cherrypy.expose
def test_data(self, **kwargs):
cherrypy.response.headers["Content-Type"] = "application/json"
return json.dumps([{
"title" : "abc",
"folder" : True,
"key" : 1,
"children" : [{"title": "b", "key": 2}]
}])
Then make sure you've restarted CherryPy app, and look in web developer tools or FireBug network tab to verify response headers and content.
The content type is ok, but the string you are returning is not valid json (for example the keys must be enclosed in double quotes).
I would recommend to prepare your data as list of dicts and then use 'json.dumps()' to convert to JSON.
(Maybe the json_out tool does the same but I would guess that even then you should return a list of dicts instead of a string.)

Resources