Forum Discussion

jaya_kiran's avatar
jaya_kiran
Occasional Contributor
4 years ago
Solved

Sub : how to do regular expression assertions for variable elements in an array

  Description : Trying to write an assertion for fields code and unit. code can be an integer or empty and unit can be a string or empty. i.e code and unit has no fixed values. And have to asser...
  • ChrisA's avatar
    ChrisA
    4 years ago

    Hi,

     

    Add a script assertion to the test step of interest.

     

    The below will get you started, but be warned, it won't work first time.  You will need to tailor this to your needs.

     

    import groovy.json.JsonSlurper
    import groovy.json.*
    import java.util.regex.*
    
    // User Json Slurper to get the JSON from the response.
    def jsonSlurper = new JsonSlurper().parseText(messageExchange.response.responseContent)
    
    // Just log how many items to check.  If you get an error here, replace message with 
    // root node of interest in the response.
    log.info("Checking ${jsonSlurper.message.size()} items in response.");
    
    // Let's iterate over the array of items...
    jsonSlurper.message.each{
    
    	// Have a look at the current items
    	log.info("Item. Code ${it.code}.  Unit ${it.unit}.);
    	
    	// Check it.code for numeric only.
    	if (it.code.matches("[0-9]+") && it.code.length() > 0) {
    		log.info("Code ${it.code} passes");
    	} else {
    		log.info("Code ${it.code} fails")
    	}
    
    	// Check it.unit for lowercase chars only.
    	if (it.unit.matches("[a-z]+") && it.unit.length() > 0) {
    		log.info("Code ${it.unit} passes");
    	} else {
    		log.info("Code ${it.unit} fails")
    	}
    	// You decide how to report failure.  E.g. dump to a file
    	// or assert.
    	
    }