Forum Discussion

jfesri's avatar
jfesri
Occasional Contributor
5 months ago

How to check for the existence of a value in Groovy script

I have an existing Groovy script (for an assertion) that I need to change to check whether a variable exists, but not caring about the actual value. The script is using results from the test step.

 

def expectedMsgs = ["""
{"msgType":"Message","message":{"variable1":"<value>","variable2":[{"variable2a":"<value>","variable2b":"<value>","variable2c":"<value>","variable2d":"<value>"}]}}

 

def msg = context.receivedMessage

 

def isMatch = expectedMsgs.stream().any { em -> org.skyscreamer.jsonassert.JSONCompare.compareJSON(em, msg, org.skyscreamer.jsonassert.JSONCompareMode.LENIENT).passed()}
log.info ("Websocket message #${context.messagetCount} ${isMatch ? "matched" : "did not match"} the list of expected string")

 

assert(isMatch)

 

Some of these values I do want to check an exact response is received and that's easy enough. But some of them, I just want to make sure the variable itself is present and value isn't null. Can't sort out how to handle that part.

 

Thanks!

Jonathan

5 Replies

  • nmrao's avatar
    nmrao
    Champion Level 3

    Here is the another example for your reference with Map data type unlike list earlier.

    It is noticeable in the below that here containsKey is used, and also in used to find if the key / word is there in the dictionary or not. 

    Also see how any, every  keywords are used at the end.

    Please follow in-line comments below:

    //Let us assume, there is a dictionary and one would like to check 
    //if certain word is there in it or not before know the meaning of that word.
    
    //Define the dictionary
    def dictionary = ['word1': 'Meaning of word 1', 'word2': 'Meaning of word 2', 'wordx': 'Meaning of word x', 'wordz': 'Meaning of word z']
    
    //Closure to check if a word found or not with logging
    def checkForWord = { 
        if (dictionary.containsKey(it)) {
            log.info("$it found")
        }
        else {
            log.info ("$it not found") 
        }
    }
    
    
    //Actually checking for words  
    checkForWord('wordx')
    checkForWord('wordp')
    
    //Another way of check using assert - this is how it should be done in the automated tests
    //Check if at least one word of the list is found in the dictionary
    assert ['wordp', 'wordz'].any { it in dictionary.keySet()}, 'Not even one word found'
    
    //Check if all the words of the list are present in the dictionary
    assert ['word1', 'word3'].every { it in dictionary.keySet()}, 'Not all words found'
  • nmrao's avatar
    nmrao
    Champion Level 3

    Do you mean that the response needs to have the same keys which are in expectedMgs? Or explain with an example?

  • soniya-01's avatar
    soniya-01
    New Contributor

    Hello, 

    So, start understand this with very easy example. 

    Let's imagine that you have a toybox, and you want to know if your favorite car inside or not. 

    In Groovy, it's like asking the computer, "Hey, does my toybox contains car?" 
    You'd use a special trick called an  "if statement" that looks like this:
    if (toybox.contains('Car')){//do something}. 

    It's simply means - "If car is in there, then do a specific thing." So, if car is there, the computer follow the instructions which you are provide in inside {} curly brackets and if car isn't there, in that case it skips that part. 

    In very simple words, "You're just telling the computer to check if your favorite car ( Any toy ) in the box and if it is not there then tell the system ( Computer ) what to do next. 

    I hope this will help you. 

    Regards
    soniya-01 

  • nmrao's avatar
    nmrao
    Champion Level 3

    soniya-01

    Here is the simple example which uses list of items in the box and checks using "contains".

    You can try with different value for favouriteToy which is not in toyBox and see the output.

    Below uses Ternary operator. For more details check documentation here

    Of course, one can use if / else too

    In this example, just logging different things to demonstrate. One can write different statements instead as needed in each case i.e., true or false.

    def favouriteToy = 'car' 
    def toyBox = ['car', 'bat', 'helicopter', 'bike', 'tractor', 'truck', 'train'] 
    toyBox.contains(favouriteToy) ? log.info("Toy box has favourite toy") : log.info("Toy box does not have ${favouriteToy}")
  • jfesri's avatar
    jfesri
    Occasional Contributor

    Thanks nmrao and soniya-01 for the help! We'll look into re-writing the Groovy script based on the examples above.