Karate - How to obtain response using execution hook - karate

I have the following feature file:
Given def query = karate.call('classpath:query/Story/FindStoryByID.js')
And def variables = { id: "xxyy" }
And request { query: '#(query)', variables: '#(variables)' }
When method POST
Then status 200
And match response.data.FindStoryByID.id != '#null'
I am currently trying to do a beforeStep in order to write whole GraphQL request (query) of the feature to a file using karate.write.
So far I have come up with this:
#Override
public boolean beforeStep(Step step, ScenarioContext context) {
if (step.getText().trim().contains("request {")) {
System.out.println(step.getText());
}
return true;
}
This successfully triggers a print, which indicates I am poking on the right direction. The problem is that I haven't still able to figure out what should I do to access a variable (query) like the one we can do on a JS/Feature file (karate.get('query');)
I am wondering if it is even possible to achieve such feat through the execution hook like this?
Thanks a lot!

Ah found it! This do the job
context.vars.get("query"));

Related

In Blazor dealing with unexpected results from the api web server

I'm developing a fairly simple Blazor app using a lot of default template functionality, and I can't figure out how to handle an ActionResult from the server that isn't the normal return value.
On the server side I've slightly modified the default controller template to look something like this:
public async Task<ActionResult<MyData>> GetSession(int id)
{
var myData= await FetchMyData(id);
if (myData== null)
{
return NotFound();
}
return myData;
}
That check for a null value was in the original template - it seems like a good idea so I kept it. On the client side my code looks like this:
public async Task<MyData> GetMyData(int id)
{
return await Http.GetJsonAsync<MyData>("/api/MyData/" + id);
}
It all works quite well, except the client side code doesn't handle the case where the server side returns a "NotFound()" result. It's not a show stopper, but it's driving me crazy that I don't know how to do it.
It seems that the GetJsonAsync() call on the client is silently unwrapping the return Value from the ActionResult wrapper (I guess?). Does that mean if I want to handle a NotFound condition I should be using a different httpclient function and maybe deserializing the object Value myself? If so, anyone want to volunteer an example?
Or am I missing something and there's an easier way?
It seems stupid to check for a condition on the server side just to send the client a warning that ultimately results in an unhandled exception.
I tried Henk Holterman's suggestion of just adding a try/catch, and it turns out the exception that was thrown had the information I wanted - that is the status being returned by the server. So what I should have done was this:
public async Task<MyData> GetMyData(int id)
{
try
{
return await Http.GetJsonAsync<MyData>("/api/MyData/" + id);
}
catch (System.Net.Http.HttpRequestException e)
{
.... process the exception
}
}
Turns out HttpRequestException has the HResult, which is what I was looking for.
Thanks Henk.

How to make a MultiMock Http Callout Test for Salesforce?

If I have an Apex function that is named authorize() that just gets a username, password, and session token, and another function called getURL('id#', 'key'), that takes an id# for the record as a string and a key for the image to return as a string as parameters. getURL calls the authorize function inside it in order to get the credentials for its callout. The authorize is a post request, and the getURL is a get request.
I am trying to figure out how to test both of these callouts just so I can make sure that getURL is returning the proper JSON as a response. It doesn't even have to be the URL yet which is its intention eventually. But I just need to test it to make sure these callouts are working and that I am getting a response back for the 75% code coverage that it needs.
I made a multiRequestMock class that looks like this:
public class MultiRequestMock implements HttpCalloutMock {
Map<String, HttpCalloutMock> requests;
public MultiRequestMock(Map<String, HttpCalloutMock> requests) {
this.requests = requests;
}
public HTTPResponse respond(HTTPRequest req) {
HttpCalloutMock mock = requests.get(req.getEndpoint());
if (mock != null) {
return mock.respond(req);
} else {
throw new MyCustomException('HTTP callout not supported for test methods');
}
}
public void addRequestMock(String url, HttpCalloutMock mock) {
requests.put(url, mock);
}
}
I then began to write a calloutTest.cls file but wasn't sure how to use this mock class in order to test my original functions. Any clarity or assistance on this would be helpful Thank you.
I believe in your calloutTest class you use Test.setMock(HttpCalloutMock.class, new MultiRequestMock(mapOfRequests)); then call the getUrl and/or authorize methods and instead of the request really executing the response returned will be that which is specified in the response(HttpRequest) method you have implemented in the MultiRequestMock class. That is basically how I see it working, for more info and an example you can see this resource on testing callout classes. This will get you the code coverage you need but unfortunately cannot check you are getting the correct JSON response. For this, you may be able to use the dev console and Execute Anonymous?
You may want to look at simplifying your HttpCalloutMock Implementation and think about removing the map from the constructor as this class really only needs to return a simple response then your calloutTest class can be where you make sure the returned response is correct.
Hope this helps

How to send data piece by piece using Flux?

I play with baeldung tutorial from github.
I wanted to see how a browser retrieves data piece by piece. So I added my simple controller method:
#GetMapping("/flux")
public Flux<Employee> getFlux() {
return Flux.fromIterable(employeeRepository.employeeData.values())
.delayElements(Duration.ofMillis(2_000))
.take(3);
}
But when I look at the browser network the data is retrieved in one chunk after 6 second delay.
How to do this correctly?
This is happening because you didn't mention Media type for the response.
Try this code.
#GetMapping(value = "/test",produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
public Flux getMapping() {
return Flux.interval(Duration.ofMillis(300)).map(f -> "HI");
}
Thanks,
Vimalesh

Linq2DB Nlog or logging

is there a way to log all linq2DB sql queries that are made to he database with NLog?
I cannot find any realistic example. There is something for miniprofiler, but this doesn't help me, because I have not experience with it.
pull request
example
example 2
Inside your Setup method you could turn on Trace and setup WriteTraceLine to Console.WriteLine
[SetUp]
public void Setup()
{
LinqToDB.Data.DataConnection.TurnTraceSwitchOn();
LinqToDB.Data.DataConnection.WriteTraceLine = (message, displayName) => { Console.WriteLine($"{message} {displayName}"); };
}
This will write all executed SQL Queries (together with params) to the Console

JAX-RS Option path param is not working

I am trying to use following construct
#ApplicationPath("app")
#Path("api/{userid}/model")
public class ModelService
{
#Get
#Path("{modelid: (.*)?}")
public Response removePreProcessor(#PathParam("userid") String sUserId, #PathParam("preprocessorid") String sPreProcessorId)
{
return Response.build();
}
}
I can not access both following REST URL
GET http://localhost:8080/XXXX/app/api/xyz/model
GET http://localhost:8080/XXXX/app/api/xyz/model/123
Let me know what is a wrong I am doing
-Thanks in advance
As I read your question, several things look strange to me but they may be context related.
One thing though seems wrong :
You are using a #PathParam("preprocessorid") but I can't see this param in your path.
Do you have any logs ?