org.openqa.selenium.NoSuchElementException even when the element is present - java

I've 4 test cases defined using TestNG within my Appium project and all 4 test cases performs almost same code execution besides the difference that all 4 test cases run on different parts of the app I'm automating. The issue I'm facing is within my test case I need to find an element and get its value which works fine in Test Case 1 but fails for Test Case 2, 3 and 4 respectively. However if I comment out Test Case 1, then the code works fine for Test Case 2 but fails for Test Case 3 and 4. If I run code for Test Case 1, 2, 3 or 4 individually, all of them work. I'm not able to understand why the code works only for the first test case in execution but fails to find the element in the next test case.
Note that the only option for me to find element is using absolute xpath value since the app I'm trying to automate does not have any other attribute defined.
Environment
java client 4.1.2
Appium server version: v1.7.2
Selenium: v3.4.0
Desktop OS/version used to run Appium if necessary: Windows 10 x64
Mobile platform/version under test: Fire TV Stick running on Android 5.1.1
Real device or emulator/simulator: Real device
Details
I've provided the code for Test1 below. As mentioned earlier, Test2, Test3 and Test4 are same as Test1. The code below is the one which fails from second Test onwards even though the code works fine when tested individually and the element is definitely present on the screen when the code is executed. However the script returns no element found.
Failing code
strTime1 = driver.findElementByXPath("/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout[1]/android.widget.FrameLayout/android.widget.FrameLayout[3]/android.widget.FrameLayout[3]/android.widget.FrameLayout[2]/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.TextView").getText();
Code To Reproduce Issue
#test //Test Case for Home tab
public void Test1_Home() throws InterruptedException, ParseException{
Thread.sleep(delay3); //Wait for 10 seconds to load the content
driver.findElementByXPath("//android.widget.FrameLayout[#content-desc="Home, Button"]").click(); //Code to click Home button
Thread.sleep(delay2); //Wait for 10 seconds to load the content
((AndroidDriver) driver).pressKeyCode(23); //Code to click first video thumbnail button
Thread.sleep(delay2); //Wait for 10 seconds to load the content
//Video pause verification code starts
((AndroidDriver) driver).pressKeyCode(23); //Pause the video
Thread.sleep(1000); //Wait for 1 seconds
strTime1 = driver.findElementByXPath("/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout[1]/android.widget.FrameLayout/android.widget.FrameLayout[3]/android.widget.FrameLayout[3]/android.widget.FrameLayout[2]/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.TextView").getText();
System.out.println(strTime1);
Thread.sleep(delay1); //Wait for 5 seconds
strTime2 = driver.findElementByXPath("/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout[1]/android.widget.FrameLayout/android.widget.FrameLayout[3]/android.widget.FrameLayout[3]/android.widget.FrameLayout[2]/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.TextView").getText();
System.out.println(strTime2);
time1 = time.parse(strTime1);
time2 = time.parse(strTime2);
System.out.println(time1);
System.out.println(time2);
if(String.valueOf(strTime1).equals(String.valueOf(strTime2)))
{
boolean result = true; //Set result to true
System.out.println("Home: Video playback pause successful");
Assert.assertTrue(result); //Passes the test case
}
else
{
boolean result = false; //Set result to false
System.out.println("Home: Video playback pause failed");
Assert.assertTrue(result); //Fails the test case
}
//Video pause verification code ends
Thread.sleep(delay2); //Allow the video to play for 10 seconds including buffering time
}
Exception stack traces
org.openqa.selenium.NoSuchElementException: An element could not be located on the page using the given search parameters. (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 10.13 seconds
Let me know if any further information is required. Any kind of help would be appreciated

could you please try to locate the element with relative xpath or accesability id?
Also it is always best practice to use latest versions of appium server and java client as they are continuously making changes to the appium.
below is the link for latest java client if you are using maven : https://mvnrepository.com/artifact/io.appium/java-client

Related

Getting "cannot activate web view"

I received an error. When I did a google search, I got some results but they were all for Android programming. I am automating a test using Windows, Java 1.8 and Selenium.
The error
org.openqa.selenium.WebDriverException: unknown error: cannot activate web view
My original code (that I did not write but am debugging and has worked):
// Clicks a link which opens a new window
action.moveToElement(el).click(el).build().perform();
Set<String> windows = driver.getWindowHandles();
for (String a: windows) {
Reporter.log(a);
driver.switchTo().window(a);
}
The error I got was that there was "no such window". So I thought maybe I needed to wait until the number of windows stabilized, so I added the following after clicking and before doing the windows stuff:
int winds = driver.getWindowHandles().size();
int owinds = winds - 1;
while (owinds != winds) {
Thread.sleep(1000);
owinds = winds;
winds = driver.getWindowHandles().size();
}
It is at this point, where it does the switch, that I get the
org.openqa.selenium.WebDriverException: unknown error: cannot activate web view
and as I mentioned before, everything in Google only talks about Android, which this is not.
Any thoughts would be welcome.
I had this problem in JavaScript using Webdriver.io. I'm answering since it had the same characteristics described here, specifically that I was opening a new tab and I'd get this error.
I first added more memory/resources to my docker container and then got an issue that was resolved by this answer: https://stackoverflow.com/a/52340526/491553.
Once I applied the following Chrome arguments, I didn't see this again:
"--no-sandbox",
"--disable-infobars", // https://stackoverflow.com/a/43840128/1689770
"--disable-dev-shm-usage", // https://stackoverflow.com/a/50725918/1689770
"--disable-browser-side-navigation", // https://stackoverflow.com/a/49123152/1689770
"--disable-gpu", // https://stackoverflow.com/questions/51959986/how-to-solve-selenium-chromedriver-timed-out-receiving-message-from-renderer-exc
"--disable-features=VizDisplayCompositor" // https://stackoverflow.com/a/55371396/491553

junit test skips after 600 seconds

I'm working on the system test of a IOT device that has various webservices.
We have 2 types, one with slow flash and the newer with faster flash memory. in the new flash the fw update can be done with aprox. 4 minutes while the slow ones take something around 12 minutes.
The problem comes in the junit test that tests the update and go back to the "previous" version. After sending the file and the update signal to the device, i use a Thread.sleep(6*60*1000) to wait for the device to expand the file, update and restart.
The junit test "skips" the test after 600s have passed, not failure, not error, just skips to the next test class..
It looks like it finished, but it just skipped the rest of the test WHILE it is inside the sleep
a small snippet of the test code althought it is mostly propietary:
public RequestCase(String path, WebServiceRequest req, WebServiceResponse resExp, String tcDesc, boolean validateResXSD) {
//super();
this.setPath(path);
this.setReq(req);
this.setResExp(resExp);
this.res = new WebServiceResponse();
this.setTcDesc(tcDesc);
this.setValidateResXSD(validateResXSD);
}
and the test snippet:
// now apply Software
String s06Req = null;
try {
s06Req = WebServiceRequestS06.makeCommandPsu(updFile.getRevision(), WebServiceRequestS06.SW_UPD);
} catch (WebServiceXMLException e) {
fail("Error creating S06 XML request. Error is: "+e.getMessage()+"\nAnd cause is :"+e.getCause());
}
RequestCase s06CommandPsu = new RequestCase(
null,
new WebServiceRequest("commandPsu", "POST", s06Req),
WebServiceResponse.RESULT_STATUS_CMD_SW_RECEIVED,
"Apply valid SW, and it is only received, but not apply now (imply Y03)",
true
);
executeCase(s06CommandPsu, WebServicesXSDValidator.S06_CommandPsu);
// Wait some time to wait charger apply new SW and reboot
try {
if (this.charger.getProductType() == Charger.ID_CT1_OLD_FLASH) {
Thread.sleep(6*60*1000);
} else {
Thread.sleep(2*60*1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
can someone help me a bit? Thanks in advance!
The test code snippet provided hre is not showing any assert/verify operation.
You have a test that sits there, waiting 600 seconds. Then it will end.
And the test will show up as passed (as it didn't cause a failure or error).
Thus:
If your tests should do something after 600 seconds, you have to code that.
Unrelated: you really should step back first. Unit tests should pass quickly, having it wait 600 seconds is not a good idea (assuming that we are talking real unit tests here, not an integration test)
Finally i found what was causing this, i will post it just in case someone stomps at the same problem.
it was caused due to the Parallelized class, more specifically in the ExecutorService awaitTermination() method where you can set a timeout..

Selenium WebDriver tests sometimes doesn't find elements

I am pretty new to all the Automated Testing thing and recently I have been having trouble with selenium because sometimes fails finding certain input fields / buttons.
I added explicit waits for every element in the page, so the test is supposed to wait for that element to appear on screen, but sometimes randomly fails to do so. I will attach the latest error thrown by selenium in a simple test.
This is one of the tests that I am trying to run and randomly fails:
#Test
public void createTaskTest(){
generateTestEnvironmentSalesForceHomePage();
this.home.clickTasksTab();
generateTestEnvironmentTaskPage();
this.taskspage.clickNewTask();
generateTestEnvironmentNewTask();
this.newtask.setDateField("12/30/2016");
this.newtask.setCostField("1500");
this.newtask.setType("Personal Appointment");
this.newtask.setPaymentType("End of the day");
this.newtask.setDoctor("House");
this.newtask.submitTask();
Assert.assertTrue(this.newtask.checkDetailsPage());
}
Error thrown by selenium:
org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.cssSelector: span.dateOnlyInput>input (tried for 130 second(s) with 500 MILLISECONDS interval)
Here is the method to find the 'missing' date input:
public void setDateField(String date){
WebDriverWait wait = new WebDriverWait(this.driver,130);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("span.dateOnlyInput>input")));
this.driver.findElement(By.cssSelector("span.dateOnlyInput>input")).sendKeys(date);
}

Take screenshot in selenium (java) only in after method

I have created a automation suite in java selenium using testng frame work.Basically in my suite the scenarios are placed in between before and after method.
I want to take the screen shot for each failed and passed test scenario.For that i have created a separate class and calling it in each script to capture the screenshot before the after Method.
The issue that i am facing here is if the scenario is getting failed the script stopped executing and it is not moving to the take screenshot line of code and so it is not capturing the screenshot for the failed ones.
So i want the take screenshot program to be only placed in after method so before the driver quit it will take the screenshot inspite of the scenario result of pass/fail.
I have written code for nearly 20 scenario using testng.
Can some one tel me the code in the after method only to take the screenshot without so much effecting the code which i have written.
The screenshot program should only be in the after method so it will capture teh screen before driver quit.
Make sure you catch exceptions so you won't exit the code prematurely.
For example, this is how I take screenshots after every test run (passed or failed). I use the exception value (if any) to dynamically name the screenshot files.
First, an example test method:
[DataSource("System.Data.SqlClient", "Data Source=DEV338\\X2B;Initial Catalog=SeleniumDb;Integrated Security=True",
"dbo.F_single_ErkenningAannemerKlasse1", DataAccessMethod.Sequential), TestMethod]
public void erkenningAannemerKlasse1()
{
try
{
frontUser.erkenningAannemerKlasse1(data);
}
catch (Exception e)
{
exception = e.Message + " " + e.StackTrace;
}
}
Then this method executes after every test. Default behaviour in Microsoft UnitTest framework, in this case.
[TestCleanup()]
public void Cleanup()
{
frontUser.takeScreenshot(data.get("testnaam"), data.get("datarow"), exception);
frontUser.closeBrowser();
}

Selenium webdriver tests pass indivdually but fail when run together

I have a java file which has 7 junit tests to run. If I run all the tests at once all but 1 passes. If I comment out certain tests and that one test always passes.
Can anybody offer any suggestions as to what could be causing this?
My first thought was something in the test Setup or cleanup but I am not sure what it could be. All I do in the clean up is exit the driver and output the time taken to run the test.
In the setup I set up the driver, the time started, create a firefox profile and read in some data from a properties file to use in the tests.
If it was the setup / cleanup surely the other 6 tests would also be effected? The test that fails is a simple test to check that entering an invalid card type displays an error message on the page.
UPDATE:
I've renamed the test so it runs first and now all 7 pass each time. What could be causing this? Do I need to set something in my test cleanup to get it back to a default state?
My test cleanup:
#After
public void testCleanup() throws IOException {
driver.quit();
endTime = System.currentTimeMillis();
long totalTime = ((endTime - startTime)/1000)/60;
System.out.println();
System.out.println("Test Suite Took: " + totalTime + " Minutes.");
}

Categories