You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级至Karate 1.4.1后,如何验证含可空属性的Schema?

Karate 1.4.1 可空属性Schema验证失败的原因及解决办法

在Karate 1.x版本中,##的语义和0.9.5有明确差异:

  • 旧版本里##(schema)可能宽松允许字段不存在或存在但为null
  • 新版本中##仅表示字段是可选(可不存在),但如果字段实际存在,其值必须严格符合后续schema规则——你定义的nested是{'name': '#string'},属于对象类型schema,默认不接受null值,因此sub: null时匹配会失败。

解决办法

你需要显式声明该字段允许为null,有两种常用实现方式:

方式1:给嵌套Schema添加可空标记

修改nested的定义,用#nullable()包裹原schema,既允许字段符合原对象规则,也允许为null:

* def nested = '#nullable({name: #string})'
* def schema = {'sub': '##(nested)'}
Then match {'sub': null} == schema

方式2:直接在字段规则中合并null判断

如果不想修改nested,可直接在sub的规则里用逻辑或(||)同时允许null和原对象schema:

* def nested = {'name': '#string'}
* def schema = {'sub': '##(#null || nested)'}
Then match {'sub': null} == schema

额外说明

Karate 1.x对Schema验证逻辑做了更严谨的划分,核心原则是:

  • ##控制字段的存在性(可选/必填)
  • 字段存在时的取值合法性由后续Schema表达式单独控制,默认不包含null,必须显式声明。

内容的提问来源于stack exchange,提问作者CC Wheeler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 23:24:58