I have created WebDriver tests which run for the same duration.
Some of the tests lest say ‘PopupX’ will appear at 30 seconds.
On some of the test ‘PopupX’ will appear at 60 Seconds
On some of the test ‘PopupX’ will appear at 35 Seconds
You understand the id.
The popup always has a unique Id being the ‘X’ to close the application and even different popups have the same ‘X’ close option.
Does anyone know of a way to constantly search and close ‘A form of continuous polling’ which will close the popup if it was to appear at anytime in any of the test cases?
I know the following method listed below works and can successfully close the popup:
public void closeGiveawayPopup() throws InterruptedException {
WebDriverWait wait = new WebDriverWait(driver, 10);
try {
List<WebElement> elements = wait
.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.cssSelector(".close")));
for (WebElement element : elements) {
if (element.isDisplayed()) {
element.click();
Thread.sleep(1000);
wait.until(ExpectedConditions.invisibilityOfAllElements(elements));
Thread.sleep(2000);
}
}
} catch (Exception e) {
throw (e);
}
I have tried to add the following method below in the TestNG 'BeforeMethod' annotation but the url dosnt even load:
public void closeGiveawayPopup() throws Exception {
try {
List<WebElement> elements = getDriver().findElements(By.cssSelector(".close"));
for (WebElement element : elements) {
if (element.isDisplayed()) {
element.click();
}
}
} catch (Exception e) {
throw (e);
}
}
Details of the popup have been listed below:
I don't think you are doing anything wrong Phil. #BeforeMethod annotation is the way to go. The only thing that needs improving is to include (if you don't have it already) a #BeforeClass annotation for your browser startup/shutdown respectively. Perhaps, this is why 'the browser does not even open' as you mention in your description above. So something like this:
#BeforeClass
public void initialSetup(String browser){
Webdriver driver = new browser ();
driver.get("https://www.buyagift.co.uk/");
}
#BeforeMethod
public void closeGiveAwayPopup(){
//same as your code
}
#Test(priority=1)
public void makeSureIarrivedOnTheHomePage(){
titleGrabbed = driver.getTitle().toString();
titleExpected = "Experience Days and Gifts from Buyagift";
Assert.assertEquals(titleGrabbed ,titleExpected )
}
#Test(priority=2)
public void clickLoginButton(){
//more actions
}
#AfterClass
public void shutDown(){
driver.quit();
}
The only way I can think of in order to have this 'continuous polling' effect that you are after is to make your #Test really really small (1 step at a time). This way hopefully you can achieve the desired effect. So don't bundle a lot of WebDriver actions under 1 #Test as you are increasing the risk of a pop-up appearing in the meantime.
The only thing that puzzles me is your comment 'the url does not even load'. Are you sure you are grabbing the actual pop-up and not closing the whole window?
If that is the case, or if the above does not work for you, try using Xpath instead of CSS. From your screenshot you need to expand both div[#id='competition_inner_ and outer details'] and find the close button somewhere (probably you are looking for an < input >, < i > or < button > tag, then I will be able to help you more and give you the full Xpath so you can try for yourself.
So something like this:
driver.findElement(By.xpath("//div[#id='competiton_giveaway_popup']//button[#id='close']"));
PS. Another thing that came to mind, double check that you are using actual Testng annotations instead of Junit as it is easy to get confused and misclick sometimes when importing from IDE (I'm looking at you Eclipse!). So you can delete the #BeforeMethod annotation and write it again making sure it points to Testng.
PS2. On your step#9 you have missed the
WebDriverWait wait = new WebDriverWait(driver, 10);
line. I hope this is not the one giving you trouble, please double check and let me know.
Best of luck!
Related
I am automating in Java Selenium, without using Page Factory.
I have an Add Candidate Button element that is clicked in two tests. One is straightforward, after entering InviteToCompany page I click this button and proceed. However, another requires me to go past InviteToCompany page, but then use Go Back Arrow to go back to 'InviteToCompany' page and click Add Candidate Button again. This is when StaleElementReferenceException appears.
I have written such a piece of code to deal with this issue, however I am wondering, if there is a cleaner and neater way, than catching exception for second test, to proceed.
public InviteToCompanyPO clickAddCandidateBtn() {
try {
getClickableElement(addCandidateBtn).click();
} catch (StaleElementReferenceException e) {
log.warn("StaleElementReferenceException caught, retrying...", e);
getClickableElement(addCandidateBtn).click();
}
return new InviteToCompanyPO(driver);
}
Before I had to write second test (the one causing staleness), this method simply looked like this:
public InviteToCompanyPO clickAddCandidateBtn() {
getClickableElement(addCandidateBtn).click();
return new InviteToCompanyPO(driver);
}
I tried writing something like this:
public InviteToCompanyPO clickAddCandidateBtn() {
wait
.ignoring(StaleElementReferenceException.class)
.until(ExpectedConditions.elementToBeClickable(addCandidateBtn))
.click();
return new InviteToCompanyPO(driver);
}
but it doesn't work.
I guess you are using a page factory?
Anyway, when you back to the InviteToCompany page and need to click Add Candidate Button again you will need to get that element again.
I mean to pass the locator or By of that element and get the WebElement object again with driver.findElement() method.
This causes by the fact that WebElement is actually a reference (pointer) to the actual Web Element on the page. And when you navigating from the page to other page the references to the objects on the previous page becoming invalid, Stale. When you open the previous page again it is rendered again, so you need to get the references (pointers) to elements on that page again.
Cleaner way You can use a Webdriver wait Like this to click
public void refreshedClick(By by){
new WebDriverWait(driver, timeout)
.ignoring(StaleElementReferenceException.class)
.until(new Predicate<WebDriver>() {
#Override
public boolean apply(#Nullable WebDriver driver) {
driver.findElement(by).click();
return true;
}
});
}
Java 8
public void refreshedClick(By by){
new WebDriverWait(driver, timeout)
.ignoring(StaleElementReferenceException.class)
.until((WebDriver d) -> {
d.findElement(by).click();
return true;
});
}
I am trying to build a bot with selenium. the problem is that from time to time the website logging me out without any notice. I know how to detect it, and I know the way to handle it. the problem is that it is not reasonable to check before every line if the server logged me out. this is what I can do:
ChromeDriver driver = new ChromeDriver();
driver.get(url);
Connect(driver, loginData);
if(isConnected(driver) == false)
reconnect(driver, loginData);
driver.findElement(By.id("element-id")).click();
if(isConnected(driver) == false)
reconnect(driver, loginData);
...
But checking if I need to reconnect every line is not a good solution.
I thought about making a thread that checks all the time if I disconnected but I don't know how to pause the main thread until I reconnect to the server when I find out I disconnected
You can have a solution similar to your own, but instead of creating your own wrapper to ChromeDriver, you can use EventFiringWebDriver for that.
you can run the check inside a while loop in a side thread, and if the server disconnects you, stop the main thread. after you reconnect, restart it again.
The website logging you out seems to be time out. As I guess, you are testing in a non-production environment, please look for how to set the time_out = 0 (no-expire).
Thread solutions would be too clumsy and a single non synchronous miss can produce undetectable erroneous results.
I solved it by wrapping ChromeDriver with a class of my own that checks before every operation if a disconnect has detected. if anyone has a better solution I would like to hear. This is my solution:
public java.util.List<WebElement> findElements(By by) throws disconnectException {
if(keepLogin) {
if(checkConnectionOver()) {
throw new disconnectException();
}
}
return driver.findElements(by);
}
public WebElement findElement(By by) throws disconnectException {
if(keepLogin) {
if(checkConnectionOver()) {
throw new disconnectException();
}
}
return driver.findElement(by);
}
public Object executeScript(String script, Object... args) throws disconnectException {
if(keepLogin) {
if(checkConnectionOver()) {
throw new disconnectException();
}
}
return driver.executeScript(script, args);
}
public void get(String url) {
driver.get(url);
}
public String getCurrentUrl() {
return driver.getCurrentUrl();
}
I'm working on a BDD project.
Sometimes the tests go too fast for the developers to see what is happening when they run them.
At the moment I'm solving it placing something like
Thread.sleep(humanWaitTime)
before each method but it defeats the purpose of writing efficient code.
Is there any way to set this globally so that it can easily be taken out when doing a regression test and not clutter my code?
Thank you!
You can use WebDriverEventListener and fake wait for not existing element,
you should:
create class: public class CustomDriverListener implements
WebDriverEventListener and implement all methods
in this class add next method:
private void fakeWaiter(WebDriver driver) {
WebDriverWait wait = new WebDriverWait(driver, 20);
try {
wait.until(listenerDriver -> listenerDriver.findElement(By.xpath("//[.='it'sFakeElement']")));
} catch (org.openqa.selenium.TimeoutException e) {
//ignore it
}
}
add invocation of this method to methods that you need, like:
#Override
public void afterFindBy(By by, WebElement element, WebDriver driver) {
fakeWaiter(driver);
}
#Override
public void afterClickOn(WebElement element, WebDriver driver) {
fakeWaiter(driver);
}
#Override
public void afterChangeValueOf(WebElement element, WebDriver driver, CharSequence[] keysToSend) {
fakeWaiter(driver);
}
#Override
public void afterScript(String script, WebDriver driver) {
fakeWaiter(driver);
}
Create EventFiringWebDriver object and register your
CustomDriverListener:
WebDriver webDriver = new ChromeDriver();
EventFiringWebDriver driver = new EventFiringWebDriver(webDriver);
driver.register(new CustomDriverListener());
Now if you use "driver" in your tests all operations will be slower(depend on timer in fakeWaiter method)
P.S. sorry for bad formatting =(
You can probably use Implicit wait,
driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);
Lets say on top of your code block, you write:-
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
Then, before each line of your code, the webdriver instance will wait for 15 seconds, you don't have to give wait times after each statement.
The implicit wait will tell to the web driver to wait for certain amount of time before it throws a "No Such Element Exception". The default setting is 0. Once we set the time, web driver will wait for that time before throwing an exception.
I got an error org.openqa.selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with. How can i solve it?
It could mean that your element visibility is set to hidden. Or it could also mean that the element is not currently in view and have to be scrolled into view.
If it's not visible while the WebDriver is looking to interact with the drop down then:
1st-) You should increase the implicit wait time, until any controller appears in the UI:
public Accesor(WebDriver driver,String url){
this.driver = driver;
this.driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get(url);
}
2nd-)Try waiting until that specific element appears (but i wouldnt recommend that):
WebElement cBoxOverlay = wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.id("cboxOverlay"))));
3rd-) If it's a real bug of the application and the UI does not show the dropdown you are looking for that is suppose to be there then try handling those kind of exceptions by taking a screenshot of the screen and trying with the next testcase or testsuite:
public void takePicture(){
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
try {
FileUtils.copyFile(scrFile, new File("c:\\tmp\\"+ getClass().getName().substring("com.automation.testsuite.".lastIndexOf(".")+1) + ""+new Date().toString().substring(0,10) +".png"));
} catch (IOException e) {
e.printStackTrace();
}
I have a page crawler developed in Java using Selenium libraries. The crawler goes through a website that launches through Javascript 3 applications which are displayed as HTML in popup windows.
The crawler has no issues when launching 2 of the applications, but on the 3rd one the crawler freezes forever.
The code I'm using is similar to
public void applicationSelect() {
...
//obtain url by parsing tag href attributed
...
this.driver = new HtmlUnitDriver(BrowserVersion.INTERNET_EXPLORER_8);
this.driver.seJavascriptEnabled(true);
this.driver.get(url); //the code does not execute after this point for the 3rd app
...
}
I have also tried clicking on the web element through the following code
public void applicationSelect() {
...
WebElement element = this.driver.findElementByLinkText("linkText");
element.click(); //the code does not execute after this point for the 3rd app
...
}
Clicking on it produces exactly the same result. For the above code, I've made sure I am getting the right element.
Can anyone tell me what could be the problem I'm having?
On the application side, I cannot disclose any information about the html code. I know this makes things harder for trying to solve the problem and for that I apologize in advance.
=== Update 2013-04-10 ===
So, I added the sources to my crawlers and saw where in this.driver.get(url) it was getting stuck on.
Basically, the driver gets lost in an infinite refresh loop. Within a WebClient object instantiated by HtmlUnitDriver, an HtmlPage is loaded which continually refreshes seemingly without end.
Here is the code from WaitingRefreshHandler, which is contained in com.gargoylesoftware.htmlunit:
public void handleRefresh(final Page page, final URL url, final int requestedWait) throws IOException {
int seconds = requestedWait;
if (seconds > maxwait_ && maxwait_ > 0) {
seconds = maxwait_;
}
try {
Thread.sleep(seconds * 1000);
}
catch (final InterruptedException e) {
/* This can happen when the refresh is happening from a navigation that started
* from a setTimeout or setInterval. The navigation will cause all threads to get
* interrupted, including the current thread in this case. It should be safe to
* ignore it since this is the thread now doing the navigation. Eventually we should
* refactor to force all navigation to happen back on the main thread.
*/
if (LOG.isDebugEnabled()) {
LOG.debug("Waiting thread was interrupted. Ignoring interruption to continue navigation.");
}
}
final WebWindow window = page.getEnclosingWindow();
if (window == null) {
return;
}
final WebClient client = window.getWebClient();
client.getPage(window, new WebRequest(url));
}
The instruction "client.getPage(window, new WebRequest(url))" calls WebClient once again to reload the page, only to once more call this very same refresh method. This seems to go on indefinetly, not filling up the memory quickly only because of the "Thread.sleep(seconds * 1000)", which forces a 3m wait before trying again.
Does anyone have any suggestion on how I can work around this issue? I got a suggestion to create 2 new HtmlUnitDriver and WebClient classes which extend the original ones. Then override the relevant methods in order to avoid this problem.
Thanks again.
I solved my eternal refresh problem by creating a do nothing RefreshHandler class:
public class RefreshHandler implements com.gargoylesoftware.htmlunit.RefreshHandler {
public RefreshHandler() { }
public void handleRefresh(final Page page, final URL url, final int secods) { }
}
In addition, I extended the HtmlUnitDriver class and by overriding the method modifyWebClient, I set the new RefreshHandler:
public class HtmlUnitDriverExt extends HtmlUnitDriver {
public HtmlUnitDriverExt(BrowserVersion version) {
super(version);
}
#Override
protected WebClient modifyWebClient(WebClient client) {
client.setRefreshHandler(new RefreshHandler());
return client;
}
}
The method modifyWebClient is a do nothing method created in HtmlUnitDriver exactly for this purpose.
Cheers.