How do I pass apikey as authorization in a POST/GET request in Karate Framework feature file [duplicate] - karate

This question already has an answer here:
Is there a way to update the headers in one feature file and use the Auth token from Karate.config.js?
(1 answer)
Closed 1 year ago.
This is the first time I am trying my hands at Karate for my work. I have a feature file that is a GET request and uses an authorization method as an apikey but when I am passing an authorization as a header its giving me an error
"required (...)+ loop did not match anything at input 'Scenario:'"
Below is my feature file for reference
Feature: Get Profile
Background:
* url 'https://csXXX-XXXX.XXXXXXXXX.net'
* header Accept = 'application/json'
* header Authorization = 'apikey XXXX-XXXX-XXXX-XXXX'
Scenario: Profile GET on an id
Given path '/v1/Profile'
And param idProfile='XXXX'
When method get
Then status 200
Any help is appreciated.

Looks like you missed the Feature: at the top of the file.
I suggest you use the quickstart or ZIP release, so you get a ready to use test to try: https://github.com/intuit/karate#getting-started

Related

Karate: Trying to get global headers working [duplicate]

This question already has an answer here:
Is there a way to update the headers in one feature file and use the Auth token from Karate.config.js?
(1 answer)
Closed 1 year ago.
I'm trying to setup a framework to run Graphql calls and create and E2E environment.
I've got the following setup so far but i can't seem to get the headers part of it working. i have managed to set the auth for each request and it all works but as it logs in for each request it doesn't really work as expected.
I want do the following steps:
run a login Test (different usernames valid/invalid)
run a logout test (Ensure token is removed)
Then login with correct user and extract the "set-cookie" header (to use globally for all future requests)
I was trying to use the following:
Karate-config.js
karate.callSingle('classpath:com/Auth/common-headers.feature', config);
headers.js
function fn() {
var headers = {}
headers["set-cookie"] = sessionAccessId
karate.log('Cookie Value: ', headers)
return headers
}
common-headers.feature
Feature: Login to Application and extract header
Background:
* url serverAuthenticateUri
* header Accept = 'application/json'
Scenario: 'Login to the system given credentials'
Given request { username: '#(username)', password: '#(password)'}
When method post
Then status 200
And match $.success == '#(result)'
And def myResult = response
* def sessionAccessId = responseHeaders['set-cookie'][0]
* configure headers = read('classpath:headers.js')
* print 'headers:', karate.prevRequest.headers
feature-file.feature
Feature: sample test script
Background:
* url serverBaseUri
* def caseResp = call read('classpath:com/E2E/POC/CommonFeatures/CreateCaseRequest.feature')
* def caseReqId = caseResp.response.data.createCaseAndRequest.siblings[0].id
* def caseId = caseResp.response.data.createCaseAndRequest.siblings[0].forensicCaseId
* def graphQlCallsPath = 'classpath:com/E2E/POC/GraphQl/intForensic/'
* def commmonFiles = 'classpath:E2E/CommonFiles/'
Scenario: TC1a - Request Server Details from Config DB (1st Run):
Should handle requesting Server Details Data from Config Database.
* def queryFile = graphQlCallsPath + '20-TC1a_req_req_valid_id.graphql'
* def responseFile = graphQlCallsPath + '20-TC1a_resp_req_valid_id.json'
Given def query = read(queryFile)
And replace query.reqId = caseReqId
And request { query: '#(query)' }
When method post
Then status 200
And json resp = read(responseFile)
And replace resp.reqId = caseReqId
And replace resp.caseID = caseId
And match resp == $
I can log in correctly and i get the set-cookie token but this isn't being passed on the feature-file.feature and i get an error saying "not logged in" in the response.
Any help appreciated! I might be looking at this totally wrong and i have tried to follow the shared-scope as much as i can but can't understand in.
Please make this change and hopefully that works !
headers["set-cookie"] = karate.get('sessionAccessId');
Why is explained here: (read the whole section carefully) https://github.com/intuit/karate#configure-headers
EDIT: one more suggestion:
var temp = karate.callSingle('classpath:com/Auth/common-headers.feature', config);
karate.configure('headers', { 'set-cookie': temp.sessionAccessId });
Some extra suggestions:
If you have just started with Karate - based on your question I would suggest you get one flow working in a single Scenario first without any use of call and with nothing whatsoever in karate-config.js. Hard-code everything and get it working first. Use the header keyword to set any headers you need. I also see you are trying to set a set-cookie header (which may work) but Karate has a special keyword for cookie.
And don't even think about callSingle() to start with :)
Once you get that first "hard-coded" flow working, then attempt to configure headers and then only finally try to do "framework" stuff. You seem to have jumped straight into super-complexity without getting the basics right.
Please read this other answer as well, because I suspect that you or someone in your team is attempting to introduce what I refer to as "too much re-use": https://stackoverflow.com/a/54126724/143475 - try not to do this.
Also note that your question is so complex that I have not been able to follow it, so please ask a simpler or more specifc question next time. If you still are stuck, kindly follow this process: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue

in Karate DSL, is there a way to have redirects perform a POST request instead of a GET request? [duplicate]

This question already has an answer here:
Post method gets converted to GET after redirection
(1 answer)
Closed 2 years ago.
I have the following Karate script that by default has redirects turned on.
Scenario: First Test
Given path 'somePath'
And request ''
And header Content-Type = 'text/html'
And param _csrf = csrf
And param username = 'username'
And param password = 'password'
When method post
Then status 200
The issue is after getting a 302 from the API, the next request automatically submits a GET request. I would like it to submit a POST request instead.
in cURL, there is an existing parameter that allows users to do that. see below.
--post302 Do not switch to GET after following a 302
is there anyway to do that in Karate DSL?
Yes please read the docs for configure folowRedirects. There is also an example on how to read the Location response header to manually make the request you want.
Scenario: get redirects can be disabled
* configure followRedirects = false
Given path 'redirect'
When method get
Then status 302
And match header Location == demoBaseUrl + '/search'
* def location = responseHeaders['Location'][0]
Given url location

Validating API response in Karate framework [duplicate]

This question already has answers here:
Can we parameterize the request file name to the Read method in Karate?
(2 answers)
Closed 1 year ago.
I want help for validating API response using karate framework.
I have API’s which are “Independent” on each other.
I have POST method along with request parameters. when I hit that particular API got the response with different parameters (no single match from request parameter and response parameter).
Now I want to validate response parameter value.
example : request: “method” post
school name: “abcd”
register date : “1:10:2010″
Response:
Principle name : ” pqrs”
Principle Email id “pqrs#gmail.com
now I want to validate that “principle name ” should not be null
I have implemented like this but it it doesn’t work
Feature: School info
Background:
* url baseUrl
Scenario: check Principles info
Given path ‘School info’
And request {school name: “abcd” ,register date : “1:10:2010”}
When method post
Then status 200
And match response.response contains {“type”: “Success”,”code”:20000}
And match response.principle list[*] { “Principle name”: “#notnull”}
whenever I run this file it always passes the API wvwnt if the Principle name filed is null.
It just checks the success message (And match response.response contains {“type”: “Success”, ”code”:20000}) and pass the API
your code for validating principlelist doesn't have proper assertions.
match each will be more convenient for validating json array with a schema
* match each response.principlelist contains {"Principal name" : "#notnull"}

Is Karate able to validate Excel file for a download endpoint? [duplicate]

This question already has answers here:
How to get the downloaded xlsx file from the api endpoint in karate?
(2 answers)
Closed 1 year ago.
I am trying to confirm the file downloaded from an api. After reviewing the recommendation from How to test download api using karate, my scenario was written like below:
Scenario: GET /project - Export project listing
Given params { someparam: 'paramvalue' }
When method GET
Then status 200
And match header Content-Disposition == 'attachment;filename="someFile.xlsx"'
And match header Content-Type == 'application/vnd.ms-excel'
And match response == read('data/exported.xlsx')
The first 2 matches pass. However, the last match (comparing the actual file) fails with a binary printout of both files and "reason: not equal".
The file "exported.xlsx" in the comparison was the output of the exact same request done via Postman, so they should match.
Is read() able to handle excel and csv files? Any help would be appreciated.
As far as I know this should have worked. read('data/exported.xlsx') will return a stream of bytes.
If this is indeed a bug you will do a great service to the community if you follow this process: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue

Karate : Passing variable from one feature file to another as a query parameter [duplicate]

This question already has answers here:
Can we parameterize the request file name to the Read method in Karate?
(2 answers)
Closed 1 year ago.
I'm trying to execute a feature file and need which takes a query parameter from another feature.
Here is the feature files :
1. This file call two feature files. First feature file add a record in the database and returns json response. I have to use a property from the response and have to pass to another feature. Please find below for the features files.
Feature:
Background:
Scenario:
Given call read('test_add.feature')
And def query1 = response.name
Given call read('test_get.feature') {'**query**' : #query1}
feature name - test_get.feature
Feature: Add a new Nat bundle device
Background:
url baseUrlWithContext
def headers = { 'Content-Type': 'application/json' }
Scenario: Addition
Given headers headers
And path '/test'
And params query
When method get
Then status 200
Error :
com.intuit.karate.exception.KarateException:
cannot convert to map: query
Instead of And params query
Try this:
And param query = query