How to check the status code of one API from karate-config.js? [duplicate] - karate

This question already has an answer here:
How to pass multiple parameters to callSingle karate on karate-config.js
(1 answer)
Closed 1 year ago.
We have to call two APIs only once in whole project which is a pre-requisite for all other features to run. All features are using values set in userId and unitId.
The first feature call is working fine but I am not sure how to add if condition on status code as only when the status code of first feature#test1 is 200 only then we want to call the second one else not.
The below code displayed the value as
User Id is -------------378
But is not going in the if condition although this API returned response code as 200.
var result = karate.callSingle('classpath:util/users.feature#test1',config);
config.userId = result.response.value[0].id;
karate.log("User Id is -------------" + config.userId)
if( result.status == 200 )
{
var result1 = karate.callSingle('classpath:util/users.feature#test2',config);
config.unitId = result1.response.value[0].id;
karate.log("Unit Id is -------------" + config.unitId)
}

It should be result.responseStatus.

Related

How to generate more than one random UUID and use in scenario outline examples in karate [duplicate]

This question already has an answer here:
How to use cucumber table when it is code driven
(1 answer)
Closed 1 year ago.
I am new to Karate API, pardon me for the mistakes if any.
I want to generate multiple random UUID and then use them in scenario outline examples
Example:
Background:
def UUID = function() {return java.util.UUID.randomUUID() + ''}
Scenario outline: to do post call
Given url 'http://localhost:8080'
def UID = UUID()
print UID
And request {CID:"", name :""}
When method POST
Then status 201
Examples:
|CID| name|
|UID1| james|
|UID2| rahul|
Here in above 'Examples' I wanted to use randomly generated UUID in data table of examples so that I can run multiple scenarios for UUID with one POST API call.
First question: How can I generate multiple random UUID ?
Second question: once multiple UUID gets generated how can i call in scenario outline examples and use them?
Can anyone suggest me on this?
Please try running the following simple example.
Feature:
Background:
* def uuid = function(){ return java.util.UUID.randomUUID() + '' }
Scenario Outline:
* url 'https://httpbin.org/anything'
* param foo = uuid()
* request { item: '#(item)' }
* method post
Examples:
| item |
| first |
| second |
It will make 2 requests, and each request will use a different param called "foo" and the URL will be like this:
https://httpbin.org/anything?foo=c1b6ab3d-5952-413b-827c-d9579a0a93b6
So it is simple. Think of the Examples: as like a "loop". Each time the Scenario Outline runs, we are calling the uuid() function again, which will return a different, random value.

Headers modification using Karate [duplicate]

This question already has an answer here:
Karate: Is there a way to pass variable as string in scenario outline and examples table [duplicate]
(1 answer)
Closed 1 year ago.
I am running API execution using Scenario Outline and csv and want to edit header in the below format where i need to change the requestorid each and every time for the execution.
If the headers uses below format and saved in .js and tried saving it in .json file:
"ID-HEADERS" :"{ 'requestorId': '1111', 'authMethod': 'basic'}"
And used below lines to edit the header which is not working:
function() {
var fun = karate.read(headersFilePath + 'headers.js');
var res = fun();
res['ID-HEADERS.requestorId'] = requestorId;
return res;
}
If you just need to set one header don't complicate it with JS:
Scenario Outline:
* url 'https://httpbin.org/anything'
* header foo = bar
* method get
Examples:
| bar |
| one |
| two |
Try it, and see the logs and HTML report. And read the documentation also.

karate gatling name resolver [duplicate]

This question already has answers here:
Is there an option for us to customize and group the test scenarios in the statics section of the Karate Gatling Report?
(2 answers)
Closed 1 year ago.
I have two scenarios in my feature file
#name=foo #name=fooRamp
Scenario : verify Performance for foo
Given def query = read('classpath:perf/testData/foo.graphql')
And request {query:'#(query)'}
And header karate-name = 'foo','fooRamp'
#name=bar #name=barRamp
Scenario : verify Performance for bar
Given def query = read('classpath:perf/testData/bar.graphql')
And request {query:'#(query)'}
And header karate-name = 'bar,'barRamp'
Two scenario I defined are
val scenario1=scenario("singleusers").exec(karateFeature("classpath:perf/foobar.feature#name=foo"))
.pause(3)
.exec(karateFeature("classpath:perf/foobar.feature#name=bar"))
val scenario2=scenario("ramp10Usersin30secs").exec(karateFeature("classpath:perf/foobar.feature#name=fooRamp"))
.pause(3)
.exec(karateFeature("classpath:perf/foobar.feature#name=barRamp"))
setUp(
scenario1.inject(atOnceUsers(1)).protocols(protocol),
scenario2.inject(rampUsers(10) during (30 seconds)).protocols(protocol)
)
What I get is
Request users metrics
foo 11 <responseTime>
bar 11 <responseTime>
I want to see in my report like
Request users metrics
foo 1 <responseTime>
bar 1 <responseTime>
fooRamp 10 <responseTime>
barRamp 10 <responseTime>
Is there any way that this can happen that I get separate names for single and ramp runs? Can nameresolver pick the different name for same feature scenario as per the scenario run in simulation? or do I need to create a duplicate scenario to achieve this?
I don't understand the logic after re-reading your question, so just do whatever conditional code you need and set a single header. Setting comma-delimited values won't work, it will take only the first.
* def temp = doSomeLogicHere()
And header karate-name = temp
There are multiple ways you can do the logic, look at the karate.info property, maybe looking at the feature name may give you what you need.

Can we add more than one statement in an 'If' statement in Karate? [duplicate]

This question already has an answer here:
Is it possible to use karate 'match' inside conditional statement?
(1 answer)
Closed 1 year ago.
I want to execute more than 1 statements provided an If condition is true. I want to know whether and how is it achievable in Intuit Karate framework.
In the Karate documentation, I find examples like below all of which have only one statement to be executed if the If condition is satisfied as listed below.
if (env == 'dev') karate.configure("ssl", true)
if (responseStatus == 200) karate.call('delete-user.feature')
if (responseStatus == 404) karate.abort()
I want to achieve something like below (only a pseudocode representation of my requirement and not as per the actual Karate syntax)
if (responseStatus ==200)
#statement 1
#statement 2
#statement 3
#end of If
Thanks!
Normally good tests should never do this. Make sure you read this also: https://stackoverflow.com/a/54126724/143475
But here are the 2 possible patterns:
a) use a second feature file:
* if (condition) karate.call('second.feature')
b) use a function, the disadvantage is only the JS API, things like match not supported
* def fun =
"""
function() {
// line 1
// line 2
}
"""
* if (condition) fun()

Getting list of questions that has not been shown or answered

I have two tables :
Question table where contains :
And then I have another table that is called
UserAnswerQuestion that contains :
That has reference to the question via question_id
The thing is that every time user answers a question I create a row in db saying :
question_id user_id has answered it and then I check if the answer is correct or not, if it's correct I put passed as a True, otherwise I put passed as a false.
Ok, from now is all ok, the thing that I can not get is I'm creating a method that returns to me the nextQuestion not answered, but I'm not able to do this method correctly.
What I'd like is to have a query that first return all questions that user have not answered yet, and then another query that returns just a question that user has not answered yet.
Note: This shown attribute was added because I want first to iterate over other questions instead of showing the ones that user has failed recently.
Is the question clear?
What I've tried?
I've tried to get the questions List<UserAnswerQuestion> findAllByUserEmailAndPassedFalseAndShownFalse(String email); but it doesn't work because with this table I can know every answer in every try that user does, so for example if I have a question that have 4 answers and 1 correct, this table can contain 4 row with the same question_question_id because the user perhaps has failed 3 times and then at the fourth it answers correctly.
Edit
I have already the questions that user can answer with this method :
public List<Question> getAllQuestionsThatUserCanAnswer(String email, Long topic){
List<Question> mList = this.questionRepository.findAllByTopicParentId(topic);
if(mList==null) return null;
List<UserAnswerQuestion> userAnswerQuestionList = this.userAnswerQuestionRepository.findAllByUserEmail(email);
for (UserAnswerQuestion userAnswerQuestion : userAnswerQuestionList) {
if(mList.contains(userAnswerQuestion.getQuestion())){
if(userAnswerQuestion.getPassed()){
mList.remove(userAnswerQuestion.getQuestion());
}
}
}
return mList;
}
Now I'm trying to do the getNext of this method but I do not know how to iterate over it.
Focus on SQL query that solve your problem
select * from Question q
left join Answer a on q.id = a.question_id
where a.id is null OR (a.passed != 'true' AND a.user_id = 1)
order by a.passed
Check scratch here