How can I disable automatic dismiss unexpected alert in Selenium Safari WebDriver - selenium

When UnexpectedAlertPresentException raised in Selenium Safari WebDriver, I want to get an alert message. However, I can't that because When it raised, Safari WebDriver self automatic dismisses the alert. As a result alert window closed and I faced NoAlertPresentException.
Nicely work with Chrome webdriver as exactly same code. I tried to set desired_capabilities below. But it doesn't work.
caps = DesiredCapabilities.SAFARI.copy()
caps['handlesAlerts'] = True
caps['unexpectedAlertBehaviour'] = 'ignore'
driver = webdriver.Safari(
executable_path='/usr/bin/safaridriver',
desired_capabilities = caps
)
try:
driver.get(url)
if browser == 'ie':
fullpage_screenshot(driver, screenshot_name)
else:
save_screenshot(driver, screenshot_name)
except UnexpectedAlertPresentException:
print('Screenshot Error:', UnexpectedAlertPresentException)
if browser == 'ie':
continue
try:
WebDriverWait(driver, 5).until(
EC.alert_is_present(),
'Timed out waiting for alert to appear'
)
alert = driver.switch_to_alert()
memo[idx] = memo[idx] + str(alert.text)
print('Alert Message:', alert.text)
alert.accept()
if not os.path.isdir('./errors/'):
os.mkdir('./errors/')
driver.get_screenshot_as_file('./errors/Error '+ screenID[idx] +'_'+ browser +'.png')
memo[idx] = str(memo[idx]) + '\n' + str(UnexpectedAlertPresentException)
continue
except TimeoutException:
print('No alert')
continue
except Exception as e:
print('Inner Exception', e)
continue
except Exception as e:
memo[idx] = memo[idx] + str(e)
print('Exception: ', e)
continue
This is I'll expected result:
Screenshot Error: <class 'selenium.common.exceptions.UnexpectedAlertPresentException'>
Alert Message: <ERROR><![CDATA[No Data.]]></ERROR>
Here is actual result when raised UnexpectedAlertPresentException at Safari WebDriver.:
Screenshot Error: <class 'selenium.common.exceptions.UnexpectedAlertPresentException'>
No alert
Screenshot Error: <class 'selenium.common.exceptions.UnexpectedAlertPresentException'>
No alert

Related

switchTab() cannot make the tab as currentTab in WebdriverIO standalone mode

webdriverio with selenium-standalone server, without wdio.
Clicking a link to open a new tab.
I can see the new tab opened, but no elements on the new tab can be located, as if the new tab never existed.
The titles of the first tab and the new tab:
C:\Users\...\test>node switchtab.js
main window: CDwindow-(D77C1A0428E3E5717A1DF2473274B905)
Title is: WebdriverIO - WebDriver bindings for Node.js
new window: CDwindow-(D77C1A0428E3E5717A1DF2473274B905)
Title is: WebdriverIO - WebDriver bindings for Node.js
switchTab: CDwindow-(BE8C6F13723E588E3E39C7C21C02C290)
current window: CDwindow-(D77C1A0428E3E5717A1DF2473274B905)
Title is: WebdriverIO - WebDriver bindings for Node.js
It always gets the first tab id as you can see. Therefore no elements on new tab can be located.
What did I do wrong? How can I make the new tab as current tab? Even though I see the new tab becomes the active tab, but apprently the code doesn't think so.
Here is the sample code snippet:
var webdriverio = require('webdriverio');
var options = { desiredCapabilities: { browserName: 'chrome' } };
var client = webdriverio.remote(options);
var mainW, newW, newW1;
client
.init()
.url('http://webdriver.io/')
.getCurrentTabId().then(function (handle) {
mainW = handle;
console.log('main window: ' + mainW);
})
.getTitle().then(function(title) {
console.log('Title is: ' + title);
})
.waitForExist('a[href="http://try.learnwebdriverio.com"]')
.click('a[href="http://try.learnwebdriverio.com"]')
.pause(5000)
.getCurrentTabId().then(function (handle) {
newW = handle;
console.log('new window: ' + newW);
})
.getTitle().then(function(title) {
console.log('Title is: ' + title);
})
.getTabIds().then(function (handle) {
console.log('switchTab: ' + handle[1]);
newW1 = handle[1];
})
.switchTab(newW1)
.pause(5000)
.getCurrentTabId().then(function (handle) {
console.log('current window: ' + handle);
})
.getTitle().then(function(title) {
console.log('Title is: ' + title);
.end();
switchTab() won't help. After .switchTab(newW1), it still gets the first tab. And even worse, I see it physically switches to the first tab.
It works by using Testrunner (with mocha, and I think other frameworks would be just the same). The only difference between standalone mode and Testrunner mode I see is that:
Different than using the standalone mode all commands that get executed by the wdio test runner are synchronous.
Therefore, It should have something to do with synchronization, which the standalone mode doesn't handle correctly.
Please note that in Testrunner mode, the new tab is also not current after clicking the link. You have to manually switchTab() to set the new tab as current.

Selenium Chrome 3.5.3 Alerts

Just a question about Selenium 3.5.3 and handling alerts...
I got the error:
org.openqa.selenium.UnhandledAlertException: unexpected alert open
...although I set this code:
...
chromeOptions.addArguments("--user-data-dir=C:\\Selenium\\Conf\\ChromeProfile");
chromeOptions.addArguments("--proxy-server=http://" + webdriverChromeUser + ":" + webdriverChromePassWd + "#" + webdriverChromeProxy);
chromeOptions.addArguments("disable-infobars");
chromCapability.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
chromCapability.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
remWebDriver = new org.openqa.selenium.remote.RemoteWebDriver(new URL(hubURL), chromCapability);
...
I would expect, that it works, but the error comes up.

Selenium webdriver IE9 event not firing

I am using nodejs, Soda with selenium
I am hitting problems trying to get the javascript to fire events like on entry of data. Script can't even get through the creation of client flow on IE. Only worried about IE 9+ btw.
Am I missing anything ? This works fine in latest FF. Below posting sample code using for FF
var soda = require('soda');
var assert = require('assert');
var browser = soda.createClient({
url: 'http://192.168.12.1/', // localhost website
port:5555,
host:'192.168.1.3', //grid ip
browser: 'firefox',
browserTimeout:5
});
var testname = 'Nits' + parseInt(Math.random() * 100000000); //create unique name for new person.
console.log('randome name: ' + testname);
browser
.chain
.session()
.setSpeed(speed)
.setTimeout(20000)
.open('/')
.and(login('dev#dev.com', 'x1212GQtpS'))
.and(killClient(killAtEnd))
.end(function(err){
console.log('done');
if(err){
console.log(err);
}else{
console.log("We're Good");
}
if (closeAtEnd){
browser.testComplete(function() {
console.log('killing browser');
});
}
});
function login(user, pass) {
return function(browser) {
browser
.click('css=a#loginButton')
.type('css=input.input-medium.email',user)
.type('css=input.input.pwd',pass)
.clickAndWait('css=a.btn.login')
.assertTextPresent('Clients',function(){ console.log('logged in ok')})
}
}
Can you be more specific about exactly where the script stops, fails, or throws an error? I suspect that IE can't handle the way you put your css selector together (i.e. the classname combinators such as 'input.input.pwd' ). I would recommend trying a different selector or rewrite/simplify your existing selector until you get it working.

Selenium RC PHPUnit test

My testcase crashes with the following error:
$this->open("/en");
$this->type("id=LoginForm_username", "seleniumfree");
$this->type("id=LoginForm_password", "seleniumfree");
$this->click("name=login");
$this->waitForPageToLoad("30000");
$this->click("link=Calendar");
$this->waitForPageToLoad("30000");
$this->click("link=Add to agenda");
$this->type("id=UserAgenda_date", "2013-10-10");
$this->select("id=UserAgenda_time", "label=01:00");
$note = $this->getEval("Math.floor(Math.random()*1000)").':note';
$this->type("id=UserAgenda_note", $note);
$this->click("name=yt0");
sleep(5);
try { //also tried with integer
$this->assertEquals("2", $this->getXpathCount("//input[#value='"+ $note + "']"));
} catch (PHPUnit_Framework_AssertionFailedError $e) {
array_push($this->verificationErrors, $e->toString());
}
Invalid response while accessing the Selenium Server at 'http://localhost:4444/selenium-server/driver/':
ERROR: Command execution failure. Please search the user group at https://groups.google.com/forum/#!forum/selenium-users for error details from the log window.
The error message is: The expression cannot be converted to return the specified type.
In firefox IDE, playing the test runs fine.Is there another way I can count the inputs by value?

unclickable element / actions with dynamic visibility

I'm evaluating Selenium2 for a project on Internet Explorer 9 and I chose the mercedes-benz website because it uses AJAX and some inline popups, so I wrote a little test.
goto mercedes-benz.ch
click onto the "A", then select "Konfigurator" in the displayed overlay
click onto "Weiter >"
click onto "> Rate ändern" and the popup will show up.
click the "i" button in the popup
I have 2 problems in my example code:
1st: How to build an Actions-Chain with dynamic content that is not yet available when building the chain
(ie. moveToElement(A).moveToElement(B): A makes B visibile, so upon building, B does not exist)
2nd: This is the img-element enclosed in an a-element, that I want to click:
<a onclick="var cf = function(){ openInfo('InsurancePpi'); return false;};
var oamSF = function(){ return oamSubmitForm('calcForm','calcForm:j_id31');};
return (cf()==false) ? false : oamSF();" href="#">
<img src="images/mb/btn_info_rb.gif">
</a>
but .click() doesn't do anything. The click seems executed, but nothing happens where a popup should be shown. If I use .sendKeys(Keys.Enter) instead of .click() it works just fine.
my example code:
package org.test.demo;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;
#Test
public class TestStep_DebugChangeRate {
public void test() {
driver.manage().deleteAllCookies();
driver.get("http://www.mercedes-benz.ch");
WebElement btnA = driver.findElement(By.xpath("//a[.='A']"));
// first problem, i cannot combine moveToElement(btnA) and
// moveToElement(btnKonfigurator), because btnKonfigurator is not
// visible at the moment of building the Action which will then fail
// in NoSuchElement, that's why I cheat with sendKeys(), any tips?
(new Actions(driver))
.moveToElement(btnA)
.click(btnA)
.sendKeys(Keys.TAB)
.sendKeys(Keys.TAB)
.sendKeys(Keys.TAB)
.sendKeys(Keys.ENTER)
.build()
.perform();
performWaitBool(driver, PerformWaitExpectedConditions.isPageLoadFinished(), "timeout waitForPageLoad");
WebElement btnContinue = driver.findElement(By.id("vsAppLnkContinue1"));
btnContinue.click();
performWaitBool(driver, PerformWaitExpectedConditions.isPageLoadFinished(), "timeout waitForPageLoad");
WebElement btnChangeRate = driver.findElement(By.id("vsAppLnkPcnChangeRate"));
btnChangeRate.click();
performWaitBool(driver, PerformWaitExpectedConditions.isPageLoadFinished(), "timeout waitForPageLoad");
WebElement frameInline = driver.findElement(By.xpath("//div[#class='contentsC']/iframe"));
WebDriver frame = driver.switchTo().frame(frameInline);
WebElement btnInfoPpi = frame.findElement(By.xpath("//a[contains(#onclick, 'InsurancePpi')]/img"));
// does not throw an error, though the info popup is not opened
btnInfoPpi.click();
Boolean isDisplayed = btnInfoPpi.isDisplayed(); // true
int elementWidth = btnInfoPpi.getSize().getWidth(); // 23
btnInfoPpi.sendKeys(Keys.Enter); // this will open the popup however
}
}
Concerning your problem with the img I would try to execute the relevant js from inside the a tag via
((JavascriptExecutor) driver).executeScript("script;");
Further I can't help cuz the page is not working for me.
Try using Selenium IDE to get the core of your actions. Export that as Java Junit4 webdriver testcase. that might help you find your solution.

Resources