testingcurlkarate

Using cURL for API automation in Karate


I'm new to Karate.

I'm automating an API test where I need to upload a large file >50MB When I do so with Karate I get an error "Broken Pipe" and according to this question Broken pipe (Write failed) when testing > max allowed Content-Length I could use "cURL" for this request.

It's working fine as follows (with hardcoded data):

* def result = karate.exec('curl -L -X POST "URL" -H "Authorization: Bearer MYTOKEN" -F "file=@"PATH""')

However, I'm having issues with the syntax when passing variables I need to pass the URL, token, and path as variables and not hardcoded text since I will be reusing this test for multiple landscapes.

How would I go about it?


Solution

  • Think of the Karate syntax as very close to JavaScript. So, string concatenation works. For example:

    * def myUrl = 'https://httpbin.org/anything'
    * def result = karate.exec('curl ' + myUrl)
    

    And a nice thing is that JavaScript Template Literals work:

    * def myUrl = 'https://httpbin.org/anything'
    * def result = karate.exec(`curl ${myUrl}`)
    

    Also note that the karate.exec() API takes an array of command-line arguments. This can make some things easier like not having to put quotes around arguments with white-space included etc.

    * def myUrl = 'https://httpbin.org/anything'
    * def result = karate.exec({ args: [ 'curl', myUrl ] })  
    

    You can build the arguments array as a second step for convenience:

    * def myUrl = 'https://httpbin.org/anything'
    * def args = ['curl']
    * args.push(myUrl)
    * def result = karate.exec({ args: args }) 
    

    Note that conditional logic and even an if statement is possible in Karate: https://stackoverflow.com/a/50350442/143475

    Also see: https://stackoverflow.com/a/62911366/143475 and https://stackoverflow.com/a/64352676/143475