Are there ways to check the structure of JSON response in Postman tests? - automated-tests

I have written several tests in Postman, based on the example snippet codes given in the Postman GUI on Windows desktop.
Mainly, I want to check for existence of the parameters in the response (exact in those cases where I need to check for particular values of the parameters) and I want to know if there's a better way to do it than the way I've been doing now.
The following test shows one such example and this is just a small part of it. The actual response schema is a lot larger so I envisioned writing 50-60 lines of such checks per API endpoint.
pm.test("Det details of a POI", function () {
pm.expect(jsonData.code).to.eql(0);
pm.expect(jsonData.data[0].provider).to.eql("google");
pm.expect(jsonData.data[0]).to.have.property("id");
pm.expect(jsonData.data[0].location).to.have.property("position");
pm.expect(jsonData.data[0].location.address).to.have.property("text");
pm.expect(jsonData.data[0].location.address).to.have.property("house");
pm.expect(jsonData.data[0].location.address).to.have.property("street");
pm.expect(jsonData.data[0].location.address).to.have.property("postalCode");
pm.expect(jsonData.data[0].location.address).to.have.property("city");
pm.expect(jsonData.data[0].location.address).to.have.property("county");
pm.expect(jsonData.data[0].location.address).to.have.property("state");
pm.expect(jsonData.data[0].location.address.country).to.eql("United Kingdom");
pm.expect(jsonData.data[0].location.address).to.have.property("countryCode");
pm.expect(jsonData.data[0].contacts).to.have.property("phone");
pm.expect(jsonData.data[0].contacts.website.value).to.include("www.google.com");
pm.expect(jsonData.data[0].contacts.website).to.have.property("label");
pm.expect(jsonData.data[0].categories[0]).to.have.property("id");
pm.expect(jsonData.data[0].categories[0]).to.have.property("title");
pm.expect(jsonData.data[0].categories[0]).to.have.property("type");
pm.expect(jsonData.data[0].categories[0]).to.have.property("system");
)};
Any tips and improvements would be greatly appreciated.

You're basically asking the same as these two Stack Overflow posts:
Schema validation using Postman
How to validate response in Postman?
Answer: There is a json format validation build into Postman it uses the Tiny Validator project to allow schema validation in post-request test scripts. Research Postman's documentation (1, 2) for examples on how to use it.

Related

Logic App using HTTP Action to access and GET Jira ticket

So I followed this answer and it works fine:
https://stackoverflow.com/a/74981947/20829088
Provided URL:
https://<YOUR_DOMAIN>.atlassian.net/rest/api/2/search?jql=project=<PROJECTID>&fields=issue,status,name&startAt=0&maxResults=8000
However, it take a lot of time. So, if I want the url to check for specific ticket depending on created time and type of ticket. For example
I want ticket that is created within 15 days and that are NOT a sub-task.
so I tried something like this.
.....&fields=issue,summary,issuetype&created>=-15d&hierarchylevel=0
I'm not sure of how it should be written I just tried this and it doesn't work.
Here is the request result in JSON:
It should be earthier [subtask=false] OR [hierarchylevel=0] OR [name=Task]
After reproducing from my end, I could able to achieve this using Condition connector of logic apps. I have initialized an array variable first and then tried to append each item that satisfies the condition. Below is the flow of my logic app.
and then I used Parse Json to retrieve the required values for condition comparision
You can use the below Code view to reproduce the same in your environment.
{"definition":{"$schema":"https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#","actions":{"For_each":{"actions":{"Compose":{"inputs":"#items('For_each')?['fields']?['created']","runAfter":{},"type":"Compose"},"Condition":{"actions":{"Append_to_array_variable":{"inputs":{"name":"Array","value":"#items('For_each')"},"runAfter":{},"type":"AppendToArrayVariable"}},"expression":{"or":[{"greaterOrEquals":["#formatDateTime(outputs('Compose'),'yyyy-MM-dd')","#formatDateTime(addDays(utcNow(),-15),'yyyy-MM-dd')"]},{"equals":["#items('For_each')?['fields']?['issuetype']?['subtask']",false]},{"equals":["#items('For_each')?['fields']?['issuetype']?['hierarchyLevel']",0]},{"equals":["#items('For_each')?['fields']?['status']?['statusCategory']?['name']","Task"]}]},"runAfter":{"Compose":["Succeeded"]},"type":"If"}},"foreach":"#body('Parse_JSON')?['issues']","runAfter":{"Parse_JSON":["Succeeded"]},"type":"Foreach"},"HTTP":{"inputs":{"authentication":{"password":"<API_KEY>","type":"Basic","username":"<USERNAME>"},"method":"GET","uri":"https://jira#<ProjectName>.atlassian.net/rest/api/2/search?jql=project=<ProjectID>"},"runAfter":{},"type":"Http"},"Initialize_variable":{"inputs":{"variables":[{"name":"Array","type":"array"}]},"runAfter":{"HTTP":["Succeeded"]},"type":"InitializeVariable"},"Parse_JSON":{"inputs":{"content":"#body('HTTP')","schema":{"properties":{"expand":{"type":"string"},"issues":{"items":{"properties":{"expand":{"type":"string"},"fields":{"properties":{"aggregateprogress":{"properties":{"progress":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"aggregatetimeestimate":{},"aggregatetimeoriginalestimate":{},"aggregatetimespent":{},"assignee":{},"components":{"type":"array"},"created":{"type":"string"},"creator":{"properties":{"accountId":{"type":"string"},"accountType":{"type":"string"},"active":{"type":"boolean"},"avatarUrls":{"properties":{"16x16":{"type":"string"},"24x24":{"type":"string"},"32x32":{"type":"string"},"48x48":{"type":"string"}},"type":"object"},"displayName":{"type":"string"},"emailAddress":{"type":"string"},"self":{"type":"string"},"timeZone":{"type":"string"}},"type":"object"},"customfield_10001":{},"customfield_10002":{},"customfield_10003":{},"customfield_10004":{},"customfield_10005":{},"customfield_10006":{},"customfield_10007":{},"customfield_10008":{},"customfield_10009":{},"customfield_10010":{},"customfield_10014":{},"customfield_10015":{},"customfield_10016":{},"customfield_10017":{"type":"string"},"customfield_10018":{"properties":{"hasEpicLinkFieldDependency":{"type":"boolean"},"nonEditableReason":{"properties":{"message":{"type":"string"},"reason":{"type":"string"}},"type":"object"},"showField":{"type":"boolean"}},"type":"object"},"customfield_10019":{"type":"string"},"customfield_10020":{},"customfield_10021":{},"customfield_10022":{},"customfield_10023":{},"customfield_10024":{},"customfield_10025":{},"customfield_10026":{},"customfield_10027":{},"customfield_10028":{},"customfield_10029":{},"customfield_10030":{},"customfield_10033":{},"description":{},"duedate":{},"environment":{},"fixVersions":{"type":"array"},"issuelinks":{"type":"array"},"issuetype":{"properties":{"avatarId":{"type":"integer"},"description":{"type":"string"},"entityId":{"type":"string"},"hierarchyLevel":{"type":"integer"},"iconUrl":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"},"self":{"type":"string"},"subtask":{"type":"boolean"}},"type":"object"},"labels":{"type":"array"},"lastViewed":{},"priority":{"properties":{"iconUrl":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"},"self":{"type":"string"}},"type":"object"},"progress":{"properties":{"progress":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"project":{"properties":{"avatarUrls":{"properties":{"16x16":{"type":"string"},"24x24":{"type":"string"},"32x32":{"type":"string"},"48x48":{"type":"string"}},"type":"object"},"id":{"type":"string"},"key":{"type":"string"},"name":{"type":"string"},"projectTypeKey":{"type":"string"},"self":{"type":"string"},"simplified":{"type":"boolean"}},"type":"object"},"reporter":{"properties":{"accountId":{"type":"string"},"accountType":{"type":"string"},"active":{"type":"boolean"},"avatarUrls":{"properties":{"16x16":{"type":"string"},"24x24":{"type":"string"},"32x32":{"type":"string"},"48x48":{"type":"string"}},"type":"object"},"displayName":{"type":"string"},"emailAddress":{"type":"string"},"self":{"type":"string"},"timeZone":{"type":"string"}},"type":"object"},"resolution":{},"resolutiondate":{},"security":{},"status":{"properties":{"description":{"type":"string"},"iconUrl":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"},"self":{"type":"string"},"statusCategory":{"properties":{"colorName":{"type":"string"},"id":{"type":"integer"},"key":{"type":"string"},"name":{"type":"string"},"self":{"type":"string"}},"type":"object"}},"type":"object"},"statuscategorychangedate":{"type":"string"},"subtasks":{"type":"array"},"summary":{"type":"string"},"timeestimate":{},"timeoriginalestimate":{},"timespent":{},"updated":{"type":"string"},"versions":{"type":"array"},"votes":{"properties":{"hasVoted":{"type":"boolean"},"self":{"type":"string"},"votes":{"type":"integer"}},"type":"object"},"watches":{"properties":{"isWatching":{"type":"boolean"},"self":{"type":"string"},"watchCount":{"type":"integer"}},"type":"object"},"workratio":{"type":"integer"}},"type":"object"},"id":{"type":"string"},"key":{"type":"string"},"self":{"type":"string"}},"required":["expand","id","self","key","fields"],"type":"object"},"type":"array"},"maxResults":{"type":"integer"},"startAt":{"type":"integer"},"total":{"type":"integer"}},"type":"object"}},"runAfter":{"Initialize_variable":["Succeeded"]},"type":"ParseJson"}},"contentVersion":"1.0.0.0","outputs":{},"parameters":{},"triggers":{"manual":{"inputs":{"schema":{}},"kind":"Http","type":"Request"}}},"parameters":{}}

LocustIO: How to do batch request

I started to use LocustIO for load testing a 3rd party API which provides a way to do batch requests (http://docs.oasis-open.org/odata/odata/v4.01/odata-v4.01-part1-protocol.html#sec_BatchRequests).
How can this be done using LocustIO?
I tried with the following:
def batch(self):
response = self.client.request(method="POST", url="/$batch", auth=("ABC", "DEF"), headers={"ContentType": "multipart/mixed; boundary=batch_36522ad7-fc75-4b56-8c71-56071383e77b"}, data="Content-Type: application/http\nContent-Transfer-Encoding: binary\n\nGET putyoururlhere HTTP/1.1\nAccept: application/json\n\n\n")
Auth is something I need to have authentication to the API, but that's not the point of the question and "putyoururlhere" should be replaced with the actual url. Either way, it gives errors when executing the test, so I must be doing something wrong.
People with experience how to do this?
Kind regards!
The data parameter should be your POST body (only), you cant put additional headers in it the way you did. You probably just want to add them as additional entries in the dict you pass as headers
Se the documentation for python requests library for more details. https://requests.readthedocs.io/en/master/

Evernote IOS SDK fetchResourceByHashWith throws exception

Working with Evernote IOS SDK 3.0
I would like to retrieve a specific resource from note using
fetchResourceByHashWith
This is how I am using it. Just for this example, to be 100% sure about the hash being correct I first download the note with a single resource using fetchNote and then request this resource using its unique hash using fetchResourceByHashWith (hash looks correct when I print it)
ENSession.shared.primaryNoteStore()?.fetchNote(withGuid: guid, includingContent: true, resourceOptions: ENResourceFetchOption.includeData, completion: { note, error in
if error != nil {
print(error)
seal.reject(error!)
} else {
let hash = note?.resources[0].data.bodyHash
ENSession.shared.primaryNoteStore()?.fetchResourceByHashWith(guid: guid, contentHash: hash, options: ENResourceFetchOption.includeData, completion: { res, error in
if error != nil {
print(error)
seal.reject(error!)
} else {
print("works")
seal.fulfill(res!)
}})
}
})
Call to fetchResourceByHashWith fails with
Optional(Error Domain=ENErrorDomain Code=0 "Unknown error" UserInfo={EDAMErrorCode=0, NSLocalizedDescription=Unknown error})
The equivalent setup works on Android SDK.
Everything else works so far in IOS SDK (chunkSync, auth, getting notebooks etc.. so this is not an issue with auth tokens)
would be great to know if this is an sdk bug or I am still doing something wrong.
Thanks
This is a bug in the SDK's "EDAM" Thrift client stub code. First the analysis and then your workarounds.
Evernote's underlying API transport uses a Thrift protocol with a documented schema. The SDK framework includes a layer of autogenerated stub code that is supposed to marshal input and output params correctly for each request and response. You are invoking the underlying getResourceByHash API method on the note store, which is defined per the docs to accept a string type for the contentHash argument. But it turns out the client is sending the hash value as a purely binary field. The service is failing to parse the request, so you're seeing a generic error on the client. This could reflect evolution in the API definition, but more likely this has always been broken in the iOS SDK (getResourceByHash probably doesn't see a lot of usage). If you dig into the more recent Python version of the SDK, or indeed also the Java/Android version, you can see a different pattern for this method: it says it's going to write a string-type field, and then actually emits a binary one. Weirdly, this works. And if you hack up the iOS SDK to do the same thing, it will work, too.
Workarounds:
Best advice is to report the bug and just avoid this method on the note store. You can get resource data in different ways: First of all, you actually got all the data you needed in the response to your fetchNote call, i.e. let resourceData = note?.resources[0].data.body and you're good! You can also pull individual resources by their own guid (not their hash), using fetchResource (use note?.resources[0].guid as the param). Of course, you may really want to use the access-by-hash pattern. In that case...
You can hack in the correct protocol behavior. In the SDK files, which you'll need to build as part of your project, find the ObjC file called ENTProtocol.m. Find the method +sendMessage:toProtocol:withArguments.
It has one line like this:
[outProtocol writeFieldBeginWithName:field.name type:field.type fieldID:field.index];
Replace that line with:
[outProtocol writeFieldBeginWithName:field.name type:(field.type == TType_BINARY ? TType_STRING : field.type) fieldID:field.index];
Rebuild the project and you should find that your code snippet works as expected. This is a massive hack however and although I don't think any other note store methods will be impacted adversely by it, it's possible that other internal user store or other calls will suddenly start acting funny. Also you'd have to maintain the hack through updates. Probably better to report the bug and don't use the method until Evernote publishes a proper fix.

Using cfs:http-publish

I'm trying to use the cfs:http-publish package at https://github.com/CollectionFS/Meteor-http-publish. While I've got the GET - /api/list functionality working, I don't know how to obtain a single document:
(GET - /api/list/:id - find one published document).
Can someone provide a curl example of this, assuming a certain collection of objections.
eg: {a:3, b:2}, {a:4, b:3}, and requiring to obtain the object with {a:3}.
Thanks.
You need to put it in the query function.
HTTP.publish({collection: myList},function( ){
return myList.find(this.query);
});
this.query contains the data you sent with your request.
curl http://localhost:3000/api/myList?a=3
I don't know enough about mongo to know if this is a potential security risk, if anyone can comment on that please do.

How to download HTML Report from HP ALM Performance Center 11.0 using rest API

I want to download HTML default report for a test run from Performance Center storage (using Rest API). Actually I need just summary.html file.
I was using the following steps in PC 11.5:
Request test scenarios:
http://{server:port}/qcbin/rest/domains/{domain}/projects/{project}/tests?fields=id,last-modified,name,owner&query={subtype-id[=PERFORMANCE-TEST]}&page-size=max
Let user choose the scenario (id) and request all its runs:
http://{server:port}/qcbin/rest/domains/{domain}/projects/{project}/runs?page-size=max&fields=id,owner,pc-start-time,duration,status,test-id&query={test-id[=234]}
Let user choose the run (id) and request Report (result entity):
http://{server:port}/qcbin/rest/domains/{domain}/projects/{project}/results?page-size=max&query={run-id[=123];name[=Reports]}&fields=id,name
Request "summary.html" file using file-id taken from previous step response:
http://{server:port}/qcbin/rest/domains/{domain}/projects/{project}/results/{file-id}/storage/report/summary.html
However it is not working with Performance Center 11.0. It fails at last step:
qccore.general-error
Not Found
I guess it is because the path of report was changed.
Can someone tell the path for summary.html for Performance Center 11.0?
I've been able to have a little bit of success with this. Rather than use the request you are using above I used the following:
http://{server:port}/qcbin/rest/domains/{domain}/projects/{project}/results/{file-id}/logical-storage/
This gave me a zip file, which contained the report inside it.

Resources