how to write equal test in postman for nested field equality - spring

I like to test my api on postman, my query params according to equality
192.168.1./student/v4/students?contactStudent.validFor.endDateTime==2021-09-26T05:00:00.246Z
"contactStudent": [
{
"mediumType": "email",
"preferred": true,
},
"validFor": {
"endDateTime": "2021-09-26T05:00:00.246Z",
"startDateTime": "2017-03-15T07:49:25.246Z"
}
my equality are working on well on postman, however how can ı write pm test for it ?
Thank you

postman has code snipet already available:
so the test is
pm.test("Your test name", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.contactStudent[0[.validFor.endDateTime).to.eql("2021-09-26T05:00:00.246Z");
});
jsonData has the ful json object from taht you are accessing each property

Related

NodeJS: AWS SDK V3: Not receiving any response data from lambda function

I'm trying to use the v3 javascript sdk to invoke a AWS Lambda function, and I'm having problems getting any meaningful response.
My code looks like so...
const { Lambda } = require("#aws-sdk/client-lambda");
const client = new Lambda();
const params = {
FunctionName: "MyLamdaFuncton",
Payload: JSON.stringify({ "action": "do_something" }),
InvocationType: "Event"
};
client.invoke(params)
.then((response) => {
console.log(JSON.stringify(response,null,4));
})
.catch((err) => {
console.error(err);
})
I can confirm from checking the CloudWatch logs that the lambda function works as exepcted. However this is the response I get in my NodeJS code...
{
"$metadata": {
"httpStatusCode": 202,
"requestId": "d6ba189d-9156-4f01-bd51-efe34a66fe34",
"attempts": 1,
"totalRetryDelay": 0
},
"Payload": {}
}
How do I get the actual response and status from the Lambda function?
If I change the payload above to intentionally throw an exception in my Lambda, the response in the console is still exactly the same.
update:
The Lambda function is written in Ruby. The response is returned like so...
{ statusCode: 200, body: JSON.generate(response.success?) }
where "response" is from another service it calls internally.
I've figured out what I was doing wrong. The issue was the "InvocationType". I got it working by changing to...
InvocationType: "RequestResponse"
Then I had to extract the response data like so...
const response_data = JSON.parse(new TextDecoder("utf-8").decode(response.Payload))

recaptcha validation API returns always true

I am using google's recaptcha test setup (Site key: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI) but always get returned success: true..
My python code is straight forward I guess
challenge = event["body"]
data = {
'secret': "6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe", ##google's generic secret
'response' : challenge
}
captcha_verify_url = "https://www.google.com/recaptcha/api/siteverify";
r = requests.get(captcha_verify_url, params=data)
I can send whatever and to get:
{
"success": true,
"challenge_ts": "2021-01-08T13:07:54Z",
"hostname": "testkey.google.com"
}
Is that a normal behavior?
Yes, this is perfectly normal behaviour designed for automated testing.
recaptcha-docs

Mock Graphql server with multiple stubs in Cypress

Problem:
I’m using cypress with angular and apollo graphQl. I’m trying to mock the graph server so I write my tests using custom responses. The issue here is that all graph calls go on a single endpoint and that cypress doesn’t have default full network support yet to distinguish between these calls.
An example scenario would be:
access /accounts/account123
when the api is hit two graph calls are sent out - a query getAccountDetails and another one with getVehicles
Tried:
Using one stub of the graph endpoint per test. Not working as it stubs with the same stub all calls.
Changing the app such that the query is appended 'on the go' to the url where I can intercept it in cypress and therefore have a unique url for each query. Not possible to change the app.
My only bet seems to be intercepting the XHR call and using this, but I don't seem to be able to get it working Tried all options using XHR outlined here but to no luck (it picks only the stub declared last and uses that for all calls) https://github.com/cypress-io/cypress-documentation/issues/122.
The answer from this question uses Fetch and therefore doesn't apply:
Mock specific graphql request in cypress when running e2e tests
Anyone got any ideas?
With cypress 6.0 route and route2 are deprecated, suggesting the use of intercept. As written in the docs (https://docs.cypress.io/api/commands/intercept.html#Aliasing-individual-GraphQL-requests) you can mock the GraphQL requests in this way:
cy.intercept('POST', '/api', (req) => {
if (req.body.operationName === 'operationName') {
req.reply({ fixture: 'mockData.json'});
}
For anyone else hitting this issue, there is a working solution with the new cypress release using cy.route2()
The requests are sent to the server but the responses are stubbed/ altered on return.
Later Edit:
Noticed that the code version below doesn't alter the status code. If you need this, I'd recommend the version I left as a comment below.
Example code:
describe('account details', () => {
it('should display the account details correctly', () => {
cy.route2(graphEndpoint, (req) => {
let body = req.body;
if (body == getAccountDetailsQuery) {
req.reply((res) => {
res.body = getAccountDetailsResponse,
res.status = 200
});
} else if (body == getVehiclesQuery) {
req.reply((res) => {
res.body = getVehiclesResponse,
res.status = 200
});
}
}).as('accountStub');
cy.visit('/accounts/account123').wait('#accountStub');
});
});
Both your query and response should be in string format.
This is the cy command I'm using:
import * as hash from 'object-hash';
Cypress.Commands.add('stubRequest', ({ request, response, alias }) => {
const previousInteceptions = Cypress.config('interceptions');
const expectedKey = hash(
JSON.parse(
JSON.stringify({
query: request.query,
variables: request.variables,
}),
),
);
if (!(previousInteceptions || {})[expectedKey]) {
Cypress.config('interceptions', {
...(previousInteceptions || {}),
[expectedKey]: { alias, response },
});
}
cy.intercept('POST', '/api', (req) => {
const interceptions = Cypress.config('interceptions');
const receivedKey = hash(
JSON.parse(
JSON.stringify({
query: req.body.query,
variables: { ...req.body.variables },
}),
),
);
const match = interceptions[receivedKey];
if (match) {
req.alias = match.alias;
req.reply({ body: match.response });
}
});
});
With that is posible to stub exact request queries and variables:
import { MUTATION_LOGIN } from 'src/services/Auth';
...
cy.stubRequest({
request: {
query: MUTATION_LOGIN,
variables: {
loginInput: { email: 'test#user.com', password: 'test#user.com' },
},
},
response: {
data: {
login: {
accessToken: 'Bearer FakeToken',
user: {
username: 'Fake Username',
email: 'test#user.com',
},
},
},
});
...
Cypress.config is what make it possible, it is kind of a global key/val getter/setter in tests which I'm using to store interceptions with expected requests hash and fake responses
This helped me https://www.autoscripts.net/stubbing-in-cypress/
But I'm not sure where the original source is
A "fix" that I use is to create multiple aliases, with different names, on the same route, with wait on the alias between the different names, as many as requests you have.
I guess you can use aliases as already suggested in Answer by #Luis above like this. This is given in documentation too. Only thing you need to use here is multiple aliases as you have multiple calls and have to manage the sequence between them . Please correct me if i understood you question in other way ??
cy.route({
method: 'POST',
url: 'abc/*',
status: 200.
response: {whatever response is needed in mock }
}).as('mockAPI')
// HERE YOU SHOULD WAIT till the mockAPI is resolved.
cy.wait('#mockAPI')

Spring MVC - Return view with Ajax using POST and sending data

I am trying to develop a simple component which job is to render particular portion of the data using a template.
I am using a Spring-Data-Rest-MVC so I've got a ready and working OOTB source of the data that suits my requirements (AJAX-based web app).
So, with what I am having problem with.
The problem lies here:
{
"panels":[
{
"id":"panel-BASIC",
"el":"panel-BASIC",
"attributes":[
{
"position":"0",
"key":"id",
"display":"value",
"dataUtility":"",
"value":"2"
},
{
"position":"1",
"key":"begin",
"display":"value",
"dataUtility":"",
"value":1384518600000
},
{
"position":"2",
"key":"end",
"display":"value",
"dataUtility":"",
"value":1384518600000
},
{
"position":"3",
"key":"interval",
"display":"value",
"dataUtility":"intervalCalculationDataUtility"
}
]
},
{
"id":"panel-ONE_TO_MANY",
"el":"panel-ONE_TO_MANY",
"attributes":[
{
"position":"0",
"key":"tasks",
"display":"table",
"dataUtility":"",
"value":"http://localhost:8080/rest/appointment/2/tasks"
}
]
},
{
"id":"panel-MANY_TO_ONE",
"el":"panel-MANY_TO_ONE",
"attributes":[
{
"position":"0",
"key":"car",
"display":"infopage",
"dataUtility":"",
"value":"http://localhost:8080/rest/appointment/2/car"
},
{
"position":"1",
"key":"assignee",
"display":"infopage",
"dataUtility":"",
"value":"http://localhost:8080/rest/appointment/2/assignee"
},
{
"position":"2",
"key":"reporter",
"display":"infopage",
"dataUtility":"",
"value":"http://localhost:8080/rest/appointment/2/reporter"
}
]
}
],
"container":"ip-SAppointment"
}
It's the descriptor which is being sent to the server, previously built in the client side using retrieved data and template descriptor.
Using a JSON I've posted I need to sent a POST request with it and than return rendered view.
The job of a controller method is rather simple:
#RequestMapping(
value = "/template/render",
method = RequestMethod.POST,
produces = MediaType.TEXT_PLAIN_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE
)
public ModelAndView getInfoPageViewData(
#RequestBody final InfoPageDescriptor body
) {
LOGGER.trace(String.format("/getInfoPageViewData -> %s", body));
final ModelMap modelMap = new ModelMap();
modelMap.put("dd", body);
return new ModelAndView(DATA_VIEW_NAME, modelMap);
}
So as You can see it wraps the sent JSON into the InfoPageDescriptor bean which is placed than into ModelMap.
The returned view will process the bean from the model map and acts accordingly to entries.
Anyway I can get this method working. With the jQuery (AJAX-POST) call like this:
function loadRenderedView(url, data, callback) {
return $.ajax({
headers : {
'Accept' : 'text/plain',
'Content-Type': 'application/json'
},
url : url,
data : JSON.stringify(data),
dataType: 'json',
type : 'post',
success : function (data) {
callback.apply(this, [data, true]);
},
failure : function () {
callback.apply(this, [data, false]);
}
});
}
I get an error: The request sent by the client was syntactically incorrect..
Could You give some hints of how I should built a request or controller-server method to make it work ?
Ok, will post it as an answer, because I need to to have a formatting here.
#vzamanillo, Your assumption may be correct here, because I've checked the logs and got these exceptions:
2013-12-14 17:15:14 DEBUG ExceptionHandlerExceptionResolver:132 - Resolving exception from handler [null]: org.springframework.web.HttpMediaTypeNotSupportedException: Invalid media type "json": does not contain '/'
2013-12-14 17:15:14 DEBUG ResponseStatusExceptionResolver:132 - Resolving exception from handler [null]: org.springframework.web.HttpMediaTypeNotSupportedException: Invalid media type "json": does not contain '/'
2013-12-14 17:15:14 DEBUG DefaultHandlerExceptionResolver:132 - Resolving exception from handler [null]: org.springframework.web.HttpMediaTypeNotSupportedException: Invalid media type "json": does not contain '/'
I think it can be about an URLs that are sent in the JSON, so I will investigate that.
Add
Log4j.logger.org.springframework = INFO, yourlogger
to your log4j.properties and check traces, it seems you are sending a Json that does not match with the InfoPageDescriptor class.
EDIT:
change the dataType of stringify to "application/json" It maybe fix the issue and change the Accept header of the ajax request to
'Accept': 'application/json',

In ExtJS, How can I list multiple returns from JSON data in a field set?

Ok, I am semi-new to ExtJS, and I am building a program that has "inputs" that are listed in a grid, and in my DB these inputs can be linked to "symptoms".
I am trying to create a function that will take in the id of the input and grab all of the symptoms from the database that are linked to that symptom, and list them in a field set.
It works fine when I click on an input that is only linked to one symptom, but if the input is linked to more than one symptom, then the error says.. "invalid property id"
This is what I have for my function.
function listSymptoms(inputID){
Ext.Ajax.request({
url: "../../inc/project4.php?list=symptoms",
reader: new (Ext.data.JsonReader)({
root: "symptoms",
inputid: "id"
}),
params: {
inputid: inputID
},
method: "POST",
success: function (f, a){
var jsonData = Ext.util.JSON.decode(f.responseText);
symptomsFieldSet.body.update(jsonData.data.name);
},
failure: function (f,a){
Ext.Msg.alert('There was a problem opening your message.');
}
});
}
I have the inputID for the function being passed in when the user clicks on one of the inputs that are held inside the grid.
I believe that my problem has something to do with this line..
symptomsFieldSet.body.update(jsonData.data.name);
I am just stumped on how to handle this. Do I need to create a data store like I have for grids? Or is there an easier way to do this?
ANY help is appreciated! thanks in advance.
I think you need to rethink the structure of your JSON response object. You can send this in your JSON response to your request. If you are using Ext.util.Ajax calls instad of a form, you'll need to decode this JSON response string using the util method Ext.util.JSON.decode(). Check out the API Documentation
{
success: true,
msg: {text: 'this can be used for error message handling' },
data : [
{id:1,
chiefComplaint: 'head hurts',
symptoms: [
{symptomID: '740.1', text: 'Headache'},
{symptomID: '12352135'. text: 'and so on'}
}
]
]
}

Resources