Modified variable name in karate framework [duplicate] - karate

This question already has an answer here:
Karate Http request add param conditionally
(1 answer)
Closed 1 year ago.
I want to modified param variable for my request(GET/POST) dynamically. As I have 2 different environment which takes different parameters for same request.
I tried below code, but not able to replace param variable(name).
I can replace param value successfully.
This function generate the dynamic param name for different enviornment
public static String paramDynamicVariable(String env, String param) {
String paramValue;
if (env.equals("test")) {
paramValue = '$' + param;
} else {
paramValue = param;
}
return paramValue;
}
Now when I am using paramValue in my test--
Scenario: xyz
Given path URLOfRequest
* print paramDynamicVariable(karate.env,'nameParam')
And param random.paramDynamicVariable(karate.env,'nameParam') = 10
It prints correct value, but in the next line it is not replacing for param name.
Please suggest if any solution is there to dynamic param name.

Please do something like this:
* def nameParam = paramDynamicVariable(karate.env, 'nameParam')
* def paramValues = {}
* paramValues[nameParam] = 10
And then:
* params paramValues
Since params accepts any JSON, all you need to do is create the JSON. Since the key is dynamic, it requires you to do a little more work.

Related

Karate : Trying to convert array to string using js method toString() in karate [duplicate]

This question already has an answer here:
Change type from string to float/double for a key value of any json object in an array
(1 answer)
Closed 1 year ago.
I'm trying to convert an Array to string using a simple js function placed in the reusable feature file. I don't see any reason why the array is not getting converted to a string when I try to run the same function on the console it works without any issue.
Can anyone suggest a way to get this issue sorted?
"""
* def formatter = function(str){
var formatstring = str.toString();
return formatstring
}
"""
feature file
* def format = call read('../common/resuable.feature)
* def result = format.formatter(value)
* print result
Input = ["ID3:Jigglypuff(NORMAL)"]
Actual result = ["ID3:Jigglypuff(NORMAL)"]
Expected result = ID3:Jigglypuff(NORMAL)
[![When tried same on console][1]][1]
[1]: https://i.stack.imgur.com/tAcIz.png
Sorry, if you print an array, it will have square-brackets and all, that's just how it is.
Please unpack arrays if you want the plain string / content:
* def input = ["ID3:Jigglypuff(NORMAL)"]
* def expected = input[0]

Karate - Unable to replace graphql query variables through data driven scenario outline 'examples' [duplicate]

I am not sure why replace is not working.
I have a graphql query:
mutation updateLocation{
updateLocation(input: {
address:"<address>",
id:"<storeID>",
name:"<name>",
workingHours: [
{
closingTime:"<closingTime>",
isClosed:false,
openingTime:"<openingTime>"
}
.......
And in feature file I have this:
Given def query = read ('classpath:graphQL/updateStore.graphql')
* replace query.address = "<address>"
* replace query.regionId = "<regionId>"
* replace query.name = "<name>"
* replace query.closingTime = "<closingTime>"
* replace query.openingTime = "<openingTime>"
* replace query.storeID = storeId
And request { query : '#(query)'}
When method post
Then status 200
Examples:
|address |regionId |name |closingTime |openingTime |
|Adrs1 |286 |st1 |20:00 |10:00 |
The replace works for address, regionid, and name but it does not work for closing time or opening time, these two values stay empty.
Also if I define header in background like this:
Given header Authorization = 'Bearer ' + token
I still have to add this line for each request in the same scenario, or I have been missing something?
Works for me:
* def query = 'closingTime:"<closingTime>"'
* replace query.closingTime = '20:00'
* match query == 'closingTime:"20:00"'
So please follow this process: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue
Note that * replace query.closingTime = closingTime should work. I recommend avoiding confusion by using different names for the Examples columns.

Expression with String placeholder in the filter part of JsonPath using karate

I am trying to filter my response using JSON Path where one of the condition using a value from a variable but I am not able to map variable properly, so my filter not working properly.
Sample response JSON:
{
"response":[
{
"id":"1234",
"confirmationCode":"abcd"
}
]
}
I am using the below script where I am using variable 'code':
* def Code = 'abcd'
* def value = karate.jsonPath($.response[?(#.confirmationCode == ' + Code +')])
Read the docs carefully please:
* def value = karate.jsonPath(response, "$.response[?(#.confirmationCode=='" + Code + "')]")

Unable to Pass Two Parameters as Argument to Javascript Function

I am trying to use karate.call to invoke function of a JS file receiving two arguments (String, Array of String). However the array of string would not be passed on to the JS file.
The JS file contains:
function(query, fragments) {
// Here lies some code
// One of them includes fragments.length;
}
And I call the JS function on another JS file in this way:
//var query = 'Some string';
//var fragments = ['fragment1', 'fragment2'];
var clean = karate.call('../helper/helper.js', [query, fragments]);
I am able to pass query which is a string. But I was unable to pass the array of string. The error says:
TypeError: Cannot read property "length" from undefined
It seems the array of string did not get passed to the JS function. Any help will be greatly appreciated. Thanks!
You can read you function first and invoke is just like any other js function
var myFun = karate.read('../helper/helper.js');
var funCall = myFun(query, fragments);
or
var myCall = karate.read('../helper/helper.js')(query, fragments);
this should work.
.call takes parameters as comma separated values , you need to use .apply if you want to pass values as an array.
var clean = karate.call('../helper/helper.js', query, fragments);
will work...
The answers here are missing an important clarification:
I often do single arg functions like:
* def concatParams =
"""
function(s) {
return "urldt=" + todaysDate + "&caseid=" + s.caseid
}
"""
And I will call that like so:
* def params = call concatParams {caseid: '3433344'}
But, when I want to do 2 params, I will define a function like so:
* def concatParams =
"""
function(d,s) {
return "urldt=" + d.date + "&caseid=" + s.caseid
}
"""
And unintuitively, neither of these will work:
* def params = call concatParams {date: '01/01/2020', caseid: '3433344'}
* def params = call concatParams '01/01/2020' '3433344'
To get it to work, instead I call it like this:
* def params = concatParams('01/01/2020', '3433344')
Documentation does not clarify this.
var clean = karate.call('../helper/helper.js', query, fragments);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
call method accepts comma separated params and apply accept array so you need to replace call into apply. your code looks like
function karate(query, fragments) {
// Here lies some code
// One of them includes fragments.length;
}
var clean = karate.apply('../helper/helper.js', [query, fragments]);

how can we pass multiple arguments in the background functions in karate feature file

i am passing the two arguments to my custom function but in background while i am passing the arguments it's skipping first taking second one only arugment.
here is the sample code
* def LoadToTigerGraph =
"""
function(args1,args2) {
var CustomFunctions = Java.type('com.optum.graphplatform.util.CareGiverTest');
var cf = new CustomFunctions();
return cf.testSuiteTrigger(args1,args2);
}"""
#*eval if (karate.testType == "component") karate.call(LoadToTigerGraph '/EndTestSample.json')
* def result = call LoadToTigerGraph "functional","/EndTestSample.json"
output :
test type is ************/EndTestSample.json
path is *************undefined
When you want to pass two arguments, you need to send them as two json key/value.
* def result = call LoadToTigerGraph { var1: "functionnal", var2: "/EndTestSample.json" }
And you just have to use args.var1 and args.var2 in your function function(args)