In karate, is it possible to construct logical AND/OR constructs with fuzzy match markers? Something like:

* 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'}

Basically, checking that the key b is present AND is value is null OR an JSON array

  • That is an example/bogus response simply to help communicate the intent of what the question is asking about. Bottom line is that I can possibly get a response that has a nested key with a value that could be either a null or JsonArray. – kpschmidt Jun 12 at 14:48
  • Valid JSON:[ { "timestamp":1510967081343, "changes":[ { "op":"add", "value":{ "id":[ "2c918083588e2ab20158b721f8f308e6", "2c918084594c27cf01596a0f05a60297" ], "type":"accessProfile" } } ] }, { "timestamp":1501118375038, "changes":[ { "op":"remove", "value":null } ] } ] – kpschmidt Jun 12 at 14:56
  • not MCVE, try again: stackoverflow.com/help/mcve - is it so hard to edit your simple JSON ? I'm not trying to be un-helpful, the best way to answer questions is to paste your example into a REAL script and try it out, so please try and respect that. – Peter Thomas Jun 12 at 14:59
  • I've been trying things out. I'm simply asking the question about the tools ability to support a construct like ('#present' && ('#null' || '#array'), and if so, what would be a valid syntax? I haven't been successful in any of my attempts so far, nor have I found anything in the docs giving me any hints to what else I might be able to try. – kpschmidt Jun 12 at 15:41
  • Peter, I don't understand why you are taking such a defensive posture. This was a legitimate question. Your supplied answer was all I was looking/hopeful for. I don't understand why you couldn't have provide that in the first place. – kpschmidt Jun 12 at 20:13

I recommend you break your match into 2 steps to avoid over-complicating things:

* 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' }

You can combine a "marker" and a "self" reference - see the last example here: https://github.com/intuit/karate#self-validation-expressions

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

For completeness, here is another option. Note that the isValid() function is re-usable, and needs to be defined (globally) only once.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.