首页 > 解决方案 > 在空手道中使用逻辑 AND/OR 和模糊匹配标记

问题描述

在空手道中,是否可以使用模糊匹配标记构建逻辑 AND/OR 结构?就像是:

* def response = {a:1, {b:null, c:2}}, {a:2, {b:[x,y,z], c:3}
* match each response == {a:'#number', {b:('#present' && ('#null' || '#array'), c:'#number'}

基本上,检查键b是否存在 且值为nullJSON数组

标签: karate

解决方案


我建议您将比赛分为两个步骤,以避免过于复杂:

* def response = [{ a: 1, b: null, c: 2 }, { a: 2, b: [x, y, z], c: 3 }]
* match each response contains { b: '#present' }
* match each response == { a: '#number', b: '##array', c: '#number' }

您可以结合“标记”和“自我”参考 - 请参阅此处的最后一个示例:https ://github.com/intuit/karate#self-validation-expressions

* match each response == { a: '#number', b: '##array? _ != null', c: '#number' }

为了完整起见,这里是另一种选择。请注意,该isValid()函数是可重用的,并且只需要(全局)定义一次。

* def isValid = function(x){ return !x || karate.match(x, '#array').pass }
* match each response == { a: '#number', b: '#? isValid(_)', c: '#number' }

推荐阅读