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

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

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

Karate Mocks- `How to create a mocks to get a value from json using the key

Karate Mocks- `How to create a mocks to get a value from json using the key.
In below example, i want to get the name using the id, iam not able to retrieve
response.json
{
"2727": "siva",
"2728": "kavi"
}
demo-mock.feature
Feature: stateful mock server
Background:
* def company = read('response.json')
Scenario: pathMatches('/companies/search/{id}}')
* def name = company.id
* def response = name
test.feature
Feature: integration test
Background:
* def port = karate.env == 'mock' ? karate.start('demo-mock.feature').port : 8080
* url 'http://localhost:' + port + '/companies/search'
#mock
Scenario: get company name
Given path '2727'
When method get
Then status 200
Read the docs: https://github.com/intuit/karate/tree/master/karate-netty#pathparams
* def id = pathParams.id

Karate: How can we retrieve the value from called feature file

I have two parameter in feature file A and I pass those values to another feature file called B.
But I am unable to retrieve the values as expected in Feature file B
CODE:
Feature File A:
And def Response = response
And def token = response.metaData.paging.token
And def totalPages = response.metaData.paging.totalPages
* def xyz =
"""
function(times){
for(currentPage=1;currentPage<=times;currentPage++){
karate.log('Run test round: '+(currentPage));
karate.call('ABC.feature', {getToken:token, page:currentPage});
}
java.lang.Thread.sleep(1*1000);
}
"""
* call xyz totalPages
Feature File B:
* def token = '#(getToken)'
* def currentPage = '#(page)'
But the output was
#getToken
#page
What would be the best way? to these values for further utilization.
Try this:
* def token = getToken
* def currentPage = page
Here's another thing, any variable defined in the calling feature will be visible, e.g. token so most of the time you don't need to pass arguments:
* print token
* print totalPages
Please avoid JS for loops as far as possible: https://github.com/intuit/karate#loops - and actually you seem to have missed the data-driven testing approach that Karate recommends: https://github.com/intuit/karate#the-karate-way
If you are still stuck, please follow this process: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue

Log requests from called features in reports [duplicate]

We are using the report verbosity option available in Karate
I have a MarketingPreferenceTest.feature calling BBB.feature.
The features are as below:
MarketingPreferenceTest.feature
Background:
* url Url
* table credentials
|Email |Password|
|'aaa#test.com'|'test1234'|
* def result = karate.callSingle('classpath:resources/BBB.feature',credentials)
Scenario Outline: Get MS
Given path 'abc'
When method GET
Then status 200
BBB.feature:
Background:
* configure retry = { count: 5, interval: 1000 }
* configure headers = { 'Content-Type': 'application/json'}
* url authenticationUrl
Scenario: Login
Given path 'login'
And request { email: '#(Email)' , password: '#(Password)' }
And retry until responseStatus == 200 && response.loginResponse.loggedIn == true
When method post
My karate.config has
karate.configure('report', { showLog: true, showAllSteps: false } );
When i run the tests in parallel, i want to see all the Given-When-Then's printed in my cucumber report from BBB.feature. How do i achieve it ?
The cucumber report is shown below which doesn't have step definitions from BBB.feature :
Expected Result: Would like to see the Steps of BBB.feature in my report marked in a rectangle box below
Just make the step involving a callSingle use a Gherkin keyword:
When def result = karate.callSingle('classpath:resources/BBB.feature',credentials)

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