What is the best way to verify values in two lists?

Hi All,

I have been trying to find different ways to verify the values, text in an application. I came up with the belong method that I use frequently to verify whatever I want. I want to know if there is a better way in verify values using two lists.

Code:
Basically I am passing two lists as arguments and verifying if the lists are same. Sometimes using contains if all the values should contain a single text

@Keyword
	def static verifyValuesAreMatchingWithExpected(eleText,textValues,xpath) {
		try {
			KeywordUtil.markPassed(assertEquals(eleText, textValues))
		}catch(AssertionError e) {
			try {
				for(vl in textValues) {
					KeywordUtil.markPassed(assertTrue(eleText.contains(vl)))
				}
			}catch(AssertionError x) {
				TestObject to = new TestObject("objectName")
				to.addProperty("xpath", ConditionType.EQUALS, xpath)
				def text=WebUI.getText(to)
				try {
					KeywordUtil.markPassed(assertTrue(text.contains(textValues)))
				}
				catch(Exception y) {
					for(vl in textValues) {
						KeywordUtil.markPassed(assertTrue(text.contains(vl)))
					}
				}
			}
		}
	}

@kazurayam @Katalon_team @Brandon_Hein @Marek_Melocik @Russ_Thomas

Please I need your help guys with suggestions to improve my code

@samuel.dasari I edited your post to display the code correctly. Edit it yourself to see what I did.

Basically, I can’t even get started to answer your question, since I wouldn’t even use that code as a starting point. You’re mixing up “testing” APIs and comparitors. Sorry. Untangling that is a long job.

Pointer: What you seem to want to do is compare two lists, which is subtly different. But that’s just a guess. Try googling and look for Groovy answers. Then use that and apply your testing code to the results.

1 Like

@Russ_Thomas I have searched in google I found so many, using those only I customized my method as above. Let me know if you can suggest an easy and more effective way of doing that.

Contains is misleading when comparing two lists.
Define your use case.
List A can have elements from list B but not all of them, and opposite.
If you need to compare if the lists are ‘identical’ … well, you may like to sort them first and make sure they have same type for elements.

As long as you don’t provide more details on your actual use cases, Google is you best friend, learn how to ask him specific questions if your time is to precious to provide such into the topics you bring to the community.

@bionel Thanks for your concern, I have already searched google and filtered many methods but there are various scenarios where I am using different method to capture text of elements by using xpath and some by using getText() method in Katalon.

The scenario where I am trying to use contains is we have pagination content where I need to verify if the text in the pagination result is showing me some particular text and I need to verify only some part of the text for example:

Actual: Showing 1 - 50 of 184 Results
Expecting to verify only “Showing”, ‘of’, “Resutls” text is available in the Acutal text

Below is the method I am using to get the text as List by just passing the xpath as String of the particular element and then I am using this list as argument to the one that I have described above.

This was the best I could make from doing a lot of research from googling. I am just asking the experts in the community to put forward with more simple ways to assert…

Thanks


	@Keyword
	def static getElementsTextUsingXpath(xpath) {
		WebUI.delay(3)
		WebDriver driver = DriverFactory.getWebDriver()
		try {
			List<WebElement> fieldElements = driver.findElements(By.xpath(xpath))
			def eleText= fieldElements.collect { it.getText() as String}.toList()
			eleText.removeAll([null, '', ' ', '  '] as Object[])
			println(eleText)
			return eleText
		}catch(Exception e) {
			List<WebElement> fieldElements = driver.findElements(By.cssSelector(xpath))
			def eleText= fieldElements.collect { it.getText() as String}.toList()
			eleText.removeAll([null, '', ' ', '  '] as Object[])
			println(eleText)
			return eleText
		}
	}```

Please show the HTML source which presents the string “Showing 1 - 50 of 184 Results”.

@samuel.dasari

Your keyword implementation does not work with the HTML element
<span> Showing 1 - 50 of 189 Results </span>
at all.


Your code doesn’t make sense to me. I would not talk about it.

Rather I would show you a sample Test Case script that works. It is entirely different from your keyword implementation.

I made an HTML file named page.html and saved it immediately under the project directory:

<html>
  <body>
    <h1>MATTER SEARCH RESULTS</h1>
    <div id="Matter_search_window_list_view">
      <div class="panel-actions">
        <span> Showing 1- 50 of 189 Results </span>
      </div>
    </div>
  </body>
</html>

My sample Test Case is:

import java.nio.file.Path
import java.nio.file.Paths

import com.kms.katalon.core.configuration.RunConfiguration
import com.kms.katalon.core.testobject.ConditionType
import com.kms.katalon.core.testobject.TestObject
import com.kms.katalon.core.util.KeywordUtil
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI

Path projectDir = Paths.get(RunConfiguration.getProjectDir())
String htmlPath = projectDir.resolve("page.html").toFile().toURI().toURL().toExternalForm()
WebUI.openBrowser("")
WebUI.navigateToUrl(htmlPath)
TestObject tObj = makeTestObject("//div[@id='Matter_search_window_list_view']/div[@class='panel-actions']/span")
WebUI.verifyElementPresent(tObj, 10)
String text = WebUI.getText(tObj)
println "text=" + text

// List<String> parts = ["Showing", "of", "Results"]
List<String> parts = ["Showing", "of", "Fakes"]      // intentional failure

boolean result = assertTextContains(text, parts)
if (!result) {
	KeywordUtil.markFailed("text '${text}' does not contain one or more parts of ${parts}")
}

WebUI.closeBrowser()

TestObject makeTestObject(String xpath) {
	TestObject tObj = new TestObject(xpath)
	tObj.addProperty("xpath", ConditionType.EQUALS, xpath)
	return tObj
}

boolean assertTextContains(String text, List<String> parts) {
	for (part in parts) {
		if (!text.contains(part)) {
			println "'${part}' is not contained in the text '${text}'"
			return false
		}
	}
	return true
}

When I ran this, it showed messages in the console:

2022-08-24 22:35:58.964 INFO  c.k.katalon.core.main.TestCaseExecutor   - --------------------
2022-08-24 22:35:58.969 INFO  c.k.katalon.core.main.TestCaseExecutor   - START Test Cases/TC1
2022-08-24 22:36:00.104 INFO  c.k.k.core.webui.driver.DriverFactory    - Starting 'Chrome' driver
8 24, 2022 10:36:00 午後 org.openqa.selenium.remote.DesiredCapabilities chrome
情報: Using `new ChromeOptions()` is preferred to `DesiredCapabilities.chrome()`
2022-08-24 22:36:00.181 INFO  c.k.k.core.webui.driver.DriverFactory    - Action delay is set to 0 milliseconds
Starting ChromeDriver 104.0.5112.79 (3cf3e8c8a07d104b9e1260c910efb8f383285dc5-refs/branch-heads/5112@{#1307}) on port 14266
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
8 24, 2022 10:36:03 午後 org.openqa.selenium.remote.ProtocolHandshake createSession
情報: Detected dialect: W3C
2022-08-24 22:36:03.716 INFO  c.k.k.core.webui.driver.DriverFactory    - sessionId = 394d61d2200f201451f1923dea8be794
2022-08-24 22:36:03.756 INFO  c.k.k.core.webui.driver.DriverFactory    - browser = Chrome 104.0.5112.101
2022-08-24 22:36:03.786 INFO  c.k.k.core.webui.driver.DriverFactory    - platform = Mac OS X
2022-08-24 22:36:03.808 INFO  c.k.k.core.webui.driver.DriverFactory    - seleniumVersion = 3.141.59
2022-08-24 22:36:03.829 INFO  c.k.k.core.webui.driver.DriverFactory    - proxyInformation = ProxyInformation { proxyOption=NO_PROXY, proxyServerType=HTTP, username=, password=********, proxyServerAddress=, proxyServerPort=0, executionList="", isApplyToDesiredCapabilities=true }
text=Showing 1- 50 of 189 Results
'Fakes' is not contained in the text 'Showing 1- 50 of 189 Results'
2022-08-24 22:36:05.115 ERROR com.kms.katalon.core.util.KeywordUtil    - ❌ text 'Showing 1- 50 of 189 Results' does not contain one or more parts of [Showing, of, Fakes]
2022-08-24 22:36:05.300 ERROR c.k.katalon.core.main.TestCaseExecutor   - ❌ Test Cases/TC1 FAILED.
Reason:
com.kms.katalon.core.exception.StepFailedException: text 'Showing 1- 50 of 189 Results' does not contain one or more parts of [Showing, of, Fakes]
	at com.kms.katalon.core.util.KeywordUtil.markFailed(KeywordUtil.java:19)
	at TC1.run(TC1:24)
	at com.kms.katalon.core.main.ScriptEngine.run(ScriptEngine.java:194)
	at com.kms.katalon.core.main.ScriptEngine.runScriptAsRawText(ScriptEngine.java:119)
	at com.kms.katalon.core.main.TestCaseExecutor.runScript(TestCaseExecutor.java:445)
	at com.kms.katalon.core.main.TestCaseExecutor.doExecute(TestCaseExecutor.java:436)
	at com.kms.katalon.core.main.TestCaseExecutor.processExecutionPhase(TestCaseExecutor.java:415)
	at com.kms.katalon.core.main.TestCaseExecutor.accessMainPhase(TestCaseExecutor.java:407)
	at com.kms.katalon.core.main.TestCaseExecutor.execute(TestCaseExecutor.java:284)
	at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:142)
	at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:133)
	at com.kms.katalon.core.main.TestCaseMain$runTestCase$0.call(Unknown Source)
	at TempTestCase1661348155534.run(TempTestCase1661348155534.groovy:25)

2022-08-24 22:36:05.326 INFO  c.k.katalon.core.main.TestCaseExecutor   - END Test Cases/TC1

1 Like