testingkaratedslkarate-call-single

Karate DSL: Conditional API Call Based on User Existence Results in "mismatched input '}'" Error


I am trying to conditionally call an API using Karate DSL. My goal is to:

Make a GET API request to check if a user exists. If the user exists (i.e., the response status is 200), call a DELETE API to remove the user.

I attempted to use an if statement in Karate DSL to conditionally call a DELETE API if a user exists. My initial approach was:

  1. Make a GET request to check if a user exists.
  2. If the GET response status is 200, proceed to call the DELETE API.

Here's the code I tried:

Given headers authorization
And headers contentType
And url host + '/user'
When method GET
Then status 200 || status 404
* if (responseStatus == 200){
  * url host + '/internal/user'
  * method DELETE
  Then status 200
  * karate.log('Deleted user')
}

However, I received a mismatched input '}' expecting <EOF> error. When I removed the curly braces {} around the if block, I encountered further errors related to the conditional logic and request structure.

I expected the code to conditionally execute the DELETE API call only if the GET request returned a 200 status. If the user does not exist (i.e., the GET request returns 404), the DELETE API call should be skipped. I was hoping for a smooth conditional check and API call flow without syntax issues.


Solution

  • I do not think karate supports this multi line conditional logic inside of feature files like you would think with JS or Java. To achieve this I think you would need to move the deletion logic inside of its own feature file and combine that with the conditional logic on a single line.

    First, create a seperate feature file for the delete logic ex. delete-user.feature

    Feature: Delete User
    
    Scenario: Delete a user
     Given url host + '/internal/user'
     When method DELETE
     Then status 200
     * karate.log('Deleted user')
    

    And then you can use this feature file in your conditional logic to be called if the user exists

    Feature: Check and Delete User
    
    Scenario: Check if user exists and delete if present
     Given headers authorization
     And headers contentType
     And url host + '/user'
     When method GET
     Then status 200 || status 404
     * if (responseStatus == 200) karate.call('delete-user.feature')
     
    

    Here are the links to the relevant karate documentation

    Karate Conditional Logic Documentation

    And if you need to pass aditional data into the called feature

    Karate Call Documentation