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 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.
Originally posted by soniya-01 on December 12, 2023
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.
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'