Karate : dynamic test data using scenario outline is not working in some cases - karate

I was tryiny to solve dynamic test data problem using dynamic scenario outline as mentioned in the documentation https://github.com/karatelabs/karate#dynamic-scenario-outline
It worked perfectly fine when I passed something like this in Example section
Examples:
|[{'entity':country},{'entity':state},{'entity':district},{'entity':corporation}]]
But I tried to generate this json object programatically , I am getting aa strange error
WARN com.intuit.karate - ignoring dynamic expression, did not evaluate to list: users - [type: MAP, value: com.intuit.karate.ScriptObjectMap#2b8bb184]
Code to generate json object
* def user =
"""
function(response){
entity_type_ids =[]
var entityTypes = response.entityTypes
for(var i =0;i<entityTypes.length;i++ ){
object = {}
object['entity'] = entityTypes[i].id
entity_type_ids.push(object)
}
return JSON.stringify(entity_type_ids)
}
"""

Related

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

Any example to have a java class instance to call once and use in all scenarios in karate with different feature files

I have been using DBUtils class from karate demo, i knew this class was nothing to deal with karate. I have a concern like an example which was given has DBUtlis class is called in background for each and every scenario and it should be mentioned in all featurefiles Background:.
Anything like we configure once and use that DB instance variable in all scenarios?? If yes examples please.
Update after below comment by peter:
config:
Main Feature File:
Reusing DB instance in another feature file
Please confirm whether this is right approach or not?
Dry Run for a String:
var result = karate.callSingle('classpath:featureFiles/dbBackground.feature', config);
config.PersonName = result.name;
Main Feature:
Feature: DB Background
Background:
* def name = "Sandeep";
Other feature:
Feature: Get Account Details
Background:
* def actualname = PersonName;
#golden
Scenario: user 1 details
* def expectedFormat = read('../requestFiles/format.json')
Given url 'https://reqres.in/api/users'
And params ({id: '1'})
When method Get
Then match response.data.email == "george.bluth#reqres.in"
Then print '###################################name is: ', actualname
Then print '###################################name is: ', PersonName
Console result seeing null:
Updated Dry run 2:
Feature: DB Background
Background:
* def name = "Sandeep";
#golden
Scenario: user sample details
* def expectedFormat = read('../requestFiles/format.json')
Given url 'https://reqres.in/api/users'
And params ({id: '1'})
When method Get
Then match response.data.email == "george.bluth#reqres.in"
output:
19:31:33.416 [ForkJoinPool-1-worker-0] DEBUG com.jayway.jsonpath.internal.path.CompiledPath - Evaluating path: $['data']['email']
19:31:33.416 [ForkJoinPool-1-worker-0] INFO com.intuit.karate - [print] ###################################name is: Sandeep
19:31:33.432 [ForkJoinPool-1-worker-0] INFO com.intuit.karate - [print] ###################################name is: Sandeep
Yes you can initialize it in karate-config.js and then it will be a global variable.
Also look at karate.callSingle(): https://github.com/intuit/karate#hooks

How to do conditional variables definition on Karate

I had written karate tests for one environment only (staging). Since the tests are successful on capturing bugs (thanks a lot Karate and Intuit team!), there is now request to run the tests on production.
Our tests are graphql-based where most of the requests are query. I wonder if it is possible for us to switch variables based on karate.env we passed on terminal?
Most of our requests look like this:
And def variables = {objectID:"1234566", cursor:"1", cursorType:PAGE, size:'10', objectType:USER}
And request { query: '#(query)', variables: '#(variables)' }
When method POST
Then status 200
I had tried reading the conditional-logic page on github page but haven't yet found a success.
What I tried so far is:
* if (karate.env == 'staging') * def variables = {objectID:"1234566", cursor:"1", cursorType:PAGE, size:'10', objectType:USER}
But to no success.
Any help will be greatly appreciated. Thanks a lot!
We keep our graphql queries & variables in separate json files, but, we're attempting to solve the same issue. Based on what Peter wrote I came up with this, though it will likely get cleaned up before deployment.
Given def query = read('graphqlQuery.graphql')
And def prodVariable = read('prod-variables.json')
And def stageVariable = read('stage-variables.json')
And def variables = karate.env == 'prod' ? prodV : stageV
And path 'api/' + 'graphql'
And request { query: '#(query)', variables: '#(variables)' }
When method post
Then status 200
This should be easy:
* def variables = karate.env == 'staging' ? { objectID: "1234566", cursor: "1", cursorType: 'PAGE', size: '10', objectType: 'USER' } : { }
Here is another hint:
* def data = { staging: { foo: 'bar }, production: { foo: 'baz' } }
* def variables = data[karate.env]
EDIT: also see this explanation: https://stackoverflow.com/a/59162760/143475

How to call a feature file using a for loop. The feature file being called will also accept parameters from the feature file calling it

example :
Contents of FooGetRequest.feature file
* eval for (var i=0; i<foobarInDB.length; i++) call read('../features/BarGetRequest.feature') { foo_code:'#(foo_code)' , bar_code:'#(foobarInDB[i])'}
This is how BarGetRequest.feature file looks like :
Background:
* url baseUrl
Given path
"/v1/foo/"+foo_code+"/skus/"+bar_code+"/bar"
When method get
Then status 200
When I execute FooGetRequest.feature file i get the following error
[java.lang.RuntimeException: javascript evaluation failed: Expected ; but found read
you can use driven data driven feature in karate for loop over feature multiple times
Assuming foobarInDB is an array of bar_code and foo_code will always be same
* set foobarInDB[*].foo_code = foo_code
* call read('../features/BarGetRequest.feature') foobarInDB
refer Data driven feature
I wrote a small java script to return me a map like { foo : bar}
* def fun = function(x){return {foo :x }}
* def fooBarMap = karate.map(fooBarMap,fun)
* def validateResponse = call read('../features/BarGetRequest.feature) propertySkuMap
and in the BarGetRequest.feature I read the values accordingly.

Getting junk value(com.intuit.karate.ScriptObjectMap#XXXX ) when i call karate feature( using Karate.call) in javascript

I am trying to call a karate feature in javascript and capture its response as below, but while doing, the response from karate.call is showing junk value(com.intuit.karate.ScriptObjectMap#XXXX ) . kindly help to get the actual values from karate.call or suggest me any best idea ?
function RequestMandator(featurepath,data) {
var Mandator = [];
data.forEach(function(data){
var TransferId = data.TransferID;
var FocusKey = data.TransferID + ':';
var TimeStamp = data.LastUpdate;
var result = karate.call(featurepath, { input: [TransferId, FocusKey,TimeStamp ] });
karate.log('Added Mandator :', result);
Mandator.push(result);
})
return Mandator;
}
Output:
11:32:53.307 [main] WARN com.intuit.karate - xml parsing failed, response data type set to string: org.xml.sax.SAXParseException; lineNumber: 5; columnNumber: 15; Open quote is expected for attribute "border" associated with an element type "table".
11:32:53.310 [main] INFO com.intuit.karate - Added Mandator : com.intuit.karate.ScriptObjectMap#102d92c4
Error:
com.intuit.karate.exception.KarateFileNotFoundException: C:\XXXXXXXX\com.intuit.karate.ScriptObjectMap#7808fb9,com.intuit.karate.ScriptObjectMap#25d958c6,com.intuit.karate.ScriptObjectMap#5eeedb60,com.intuit.karate.ScriptObjectMap#6ad6fa53,com.intuit.karate.ScriptObjectMap#6f099cef,com.intuit.karate.ScriptObjectMap#2d66530f,com.intuit.karate.ScriptObjectMap#25b865b5 (The filename, directory name, or volume label syntax is incorrect)
at com.intuit.karate.FileUtils.getFileStream(FileUtils.java:146)
at com.intuit.karate.FileUtils.readFile(FileUtils.java:110)
at com.intuit.karate.ScriptBridge.read(ScriptBridge.java:67)
Please refer to the documentation on type-conversion: https://github.com/intuit/karate#type-conversion
It is not possible to figure out based on the incomplete information you have provided. Still let me try, I think you have done some mistake in string concatenation before calling this function. And the value of featurepath is completely wrong.
In the example below, see how a string concatenation within a JS function leads to what you call "junk value":
* def fun = function(){ var temp = { hello: 'world' }; return temp + '' }
* def bar = fun()
* print "bar:", bar
Results in output:
13:52:50.912 [main] INFO com.intuit.karate - [print] bar: [object Object]
If you still are stuck, the only suggestion I have is follow the instructions here please: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue