0

I am trying below in Karate.

I have a json schema ( for response validation) in .json file. There are few REGEXs that are common in many schemas. I want to extract them into one common file as key value pairs and use it across other schemas. Is it possible? if so, how can I do that? Is templating allowed in json schema?

Example:

Sample Json Schema File ( sample-response.json):

{
  "response": {
    "name": "#string",
    "amount": "#regex ^(-?)([0]|[1-9][0-9]{0,15})[.][0-9]{2}$"
  }
}

Feature File

Feature: Example feature

  Background:

  * def sampleResponse = read('./sample-response.json');



  Scenario: Example scenario

    When url 'https://someurl.com'
    And method get
    Then status 200
    And  match response == sampleResponse

What would I like to Do?

I would like to store the amount regex in json file as a reusable variable and use templating in json file to replace it. Is it possible?


{
  "response": {
    "name": "#string",
    "amount": "{{get regex from this template}}"
  }
}
Farhan
  • 13
  • 4

1 Answers1

1

Yes. Embedded expressions work even when reading files.

So do this:

{
  "response": {
    "name": "#string",
    "amount": "#(amount)"
  }
}

And then do this:

Background:
* def amount = 100
* def sampleResponse = read('sample-response.json')

If you want the amount to come from another JSON file, why not, say this below is data.json:

{ "amount": 100 }

Then you do this:

Background:
* def data = read('data.json')
# you don't need the next line if you use "data.amount" as the embedded expression
* def amount = data.amount
* def sampleResponse = read('sample-response.json')
Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • Is it possible to make data.json available as global for all features, instead reading it in each feature file? – Farhan Jul 12 '19 at 00:49
  • @Farhan yes, set it in `karate-config.js`: `config.data = read('data.json');` – Peter Thomas Jul 12 '19 at 01:18
  • well. That of that initially. But a bit confused about what api calls are available in js and feature files. – Farhan Jul 12 '19 at 01:35
  • Btw, Is there a way I can debug js files/ inline JS in feature files from IDE? – Farhan Jul 12 '19 at 01:35
  • @Farhan you can't, and this is one reason we recommend you keep your JS to a minimum and use Java if you have some very complex custom logic. that said, the Karate UI solves for debugging to a large extent: https://github.com/intuit/karate/wiki/Karate-UI – Peter Thomas Jul 12 '19 at 01:56