Search code examples
karate

validation using combination of a "marker" and a "self" reference


In Karate, I am trying to validate a json response using a combination of a marker and self reference variable as suggested in this post. But the null check is not working as intended.

Trying to validate - 'name' key is string, optional and if present should not be null

Please find the code snippet below:

    * def aTest =
    """
    {
        name: null,
        type: "House",
    }
    """

    * def eTest =
    """
    {
      name: '##string? _ !==null',
      type: '##string',
      street: '##string'
    }
    """

    * match aTest == eTest

When I run the test, I am expecting the test to fail for 'name' key. But the test is passing. Not sure what am I doing wrong. Can someone guide me on this please.


Solution

  • I think that example was specific to #array. I tried #present and it worked. This may be a small bug in Karate.

    * def aTest = { name: null, type: 'House' }
    * def eTest = { name: '#present? _ != null', type: '##string', street: '##string' }
    * match aTest == eTest
    

    EDIT - after reading comment, this is a very interesting case that has me stumped. I think there is no way to do this in a single step and I have a question as to how important this is. My guess is this has never come up before because if the value is null, most systems just ignore the field an treat it as not present as explained here: https://github.com/karatelabs/karate#null-and-notpresent

    Anyway, here is one solution, there may be others. There is an edge case where it will fail if the value is '', but I leave that as an exercise :)

    * def expected = aTest.name ? '#string' : '#notpresent'
    * def eTest = ({ name: expected })
    * match aTest == eTest