Webdriver/Selenium Alert window issue - selenium

My company wants me to develop a "Visual" GUI style BDD function using JBehave and Selenium, which uses javascript alert/confirm popup window to prompt user what is the exact step the running test reaches, eg:
Given I goto "www.google.com"
When I login
So we want to add Javascript alert window to popup during the automation test, the popped up window has the "OK" button, so when user click the OK button, the test will continue to the next step, and so on...
My issue is: I wrote a javascript func using Selenium's executeScript API which invoke the pop up alert window:
public void stepText(String step) {
executeScript("alert('"+step+"');");
}
So I expect when I click the OK button, the popped up window will disappear and test will continue to next step... But what shocked me is that when I click it, the test throw exception and crashed...
The exception is: selenium.WebDriverException
But I found if I add the following code to make the test automatically detect the alert window and accept it by using the following usual selenium alert handle function:
Alert alert=switchTo().alert();
alert.accept();
This can make the test runs well, so it looks I can NOT manually click the alert (after I manually click, the selenium still can NOT go back to the browser...lost connection to browser?), but the automation alert handle code works...
Of course, we want to let user to manually to click alert window to control the test execution, not the automation handle alert.
I really got stuck here for a while, and did a lot googling to search, but can not find similar example online, I hope you can shed me light on it, since you are much more guru than me on JBehave and Selenium.
I will be much grateful if you can help me out.

Selenium is a browser automation tool, it does not anticipate user's interactions.
Therefore, I'd use a simple Java GUI window to present the user with messages/options. Afterall, you are testing a web application in a browser, but the program itself is Java and has nothing to do with the browser. A usual Swing option dialog should be enough.
JOptionPane.showMessageDialog(null, "Login successful.");
String loginAs = JOptionPane.showInputDialog("Login as:", "admin");
int choice = JOptionPane.showConfirmDialog(null, "Use production data?");
(note that you don't want to invoke this in the EventQueue.invokeLater() block, because you want the dialogs to be blocking)
This way, you won't interact with Selenium or the browser in any way, you won't confuse it and you'll get the user input cleanly.
That said, if you insist on using alerts, I think it's definitely doable, but as of now (June 2013, Selenium 2.33.0), I don't know how:
The issue is not reproducible on IE8. After the executeScript("alert('Something.')"); call, Selenium waits for the call to return something and then proceeds normally. So you're good on IE.
However, with FF21, Selenium fails immediatelly with UnhandledAlertException just as you said.
I tried two obvious solutions:
js.executeScript("alert('something')");
new WebDriverWait(driver, 10)
.pollingEvery(100, TimeUnit.MILLISECONDS)
.ignoring(UnhandledAlertException.class)
.until(ExpectedConditions.not(ExpectedConditions.alertIsPresent()))
.wait();
and
js.executeScript("alert('something')");
boolean alertVisible = true;
while (alertVisible) {
try {
driver.switchTo().alert();
} catch (NoAlertPresentException ignored) {
alertVisible = false;
}
}
Both make FF fail horribly with an internal JavaScript exception. Possibly a bug that might get fixed (please test it, check whether it had been reported and report it if you're interested in it), so I'll leave the solutions here for future generations.
But as I said before, it's possible that it won't get fixed, since Selenium doesn't count on manual user interactions.
Not sure how this behaves in other browsers.

Related

Trying to automate a web page and pause in debugger error [duplicate]

Everytime I try to access this website and open google-chrome-devtools I am unable to inspect any of the elements through the Inspector as the UI is having an overlay along with a message Paused in debugger.
The upvoted and accepted answer of this discussion says to check the Source tab, check under the Event Listener Breakpoints panel if you've set any breakpoints under 'Mouse'. I have cross checked that none of the Sources -> EventListenerBreakpoint are set.
The upvoted and accepted answer of this discussion says to check if the little octagonal stop/pause sign (at lower left of Chrome "Sources") is colored (blue or purple). I am not sure why do I need to do that additionally for selected websites.
Snapshot:
The upvoted and accepted answer of this discussion speaks about the Manual Steps.
All the solutions seem to point towards the manual process. But this issue seems to me the root cause behind Selenium being unable to getPageSource().
Code trials:
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.addArguments("disable-infobars");
options.addArguments("--disable-extensions");
WebDriver driver = new ChromeDriver(options);
driver.get("http://rd.huangpuqu.sh.cn/website/html/shprd/shprd_tpxw/List/list_0.htm");
Output: Chrome opens but doesn't navigates to the url.
So my questions are:
In which case can Paused in debugger error occurs?
Is it an error from the frontend development?
How can I bypass this error during the Automated Tests through Selenium?
In which cases can the Paused in debugger error occur?
Anytime you are accessing this page with the dev tools open. The debugger; line will pause javascript execution, but browsers will ignore it if the dev tools are closed.
Is it an error from the frontend development?
In this case, no--they're deliberately trying to keep you out. The purpose of this function is to pause execution and then redirect your browser to a different page if it takes longer than 100ms to resume. I would speculate that this is designed to interfere with automated crawlers like selenium, because a regular user wouldn't be affected and a human developer can just hack around it.
How can I bypass this error during the Automated Tests through Selenium?
My first recommendation would be to try running Selenium headlessly, if that's an option. If not, use the hotkey to resume execution (F8). You can use whatever method you like for generating a keypress; with the java.awt package it will look something like this:
Robot robot = null;
try
{
robot = new Robot();
}
catch(Exception e)
{
//handle failure
}
robot.keyPress(KeyEvent.VK_F8);
Remember that you have to trigger this within 100ms, so use whatever logic you like to detect the block and respond quickly. If you just want something quick and dirty, I would just make it spam F8 keypresses every 50ms for a period of time until you're certain the page has loaded.
EDIT: On further investigation, this page is extremely messy and hostile to anyone with the dev tools open. There is not one but several functions that trigger debugger;and they get called repeatedly on a timer for as long as you're on the page. Running headlessly seems like the best choice, unless you want to continue spamming F8 for the entire session.

Debugger.setPauseOnExceptions for Selenium debugging not working [duplicate]

Everytime I try to access this website and open google-chrome-devtools I am unable to inspect any of the elements through the Inspector as the UI is having an overlay along with a message Paused in debugger.
The upvoted and accepted answer of this discussion says to check the Source tab, check under the Event Listener Breakpoints panel if you've set any breakpoints under 'Mouse'. I have cross checked that none of the Sources -> EventListenerBreakpoint are set.
The upvoted and accepted answer of this discussion says to check if the little octagonal stop/pause sign (at lower left of Chrome "Sources") is colored (blue or purple). I am not sure why do I need to do that additionally for selected websites.
Snapshot:
The upvoted and accepted answer of this discussion speaks about the Manual Steps.
All the solutions seem to point towards the manual process. But this issue seems to me the root cause behind Selenium being unable to getPageSource().
Code trials:
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.addArguments("disable-infobars");
options.addArguments("--disable-extensions");
WebDriver driver = new ChromeDriver(options);
driver.get("http://rd.huangpuqu.sh.cn/website/html/shprd/shprd_tpxw/List/list_0.htm");
Output: Chrome opens but doesn't navigates to the url.
So my questions are:
In which case can Paused in debugger error occurs?
Is it an error from the frontend development?
How can I bypass this error during the Automated Tests through Selenium?
In which cases can the Paused in debugger error occur?
Anytime you are accessing this page with the dev tools open. The debugger; line will pause javascript execution, but browsers will ignore it if the dev tools are closed.
Is it an error from the frontend development?
In this case, no--they're deliberately trying to keep you out. The purpose of this function is to pause execution and then redirect your browser to a different page if it takes longer than 100ms to resume. I would speculate that this is designed to interfere with automated crawlers like selenium, because a regular user wouldn't be affected and a human developer can just hack around it.
How can I bypass this error during the Automated Tests through Selenium?
My first recommendation would be to try running Selenium headlessly, if that's an option. If not, use the hotkey to resume execution (F8). You can use whatever method you like for generating a keypress; with the java.awt package it will look something like this:
Robot robot = null;
try
{
robot = new Robot();
}
catch(Exception e)
{
//handle failure
}
robot.keyPress(KeyEvent.VK_F8);
Remember that you have to trigger this within 100ms, so use whatever logic you like to detect the block and respond quickly. If you just want something quick and dirty, I would just make it spam F8 keypresses every 50ms for a period of time until you're certain the page has loaded.
EDIT: On further investigation, this page is extremely messy and hostile to anyone with the dev tools open. There is not one but several functions that trigger debugger;and they get called repeatedly on a timer for as long as you're on the page. Running headlessly seems like the best choice, unless you want to continue spamming F8 for the entire session.

Is there a change in the handling of unhandled alert in ChromeDriver and Chrome with Selenium?

I have a test that has been running fine for months. One thing it does is cause an alert and then verify the alert text. This is running with Selenium, Java and Chrome Driver 76.0.3809.68.
Lately it has been giving me the error:
"No such alert".
What happens is it clicks a button and waits for an alert if there:
try {
button.click();
} catch (UnhandledAlertException ex) {
// nothing
}
// then here goes code to accept the alert and get the text
when stepping through I see the alert. When I run it, I see the alert but it disappears. I did read something in the (Chrome Driver) release notes about unexpected alerts but it was a bit vague.
We have a global page which sets the options for Chrome, but everyone uses it and I don't want to screw up for other people. I did do it locally (did not git push) and it worked when I set the options before creating the driver.
Then I tried to do this, which does not seem to work. Should it, or once the web page is retrieved, can you not change options?
// Somewhere after web page retrieved this gets called:
public void setIgnoreAlert() {
ChromeDriver cd = (ChromeDriver) driver;
ChromeOptions cap = new ChromeOptions();
cap.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
Capabilities other = cap;
cd.getCapabilities().merge(other);
}
Which I was really hoping would work, but did not. Do you have to set the behavior before the Chrome instance comes up? That is, can you not set it as I did above? Any other suggestions on how to set it after the Chrome instance is up?
--- added later to answer question
This is done immediately after the try-catch block with button.click():
The method configPage.getAndHandleAlertPopUp() does the following:
public String getAndHandleAlertPopUp() {
Alert alert = driver.switchTo().alert();
String alertPopup = alert.getText();
alert.accept();
return alertPopup;
}
You saw it right. As per the User Prompts section within WebDriver - W3C Recommendation:
The common denominator for user prompts is that they are modal windows requiring users to interact with them before the event loop is unpaused and control is returned to the current top-level browsing context.
By default user prompts are not handled automatically unless a user prompt handler has been defined. When a user prompt appears, it is the task of the subsequent command to handle it. If the subsequent requested command is not one listed in this chapter, an unexpected alert open error will be returned.
User prompts that are spawned from beforeunload event handlers, are dismissed implicitly upon navigation or close window, regardless of the defined user prompt handler.
A user prompt has an associated user prompt message that is the string message shown to the user, or null if the message length is 0.
As per the discussion in ChromeDriver should return user prompt (or alert) text in unhandled alert error response:
When a user prompt handler is triggered, the W3C Specification states that the error response should return an "annotated unexpected alert open error" which includes an optional dictionary containing the text of the user prompt. ChromeDriver should supply the optional information.
Clearly, ChromeDriver was not compliant with this standard as the #Test were annotated with #NotYetImplemented as follows:
#Test
#NotYetImplemented(CHROME)
#NotYetImplemented(CHROMIUMEDGE)
#Ignore(value = HTMLUNIT, reason = "https://github.com/SeleniumHQ/htmlunit-driver/issues/57")
#NotYetImplemented(value = MARIONETTE,
reason = "https://bugzilla.mozilla.org/show_bug.cgi?id=1279211")
#NotYetImplemented(EDGE)
public void testIncludesAlertTextInUnhandledAlertException() {
driver.get(alertPage("cheese"));
driver.findElement(By.id("alert")).click();
wait.until(alertIsPresent());
assertThatExceptionOfType(UnhandledAlertException.class)
.isThrownBy(driver::getTitle)
.withMessageContaining("cheese")
.satisfies(ex -> assertThat(ex.getAlertText()).isEqualTo("cheese"));
}
Now this feature have been implemented with ChromeDriver v76.0:
Resolved issue 2869: ChromeDriver should return user prompt (or alert) text in unhandled alert error response [Pri-2]
So you have to handle the alert as a mandatory measure.
A bit more of your code code block for ...then here goes code to accept the alert and get the text... would have helped us to debug the issue in a better way. However here are the options:
Induce WebDriverWait for alertIsPresent() as follows:
new WebDriverWait(driver, 10).until(ExpectedConditions.alertIsPresent());
Your code trials was perfect perhaps as you have passed the CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE in a structured way:
public void setIgnoreAlert() {
ChromeOptions opt = new ChromeOptions();
opt.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
}
Another perspective would be to disable the beforeunload event handlers and you can find a couple of related discussions in:
How to disable a “Reload site? Changes you made may not be saved” popup for (python) selenium tests in chrome?
How to handle below Internet Explorer popup “Are you sure you want to leave this page?” through Selenium
Note: Once the WebDriver and Web Browser instances are initialized you won't be able to change the configuration on the run. Even if you are able to extract the Session ID, Cookies and other capabilities and session attributes from the Browsing Session still you won't be able to alter those attributes of the WebDriver.
You can find a detailed discussion in How can I reconnect to the browser opened by webdriver with selenium?

Selenium - watch for an error condition AND run 'happy path' test code

My app displays an error dialog whenever a JavaScript error occurs. This is always a bad sign, so I want to set up my tests so that, if the error dialog appears, it causes the test to fail there and then.
So I'd like to do something like (very much pseudocode!);
// start a new 'guard' thread;
start {
found = this.driver.wait(untilVisible(By.css('.myErrorDialog')), VERY_LONG_TIMEOUT);
if (found) {
// the error dialog appeared! That's bad!
throw();
}
}
// now run the test
login();
clickButton();
testBannerContains();
But I'm having trouble and I think it has to do with the way Selenium schedules actions.
What I've found is that for a single driver, I can only schedule one thing at a time, so the guard I set up early in the test blocks the body of the test from starting.
Is there a better way to handle conditions like 'this should never happen', or a way to create two independent threads in the same test?
So the problem with the code you have is that it immediately runs it and waits for a VERY_LONG_TIMEOUT amount of time for that error dialog to appear. Since it never does, it continues to wait. You have already discovered that is not what you want... ;)
I haven't done anything like this but I think you want a JS event handler that watches for the event that is triggered when the error dialog appears. See the link below for some guidance there.
Can my WebDriver script catch a event from the webpage?
One option would be to watch for that event to fire and then store true (or whatever) in some JS variable. Before leaving a page, check to see if the variable is set to true and if so, fail the test. You can set and get JS variables using JavascriptExecutor. Some google searches should get you all you need to use it.

Browser crashes during automated test runs

For reliability testing, we are testing our web application through selenium automated tests runs on infinite loop on the Firefox /IE browser. Can some one have an idea on how to track when browser crashes/ hung up with out exiting/stopping the test run?
i guess it could be done this way,
if the browser crashes : as there will not be any window opened, you will get an error
generated in javascript for further commands which you send and that will be sent to the
client code.
example :
try to close the window which is already closed or not existed and you will get an exception / error and catch this in the code. (java code example) :
try {
selenium.close(); //if it is a main window
} catch(SeleniumException se) {
if(!se.getMessage().equals("Current window or frame is closed!"))
//do what ever you want here
}
as i said this is to give you some idea about how to go a head and may not be exactly what
you are looking for.
but i have a logic done in this way to close the entire application (multi window)
window by window and it works fine