General

Setting up a repeatable Search Method in Katalon Studio

Another one of my project goals was to extend functionality within tests by allowing a single task to be repeated multiple times for different criteria. Search is a good example.

In the original incarnation, my search test would look for one item, confirm it was returned and that was the end. Getting a result back was good enough to say the functionality was working. But the actual search function could look for multiple criteria and I was only looking for one. Could that code be extended to be more dynamic without adding a slew of bloat? Yes it can.

For my scenario, I want to search for a item by the state it’s located in, by the city it’s located in, or by it’s numerical code. For example, I can locate Warehouse 13 by searching for it by Arizona, or by AZ or by 13. All 3 criteria can be handled in one method.

The code below gets the job done. First, it will search for the given criteria. It will then read the text of the returned result and determine if the search criteria is contained within that returned text.

As an example, if I search for “Tallahassee”, that word needs to be in the name of the Warehouse.

If I search for AZ, that needs to be listed in the location.

If I search for 333, that number needs to be in the Warehouse description.
Since I am searching for known commodities, if I don’t get my expected result back, something is wrong. There will always be a result for Tallahassee. There will always be a result for 333. And there will always be a result for AZ.

Since I know the outcome, I can pass my search string and my result as parameters to confirm those are the results. Anything else means something is wrong.

This hard coding could be reduced by using a file or sheet, but that’s for another iteration. This still produces 9 more search tests and is easy to manage. If these pass, I’m quite confident the search function is in a working state.

def searchForWarehouse(String warehouseSearchCriteria, String nameOfWarehouse){
    /* Enter a Warehouse and confirm the Warehouse exists
     * @param warehouseSearchCriteria, search criteria of the Warehouse to look for
     * @param nameOfWarehouse, the text that should be returned for Warehouse details
     * @return that the Warehouse was found, otherwise an error
     */
    KeywordLogger log = new KeywordLogger()
    //Enter search criteria
    WebUI.setText(findTestObject('Project/Search Warehouse/input-Search Warehouse'), warehouseSearchCriteria)
    WebUI.delay(2)
    //Confirm there are results
    int returnedResults=WebUI.getText(findTestObject('Project/Search Warehouse/text-Warehouse Search - Results Found')).replaceAll("[^0-9]","").toInteger()
    if (returnedResults==0) {
        log.logWarning('ERROR: No results were returned. No Warehouse matches the search criteria.')
        log.logWarning('ERROR: The Warehouse ' + warehouseSearchCriteria + ' is not valid')
    } else {
    //Does the Warehouse result contain the expected criteria?
        String WarehouseName=WebUI.getText(findTestObject('Project/Search Warehouse/link-Name of Returned Warehouse'))
        log.logWarning('Warehouse Name= ' + WarehouseName)
        if (WarehouseName.contains(nameOfWarehouse)==true){
            log.logWarning('SUCCESS: The expected Warehouse Name was returned')
        } else {
            log.logError('ERROR: The expected Warehouse Name was not returned')
            KeywordUtil.markFailed('ERROR: The expected Warehouse Name was not returned')
        }
    }
}


//Look for several Warehouse locations and verify results are returned
//Search by City Name
searchForWarehouse('ukiah', 'Project Warehouse #111 UKIAH, CA')
searchForWarehouse('tallahassee', 'Project Warehouse #222 TALLAHASSEE, FL')
searchForWarehouse('worcester', 'Project Warehouse #333 WORCESTER, MA')

//Search by Warehouse Number
searchForWarehouse('646', 'Project Warehouse #646 W MILWAUKEE, WI')
searchForWarehouse('997','Project Warehouse #997 BILOXI, MS')
searchForWarehouse('999','This Warehouse does not exist')

//Search by State
searchForWarehouse('NY','NY')
searchForWarehouse('AZ','AZ')
searchForWarehouse('TX','TX')

searchForWarehouse on Github

Other articles of interest:

To markFailedAndStop or Not To markFailedAndStop?

Based on the criteria of the original tests I set up several months ago, if an object was missing, that was a critical error and needed to be flagged. Since we were making heavy adjustments to the code base, anything missing needed to be checked. Things have changed quite a bit, so if an object is missing, should the situation be handled within an IF statement  or does a missing object represent a much larger problem and the test has to be flagged as an Error?

This continues on from the idea of checking for the existence of an object without throwing an error. Using a Custom Keyword is was possible to suppress the error and not fill the log with False Positives.

Taking that a step further, it seems we could check if an object exists and continue on with the test if needed or exit out of the test completely.

Using the example from before, let’s say we want to count the number of Tasks a user has. If a user doesn’t have any Tasks to display, that’s not a critical error. They may not have made any. We could handle that within the IF statement and not try to count something that doesn’t exist.

Conversely, what if we tried to create a Task, but the New Task button was missing. Now we have a problem. We want to perform an action and piece of functionality is missing. And if the New Task button is missing, attempting to run code to fill in a series of input fields, then confirm it was saved won’t work and will lead to multiple errors. It would be better to mark the test as failed when we first notice the New Task button is missing.

We could handle both of those conditions within a single Custom Keyword. We can check for our object and if it’s a critical object, stop the test on failure. We can add a “critical” flag and handle both.

Our previous "verifyObjectPresent" method would be extended to create the following:

@Keyword
//Function to determine if an item exists on the page using WebUiCommonHelper.findWebElement
boolean verifyObjectPresent(String objectReference, boolean critical) {
    try {
        WebUiCommonHelper.findWebElement(findTestObject(objectReference),5)
        return true;
    } catch (Exception e) {
        if (critical==true){
            log.logWarning("The object with the name, " + objectReference + " was not found. Execution Halted.")
            KeywordUtil.markFailedAndStop("ERROR: The object with the name, " + objectReference + " was not found. Exiting Test.")
        } else {
            log.logWarning("The object with the name, " + objectReference + " was not found.")
            return false;
        }
    }
}

We are now accepting “boolean critical” as a parameter. If the object is missing and this is true, we note the missing object and execute, “markFailedAndStop.” If it’s not a critical object, the name of the object is noted, but execution continues. Control then returns to the Test Case to handle a non-critical missing object.

A call to the Custom Keyword would look like the following:

    boolean elementVisible=CustomKeywords.'commonCode.verifyObjects.verifyObjectPresent'('Blog/text-blogTitle', false)
    if (elementVisible==true){
        blogTitle = WebUI.getText(findTestObject('Blog/text-blogTitle'))
        log.logWarning('Blog Title: ' + blogTitle)
    }
    log.logWarning("Test Complete")

If the blog title exists, get the text of that object. If it doesn’t, take the appropriate action based on the critical parameter. If it’s a critical object, mark the tests as failed and exit.

I like this approach because it removes a lot of redundant check, so I plan to make adjustments to replace my standard “verify” based calls with this method. I can now decide how to handle a missing object within a single method and if it’s a real problem, stop the code.

https://github.com/DonPedroQA/qajamboree/blob/master/Katalon/verifyObjectPresent.groovy

Other articles of interest:

Checking for the presence of an object without throwing an error

One of my goals has to been to make my tests less noisy and not generate errors in the log unless it’s really necessary. For example, if an object is missing from the page, that may or may not be an error. If a tab is missing, the user may not meet the criteria to make it display.

When checking for the existence of an object using the WebUI.verifyElementVisible() keyword, a lot of additional logging that can be misleading. For example, this code block will execute as expected, but generates 2 entries for the Failed log.

    @Keyword
    //Function to determine if an item exists on the page
    boolean verifyObjectVisible(String objectReference) {
        try {
            WebUI.verifyElementPresent(findTestObject(objectReference),5)
            return true;
        } catch (Exception e) {
            log.logWarning("The object with the name, " + objectReference + " was not found. Exiting Test.")
            return false;
        }
    }

There is a cleaner way to check for an object using the WebUiCommonHelper.findWebElement command, which is part of the,

import com.kms.katalon.core.webui.common.WebUiCommonHelper library and performs the same function. I like it better because it allows for better handling of errors and logging.

Below is a Custom Keyword that wraps the use of the findWebElement statement within a Try/Catch block to determine if the object exists. The benefit is suppressing an error if the object doesn’t exit.

    @Keyword
    //Function to determine if an item exists on the page using WebUiCommonHelper.findWebElement
    //This does not throw an exception error to the log so it looks cleaner
    boolean verifyObjectPresent(String objectReference) {
        try {
            WebUiCommonHelper.findWebElement(findTestObject(objectReference),5)
            return true;
        } catch (Exception e) {
            return false;
        }
    }

A call to the Custom Keyword would then look like:

    //Check if there are existing notes on the page and count how many
    boolean elementVisible=CustomKeywords.'tools.commonCode.verifyObjectPresent'(katalonObject)
    if (elementVisible==true){
        originalNumberOfTasks=CustomKeywords.'tools.commonCode.countRowsPerPage'(xpath)
    } else {
        log.logWarning('Customer has no Tasks available at this time')
    }

This gives control within the code whether or not to display an error. In looking at the code above, if no Tasks are displayed on the page, a notification message is display, not an error. The test hasn’t failed and there is no problem with the site, a user may not have created an tasks which is why they don’t exit.

 

The verifyElementPresent or verifyElementVisible will perform the same task, but will log multiple errors if an element isn’t found, even when wrapped in a Try/Catch block.

Other articles of interest:

More Katalon Studio and Automation to come

Although I haven’t posted anything for some time now, I haven’t abandoned automation or Katalon Studio. Quite the opposite. I’ve completed several Udemy courses for Groovy, Java, automation and SQL. Along with that, I’ve used this slower time of the year to review all my code and make improvements so that my tests are more resilient, more modular, more scalable and less “noisy.”

There have also been quite a few changes to Katalon Studio. There is the ability to import and export Custom Keywords, so moving more code to that section of the project seems ideal. The Execution Profiles are a bit easier to work with, so I’ve moved more data out of the tests themselves and set them up as Global Variables. Cucumber BDD is available as well, and while I’m not using it currently, I did take a Udemy course on it so it might be something I try to incorporate into my project in the future.

Of course, after running the tests hundreds of times, I’ve noted areas of improvement such as better handling for transient conditions like an item not being found. And with some new found experience, I see how a test that performs one task can be parameterize, turned into a method and perform the same task multiple times with different input.

I’m quite pleased with the improvements and will share some of my discoveries. To that end, I have created a rather unexciting Github repository where I have shared some code snippets. It’ll get better over time. At least I hope so.

You can access it at: https://github.com/DonPedroQA/qajamboree

Other articles of interest:

One ReplaceAll Statement to Rule Them All!

Well, sort of.

In reviewing my code to make it more efficient, I noticed I have several variations on the .replaceAll() statement. In some case I'm trying to remove the $ and , from a value. In others I'm trying to remove the newline and CRLF characters. For another the goal was to remove the ( and ) from a value. And yet another was for the \ in a date. On top of this, I called replace several times in a row in order to remove specific characters or a string.

While those work, there is a way to accomplish this in a single call and return just the number I'm really looking for.

For example, I have the value $5,573,127 and want just the integer value. That can be done with:

tempText=tempText.replaceAll("[^0-9]","").toInteger()

Everything that isn't a number will be removed and I'll have 5573127 as an Integer. This includes ()[]$,. and -.

If the value is -$5,573,127.35 and I need to keep the decimal or the negative, it's a simple change to add them at the end as values to keep.

tempText=tempText.replaceAll("[^0-9.-]","").toDouble()

Now, if there is additional text, such as "Showing 1 to 8 of 2,056 entries", that can be handled by passing the text string to remove to the .replaceAll(). We then use the pipe | delimiter to indicate there is more conversion we wish to make.

tempText="Showing 1 to 8 of 2,056 entries"
removeText="Showing 1 to 8 of"
tempText=tempText.replaceAll(removeText + "|[^0-9]","").toInteger()
or
tempText=tempText.replaceAll("1 to 8|[^0-9]","").toInteger()

We now have 2056 as the number of entries. We specifically need to remove the 1 to 8 text or else the 1 and 8 will be retained giving us 182056 as a result, which is incorrect.

This will save quite a few lines of codes and make the .replaceAll() much more consistent across my projects. It pretty much won't matter what I'm reading, it'll be easy to get back just the number with one command.

Other articles of interest:

Recent Comments

  • Create a Dynamic Object at Runtime (1)
    • Jeremy Brien: I appreciate this! I saw this post on LinkedIn this morning and was able to find a use case for it! I found that defining my xpath with an iterable variable allows me to loop through and capture text from tables created...
  • Output status messages and test information by writing to the Log File Viewer in Katalon Studio (2)
    • Don Pedro: That would be things like: log.logWarning(‘The import date listed on the site is: ‘ + importDate) log.logWarning(‘The value from the site is: ‘ + salesFigure) log.logWarning(‘Filter Results for ‘ +...
    • Prashant Pednekar: Thanks for the informative article but can we also put some variable values to make it more exciting.
  • Setting up a repeatable Search Method in Katalon Studio (1)
    • RJ: Thanks a lot! This is very helpful 🙂
  • Filling forms with random numbers in Katalon Studio (3)
    • Patrick Clough: We created a handy random string generator custom keyword. The method takes in a string for the type of string you want, and an integer for the length. Looks like this: static String RANDOM_ALPHANUM =...
    • Don Pedro: randomNumber is the variable that holds the result of generating a new random number. Depending on how things work on your site, you might need to convert the number to a String before it’s recognized correctly....
    • Seth: When you are setting up randomNumber is this a new keyword or a new variable? I am trying to randomly generate unique socials and can’t seem to connect my generator to my Set Text.
  • Working with Dates and Date Formatting in Katalon Studio (5)
    • Ann: THANK YOU ! That worked perfectly !
    • Don Pedro: import groovy.time.TimeCategory currentDate = new Date() println currentDate use( TimeCategory ) { after30Mins = currentDate + 30.minutes } println after30Mins https://stackoverflow.com/ques tions/21166927/incrementing...
    • ricky julianto nugroho: hay can u gave me an example for plus a hour in the time ? example : now is 15 pm i want to print 16 in the text thank you
  • Boostnote for Code Snippets (1)
    • Manual: Hi Don, Regarding the code snippets and examples that you have created. Is there any GitHub repo or something that can be shared? Thanks
  • Using TypeIt4Me with Katalon Studio (3)
    • Manual: That’s great thanks for sharing.
    • Don Pedro: Added a screenshot to show some examples of how I have shortcuts configured for Groovy code. TypeIt4Me supports groups, so you can create shortcuts related to Groovy, Selenium, and other topics to keep them organized. You can...
    • Manual: Hi Don, I like the idea of using the TypeIt4Me for scripting test code. Could you please share how I can create. I also like the idea of creating code templates to use with code editors. Thanks, Manual
  • Another success with Katalon Studio (2)
    • Don Pedro: Since Katalon is free, a very practical demonstration of what it can would be to create the code needed to fill in forms. That was one of my first tasks as Katalon could fill in a lengthy form in seconds versus the minute or...