Selenium with PHPUnit not loading page - selenium

I am trying to make a test suit for a php project using phpunit and phpunit-selenium. In my composer file I have
"require-dev": {
"phpunit/phpunit": "^5.7",
"phpunit/phpunit-selenium": "^3.0"
}
The installed phpunit version is 5.7.4
I am using selenium-server-standalone-3.0.1.jar as the selenium server. I start the server with
java -Dwebdriver.gecko.driver="C:\Harlan\Selenium\geckodriver.exe" -jar selenium-server-standalone-3.0.1.jar
In my test class I have
require_once dirname(__FILE__) . '/../../vendor/autoload.php';
class UserSubscriptionTest extends PHPUnit_Extensions_Selenium2TestCase {
public function setUp() {
$this->setHost('localhost');
$this->setPort(4444);
$this->setBrowserUrl('http://localhost/cwckids/web/user/login');
$this->setBrowser('firefox');
}
public function tearDown() {
$this->stop();
}
public function testFormSubmissionWithUsername()
{
$this->byName('login-form[login]')->value('admin');
$this->byName('login-form[password]')->value('mypassword');
$this->byId('login-form')->submit();
$content = $this->byTag('body')->text();
$this->assertEquals('Everything is Good!', $content, 'something wrong!!');
}
}
My problem is that the firefox browser opens up but doesn't load the page http://localhost/cwckids/web/user/login
The test fails immediately because it cannot find the elements. It give a message saying
Unable to locate element: {"method":"name","selector":"login-form[login]"}
I couldn't find a solution for the problem. Is it some version incompatibility? I tried with a few versions of Firefox and also selenium server. My Firefox version is 50.1.0. If it is a version incompatibility can someone suggest correct versions? Thanks
The complete trace
C:\xampp\htdocs\seleniumtest>phpunit tests/acceptance/UserSubscriptionTest.php
PHPUnit 5.7.4 by Sebastian Bergmann and contributors.
E 1 / 1 (100%)
Time: 6.51 seconds, Memory: 9.25MB
There was 1 error:
1) UserSubscriptionTest::testFormSubmissionWithUsername
PHPUnit_Extensions_Selenium2TestCase_WebDriverException: Unable to locate element: {"method":"name","selector":"login-form[login]"}
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.53.1', revision: 'a36b8b1', time: '2016-06-30 17:37:03'
System info: host: 'DESKTOP-I0LAEAM', ip: '192.168.8.101', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_77'
Driver info: driver.version: unknown
C:\xampp\htdocs\seleniumtest\vendor\phpunit\phpunit-selenium\PHPUnit\Extensions\Selenium2TestCase\Driver.php:165
C:\xampp\htdocs\seleniumtest\vendor\phpunit\phpunit-selenium\PHPUnit\Extensions\Selenium2TestCase\CommandsHolder.php:108
C:\xampp\htdocs\seleniumtest\vendor\phpunit\phpunit-selenium\PHPUnit\Extensions\Selenium2TestCase\Element\Accessor.php:134
C:\xampp\htdocs\seleniumtest\vendor\phpunit\phpunit-selenium\PHPUnit\Extensions\Selenium2TestCase\Element\Accessor.php:175
C:\xampp\htdocs\seleniumtest\vendor\phpunit\phpunit-selenium\PHPUnit\Extensions\Selenium2TestCase\Element\Accessor.php:108
C:\xampp\htdocs\seleniumtest\vendor\phpunit\phpunit-selenium\PHPUnit\Extensions\Selenium2TestCase.php:394
C:\xampp\htdocs\seleniumtest\tests\acceptance\UserSubscriptionTest.php:66
C:\xampp\htdocs\seleniumtest\tests\acceptance\UserSubscriptionTest.php:66
C:\xampp\htdocs\seleniumtest\vendor\phpunit\phpunit-selenium\PHPUnit\Extensions\Selenium2TestCase.php:348
C:\xampp\htdocs\seleniumtest\vendor\phpunit\phpunit-selenium\PHPUnit\Extensions\Selenium2TestCase.php:314
ERRORS!
Tests: 1, Assertions: 0, Errors: 1.

There's a few things I'd suggest changing:
You are missing a call to $this->url(); from, what I can see within your test method:
public function testFormSubmissionWithUsername()
{
$this->url('your actual URL here'); // Add this line
$this->byName('login-form[login]')->value('admin');
$this->byName('login-form[password]')->value('mypassword');
$this->byId('login-form')->submit();
$content = $this->byTag('body')->text();
$this->assertEquals('Everything is Good!', $content, 'something wrong!!');
}
You are also not calling the parent::setUp() method from within your own setUp method:
protected function setUp()
{
parent::setUp();
// Set your browser, port setup etc here
}
There's also no need to explicitly call $this->stop(); from within tearDown, so remove that function completely.
Lastly, I'd tell selenium to take screenshots of failures, they save a lot of time:
/**
* Override this method from \PHPUnit_Framework_TestCase so we can capture a screenshot.
*
* #return void
*/
public function onNotSuccessfulTest($exception)
{
$filedata = $this->currentScreenshot();
$file = YOUR_SCREENSHOT_DIR . '\testfails\\' . basename(get_class($this)) . '.png';
file_put_contents($file, $filedata);
parent::onNotSuccessfulTest($exception);
}

Related

handling calendar in selenium

whenever my code is executing it is getting navigating to some other page. My code is of how to handle with calendar in selenium.
please help
package basic;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class calender {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new ChromeDriver();
//Launching website
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("https://www.path2usa.com/travel-companions");
//selecting dates
driver.findElement(By.xpath("//*[#id=\"travel_date\"]")).click();
while(!driver.findElement(By.cssSelector("[class='datepicker-days'] th[class='datepicker-switch']")).getText().contains("April"))
{
driver.findElement(By.cssSelector("[class='datepicker-days'] th[class='next']")).click();
}
List<WebElement> dates = driver.findElements(By.className("day"));
//grab common attribute // put into list and iterate
int count = driver.findElements(By.className("day")).size();
for(int i=0;i<count;i++)
{
String text = driver.findElements(By.className("day")).get(i).getText();
if(text.equalsIgnoreCase("23"))
{
driver.findElements(By.className("day")).get(i).click();
break;
}
}
}
}
starting ChromeDriver 73.0.3683.68 (47787ec04b6e38e22703e856e101e840b65afe72) on port 13761
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
Apr 01, 2019 9:38:18 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Cannot locate an element using css selector=[class='datepicker-days'] th[class='datepicker-switch']
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
System info: host: 'Nilufars-MacBook-Air.local', ip: '2405:204:4383:7327:1104:ad36:576:9d64%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.6', java.version: '1.8.0_201'
Driver info: driver.version: RemoteWebDriver
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:327)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByCssSelector(RemoteWebDriver.java:420)
at org.openqa.selenium.By$ByCssSelector.findElement(By.java:431)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315)
at basic.calender.main(calender.java:23)
Welcome to SO.
You can directly select the date as shown below.
driver.findElement(By.xpath("//input[#name='travel_date']")).sendKeys("25 May 2019");
This way you will save your execution time by ignoring the month loop and date loop.
Simplified code:
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("https://www.path2usa.com/travel-companions");
//selecting the date
driver.findElement(By.xpath("//input[#name='travel_date']")).sendKeys("25 May 2020");
//continue your test with next steps
// quit the driver.
driver.quit();

MicrosoftWebDriver loading web driver null

I have the error when run selenium on local machine which is Windows 10 Enterpise 64-bit (Microsoft Edge Version: 25.10586.672.0)and Microsoft WebDriver - Release 10240. My Selenium version is: 3.6.0
public class SeleniumTest {
private WebDriver driver;
#BeforeClass
public void getWebDriver() {
try {
System.setProperty("webdriver.edge.driver", "myapp/driver/MicrosoftWebDriver.exe");
DesiredCapabilities capabilities = DesiredCapabilities.edge();
capabilities.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);
capabilities.setCapability(CapabilityType.PAGE_LOAD_STRATEGY, "eager");
capabilities.setPlatform(Platform.WIN10);
capabilities.setBrowserName(BrowserType.EDGE);
capabilities.setVersion("");
driver = new EdgeDriver(capabilities);
} catch (Exception e) {
e.printStackTrace();
}
driver.get(Constant.URL);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
}
#AfterClass
public void quitDriver() throws InterruptedException {
Thread.sleep(3000);
driver.quit();
}
#Test ()
public void aTest() {
}
#Test ()
public void bTest() {
}
}
When I run code it open the Edge Browser and has error:
org.openqa.selenium.NoSuchSessionException: null (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 873 milliseconds
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T15:28:36.4Z'
System info: host: 'computername', ip: 'myip', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_111'
Driver info: driver.version: EdgeDriver
You may consider to look into the Release Notes as it mentions:
Updating .NET bindings to not send incorrect W3C Firefox capabilities
Previously, RemoteWebDriver would send the same capabilities dictionary
using both the "desiredCapabilities" and "capabilities" properties when
requesting a new remote session. In the case of the language bindings
expressly requesting to use the legacy Firefox driver, the capabilities
dictionary will include properties that are invalid for the W3C-compliant
remote server. To resolve that issue, we will mask the explicit attempt by
setting a property that causes the .NET RemoteWebDriver to send a
legacy-only compatible new session request when explicitly requesting the
legacy driver.
I don't see any significant error as such in your code except one, to see NoSuchSessionException. Instead of:
DesiredCapabilities capabilities = DesiredCapabilities.edge();
You should use:
DesiredCapabilities cap = new DesiredCapabilities();
It's possible you also need to start a driver service, i.e.
service = new EdgeDriverService.Builder()
.usingDriverExecutable(new File("path/to/my/MicrosoftWebDriver.exe"))
.usingAnyFreePort()
.build();
service.start();
Have a look at this example of an EdgeDriver.

Difficult to run the script in selenium webdriver which contains HtmlUnitDriver

I am unable to run the basic selenium script which contains the HtmlUnitDriver. If I try to run the code I get the following error.
Code:
public class SampleUnitDriver
{
public static void main(String[] args) throws Exception
{
HtmlUnitDriver unitDriver = new HtmlUnitDriver();
unitDriver.get("http://google.com");
System.out.println("Title of the page is -> " + unitDriver.getTitle());
Thread.sleep(3000L);
WebElement searchBox = unitDriver.findElement(By.className("gsfi"));
searchBox.sendKeys("Selenium");
WebElement button = unitDriver.findElement(By.name("gbqfba"));
button.click();
System.out.println("Title of the page is -> " + unitDriver.getTitle());
}
}
Error:
Title of the page is -> Google
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Returned node was not a DOM element
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.53.0', revision: '35ae25b1534ae328c771e0856c93e187490ca824', time: '2016-03-15 10:43:46'
System info: host: 'user-PC', ip: '192.168.1.52', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_51'
Driver info: driver.version: SampleUnitDriver
at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElementByCssSelector(HtmlUnitDriver.java:1060)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElementByClassName(HtmlUnitDriver.java:1032)
at org.openqa.selenium.By$ByClassName.findElement(By.java:391)
at org.openqa.selenium.htmlunit.HtmlUnitDriver$5.call(HtmlUnitDriver.java:1725)
at org.openqa.selenium.htmlunit.HtmlUnitDriver$5.call(HtmlUnitDriver.java:1721)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.implicitlyWaitFor(HtmlUnitDriver.java:1367)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElement(HtmlUnitDriver.java:1721)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElement(HtmlUnitDriver.java:606)
at com.digitalmqc.automation.action.SampleUnitDriver.main(SampleUnitDriver.java:16)
The class name gsfi of the input box is generated by javascript so you have 2 options:
Easy One: Just select it by using the id lst-ib
Better One: Wait for the element to be fully interactive. The reason behind this one being better is that you are trying to input text into the box which javascript plays a role. The former option may throw some unexpected errors.

cucumber jvm selenium example

I am using standart exsample:
cucumber-jvm-selenium-example
When I run test:
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.michalvich.cucumber.selenium.example.GoogleSearchTest
Feature: Search on Google
As an user
I want to search on Google
So that I can see results
Scenario: results are shown # com\michalvich\cucumber\selenium\example\GoogleSearch.feature:6
Given the page is open "http://www.google.com" # GoogleSearchScenario.the_page_is_open(String)
[1A Given the page is open "http://www.google.com" # GoogleSearchScenario.the_page_is_open(String)
When I search for "Cucumber" # GoogleSearchScenario.I_search_for(String)
[1A When I search for "Cucumber" # GoogleSearchScenario.I_search_for(String)
org.openqa.selenium.NoSuchElementException: Unable to locate element with name: q
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.28.0', revision: '18309', time: '2012-12-11 15:53:30'
System info: os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_17'
Driver info: driver.version: HtmlUnitDriver
at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElementByName(HtmlUnitDriver.java:749)
at org.openqa.selenium.By$ByName.findElement(By.java:292)
at org.openqa.selenium.htmlunit.HtmlUnitDriver$5.call(HtmlUnitDriver.java:1247)
at org.openqa.selenium.htmlunit.HtmlUnitDriver$5.call(HtmlUnitDriver.java:1244)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.implicitlyWaitFor(HtmlUnitDriver.java:987)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElement(HtmlUnitDriver.java:1244)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElement(HtmlUnitDriver.java:393)
at com.michalvich.cucumber.selenium.example.GoogleSearchScenario.I_search_for(GoogleSearchScenario.java:26)
at ?.When I search for "Cucumber"(com\michalvich\cucumber\selenium\example\GoogleSearch.feature:8)
But if I change driver:
System.setProperty("webdriver.chrome.driver", "path\\to\\chromedriver.exe");
driver = new ChromeDriver();
It works.
You need to wait for Google ajax to refresh, otherwise you will only have Google return as the page title
#When("^I search for \"([^\"]*)\"$")
public void I_search_for(String search) throws Throwable {
WebElement element = driver.findElement(By.name("q"));
element.sendKeys(search);
element.submit();
// Google ajax wait for 5 seconds
long end = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < end) {
WebElement resultsDiv = driver.findElement(By.className("gssb_e"));
// If results have been returned, the results are displayed in a drop down.
if (resultsDiv.isDisplayed()) {
break;
}
}
}

Selenium WebDriver: Random Error determining if element is visible

I'm using Selenium 2.2.
I am trying to click on elements which are not displayed at first, but become visible
during the test. At first sometimes the webdriver seemed to work too fast so the Elements were not visible in time resulting in ElementNotVisibleExceptions. I added WebDriverWait to wait for these elements to become visible/clickable. But now I'm getting this random error when using
WebDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.id("id")));
same for
WebDriverWait.until(ExpectedConditions.elementToBeClickable(By.id("id")));
here is the stacktrace
org.openqa.selenium.WebDriverException: Error determining if element is displayed (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 219 milliseconds
Build info: version: '2.20.0', revision: '16008', time: '2012-02-27 19:03:59'
System info: os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1 build 2600 Service Pack 3', java.version: '1.6.0'
Driver info: driver.version: RemoteWebDriver
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:44)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:516)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:170)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:123)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:438)
at org.openqa.selenium.remote.RemoteWebElement.isDisplayed(RemoteWebElement.java:280)
at org.openqa.selenium.support.ui.ExpectedConditions.elementIfVisible(ExpectedConditions.java:136)
at org.openqa.selenium.support.ui.ExpectedConditions.access$1(ExpectedConditions.java:135)
at org.openqa.selenium.support.ui.ExpectedConditions$4.apply(ExpectedConditions.java:106)
at org.openqa.selenium.support.ui.ExpectedConditions$4.apply(ExpectedConditions.java:1)
at org.openqa.selenium.support.ui.ExpectedConditions$11.apply(ExpectedConditions.java:252)
at org.openqa.selenium.support.ui.ExpectedConditions$11.apply(ExpectedConditions.java:1)
at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:201)
at MyTest.myTest(MyTest.java:xx)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:600)
at junit.framework.TestCase.runTest(TestCase.java:168)
at junit.framework.TestCase.runBare(TestCase.java:134)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:124)
at junit.framework.TestSuite.runTest(TestSuite.java:243)
at junit.framework.TestSuite.run(TestSuite.java:238)
at junit.framework.TestSuite.runTest(TestSuite.java:243)
at junit.framework.TestSuite.run(TestSuite.java:238)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:83)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
This only happens sometimes. Ignoring the WebDriverException might solve this problem, but that doesn't seem like a clean solution. It can't be a timeout issue because i tried setting my timeout limit to a minute and more and it still fails after a couple of milliseconds.
Anybody got a clean solution to that?
Thanks in advance
Edit: btw. I'm using the InternetExplorerDriver
Make sure page has only one modalPanel. Try get visible panel (java):
public WebElement getVisibleModalPanel(){
for (WebElement element : driver.findElements(By.cssSelector('csslocator'))) {
if (element.isDisplayed()) {
return element;
}
}
return null;
}
Implement wait for such thing:
(new WebDriverWait(getDriver(), timeout, 400)).ignoring(StaleElementReferenceException.class).until(
new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
for (WebElement element : driver.findElements(By.cssSelector(locator))) {
if (element.isDisplayed()) {
return true;
}
}
return false;
}
});