How to check if all element are displayed on web page? - java

I have to check if all web elements are presented at web page. If not presented write to log which exactly element is missed.
To write easy test for is not so difficult:
public boolean allUIElementsExist() {
boolean allPresent = true;
if (!this.tipFrequency.isDisplayed()) {
allPresent = false;
Logger.logFail("no tip `should be the same as how often you get paid`");
}
if (!this.tipAmount.isDisplayed()) {
allPresent = false;
Logger.logFail("no tip 'Borrow equal to the amount of your purchase'");
}
if (!this.payBack.isDisplayed()) {
allPresent = false;
Logger.logFail("no 'Pay it back in'");
}
if (!this.useTool.isDisplayed()) {
allPresent = false;
Logger.logFail("no 'Use our easy finance tool to quickly explore payment options'");
}
if (!this.biWeekly.isDisplayed()) {
allPresent = false;
Logger.logFail("no 'biWeekly'");
}
if (!this.semiMonthly.isDisplayed()) {
allPresent = false;
Logger.logFail("no 'semi-monthly (twice a month)'");
}
if (!this.month.isDisplayed()) {
allPresent = false;
Logger.logFail("no 'monthly'");
}
if (!this.withPayments.isDisplayed()) {
allPresent = false;
Logger.logFail("no 'With payments of:'");
}
if (!this.includingLPP.isDisplayed()) {
allPresent = false;
Logger.logFail("no 'including LPP'");
}
if (!this.startNewApplication.isDisplayed()) {
allPresent = false;
Logger.logFail("no 'Start new application'");
}
if (!this.easyfinancialLink.visibilityOfElementWait()) {
allPresent = false;
Logger.logFail("no 'easyfinancialLink'");
}
return allPresent;
}
It works. But to go through all if statements doesn't look the best solution.
How to recreate this code to much better approach?

Make the elements a list, iterate through them, and evaluate each one the same way.
Find a way to use webelement methods to add information about the element into the log message, instead of writing each one by hand. This way, you don't have to write a lot of log messages & they always have the right information about the element (less room for writing errors).
Example: For each element in a list of WebElements named ElementsList, check if element is displayed. If not, write a log fail message with the name of the tag and the text it contained. (If the element has no text, it will just not add any text to the string.)
for(WebElement element : ElementsList) {
if (!this.element.isDisplayed()) {
allPresent = false;
Logger.logFail("WebElement not displayed: " + element.getTagName() + " Text: " + element.getText());
}

Related

Selenium Java compare not true?

i'm trying to compare some texts with this code bellow:
driver.get("https://www.hotel.de/");
boolean status = false;
String searchText = "Hannover, Niedersachsen";
WebElement inputBox = driver.findElement(By.xpath("//div[#class='LocationAutoSuggest__container--2Hli_']//input"));
Now i send String "Hannover" to Searchbox:
Actions actions = new Actions(driver);
actions.moveToElement(inputBox).click().sendKeys("Hannover").build().perform();
Thread.sleep(3000);
List<WebElement> listsearch = driver.findElements(By.id("react-autowhatever-1"));
And compare the found text with searchText :
for(WebElement listElem : listsearch) {
System.out.println(listElem.getText());
System.out.println(searchText.equals(listElem.getText()));
if(searchText.equals(listElem.getText())) {
System.out.println("hooho");
status = true;
break;
} else {
status = false;
}
}
System.out.println(status);
==> Could you tell me: why i become FALSE instead of TRUE? (How can i see the logs, to know what was actually compared?). Many thanks.
Check the size of your List if it zero than directly false will be printed.
If size is not greater than zero check your locator.

How to improve resursive function performance?

I created a recursive function. The goal of this function is to browse all frames til to find the element. But it is very slow.
Please find below the function:
private WebElement browseFramesToFindElement(By locator) {
WebElement element = null;
if (isElementPresent(locator, 1))
element = this.driver.findElement(locator);
if (element == null) {
List<WebElement> frames = this.driver.findElements(By.xpath("//frame"));
int i = 0;
while (i < frames.size() && element == null) {
this.driver.switchTo().frame(this.driver.findElement(By.xpath("//frame[#id = '" + frames.get(i).getAttribute("id") + "']")));
element = browseFramesToFindElement(locator);
if (element == null)
driver.switchTo().parentFrame();
i++;
}
}
return element;
}
private boolean isElementPresent(By by, int secToWait) {
this.driver.manage().timeouts().implicitlyWait(secToWait, TimeUnit.SECONDS);
try {
this.driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
Could you please tell me if it is possible to improve performance? And How? Thank you in advance.
I am not sure your performance issues are related with that you have ineffective recursion algorithm. I would suggest you to:
Change xpath locators to css locators (likely will help)
Tune wait timeouts and watch for the result (not sure but that might give a direction)

Appium is able to see beyond what is displayed on screen

Appium is able to see and find elements that is not displayed on screen
I am trying to build a test automation project, I would like my driver to scroll down
and then perform some operation. but for some reason appium is able to find element even without scrolling down . I am not sure how appium is able to identify element that is not on screen and is only visible to naked eye when you scroll down. Anyone with similar issue found a workaround ?
I am using ExpectedCondition.visibilityOF(element) to determine if element is vsible on screen
public boolean verifyCoverage(String coverage, String value, String type) throws IOException, InterruptedException {
int counter = 0;
for (int i = 0; i < 15; i++) {
AndroidElement element = (AndroidElement) driver.findElementByAndroidUIAutomator("UiSelector().textContains(\"" + coverage + "\")");
//WebElement coverageOption= driver.findElementByXPath("//android.widget.Button[contains(text(),'"+coverage+"')]");
if (AndroidUtilities.waitForVisibility(driver, element)) {
return true;
}
else {
System.out.println ("Cannot see");
return false;
}
}
public static boolean waitForVisibility(AndroidDriver<WebElement> driver, AndroidElement AndroidElement){
try{
// driver.findElementByAndroidUIAutomator("UiSelector().resourceId(\""+targetResourceId+"\")");
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.visibilityOf(AndroidElement));
boolean isElementPresent = AndroidElement.isDisplayed();
return isElementPresent;
}catch(Exception e){
boolean isElementPresent = false;
System.out.println(e.getMessage());
return isElementPresent;
}
}
As an answer i would recommend you to use visibilityOfElementLocated instean of visibilityOf.
Plus, if you want to check an element for the existence without getting exceptions, try to take that approach:
if (!((AndroidDriver)driver).findElementsByAndroidUIAutomator("UiSelector().textContains(\"" + coverage + "\")").isEmpty()) {
//some logic when element is located
} else {
//scroll to the particular element
}
You can try these two solution within the page it will able to scroll to the element and do your actions .
MobileBy.AndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().textContains(\""+element+"\").instance(0))"));
MobileBy.AndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().textMatches(\"" + NumbersCount + "\").instance(0))"));

Using Iterator with Java Selenium WebDriver

Using Selenium to gather text of all p elements within a specific div. I noticed while using List, Selenium scanned the whole DOM and stored empty text. So, I wanted to iterate through the DOM and only store values that are not equal to empty text via java.util.Iterator. Is this possible? Is there a more efficient way other than the List approach?
Iterator Approach:
public static boolean FeatureFunctionsCheck(String Feature){
try
{
Iterator<WebElement> all = (Iterator<WebElement>) Driver.Instance.findElement(By.xpath("//a[contains(text()," + Feature + ")]/ancestor::h3/following-sibling::div/div[#class='navMenu']/p"));
boolean check = false;
while(all.hasNext() && check){
WebElement temp = all.next();
if(!temp.getText().equals(""))
{
Log.Info("Functions: " + temp.getText());
all = (Iterator<WebElement>) Driver.Instance.findElement(By.xpath("//a[contains(text()," + Feature + ")]/ancestor::h3/following-sibling::div/div[#class='navMenu']/p"));
}
else
check = true;
}
return false;
}
catch(Exception e)
{
Log.Error("Failed()" + e);
return false;
}
}
Iterator Approach throws exception...
java.lang.ClassCastException: org.openqa.selenium.remote.RemoteWebElement cannot be cast to java.util.Iterator
List Approach Works, However Not Sure If This Is Efficient
public static boolean FeatureFunctionsCheck(String Feature){
try
{
List<WebElement> AllModelFunctions = new ArrayList<WebElement>();
Log.Info("[Test-235]: Selecting Feature");
for(WebElement element: AllModelFunctions){
if(!element.getText().equals(""))
{
Log.Info("Functions: " + element.getText());
}
}
return false;
}
catch(Exception e)
{
Log.Error("Failed()" + e);
return false;
}
}
findElement returns one WebElement. What you probably meant to do is to search for all elements with given xpath, using findElements:
Driver.Instance.findElements(...
Also the syntax is over-complicated. You can just get the list and iterate through it:
List<WebElement> elements = Driver.Instance.findElements(...);
for(WebElement element : elements) {
if(!element.getText().equals(""))
{
Log.Info("Functions: " + element.getText());
}
}
BTW I have to fully trust that Driver.Instance is an instance of the driver (typically in Java you don't have capitals for class instances, so I'm not sure if I understood it right). A more common syntax would be something like:
WebDriver driver = new FirefoxDriver(); // or another browser
driver.findElements(...);
// ...

can't delete from getContentResolver().delete

I can't delete a conversation from getContentResolver, I don't know in which part am doing mistakes, as I also searched about these but can't help myself and I also tried different sols which were given on stackoverflow but same result & thanks a lot in advance.
Here is the code:
public static boolean deleteSmsofContact(Context context, String number,
boolean deleteLocked)
{
int result;
if (deleteLocked) {
//changes values
String[] selectionArgs=new String[]{number};
String selection= ""+"address=?";
//
result = context.getContentResolver().delete(Uri.parse("content://sms/"),selection,selectionArgs);
// Log.d("UF","WOW "+result+" " +number);
} else {
result = context.getContentResolver().delete(Constants.URI_SMS,
"address=? AND locked=?", new String[] { number, "1" });
}
if (result > 0) {
return true;
}
return false;
}
Here is the method from which I am calling:
boolean result = Utils.deleteSmsofContact(InboxActivity.this, sms.getNumber(), true);
if (result) {
dataList.remove(threadPosition);
iAdapter.notifyDataSetChanged();
Toast.makeText(InboxActivity.this,"Removed",Toast.LENGTH_LONG).show();
}else
{
Toast.makeText(InboxActivity.this,"cant removed",Toast.LENGTH_LONG).show();
}
Well I posted it but did not get the answer so finally I searched a lot on this and the correct answer is until or unless your app is not set a default you can't delete any sms or whole conversation.
Follow this link it will make your app set a default OR you will be able to delete.

Categories

Resources