Search code examples
groovyready-apijsonslurper

groovy JsonSlurper assertion for random number, random alphanumeric and date


I am pretty new to service testing and Groovy. The following is my response,

{
    encodedDiscountId=1275479, 
    encodedGuid=gOHSkGzQEee4-AJiXJP2jg,
    expirationDate=2017-08-17 17:00:00
}

I need help for the following assertions:

  1. I need to assert if the DiscountId value is all random numerical of 7 digit long.
  2. I need to assert I am getting an alpha numeric in upper and lower case with "-"
  3. I need to assert the expirationDate should be 30 days from the system date.

I tried the script assertion and keep getting this error.

import groovy.json.JsonSlurper

def response = messageExchange.response.responseContent
def slurper = new JsonSlurper()
def json = slurper.parseText(response)
assert json.encodedDiscountId.size() == 7
assert json.encodedDiscountId.matches("[0-9]")

Error:

assert json.encodedDiscountId.matches("[0-9]") | | | | 1043947 false [encodedDiscountId:1043947, encodedGuid:l0wWcG2KEee4-AJiXJP2jg, expirationDate:2017-08-18 17:00:00]

Solution

  • Your regex is only for a single character in the character class from 0-9. You need to assert that the entire string is numbers, something like /^[0-9]+$.

    ^ matches the beginning of the line and $ matches the end, and [0-9]+ means at least 1 number. And since it looks like the encodedDiscountId is always 7 digits, you can include that in the regex as ^[0-9]{7}$.

    Since there is a $ in the regex if you are using double quotes you need to escape it as \$ ("^[0-9]+\$") or use slashy strings (/^[0-9]+$/) or single quotes ('^[0-9]+$').