How to extract value from GET request in karate - karate

I am new to REST and Karate testing. Our project uses Karate for service virtualization during integration tests. I am calling a RESTful GET API with the following url structure:
http://localhost:8080/SampleService/v1/person/{personId}/personAssetRelationships
Below is the Scenario I have written
#Scenario to get all assets a person was ever assigned
Scenario:
pathMatches(/SampleService/v1/person/{personId}/personAssetRelationships) &&
methodId('get')
* def responseStatus = 200
* def response =
"""
[
{
"personId": "13",
"assetIdentifier": "21324",
"assignedDate": "2020-11-22",
"returnedDate": "9999-12-31",
"replacedAssetIdentifier": null
}
]
"""
This works during my integration test. The only concern is that the personId in my response is static. I want to be able to use the personId that is passed in the request path in my response. I am not sure how a I can do that. Any suggestions would be helpful.
Thanks.

Won't pathParams.personId work, read the docs: https://github.com/intuit/karate/tree/master/karate-netty#pathparams
"personId": "#(pathParams.personId)",

Related

SoapUI Webservice Testing: Can we test an API connection through SoapUI without running the API?

I come across a requirement to test if the webservice is responding(API Monitoring). Although we can't run the API as it is a Production API and it will issue orders.
I am currently using SoapUI and wondering if there's a way we could do it there?
Thanks.
Do the following in a Groovy Script step:
def req = new URL("http://www.dneonline.com/calculator.asmx?wsdl").openConnection()
def resp = req.getResponseCode()
if (resp.equals(200)) {
log.info('pass')
def respContent = req.getInputStream().getText()
}
else {
log.info('fail')
}

Can we pass method and path while calling feature from inside another feature

When you call a feature (with a few Scenarios) from inside another feature, I want to pass method and path
as these are common scenarios - called from two different endpoints where base url remain same but path and also the method differ.
This situation arise because I am trying to put the common scenarios in a feature and call that feature from other feature files where the scenarios are all common and they differ only in path and method.
I have referred to this issue: 'https://github.com/intuit/karate/issues/239' and know that it is possible but in my case I need to pass the path and method as arguments while calling the feature file because that is the only thing differing with two modules calling the common scenarios.
So the question is can we pass path and method as parameters while calling a feature file. Currently I am getting error but do not understand why it should fail.
I tried the following:
booking.feature
Background:
* def pathVar = '/bookings'
Scenario: Calling basic validation feature for create booking module
* call read('classpath:feature/basic-validations.feature') {path1: '#(pathVar)', action: 'post'}
basic-validations.feature
Background:
* url baseURL
* header Accept = 'application/json'
* def data = read(datafile)
* header API-Version = 1
* path '#(path1)'
* header Authorization = 'Bearer' + data.booking.token
Scenario: Empty request validation
Given request {}
When method '#(action)'
Then status 400
Scenario: Request-Body element is empty or null.
Given def req = ({ "request_body": null })
And request req
When method '#(action)'
Then status 400
Scenario: When parameter value for name in request body is incorrect.
Given def req = ({ "request_body": [ { "name": "shipment_standard_booking", "action":
"create", "path": "/standardBooking", "body": data.booking.standardBooking.requestBody }]
})
And def name = 'test'
And set req.request_body[*].name = name
And request req
When method '#(action)'
Then status 400
And match $.debugMessage == 'Validations failed due to bad input payload request. WorkItem
name (' +name+ ') is invalid'
The path step can take variables. The method step also can take a variable: https://github.com/intuit/karate#method
* def methodVar = 'post'
* url foo
* request bar
* method methodVar
But I totally don't recommend it - or the approach you are taking. Reasons are explained here, please take some time to read it: https://stackoverflow.com/a/54126724/143475
I think you also have mis-understood embedded expressions, so please read this: https://github.com/intuit/karate#rules-for-embedded-expressions
If you still decide to do this and get stuck, you can assume that either Karate does not support what you want to do - or that you need to contribute code.
Also read this for other ideas: https://stackoverflow.com/a/50350442/143475

Is anyone using Karate for Salesforce API testing? [duplicate]

Karate has been super helpful to validate our rest apis which gives json response. Now we have apis which gives us response in avro format. May also need to send the payload in avro format. How can i test the rest endpoints which gives response in AVRO format using karate? Is there any easy way I can tweak and get it done. Thanks!
Here's my suggestion, and in my opinion this will work very well.
Write a simple Java utility, maybe a static method that can take JSON and convert it to AVRO and vice versa.
Now you can define all your request data as JSON - but just before you make the request to the server, convert it to AVRO. I am not sure if the server call is HTTP or not. If it is HTTP - then you know what to do in Karate, just send binary as the request body etc.
Else you may not even use the Karate HTTP DSL like method, request etc. You have to write one more Java helper that will take your JSON (or AVRO) and make the call to the server (specific for your project) and return the response, converted back to JSON. For example:
* def Utils = Java.type('com.myco.avro.Utils')
* def json = { hello: 'world' }
* def req = Utils.toAvro(json)
* def res = Utils.send(req)
# you can combine this with the above
* def response = Utils.fromAvro(res)
* match response == { success: true }
Yes, you might be using Karate mostly for matching, reporting, environments etc. Which is still valuable ! Many people don't realize that HTTP is just 10% of what Karate can do for you.

How to update test results in VSTS/Microsoft Test Manager using APIs/endpoint

How to update the test results in VSTS/Microsoft Test Manager using APIs.
How to update the test results in VSTS/Microsoft Test Manager using Selenium/Java.
Procedure to update the test results through APIs:
First get the testPoints of the test case using following API:
For this you need plan id, suite id, and test case id. Open the suite in web view, in URL you can find plan id and suite id, test case id is id of the test case.
GET https://{instance}/DefaultCollection/{project}/_apis/test/plans/{plan}/suites/{suite}/points?api-version={version}&testCaseId={string}
Send the request and note the the testPoints (in response).
For details refer: https://learn.microsoft.com/en-us/vsts/integrate/previous-apis/test/points?view=vsts#get-a-test-point
Then create a test run for this. To create a test run you need plan id, testPoints, and run name. You already have plan id, You got testPoints from previous request, run name can be anything.
Sample request:
POST https://{instance}/DefaultCollection/{project}/_apis/test/runs?api-version={version}
Sample body
{
"name": "Sprint 10 Test Run",
"plan": {
"id": 1234
},
"pointIds": [
10
]
}
Send the request and note the run id (response).
For details refer: https://learn.microsoft.com/en-us/vsts/integrate/previous-apis/test/runs?view=vsts#create-new-test-run
Add test results.
For this you need test run id (which you got from previous request), test case id, and test points (you got it from first request).
POST https://{instance}/DefaultCollection/{project}/_apis/test/runs/{run}/results?api-version={version}
Sample body
[
{
"state": "Completed",
"testPoint": {
"id": 10
},
"outcome": "Passed",
"testCase": {
"id": 4567
}
}
]
Send the request and note result id (from response).
For details refer: https://learn.microsoft.com/en-us/vsts/integrate/previous-apis/test/results?view=vsts#add-test-results-to-a-test-run
Update test run
For this you need results id from previous request (add result)
PATCH
https://{instance}/DefaultCollection/{project}/_apis/test/runs/{run}?api-version={version}
Sample body
[
{
"id": 100000,
"state": "Completed"
}
]
For details refer: https://learn.microsoft.com/en-us/vsts/integrate/previous-apis/test/runs?view=vsts#update-test-run
Now check VSTS/Test Manager for result updates.
Additionally you can update the results for specific configuration also, just add configuration also in the body of add test results.
For configuration details refer: https://learn.microsoft.com/en-us/vsts/integrate/previous-apis/test/configurations?view=vsts#get-a-list-of-test-configurations
Now to update the results using Java, use RestAssured to send get, post, patch request and retrieve the specific data from the response.
For rest-assured details refer: https://github.com/rest-assured/rest-assured/wiki/Usage
For sending post and patch request you may want to create json objects/bodies, for that use minidev json libraries.
How to create json object/array: How to create JSON Object using String?

karate | xml post method exeuction

I’m having issue with xml post request where post method is not executed. When I try to post same request body in post man it worked.My test is success with 200 but actual request is not executed.
Please let me know if I’m missing
To pass the request body,I’m calling through java object and payload is correctly constructed and printed.In execution test is success and doesn’t print response.But actually test is not executed.
Only headers are printed.
***************** create-user.feature*****************
Feature: create ims user for provided country
Requires country code,
Background:
# load secrets from json
* def createuser = Java.type('com.user.JavaTestData')
* def create = createuser.createUser("US")
Scenario: get service token
Given url imscreateuserurl
And request create
When method post
Then status 200
* print response
***************** create-user.feature*****************
Here is java class
public class JavaTestData {
private static final Logger logger = LoggerFactory.getLogger(JavaTestData.class);
public static String createUser(String countryCodeInput) {
logger.debug("create user for country code input", countryCodeInput);
Unless you post a full working example, no one can help you. Pretty clear that the value of create is null or empty.
Also I personally think you are wasting your time using Java. The whole point of Karate is to avoid using Java as far as possible.
Look at these examples for ideas: https://github.com/intuit/karate/blob/master/karate-junit4/src/test/java/com/intuit/karate/junit4/xml/xml.feature
Edit: also refer to the doc on type-conversion: https://github.com/intuit/karate#type-conversion
#Peter, here is my feature file
Feature: create ims user for provided country
Requires country code,
Background:
# load secrets from json
* def createuser = Java.type('com.adobe.imscreateuser.JavaTestData')
* def create = createuser.createUser("US")
Scenario: get service token
Given url imscreateuserurl
And header Content-Type = 'application/xml; charset=utf-8'
And request create
When method post
Then status 200
* print response
I have performed print for create and showing complete payload.At when method post -> statement its going as null or empty...
Not sure where it is missing