【问题标题】:How to use templating in karate specific json schema如何在空手道特定的 json 模式中使用模板
【发布时间】:2019-07-11 02:03:03
【问题描述】:

我正在空手道下面尝试。

我在 .json 文件中有一个 json 架构(用于响应验证)。在许多模式中,很少有常见的 REGEX。我想将它们作为键值对提取到一个通用文件中,并在其他模式中使用它。是否可以?如果是这样,我该怎么做? json 模式中是否允许模板化?

示例:

示例 Json 架构文件 (sample-response.json):

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

功能文件

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

我想做什么?

我想将数量正则表达式存储在 json 文件中作为可重用变量,并使用 json 文件中的模板来替换它。 是否可以?


{
  "response": {
    "name": "#string",
    "amount": "{{get regex from this template}}"
  }
}

【问题讨论】:

  • 编辑你的问题,给出一两个简单的例子,然后再试一次。另请阅读:stackoverflow.com/help/minimal-reproducible-example
  • 嗨@PeterThomas,更新了更多细节
  • 您可以在 JSON Schema 中使用 $ref 关键字来引用其他 JSON Schema 文件的部分内容。抱歉,我现在无法提供更多详细信息。

标签: jsonschema karate


【解决方案1】:

是的。 Embedded expressions 即使在 reading files 时也能正常工作。

这样做:

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

然后这样做:

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

如果您希望 amount 来自另一个 JSON 文件,为什么不呢,说下面是 data.json

{ "amount": 100 }

然后你这样做:

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')

【讨论】:

  • 是否可以将 data.json 作为全局用于所有功能,而不是在每个功能文件中读取它?
  • @Farhan 是的,设置在karate-config.js:config.data = read('data.json');
  • 好吧。最初的那个。但是对于 js 和功能文件中可用的 api 调用有点困惑。
  • 顺便说一句,有没有办法可以在 IDE 的功能文件中调试 js 文件/内联 JS?
  • @Farhan 你不能,这是我们建议你将 JS 保持在最低限度并在你有一些非常复杂的自定义逻辑时使用 Java 的原因之一。也就是说,Karate UI 在很大程度上解决了调试问题:github.com/intuit/karate/wiki/Karate-UI
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多