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

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

Related

How do I pass apikey as authorization in a POST/GET request in Karate Framework feature file [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.
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

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

Use header in multiple calls in the same scenario in Karate

Having a feature with only one scenario with more than one http calls, I want to use the same host and headers for all calls. However, although I am able to set the url to apply for all calls, the header seems to only be applied in the first call and then reset. Does someone have any info on why this is happening and/or a suggestion on how to do it correctly (besides adding them in each call separately)?
Either by setting them in the Background or with a generic Given, url is used in both calls, but the header is only included in the first:
1)
Feature: sample
Background:
* header Content-Type = 'application/json'
* url http://localhost:8080
Scenario: do multiple calls
Given path /sample/
When method GET
Then status 200
Given path /sample2/
When method GET
Then status 200
2)
Feature: sample2
Given header Content-Type = 'application/json'
And url http://localhost:8080
Scenario: do multiple calls
Given path /sample/
When method GET
Then status 200
Given path /sample2/
When method GET
Then status 200
You really really should read the documentation: https://github.com/intuit/karate#configure-headers
Just do:
Background:
* configure headers = { 'Content-Type': 'application/json' }
And there are many more options, just read the docs. Note that you typically never need to set the Content-Type because Karate does that automatically based on the request body.
I had the same problem. It was fixed when I added the "Header" informations I always use to the "karate-config.js".
var accessToken = karate.callSingle("classpath:helpers/authentication.feature").accessToken
karate.configure("headers",{Authorization: "Bearer " + accessToken})

Karate API : How to hit an endpoint url with post method which does not have request body

I am getting below error when I am trying hit a endpoint url with post method which does not have a body. In postman I am able to hit endpoint url with post method without body. I tried all steps by referring the Karate API docs.
**Error** : com.intuit.karate.exception.KarateException: TestScenarios.feature:56 -
request body is required for a POST, please use the 'request' keyword
testurl is :
**test-api.test.com/test-com/api/check/initiate?
lang=en&cntCode=us&id=8d1b9355**
Attempt 1:
Given url 'test-api.test.com/test-com/api/check/initiate?lang=en&cntCode=us&id=8d1b9355'
When method post
Then status 200
* print response
Attempt 2:
Given url testurl
And param lang= en
And param cCode = us
And param id= '8d1b9355'
When method post
* print 'Response'+response
Attempt 3:
Given url testurl
And form field lang= en
And form field cCode = us
When method post
Then status 200
Can someone help me to understand the issue and wrong in my approach.
Two possible options depending on your server:
* request {}
Or as per the docs:
* request ''

Scope of any element/object of a response json is within the scenario only

Scenario: Generenate jwt and check status
Given path '/sdk/jwt'
header Authorization = call read('jwt.js') { token: 'e68c82a665847c', secret: 'f08f06f1f41f4479854c' }
When method get
Then status 200
And def tkn = response
Scenario: Get project meta info for an instance
Given path '/meta/project'
And header Authorization = JWT tkn #which the response of 1st scenario.
When method get
Then the is status 200
But tkn value is not coming in the second scenario.
Define in background, it will work as before test