Karate doesn't recognize dashes - karate

I wrote a simple mock that checks if a specific header exists then return a specif response based on that, but karate doesn't understand dashes(-) in my headers for an example Client-ID gives an error of ReferenceError: "ID" is not defined in <eval> at line number 1 but header Accept work fine. i'm passing this header through postman.
and this how the code looks
* def fun = function(){ var test = requestHeaders; for(i in test) if(test.Client-ID) return true}

When you have characters like - part of the JSON key, you need to use quotes.
* def foo = { 'Content-Type': 'application/json' }
* match foo['Content-Type'] == 'application/json'
Also try if this works for you, it may be simpler:
Scenario: pathMatches('/v1/headers') && karate.get("requestHeaders['Client-ID']")
And in case you are testing a value, headerContains() can be used: https://github.com/intuit/karate/tree/master/karate-netty#headercontains

Related

Getting Illegal character in query when doing a conditional GET with multiple parameters

Code:
Feature: GET API headers feature
Scenario: pass GetWatchList with headers
Given header x-apisignatures = '543aba07839'
And header ssotoken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJ1bmlxdWUiOiJjYTM4MDAzZS0wYThiLTQ3YjktOWFjNS00YzMyN2MwNTUyMGYiLCJ1c2VyVHlwZSI6IlJJTHBlcnNvbiIsImF1dGhMZXZlbCI6IjIwIiwiZGV2aWNlSWQiOiJlZWIxOGRlOGRiNjE3MDg4MjViNTdjNGU5NDg1ZmFjYTU1MGE1OTBkY2Y1MjIzNzkyYzUwYjVhZWRjZGI5ZmUxNDQxZTFiMzhmZWI2NDFhZmUwNGI3NGY0NDA5OWMzZGQwZWI0OTRiZjgwMTYxOWYyNTAyNjI2YTJjZjdkMTZmZCIsImp0aSI6IjFmN2IwODkxLTJkMGUtNDBhZS04MWJiLWQwODVjY2NhOGYyZSIsImlhdCI6MTY2NDI3Njk0NH0.6Q7CPtQIN0uB1ZbVQBj5dshqioop3dJKEpla5DQS5K5qtRPw38SxTEJ1f1DJ_Ka_sgMp_fdh9EEABipTgtgMqg'
And header uniqueid = 'ca38003e-0a8b-47b9-9ac5-4c327c05520f'
And header x-page = 'Home'
When url 'https://jiocinemaqa-api.jio.ril.com/user/v1/watchlist?groups=[["Movie"],["Show"]]'
When method GET
Then status 200
* print response
Try this public API to test:
* url 'https://httpbin.org/anything'
* param groups = '[["Movie"],["Show"]]'
* method get
And you can verify in the response you see this:
"args": {
"groups": "[[\"Movie\"],[\"Show\"]]"
},
And also:
"url": "https://httpbin.org/anything?groups=[[\"Movie\"]%2C[\"Show\"]]"
This proves that Karate is sending the right thing. Keep in mind that your server may have a bug.

How to call a js function in other file with arguments in karate?

I have a karate feature which needs to call a JavaScript function with arguments from js file. Not in the feature itself. Want to organise many js function in separate file and call it from a feature file. Just like creating java step definitions with cucumber.
Feature: Inside new
Background:
* def result = call read(‘GetTokens.feature')
Given url devURL
* def at = result.access_token
* def rt = result.refresh_token
* def data = read('classpath:src/main/resources/GetHeaders.js', at, rt)
* configure headers = data
Scenario Outline: new
Given path ‘new’
And request ‘’
When method post
And status 201
This feature calls GetHeaders.js But not able to read the arguments. Is there anything wrong with the way it's been called. Or karate framework/nashorn can't support.
#GetHeaders.js
var f1 = function(at, rt){
var head = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'token': at,
'refresh-token': rt,
'channel': 'online'
}
return head
}
Move the js code to a function within a feature file. The function can be called using any number of arguments just like any other js or java functions. Below is the sample code incase you want any reference.
* def GetHeaders =
"""
function(at, rt){
var head = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'token': at,
'refresh-token': rt,
'channel': 'online'
}
return head
}
"""
* karate.log(GetHeaders('shfusdfhdskfds', 'ueworuewoew767638'))

Karate - Trouble passing correct headers for authorization

I am have some problems passing in the correct headers for my graphql endpoints
The use case in Postman:
call requestToken endpoint to obtain sessionToken value
requestToken response contains Key Value " and Token Value.
For subsequent calls, I set postman headers as:
Key = X_SESSION_TOKEN Value = Token Value
The user case in Karate
1st feature 'requestToken.feature' successfully calls and stores key + tokenValue
2nd feature successfully defines and prints the token value
here is my 2nd request:
Feature: version
Background:
* url 'http://api-dev.markq.com:5000/'
* def myFeature = call read('requestToken.feature')
* def authToken = myFeature.sessionToken
* configure headers = { 'X_SESSION_TOKEN': authToken , 'Content-Type': 'application/json' }
Scenario: get version
Given path 'query'
Given text query =
"""
query {
version
}
"""
And request { query: '#(query)' }
When method POST
Then status 200
And print authToken
And print response
I am not sure I send the headers right. Its coming back 200, but I keep getting a error 'token malformed' in the response message
Any suggestions? New at this, thanks!
Honestly this is hard to answer, a LOT depends on the specific server.
EDIT: most likely it is this change needed, explained here: https://github.com/intuit/karate#embedded-expressions
* configure headers = { 'X_SESSION_TOKEN': '#(authToken)' , 'Content-Type': 'application/json' }
2 things from experience:
should it be X-SESSION-TOKEN
add an Accept: 'application/json' header
And try to hardcode the headers before attempting call etc.
Here is an example that works for me:
* url 'https://graphqlzero.almansi.me/api'
* text query =
"""
{
user(id: 1) {
posts {
data {
id
title
}
}
}
}
"""
* request { query: '#(query)' }
* method post
* status 200

In Karate - Feature file calling from another feature file along with variable value

My apologies it seems repetitive question but it is really troubling me.
I am trying to call one feature file from another feature file along with variable values. and it is not working at all.
Below is the structure I am using.
my request json having variable name. Filename:InputRequest.json
{
"transaction" : "123",
"transactionDateTime" : "#(sTransDateTime)"
}
my featurefile1 : ABC.Feature
Background:
* def envValue = env
* def config = { username: '#(dbUserName)', password: '#(dbPassword)', url: '#(dbJDBCUrl)', driverClassName: "oracle.jdbc.driver.OracleDriver"};
* def dbUtils = Java.type('Common.DbUtils')
* def request1= read(karate.properties['user.dir'] + 'InputRequest.json')
* def endpoint= '/v1/ABC'
* def appDb = new dbUtils(config);
Scenario: ABC call
* configure cookies = null
Given url endpoint
And request request1
When method Post
Then status 200
Feature file from which I am calling ABC.Feature
#tag1
**my featurefile1: XYZ.Feature**
`Background`:
* def envValue = env
Scenario: XYZ call
* def sTransDateTime = function() { var SimpleDateFormat = Java.type('java.text.SimpleDateFormat'); var sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'+00:00'"); return sdf.format(new java.util.Date()); }
* def result = call read(karate.properties['user.dir'] + 'ABC.feature') { sTransDateTime: sTransDateTime }
Problem is,
While executing it, runnerTest has tag1 configured to execute.
Currently, it is ignoring entire ABC.feature to execute and also not generating cucumber report.
If I mention the same tag for ABC.feature (Which is not expected for me as this is just reusable component for me ) then it is being executed but sTransDateTime value is not being passed from XYZ.feature to ABC.feature. Eventually, InputRequest.json should have that value while communicating with the server as a part of the request.
I am using 0.9.4 Karate version. Any help please.
Change to this:
{ sTransDateTime: '#(sTransDateTime)' }
And read this explanation: https://github.com/intuit/karate#call-vs-read
I'm sorry the other part doesn't make sense and shouldn't happen, please follow this process: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue

Karate framework variable usage

I have this steps:
...
Then status 200
And match response.requests[0].request.url == "/endpoint"
And json body = response.requests[0].request.body
And match body == { "something": "something"}
To simplify, I tried to put response.requests[0].request in a variable called request:
...
Then status 200
And def request = response.requests[0].request
And match request.url == "/endpoint"
And json body = request.body
And match body == { "something": "something"}
I'm having the following error:
'request' is not a variable, use the form '* request <expression>' instead
I read the documentation and the use of request seems to be fine:
Given def color = 'red '
And def num = 5
Then assert color + num == 'red 5'
What am I doing wrong?
Thanks in advance.
Just make this change:
* def req = response.requests[0].request
# other steps
* request req
We simply disallow def request (using request as a variable name) because a lot of newbie users get confused. The error message has worked 99.9% of the time for users to understand what the problem is, but I guess you fall in the 0.1% :)