Headers modification using Karate [duplicate] - header

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.

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.

Is it possible to generate dynamic variable names in Karate? [duplicate]

This question already has an answer here:
How to set dynamic value as a key to json string in request
(1 answer)
Closed 1 year ago.
I am making a REST API call which returns a response like this
{"id":"726295ab-d6bc-4f09-8cb7-6f6f54fc9364", "name":"Customer Data"}
I create 5 objects like this and I want to store the ids of all the 5 objects from response in 5 different variables.
I tried using something like
* def catID_<categoryName> = $.id
and provided the name of the object in the Examples section. It works fine most of the times except when the name has spaces in it.
no step-definition method match found for: * def catID_Customer Data = $.id
Is it possible to do something like this?
* def catName = replace all spaces in the name with _
* def #(catName)_id = $.id
or is there a better way to achieve this?
You seem to be doing things Karate is not designed to do, so by default please assume that this is not supported.
Most likely, adding keys to a JSON object is a more elegant approach instead of trying to dynamically hack def. For example:
* def variables = {}
* variables['<someDynamicName>'] = $.id
# then later
* print variables['actual name']
Also note that the '< and >' are not required: https://github.com/karatelabs/karate#scenario-outline-enhancements

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

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.

How to use for loop for login in karate framework [duplicate]

We're using Karate for backend testing of a microservice. I'd like to be able to make N calls to the backend API, where N is configurable as a number without having to do ugly things.
This was my first approach:
Given url baseUrl
And headers HEADERS
When method get
Then status 200
Given url baseUrl
And headers HEADERS
When method get
Then status 200
Given url baseUrl
And headers HEADERS
When method get
Then status 200
(Just repeating the call) It works, but obviously does not scale well (imagine 1000 of these).
Next approach was a bit better - I put the call in a separate feature and used the https://github.com/intuit/karate#data-driven-features approach:
* table jwts
| headers |
| HEADERS |
| HEADERS |
| HEADERS |
| HEADERS |
| HEADERS |
* def result = call read('call-once.feature') jwts
Slightly better but still does not scale. We also tried varieties of karate.repeat() which seems like the most natural approach, but had trouble with the syntax. None of the examples I could find had an API call inside of a for-each.
* def callFunction = function (HEADERS) { read('call-putaway-once.feature'); { HEADERS: '#(HEADERS)'} }
* def result = karate.repeat(5, callFunction)
But couldn't get any varieties of that working.
Can anyone provide an example of how to repeat the same exact Karate lines N times? I'm really looking for something like:
for (int i = 0; i < numTimes; i++) {
Given url baseUrl
And headers HEADERS
When method get
Then status 200
}
(Or functionally equivalent).
Thanks!
Here you go. First, the second called.feature:
#ignore
Feature:
Scenario:
Given url 'http://httpbin.org'
And path 'headers'
And header X-Karate = count
When method get
Then status 200
And now you can do this in your first feature:
* def fun = function(x){ return { count: x } }
* def data = karate.repeat(5, fun)
* call read('called.feature') data
P.S. by the way search the readme for "polling", there is an example of an API call in a loop: polling.feature
Karate almost have a feature to do this : retry until.
This feature doesn't repeat "n" time, but repeat until a condition is not validate
Example here : polling.feature
For a simple request it's seems like :
Given url baseUrl
And headers HEADERS
And retry until responseStatus == 200
When method get

How could response be checked conditionally? [duplicate]

This question already has an answer here:
Check 2 differents status with Karate
(1 answer)
Closed 1 year ago.
I'm doing data driven test with Karate, and met a block issue. The REST API response body is in different structure with different status. For example, when the status is 200, the response body is JSON array. When the status is 4** and 5***, the response body either is string or blank. I hope to check the response conditionally using the blow code. But seems it doesn't work.
"* eval if (verInfo.statusCode == 200) (match each response contains any verInfo.respBody) //verInfo.statusCode and verInfo.respBody is from the test data(DDT)
* eval if (verInfo.statusCode != 200) match response contains verInfo.respBody"
First, you cannot mix Karate script and JavaScript like this.
Second I suggest you use the responseStatus built-in variable. I also suggest using proper data-driven approaches instead of over-engineering your tests with conditional logic.
So you can do this, (and there are many other ways if you go through the docs and examples):
Scenario Outline:
Given url 'http://foo.bar'
And request <req>
When method post
Then match responseStatus == <code>
And match response == <body>
Examples:
| req | code | body |
| 'a' | 200 | 'foo' |
| 'b' | 400 | '' |