diff --git a/.gitignore b/.gitignore index 29c7580..88c6a2e 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,4 @@ +/SeleniumClientTest/phpunit.xml +/build +/.idea /*.project diff --git a/SeleniumClient/By.php b/SeleniumClient/By.php index 78a0c80..4ad656b 100644 --- a/SeleniumClient/By.php +++ b/SeleniumClient/By.php @@ -43,10 +43,21 @@ public static function cssSelector($selectorValue) { return new By("css selector * @return \SeleniumClient\By */ public static function id($selectorValue) { return new By("id", $selectorValue); } - + + /** + * Locate by JavaScript selector + * @param string $selectorValue + * @param string $selectorDefinition + * @return \SeleniumClient\By + */ + public static function jsSelector($selectorValue, $selectorDefinition = '$') + { + return new By("js selector {$selectorDefinition}", $selectorValue); + } + /** * Locate by element's name - * @param unknown_type $selectorValue + * @param String $selectorValue * @return \SeleniumClient\By */ public static function name($selectorValue) { return new By("name", $selectorValue); } diff --git a/SeleniumClient/DesiredCapabilities.php b/SeleniumClient/DesiredCapabilities.php index 58a0aa7..42ba02f 100644 --- a/SeleniumClient/DesiredCapabilities.php +++ b/SeleniumClient/DesiredCapabilities.php @@ -1,23 +1,23 @@ _trace = $value; return $this; } - - public function setUrl($value) + + /** + * @param string $value + * @return $this + */ + public function setUrl($value) { $this->_url = $value; return $this; } - + + /** + * @param bool $value + * @return $this + */ public function setPolling($value) { $this->_polling = $value; return $this; } - + + /** + * @param string $value + * @return $this + */ public function setJsonParams($value) { $this->_jsonParams = $value; return $this; } - + + /** + * @param string $value + * @return $this + */ public function setHttpMethod($value) { $this->_httpMethod = $value; return $this; } - - public function execute() + + /** + * @return string The response body + * @throws \Exception + */ + public function execute() { if (empty($this->_url) || empty($this->_httpMethod)) { throw new \Exception("Must specify URL and HTTP METHOD"); } @@ -96,7 +116,7 @@ public function execute() echo "URL: " . $this->_url . "\n"; echo "METHOD: " . $this->_httpMethod . "\n"; - echo "PARAMETTERS: "; + echo "PARAMETERS: "; if (is_array($this->_jsonParams)) { echo print_r($this->_jsonParams); } else echo "NONE"; { echo "\n"; } @@ -112,5 +132,7 @@ public function execute() $this->_responseHeaders = $responseHeaders; $this->_responseBody = $responseBody; + + return $this->_responseBody; } } \ No newline at end of file diff --git a/SeleniumClient/Http/HttpFactory.php b/SeleniumClient/Http/HttpFactory.php index 6e31230..07bb002 100644 --- a/SeleniumClient/Http/HttpFactory.php +++ b/SeleniumClient/Http/HttpFactory.php @@ -1,16 +1,16 @@ validateSeleniumResponseCode(); - $this->validateHttpCode (); + $this->validateHttpCode(); - return $this->_responseBody; + return $responseBody; } protected function validateHttpCode() diff --git a/SeleniumClient/SelectElement.php b/SeleniumClient/SelectElement.php index cf2a911..3494db3 100644 --- a/SeleniumClient/SelectElement.php +++ b/SeleniumClient/SelectElement.php @@ -1,21 +1,21 @@ isSelected()) { $option->click(); @@ -62,30 +62,30 @@ public function selectByValue($value) } } - /** - * Sets an option selected by a partial text match - * @param String $text - * @throws \Exception - */ - public function selectByPartialText($text) - { - $options = $this->_element->findElements(By::xPath(".//option[contains(text(), '" . $text . "')]")); - - $matched = false; - foreach($options as $option) - { - - if(!$option->isSelected()) - { - $option->click(); - } - - $matched = true; - } - - if (!$matched) - { - throw new \Exception("Cannot locate option in select element with text: " . $text); - } + /** + * Sets an option selected by a partial text match + * @param String $text + * @throws \Exception + */ + public function selectByPartialText($text) + { + $options = $this->_element->findElements(By::xPath(".//option[contains(text(), '" . $text . "')]")); + + $matched = false; + foreach($options as $option) + { + /** @var $option WebElement */ + if(!$option->isSelected()) + { + $option->click(); + } + + $matched = true; + } + + if (!$matched) + { + throw new \Exception("Cannot locate option in select element with text: " . $text); + } } } \ No newline at end of file diff --git a/SeleniumClient/TargetLocator.php b/SeleniumClient/TargetLocator.php index 1a72813..592d03d 100644 --- a/SeleniumClient/TargetLocator.php +++ b/SeleniumClient/TargetLocator.php @@ -1,21 +1,23 @@ _driver->getAlertText(); return new Alert($this->_driver); //validate that the Alert object can be created, if not throw an exception, try to use a factory singleton o depency of injection to only use 1 instance } + + /** + * Opens a new tab for the given URL + * @param string $url The URL to open + * @return string The handle of the previously active window + * @see http://stackoverflow.com/a/9122450/650329 + * @throws SeleniumJavaScriptErrorException If unable to open tab + */ + public function newTab($url) + { + $script = "var d=document,a=d.createElement('a');a.target='_blank';a.href='%s';a.innerHTML='.';d.body.appendChild(a);return a"; + $element = $this->_driver->executeScript( sprintf( $script, $url ) ); + + if ( empty( $element ) ) { + throw new SeleniumJavaScriptErrorException( 'Unable to open tab' ); + } + + $existingHandles = $this->_driver->getCurrentWindowHandles(); + $anchor = new WebElement( $this->_driver, $element['ELEMENT'] ); + $anchor->click(); + + $this->_driver->executeScript( 'var d=document,a=arguments[0];a.parentNode.removeChild(a);', array( $element ) ); + $newHandles = array_values( array_diff( $this->_driver->getCurrentWindowHandles(), $existingHandles ) ); + $newHandle = $newHandles[0]; + $oldHandle = $this->_driver->getCurrentWindowHandle(); + + $this->getWindow( $newHandle ); + + return $oldHandle; + } #endregion } \ No newline at end of file diff --git a/SeleniumClient/WebDriver.php b/SeleniumClient/WebDriver.php index 08af629..95cdd42 100644 --- a/SeleniumClient/WebDriver.php +++ b/SeleniumClient/WebDriver.php @@ -1,16 +1,16 @@ startSession($desiredCapabilities); } + + /** + * @param string $name + * @param array $args + * @return mixed + * @throws \Exception + */ + public function __call( $name, array $args ) + { + $arr = explode( 'By', $name ); + $call = $arr[0]; + $by = count( $arr ) > 1 ? lcfirst( $arr[1] ) : ''; + + $valid = false; + + switch ( $call ) { + case 'findElement': + case 'findElements': + if ( method_exists( '\\SeleniumClient\\By', $by ) ) { + $valid = true; + } + } + + if ( !$valid ) { + throw new \Exception( 'Invalid magic call' ); + } + + $method = new \ReflectionMethod( '\\SeleniumClient\\By', $by ); + $byArgs = array_splice( $args, 0, $method->getNumberOfParameters() ); + array_unshift( $args, $method->invokeArgs( null, $byArgs ) ); + + return call_user_func_array( array( $this, $call ), $args ); + } /** * Set whether production or testing mode for library @@ -55,11 +114,11 @@ public function __construct(DesiredCapabilities $desiredCapabilities = null, $ho public function setEnvironment($value) { $this->_environment = $value; } /** - * Get current Selenium environment - * @return String - */ - public function getEnvironment() { - return $this->_environment; + * Get current Selenium environment + * @return String + */ + public function getEnvironment() { + return $this->_environment; } /** @@ -332,57 +391,114 @@ public function screenshot($overrideScreenshotsDirectory = null) return $fileName; } + + return null; } - - /** - * Gets an element within current page - * @param By $locator - * @param Boolean $polling - * @return \SeleniumClient\WebElement - */ - public function findElement(By $locator, $polling = false) - { - $command = "element"; - $params = array ('using' => $locator->getStrategy(), 'value' => $locator->getSelectorValue()); - $urlHubFormatted = $this->_hubUrl . "/session/{$this->_sessionId}/{$command}"; - - $httpClient = HttpFactory::getClient($this->_environment); - $results = $httpClient->setUrl($urlHubFormatted)->setHttpMethod(HttpClient::POST)->setJsonParams($params)->setPolling($polling)->execute(); - - $result = null; - if (isset($results["value"]["ELEMENT"]) && trim ($results["value"]["ELEMENT"]) != "") { $result = new WebElement($this, $results["value"]["ELEMENT"]); } - return $result; - } - - /** - * Gets elements within current page - * @param By $locator - * @param unknown_type $polling - * @return Array \SeleniumClient\WebElement - */ - public function findElements(By $locator, $polling = false) + + /** + * Gets an element within current page + * @param By $locator + * @param bool $polling + * @param int $elementId + * @throws Http\SeleniumNoSuchElementException + * @return \SeleniumClient\WebElement + */ + public function findElement(By $locator, $polling = false, $elementId = -1) { - $command = "elements"; - $params = array('using' => $locator->getStrategy(), 'value' => $locator->getSelectorValue()); - $urlHubFormatted = $this->_hubUrl . "/session/{$this->_sessionId}/{$command}"; - - $httpClient = HttpFactory::getClient($this->_environment); - $results = $httpClient->setUrl($urlHubFormatted)->setHttpMethod(HttpClient::POST)->setJsonParams($params)->setPolling($polling)->execute(); - - $result = null; - if (isset($results["value"]) && is_array($results["value"])) - { - $webElements = array(); - - foreach($results ["value"] as $element) { $webElements[] = new WebElement($this, $element["ELEMENT"]); } + if (strpos($locator->getStrategy(), 'js selector ') === 0) { + $result = $this->findElements($locator, $polling, $elementId); + if (!$result) { + throw new SeleniumNoSuchElementException(); + } + return $result[0]; + } else { + $command = "element"; + if ($elementId >= 0) { + $command = "element/{$elementId}/{$command}"; + } + $params = array ('using' => $locator->getStrategy(), 'value' => $locator->getSelectorValue()); + $urlHubFormatted = $this->_hubUrl . "/session/{$this->_sessionId}/{$command}"; - $result = $webElements; - } - return $result; + $httpClient = HttpFactory::getClient($this->_environment); + $results = $httpClient->setUrl($urlHubFormatted)->setHttpMethod(HttpClient::POST)->setJsonParams($params)->setPolling($polling)->execute(); + + $result = null; + if (isset($results["value"]["ELEMENT"]) && trim ($results["value"]["ELEMENT"]) != "") { $result = new WebElement($this, $results["value"]["ELEMENT"]); } + return $result; + } } - - /** - * Gets element that is currenly focused + + /** + * Gets elements within current page + * @param By $locator + * @param bool $polling + * @param int $elementId + * @throws SeleniumInvalidSelectorException + * @return \SeleniumClient\WebElement[] + */ + public function findElements(By $locator, $polling = false, $elementId = -1) + { + $environment = $this->_environment; + $hubUrl = $this->_hubUrl; + $sessionId = $this->_sessionId; + + $execute = function ($command, array $params) use ($polling, $environment, $hubUrl, $sessionId) { + $urlHubFormatted = $hubUrl . "/session/{$sessionId}/{$command}"; + $httpClient = HttpFactory::getClient($environment); + return $httpClient->setUrl($urlHubFormatted) + ->setHttpMethod(HttpClient::POST) + ->setJsonParams($params) + ->setPolling($polling) + ->execute(); + }; + + if (strpos($locator->getStrategy(), 'js selector ') === 0) { + $function = substr($locator->getStrategy(), 12); + $script = "return typeof window.{$function};"; + $valid = $this->executeScript($script) == 'function'; + $selector = addslashes($locator->getSelectorValue()); + + if (!$valid) { + throw new SeleniumInvalidSelectorException('The selectorElement is not defined'); + } + + if ($elementId >= 0) { + // todo refactor child selection strategy to separate classes + if (strpos($function, 'document.') === 0) { + // assume child.$function($selector) + $function = substr($function, 9); + $script = sprintf('return arguments[0].%s("%s")', $function, $selector); + } else { + // assume $function($selector, child) + $script = sprintf('return %s("%s", arguments[0])', $function, $selector); + } + $args = array(array('ELEMENT' => $elementId)); + } else { + $script = sprintf('return %s("%s")', $function, $selector); + $args = array(); + } + + $params = array('script' => $script, 'args' => $args); + $results = $execute('execute', $params); + } else { + $params = array('using' => $locator->getStrategy(), 'value' => $locator->getSelectorValue()); + $command = $elementId >= 0 ? "element/{$elementId}/elements" : "elements"; + $results = $execute($command, $params); + } + + $webElements = array(); + + if (isset($results['value']) && is_array($results['value'])) { + foreach ($results['value'] as $element) { + $webElements[] = new WebElement($this, is_array($element) ? $element['ELEMENT'] : $element); + } + } + + return $webElements ?: null; + } + + /** + * Gets element that is currently focused * @return \SeleniumClient\WebElement */ public function getActiveElement() @@ -413,19 +529,19 @@ public function waitForElementUntilIsPresent(By $locator, $timeOutSeconds = 5) $wait = new WebDriverWait($timeOutSeconds); - $dynamicElement = $wait->until($this, "findElement", array($locator, TRUE)); + $dynamicElement = $wait->until($this, "findElement", array($locator, true)); return $dynamicElement; } - /** - * Stops the process until an element is not found - * @param By $locator - * @param Integer $timeOutSeconds - * @return boolean true when element is gone, false if element is still there - */ - public function waitForElementUntilIsNotPresent(By $locator, $timeOutSeconds = 5) - { + /** + * Stops the process until an element is not found + * @param By $locator + * @param Integer $timeOutSeconds + * @return boolean true when element is gone, false if element is still there + */ + public function waitForElementUntilIsNotPresent(By $locator, $timeOutSeconds = 5) + { for ($second = 0; ; $second++) { if ($second >= $timeOutSeconds) return false; @@ -436,7 +552,8 @@ public function waitForElementUntilIsNotPresent(By $locator, $timeOutSeconds = 5 } sleep(1); } - } + return false; + } #endregion @@ -645,6 +762,7 @@ public function webElementDescribe($elementId) /** * Find an element within another element + * @deprecated * @param Integer $elementId * @param By $locator * @param Boolean $polling @@ -652,20 +770,12 @@ public function webElementDescribe($elementId) */ public function webElementFindElement($elementId, By $locator, $polling = false) { - $command = "element"; - $params = array('using' => $locator->getStrategy(), 'value' => $locator->getSelectorValue()); - $urlHubFormatted = $this->_hubUrl . "/session/{$this->_sessionId}/element/{$elementId}/{$command}"; - - $httpClient = HttpFactory::getClient($this->_environment); - $results = $httpClient->setUrl($urlHubFormatted)->setHttpMethod(HttpClient::POST)->setJsonParams($params)->setPolling($polling)->execute(); - - $result = null; - if (isset($results["value"]["ELEMENT"]) && trim($results["value"]["ELEMENT"]) != "") { $result = new WebElement($this, $results["value"]["ELEMENT"]); } - return $result; + return $this->findElement($locator, $polling, $elementId); } /** * Find elements within another element + * @deprecated * @param Integer $elementId * @param By $locator * @param Boolean $polling @@ -673,23 +783,7 @@ public function webElementFindElement($elementId, By $locator, $polling = false) */ public function webElementFindElements($elementId, By $locator, $polling = false) { - $command = "elements"; - $params = array ('using' => $locator->getStrategy (), 'value' => $locator->getSelectorValue()); - $urlHubFormatted = $this->_hubUrl . "/session/{$this->_sessionId}/element/{$elementId}/{$command}"; - - $httpClient = HttpFactory::getClient($this->_environment); - $results = $httpClient->setUrl($urlHubFormatted)->setHttpMethod(HttpClient::POST)->setJsonParams($params)->setPolling($polling)->execute(); - - $result = null; - if (isset($results["value"]) && is_array($results["value"])) - { - $webElements = array(); - - foreach($results ["value"] as $element) { $webElements[] = new WebElement($this, $element["ELEMENT"]); } - - $result = $webElements; - } - return $result; + return $this->findElements($locator, $polling, $elementId); } /** @@ -697,17 +791,17 @@ public function webElementFindElements($elementId, By $locator, $polling = false * @param Integer $elementId * @return Array */ - public function webElementGetCoordinates($elementId) - { - $command = "location"; - $urlHubFormatted = $this->_hubUrl . "/session/{$this->_sessionId}/element/{$elementId}/{$command}"; - - $httpClient = HttpFactory::getClient($this->_environment); - $results = $httpClient->setUrl($urlHubFormatted)->setHttpMethod(HttpClient::GET)->execute(); - + public function webElementGetCoordinates($elementId) + { + $command = "location"; + $urlHubFormatted = $this->_hubUrl . "/session/{$this->_sessionId}/element/{$elementId}/{$command}"; + + $httpClient = HttpFactory::getClient($this->_environment); + $results = $httpClient->setUrl($urlHubFormatted)->setHttpMethod(HttpClient::GET)->execute(); + $result = null; if (isset($results["value"]) && is_array($results["value"])) { $result = $results ["value"]; } - return $result; + return $result; } /** @@ -715,19 +809,19 @@ public function webElementGetCoordinates($elementId) * @param Integer $elementId * @return Array */ - public function webElementGetLocationOnScreenOnceScrolledIntoView($elementId) - { - $command = "location_in_view"; - $urlHubFormatted = $this->_hubUrl . "/session/{$this->_sessionId}/element/{$elementId}/{$command}"; - - $httpClient = HttpFactory::getClient($this->_environment); - $results = $httpClient->setUrl($urlHubFormatted)->setHttpMethod(HttpClient::GET)->execute(); - - $result = null; - if (isset($results["value"]) && is_array($results["value"])) { - $result = $results ["value"]; - } - return $result; + public function webElementGetLocationOnScreenOnceScrolledIntoView($elementId) + { + $command = "location_in_view"; + $urlHubFormatted = $this->_hubUrl . "/session/{$this->_sessionId}/element/{$elementId}/{$command}"; + + $httpClient = HttpFactory::getClient($this->_environment); + $results = $httpClient->setUrl($urlHubFormatted)->setHttpMethod(HttpClient::GET)->execute(); + + $result = null; + if (isset($results["value"]) && is_array($results["value"])) { + $result = $results ["value"]; + } + return $result; } #endregion @@ -761,11 +855,16 @@ private function executeScriptInternal($script, $async, $args) $command = "execute"; if($async === true) { $command = "execute_async"; } - - if($args == null) { $args = array(); } - $params = array ('script' => $script, 'args' => $args); + $params = array ('script' => $script, 'args' => array()); $urlHubFormatted = $this->_hubUrl . "/session/{$this->_sessionId}/{$command}"; + + foreach ((array)$args as $arg) { + if ($arg instanceof WebElement) { + $arg = array('ELEMENT' => $arg->getElementId()); + } + $params['args'][] = $arg; + } $httpClient = HttpFactory::getClient($this->_environment); $results = $httpClient->setUrl($urlHubFormatted)->setHttpMethod(HttpClient::POST)->setJsonParams($params)->execute(); diff --git a/SeleniumClient/WebDriverWait.php b/SeleniumClient/WebDriverWait.php index c93bd34..13d5be1 100644 --- a/SeleniumClient/WebDriverWait.php +++ b/SeleniumClient/WebDriverWait.php @@ -15,7 +15,7 @@ namespace SeleniumClient; -require_once("Exceptions.php"); +require_once __DIR__ . '/Exceptions.php'; class WebDriverWait { @@ -44,59 +44,50 @@ public function getSeconds() */ public function until($seleniumObject, $method, array $args) { - if (!isset($seleniumObject)) { throw new \Exception("seleniumObject parameter has not been initialized"); } - else if (!isset($method)) { throw new \Exception("method parameter has not been initialized"); } + if (!isset($seleniumObject)) { + throw new \Exception("seleniumObject parameter has not been initialized"); + } else if (!isset($method)) { + throw new \Exception("method parameter has not been initialized"); + } + + $seconds = $this->_seconds; + $elapsed = -1; + $start = microtime(true); + + while ($elapsed < $seconds) { + // the amount of time to sleep until the next whole second + if ($elapsed > 0 && ($sleep = 1000000 * (1 - ($elapsed - (int)$elapsed))) > 0) { + usleep($sleep); + } - $seconds = $this->_seconds; - - $wait = true; - - while ($wait) - { try { $resultObject = call_user_func_array(array ($seleniumObject, $method), $args); + if ($resultObject !== null && $resultObject !== false) { + return $resultObject; + } } catch (\Exception $ex) { - } - - if ($resultObject != null && $resultObject != false) { $wait = false; } - else - { - if ($seconds <= 0) - { - $exMessage = "Timeout for specified condition caused by object of class: " . get_class($seleniumObject) . ", method invoked: ". $method . "."; - - if($args != null && count($args) > 0) - { - $stringArgs = Array(); - foreach($args as $arg) - { - if(is_object($arg) && method_exists( $arg, '__toString' )) - { - $stringArgs[] = $arg; - } - else if(is_object($arg) && !method_exists( $arg, '__toString' )) - { - $stringArgs[] = get_class($arg); - } - else - { - $stringArgs[] = $arg; - } - } - - $exMessage .= " Arguments: <" . implode(">,<",$stringArgs).">"; - } - - throw new WebDriverWaitTimeoutException ($exMessage); - } - - sleep(1); - - $seconds = $seconds - 1; - } - } - return $resultObject; + $elapsed = microtime(true) - $start; + } + + $exMessage = "Timeout for specified condition caused by object of class: " . get_class($seleniumObject) . ", method invoked: " . $method . "."; + + if ($args != null && count($args) > 0) { + $stringArgs = Array(); + foreach ($args as $arg) { + if (is_object($arg) && method_exists($arg, '__toString')) { + $stringArgs[] = $arg; + } else if (is_object($arg) && !method_exists($arg, '__toString')) { + $stringArgs[] = get_class($arg); + } else { + $stringArgs[] = $arg; + } + } + + $exMessage .= " Arguments: <" . implode(">,<", $stringArgs) . ">"; + } + + throw new WebDriverWaitTimeoutException ($exMessage); } } \ No newline at end of file diff --git a/SeleniumClient/WebElement.php b/SeleniumClient/WebElement.php index e05680f..51b7895 100644 --- a/SeleniumClient/WebElement.php +++ b/SeleniumClient/WebElement.php @@ -17,6 +17,20 @@ use SeleniumClient\Http\SeleniumStaleElementReferenceException; +/** + * @param string $value The attribute value + * + * @method \SeleniumClient\WebElement setClassName($value) Set element's class name + * @method \SeleniumClient\WebElement setInnerHTML($value) Set element's inner html + * @method void setOuterHTML($value) Set element's outer html + * @method \SeleniumClient\WebElement setText($value) Set element's text + * @method \SeleniumClient\WebElement setValue($value) Set element's value + * + * @method string getClassName() Get element's class name + * @method string getInnerHTML() Get element's inner html + * @method string getOuterHTML() Get element's outer html + * @method string getValue() Get element's value + */ class WebElement { private $_driver = null; @@ -27,6 +41,30 @@ function __construct(WebDriver $driver, $elementId) $this->_driver = $driver; $this->_elementId = $elementId; } + + /** + * @param string $name + * @param array $args + * @return mixed + * @throws \Exception + */ + public function __call($name, array $args) + { + $whitelist = array('className', 'innerHTML', 'outerHTML', 'text', 'value'); + $method = lcfirst(substr($name, 3)); + $operation = in_array($method, $whitelist) ? substr($name, 0, 3) : ''; + + switch ($operation) { + case 'set': + $this->setAttribute($method, $args[0]); + return ($method != 'outerHTML') ? $this : null; + case 'get': + return $this->getAttribute($method); + break; + default: + throw new \Exception('Invalid magic call'); + } + } /** * Gets element's id @@ -51,7 +89,24 @@ public function getText() { return $this->_driver->webElementGetText($this->_ele * @return String */ public function getTagName() { return $this->_driver->webElementGetTagName($this->_elementId); } - + + /** + * Sets element's specified attribute's value + * @param string $attributeName The element's attribute name + * @param string $value The value to set the attribute + * @return $this + */ + public function setAttribute($attributeName, $value) + { + $key = $attributeName == 'text' // detect whether to use textContent or innerText + ? 'var k=typeof arguments[0].textContent!="undefined"?"textContent":"innerText"' + : sprintf('var k="%s"', addslashes($attributeName)); + + $script = sprintf("{$key};arguments[0][k]='%s';return true", addslashes($value)); + $this->_driver->executeScript( $script, array( array( 'ELEMENT' => $this->getElementId() ) ) ); + return $this; + } + /** * Gets element's specified attribute's value * @param String $attributeName @@ -102,7 +157,40 @@ public function submit() { $this->_driver->webElementSubmit($this->_elementId); * @return Array */ public function describe() { return $this->_driver->webElementDescribe($this->_elementId); } - + + /** + * @param string $class + * @return $this + */ + public function addClass($class) + { + $script = sprintf("if(!arguments[0].className.match(/\b{$class}\b/))arguments[0].className+=' {$class}'"); + $this->_driver->executeScript($script, array(array('ELEMENT' => $this->_elementId))); + return $this; + } + + /** + * @param string $class + * @return $this + */ + public function hasClass($class) + { + $script = sprintf("return arguments[0].className.match(/\b{$class}\b/)"); + $this->_driver->executeScript($script, array(array('ELEMENT' => $this->_elementId))); + return $this; + } + + /** + * @param string $class + * @return $this + */ + public function removeClass($class) + { + $script = sprintf("arguments[0].className = arguments[0].className.replace(/\b{$class}\b/, '').replace(/\s{2,}/, ' ').replace(/^\s+|\s+$/, '')"); + $this->_driver->executeScript($script, array(array('ELEMENT' => $this->_elementId))); + return $this; + } + /** * Get element's coordinates * @return Array @@ -114,28 +202,28 @@ public function getCoordinates() {return $this->_driver->webElementGetCoordinate * @return Array */ public function getLocationOnScreenOnceScrolledIntoView() {return $this->_driver->webElementGetLocationOnScreenOnceScrolledIntoView($this->_elementId);} - + /** * Find element within current element * @param By $locator * @param Boolean $polling - * @return SeleniumClient\WebElement + * @return \SeleniumClient\WebElement */ - public function findElement(By $locator, $polling = false) { return $this->_driver->webElementFindElement($this->_elementId, $locator, $polling); } + public function findElement(By $locator, $polling = false) { return $this->_driver->findElement($locator, $polling, $this->_elementId); } /** * Find elements within current element * @param By $locator - * @param Bolean $polling - * @return Array SeleniumClient\WebElement + * @param Boolean $polling + * @return \SeleniumClient\WebElement[] */ - public function findElements(By $locator, $polling = false) { return $this->_driver->webElementFindElements($this->_elementId, $locator, $polling); } + public function findElements(By $locator, $polling = false) { return $this->_driver->findElements($locator, $polling, $this->_elementId); } /** * Wait for expected element to be present within current element * @param By $locator * @param Integer $timeOutSeconds - * @return Ambiguous + * @return mixed */ public function waitForElementUntilIsPresent(By $locator, $timeOutSeconds = 5) { @@ -144,7 +232,7 @@ public function waitForElementUntilIsPresent(By $locator, $timeOutSeconds = 5) $wait = new WebDriverWait($timeOutSeconds); - $dynamicElement = $wait->until($this, "findElement", array($locator, TRUE)); + $dynamicElement = $wait->until($this, "findElement", array($locator, true)); return $dynamicElement; } @@ -232,7 +320,7 @@ public function waitForElementUntilIsPresentWithSpecificText(By $locator, $targe $currentText = null; $webDriverWait = new WebDriverWait($timeOutSeconds); - $dynamicElement = $webDriverWait->until($this, "findElement", array($locator, TRUE)); + $dynamicElement = $webDriverWait->until($this, "findElement", array($locator, true)); try { diff --git a/SeleniumClientTest/Demo/AutoLoader.php b/SeleniumClientTest/Demo/AutoLoader.php deleted file mode 100644 index 0f27c99..0000000 --- a/SeleniumClientTest/Demo/AutoLoader.php +++ /dev/null @@ -1,17 +0,0 @@ -_driver->get($this->_testUrl); //access text input - $webElement = $this->_driver->findElement(By::id("txt1")); - $webElement->clear(); + $webElement = $this->_driver->findElement(By::id("txt1")); + $webElement->clear(); $webElement->sendKeys("Text sent 1"); $this->assertEquals("Text sent 1", $webElement->getAttribute("value")); - $webElement = $this->_driver->findElement(By::id("txt2")); - $webElement->clear(); + $webElement = $this->_driver->findElement(By::id("txt2")); + $webElement->clear(); $webElement->sendKeys("Text sent 2"); - + $this->assertEquals("Text sent 2", $webElement->getAttribute("value")); //access listbox @@ -50,25 +53,23 @@ public function testDemo1() $this->assertTrue($selectElement->getElement()->findElement(By::xPath(".//option[@value = 4]"))->isSelected()); - //access checkbox - $webElement = $this->_driver->findElement(By::cssSelector("html body table tbody tr td fieldset form p input#chk3")); - $webElement->click(); + //access checkbox + $webElement = $this->_driver->findElement(By::id("chk3")); + $webElement->click(); $this->assertTrue($webElement->isSelected()); - //access radio - $webElement = $this->_driver->findElement(By::id("rd3")); - $webElement->click(); - + //access radio + $webElement = $this->_driver->findElement(By::id("rd3")); + $webElement->click(); + $this->assertTrue($webElement->isSelected()); - //access button - $webElement = $this->_driver->findElement(By::id("btnSubmit")); - $webElement->click(); + //access button + $webElement = $this->_driver->findElement(By::id("btnSubmit")); + $webElement->click(); - //access h2 - $webElement = $this->_driver->findElement(By::cssSelector("html body h2#h2FormReceptor")); + //access h2 + $webElement = $this->_driver->findElement(By::cssSelector("html body h2#h2FormReceptor")); $this->assertEquals("Form receptor", $webElement->getText()); - - sleep(20); } } \ No newline at end of file diff --git a/SeleniumClientTest/Demo/Demo2.php b/SeleniumClientTest/Demo/Demo2.php index 8d6de9e..b7218c6 100644 --- a/SeleniumClientTest/Demo/Demo2.php +++ b/SeleniumClientTest/Demo/Demo2.php @@ -1,16 +1,18 @@ _driver->get($this->_testUrl); + $this->_driver->get($this->_testUrl); $this->_driver->findElement(By::id("btnAlert"))->click(); $this->assertEquals("Here is the alert", $this->_driver->getAlertText()); $this->_driver->acceptAlert(); @@ -39,14 +41,14 @@ public function testDemo2() $mainWindowHandle = $this->_driver->getCurrentWindowHandle(); //open popup window / handle its elements - $this->_driver->findElement(By::id("btnPopUp1"))->click(); + $this->_driver->findElement(By::id("btnPopUp1"))->click(); $this->_driver->switchTo()->getWindow("popup1"); - + $webElement = $this->_driver->waitForElementUntilIsPresent(By::id("txt1")); - - $webElement->sendKeys("test window"); - + + $webElement->sendKeys("test window"); + $this->assertEquals("test window", $webElement->getAttribute("value")); $this->_driver->closeCurrentWindow(); @@ -54,19 +56,19 @@ public function testDemo2() $this->_driver->switchTo()->getWindow($mainWindowHandle); //get iframe / handle its elements - $this->_driver->getFrame("iframe1"); - - $webElement = $this->_driver->waitForElementUntilIsPresent(By::id("txt1")); - $webElement->sendKeys("test iframe"); - + $this->_driver->getFrame("iframe1"); + + $webElement = $this->_driver->waitForElementUntilIsPresent(By::id("txt1")); + $webElement->sendKeys("test iframe"); + $this->assertEquals("test iframe", $webElement->getAttribute("value")); $this->_driver->switchTo()->getWindow($mainWindowHandle); //wait for element to be present - $this->_driver->findElement(By::id("btnAppendDiv"))->click(); - $wait = new WebDriverWait(8); - $label = $wait->until($this->_driver,"findElement",array(By::id("dDiv1-0"),true)); + $this->_driver->findElement(By::id("btnAppendDiv"))->click(); + $wait = new WebDriverWait(8); + $label = $wait->until($this->_driver,"findElement",array(By::id("dDiv1-0"),true)); $this->assertEquals("Some content",$label->getText()); sleep(5); diff --git a/SeleniumClientTest/Tests/AbstractTest.php b/SeleniumClientTest/Tests/AbstractTest.php new file mode 100644 index 0000000..1d2e693 --- /dev/null +++ b/SeleniumClientTest/Tests/AbstractTest.php @@ -0,0 +1,125 @@ +quit(); + } catch ( Exception $e ) { + } + } + } ); + + $initialized = true; + } + + public function setUp() + { + $this->_url = self::$_config['url']; + $browser = self::$_config['browser']; + + if ( self::$_config['persist'] ) { + if ( !self::$_handle ) { + $capabilities = new DesiredCapabilities( $browser ); + $driver = new WebDriver( $capabilities ); + self::$_driverInstances[] = $driver; + } else { + /** @var $driver WebDriver */ + $driver = end( self::$_driverInstances ); + } + } else { + $capabilities = new DesiredCapabilities( $browser ); + $driver = new WebDriver( $capabilities ); + self::$_driverInstances[] = $driver; + } + + $this->_driver = $driver; + $this->_driver->get($this->_url); + $this->_position = $this->_driver->getCurrentWindowPosition(); + $this->_size = $this->_driver->getCurrentWindowSize(); + self::$_handle = $this->_driver->getCurrentWindowHandle(); + } + + public function tearDown() + { + // return if the driver wasn't initialized + if ( !$this->_driver ) { + return; + } + + if ( self::$_config['persist'] ) { + try { + $this->_driver->dismissAlert(); + } catch ( Exception $e ) { + } + try { + foreach ( $this->_driver->getCurrentWindowHandles() as $handle ) { + // skip the original window + if ( $handle == self::$_handle ) { + continue; + } + // try to close any other windows that were opened + try { + $this->_driver->getWindow( $handle ); + $this->_driver->closeCurrentWindow(); + } catch ( Exception $e ) { + } + } + $this->_driver->getWindow( self::$_handle ); + $this->_driver->getActiveElement(); + } catch ( SeleniumUnknownErrorException $e ) { + // test case may have closed the parent window + self::$_handle = null; + return; + } + $this->_driver->clearCurrentCookies(); + $this->_driver->setWindowPosition( self::$_handle, $this->_position['x'], $this->_position['y'] ); + $this->_driver->setWindowSize( self::$_handle, $this->_size['width'], $this->_size['height'] ); + } else { + try{ + $this->_driver->quit(); + } catch ( Exception $e ) { + } + } + } +} \ No newline at end of file diff --git a/SeleniumClientTest/Tests/AlertTest.php b/SeleniumClientTest/Tests/AlertTest.php index 9c6353f..bf94387 100644 --- a/SeleniumClientTest/Tests/AlertTest.php +++ b/SeleniumClientTest/Tests/AlertTest.php @@ -1,26 +1,21 @@ _driver = new WebDriver(); + parent::setUp(); $this->_alert = new Alert($this->_driver); } - - public function tearDown() - { - if($this->_driver != null) { $this->_driver->quit(); } - } - + /* * TODO: * consider no selenium server running @@ -30,8 +25,6 @@ public function tearDown() public function testGetAlertShouldGetAlertText() { - $this->_driver->get($this->_url); - $this->_driver->findElement(By::id("btnAlert"))->click(); $alertText = $this->_alert->getText(); @@ -41,8 +34,6 @@ public function testGetAlertShouldGetAlertText() public function testGetAlertShouldDismissAlert() { - $this->_driver->get($this->_url); - $this->_driver->findElement(By::id("btnConfirm"))->click(); $this->_alert->dismiss(); @@ -54,8 +45,6 @@ public function testGetAlertShouldDismissAlert() public function testGetAlertShouldAcceptAlert() { - $this->_driver->get($this->_url); - $this->_driver->findElement(By::id("btnConfirm"))->click(); $this->_alert->accept(); @@ -67,8 +56,6 @@ public function testGetAlertShouldAcceptAlert() public function testGetAlertShouldSendKeysToAlert() { - $this->_driver->get($this->_url); - $this->_driver->findElement(By::id("btnPrompt"))->click(); $this->_alert->sendKeys("alert text"); diff --git a/SeleniumClientTest/Tests/DesiredCapabilitiesTest.php b/SeleniumClientTest/Tests/DesiredCapabilitiesTest.php index 4998578..9656822 100644 --- a/SeleniumClientTest/Tests/DesiredCapabilitiesTest.php +++ b/SeleniumClientTest/Tests/DesiredCapabilitiesTest.php @@ -7,16 +7,6 @@ class DesiredCapabilitiesTest extends PHPUnit_Framework_TestCase { private $_capability = null; - public function setUp() - { - - } - - public function tearDown() - { - - } - public function testDesiredCapabilityShouldConstruct() { $this->_capability = new DesiredCapabilities('firefox','3.6','windows'); diff --git a/SeleniumClientTest/Tests/SelectElementTest.php b/SeleniumClientTest/Tests/SelectElementTest.php index 4c45d2e..845fc74 100644 --- a/SeleniumClientTest/Tests/SelectElementTest.php +++ b/SeleniumClientTest/Tests/SelectElementTest.php @@ -1,57 +1,40 @@ _driver = new WebDriver(); - } - - public function tearDown() - { - if($this->_driver != null) { $this->_driver->quit(); } - } - public function testSelectByValueShouldSelect() { - $this->_driver->get($this->_url); - $select = new SelectElement($this->_driver->findElement(By::id("sel1"))); $select->selectByValue("2"); $this->assertTrue($select->getElement()->findElement(By::xPath("option[@value = 2]"))->isSelected()); - $select = new SelectElement($this->_driver->findElement(By::id("sel2"))); - - $select->selectByValue("onions"); - + $select = new SelectElement($this->_driver->findElement(By::id("sel2"))); + + $select->selectByValue("onions"); + $this->assertTrue($select->getElement()->findElement(By::xPath("option[@value = 'onions']"))->isSelected()); } - public function testSelectByPartialTextShouldSelect() - { - $this->_driver->get($this->_url); - - $select = new SelectElement($this->_driver->findElement(By::id("sel1"))); - - $select->selectByPartialText("Red"); - - $this->assertTrue($select->getElement()->findElement(By::xPath("option[@value = 2]"))->isSelected()); - - $select = new SelectElement($this->_driver->findElement(By::id("sel2"))); - - $select->selectByPartialText("peppers"); - - $this->assertTrue($select->getElement()->findElement(By::xPath("option[@value = 'greenpeppers']"))->isSelected()); + public function testSelectByPartialTextShouldSelect() + { + $select = new SelectElement($this->_driver->findElement(By::id("sel1"))); + + $select->selectByPartialText("Red"); + + $this->assertTrue($select->getElement()->findElement(By::xPath("option[@value = 2]"))->isSelected()); + + $select = new SelectElement($this->_driver->findElement(By::id("sel2"))); + + $select->selectByPartialText("peppers"); + + $this->assertTrue($select->getElement()->findElement(By::xPath("option[@value = 'greenpeppers']"))->isSelected()); } } diff --git a/SeleniumClientTest/Tests/TargetLocatorTest.php b/SeleniumClientTest/Tests/TargetLocatorTest.php index 1f73595..198465c 100644 --- a/SeleniumClientTest/Tests/TargetLocatorTest.php +++ b/SeleniumClientTest/Tests/TargetLocatorTest.php @@ -1,28 +1,23 @@ _driver = new WebDriver(); + parent::setUp(); $this->_targetLocator = new TargetLocator($this->_driver); } - public function tearDown() - { - if($this->_driver != null) { $this->_driver->quit(); } - } - /* * TODO: * consider no selenium server running @@ -32,8 +27,6 @@ public function tearDown() public function testGetDefaultFrameShouldGetFrameWebElement() { - $this->_driver->get($this->_url); - $webElement = $this->_targetLocator->getDefaultFrame()->findElement(By::id("txt1")); $webElement->sendKeys("test iframe"); @@ -42,8 +35,6 @@ public function testGetDefaultFrameShouldGetFrameWebElement() public function testGetFrameByIndexShouldGetFrameWebElement() { - $this->_driver->get($this->_url); - $webElement = $this->_targetLocator->getFrameByIndex(0)->findElement(By::id("txt1")); $webElement->sendKeys("test iframe"); @@ -52,8 +43,6 @@ public function testGetFrameByIndexShouldGetFrameWebElement() public function testGetFrameByIndexShouldGetFrameWebElementGetBackToParentWindow() { - $this->_driver->get($this->_url); - $webElement = $this->_targetLocator->getFrameByIndex(0)->findElement(By::id("txt1")); $webElement->sendKeys("test iframe"); @@ -72,8 +61,6 @@ public function testGetFrameByIndexShouldGetFrameWebElementGetBackToParentWindow public function testGetFrameByNameShouldGetFrameWebElement() { - $this->_driver->get($this->_url); - $webElement = $this->_targetLocator->getFrameByName("iframe1")->findElement(By::id("txt1")); $webElement->sendKeys("test iframe"); @@ -82,8 +69,6 @@ public function testGetFrameByNameShouldGetFrameWebElement() public function testGetFrameByNameShouldGetFrameWebElementGetBackToParentWindow() { - $this->_driver->get($this->_url); - $webElement = $this->_targetLocator->getFrameByName("iframe1")->findElement(By::id("txt1")); $webElement->sendKeys("test iframe"); @@ -102,8 +87,6 @@ public function testGetFrameByNameShouldGetFrameWebElementGetBackToParentWindow( public function testGetFrameByWebElementShouldGetFrameWebElement() { - $this->_driver->get($this->_url); - $webElement = $this->_driver->findElement(By::id("iframe1")); $webElement = $this->_targetLocator->getFrameByWebElement($webElement)->findElement(By::id("txt1")); $webElement->sendKeys("test iframe"); @@ -113,8 +96,6 @@ public function testGetFrameByWebElementShouldGetFrameWebElement() public function testGetFrameByWebElementShouldGetFrameWebElementGetBackToParentWindow() { - $this->_driver->get($this->_url); - $webElement = $this->_driver->findElement(By::id("iframe1")); $webElement = $this->_targetLocator->getFrameByWebElement($webElement)->findElement(By::id("txt1")); $webElement->sendKeys("test iframe"); @@ -135,8 +116,6 @@ public function testGetFrameByWebElementShouldGetFrameWebElementGetBackToParentW public function testGetWindowShouldGetWindowWebElement() { - $this->_driver->get($this->_url); - $this->_driver->findElement(By::id("btnPopUp1"))->click(); $webElement = $this->_targetLocator->getWindow("popup1")->waitForElementUntilIsPresent(By::id("txt1")); @@ -147,8 +126,6 @@ public function testGetWindowShouldGetWindowWebElement() public function testGetWindowShouldGetWindowWebElementGetBackToParentWindow() { - $this->_driver->get($this->_url); - $window1Handle = $this->_driver->getCurrentWindowHandle(); $this->_driver->findElement(By::id("btnPopUp1"))->click(); @@ -177,8 +154,6 @@ public function testGetWindowShouldGetWindowWebElementGetBackToParentWindow() public function testGetActiveElementShouldGetActiveElement() { - $this->_driver->get($this->_url); - $this->_driver->findElement(By::id("txt1"))->sendKeys("test"); $webElement = $this->_targetLocator->getActiveElement(); @@ -188,8 +163,6 @@ public function testGetActiveElementShouldGetActiveElement() public function testGetAlertShouldGetAlertInstance() { - $this->_driver->get($this->_url); - $this->_driver->findElement(By::id("btnAlert"))->click(); $alert = $this->_targetLocator->getAlert(); @@ -199,8 +172,6 @@ public function testGetAlertShouldGetAlertInstance() public function testGetAlertShouldGetAlertText() { - $this->_driver->get($this->_url); - $this->_driver->findElement(By::id("btnAlert"))->click(); $alertText = $this->_targetLocator->getAlert()->getText(); @@ -210,8 +181,6 @@ public function testGetAlertShouldGetAlertText() public function testGetAlertShouldDismissAlert() { - $this->_driver->get($this->_url); - $this->_driver->findElement(By::id("btnConfirm"))->click(); $this->_targetLocator->getAlert()->dismiss(); @@ -223,8 +192,6 @@ public function testGetAlertShouldDismissAlert() public function testGetAlertShouldAcceptAlert() { - $this->_driver->get($this->_url); - $this->_driver->findElement(By::id("btnConfirm"))->click(); $this->_targetLocator->getAlert()->accept(); @@ -236,8 +203,6 @@ public function testGetAlertShouldAcceptAlert() public function testGetAlertShouldSendKeysToAlert() { - $this->_driver->get($this->_url); - $this->_driver->findElement(By::id("btnPrompt"))->click(); $alert = $this->_targetLocator->getAlert(); @@ -248,5 +213,17 @@ public function testGetAlertShouldSendKeysToAlert() $this->assertEquals("alert text", $alertText); } + + public function testNewTabShouldGetNewWindow() + { + $oldHandle1 = $this->_driver->getCurrentWindowHandle(); + $numHandles = count($this->_driver->getCurrentWindowHandles()); + $oldHandle2 = $this->_targetLocator->newTab($this->_url); + $this->assertEquals($oldHandle1, $oldHandle2); + $newHandle = $this->_driver->getCurrentWindowHandle(); + $this->assertNotEquals($oldHandle1, $newHandle); + $this->assertEquals($numHandles + 1, count($this->_driver->getCurrentWindowHandles())); + } + //TODO TEST WITH INVALID URL, INVALID PORT INVALID BROWSERNAME } \ No newline at end of file diff --git a/SeleniumClientTest/Tests/WebDriverTest.php b/SeleniumClientTest/Tests/WebDriverTest.php index 5ea0ba2..4e45504 100644 --- a/SeleniumClientTest/Tests/WebDriverTest.php +++ b/SeleniumClientTest/Tests/WebDriverTest.php @@ -1,27 +1,15 @@ _driver = new WebDriver(); } - - public function tearDown() - { - if($this->_driver != null) { $this->_driver->quit(); } - } - /* * TODO: * consider no selenium server running @@ -31,7 +19,6 @@ public function tearDown() public function testAcceptAlertShouldGetText() { - $this->_driver->get($this->_url); $this->_driver->findElement(By::id("btnConfirm"))->click(); $this->_driver->acceptAlert(); $this->assertEquals("TRUE", strtoupper($this->_driver->getAlertText())); @@ -39,7 +26,6 @@ public function testAcceptAlertShouldGetText() public function testDismissAlertShouldGetText() { - $this->_driver->get($this->_url); $this->_driver->findElement(By::id("btnConfirm"))->click(); $this->_driver->dismissAlert(); $this->assertEquals("FALSE", strtoupper($this->_driver->getAlertText())); @@ -47,7 +33,6 @@ public function testDismissAlertShouldGetText() public function testSetPromptTextShouldGetText() { - $this->_driver->get($this->_url); $this->_driver->findElement(By::id("btnPrompt"))->click(); $this->_driver->setAlertValue("Some value sent"); $this->_driver->acceptAlert(); @@ -56,7 +41,6 @@ public function testSetPromptTextShouldGetText() public function testGetAlertTextShouldGetText() { - $this->_driver->get($this->_url); $this->_driver->findElement(By::id("btnAlert"))->click(); $this->assertEquals("Here is the alert", $this->_driver->getAlertText()); } @@ -70,8 +54,6 @@ public function testSwitchToShouldGetTargetLocatorInstance() public function testSwitchToDefaultFrameShouldGetFrameWebElement() { - $this->_driver->get($this->_url); - $webElement = $this->_driver->switchTo()->getDefaultFrame()->findElement(By::id("txt1")); $webElement->sendKeys("test iframe"); @@ -80,8 +62,6 @@ public function testSwitchToDefaultFrameShouldGetFrameWebElement() public function testSwitchToFrameByIndexShouldGetFrameWebElement() { - $this->_driver->get($this->_url); - $webElement = $this->_driver->switchTo()->getFrameByIndex(0)->findElement(By::id("txt1")); $webElement->sendKeys("test iframe"); @@ -90,8 +70,6 @@ public function testSwitchToFrameByIndexShouldGetFrameWebElement() public function testSwitchToFrameByIndexShouldGetFrameWebElementGetBackToParentWindow() { - $this->_driver->get($this->_url); - $webElement = $this->_driver->switchTo()->getFrameByIndex(0)->findElement(By::id("txt1")); $webElement->sendKeys("test iframe"); @@ -110,8 +88,6 @@ public function testSwitchToFrameByIndexShouldGetFrameWebElementGetBackToParentW public function testSwitchToFrameByNameShouldGetFrameWebElement() { - $this->_driver->get($this->_url); - $webElement = $this->_driver->switchTo()->getFrameByName("iframe1")->findElement(By::id("txt1")); $webElement->sendKeys("test iframe"); @@ -120,8 +96,6 @@ public function testSwitchToFrameByNameShouldGetFrameWebElement() public function testSwitchToFrameByNameShouldGetFrameWebElementGetBackToParentWindow() { - $this->_driver->get($this->_url); - $webElement = $this->_driver->switchTo()->getFrameByName("iframe1")->findElement(By::id("txt1")); $webElement->sendKeys("test iframe"); @@ -140,8 +114,6 @@ public function testSwitchToFrameByNameShouldGetFrameWebElementGetBackToParentWi public function testSwitchToFrameByWebElementShouldGetFrameWebElement() { - $this->_driver->get($this->_url); - $webElement = $this->_driver->findElement(By::id("iframe1")); $webElement = $this->_driver->switchTo()->getFrameByWebElement($webElement)->findElement(By::id("txt1")); $webElement->sendKeys("test iframe"); @@ -151,8 +123,6 @@ public function testSwitchToFrameByWebElementShouldGetFrameWebElement() public function testSwitchToFrameByWebElementShouldGetFrameWebElementGetBackToParentWindow() { - $this->_driver->get($this->_url); - $webElement = $this->_driver->findElement(By::id("iframe1")); $webElement = $this->_driver->switchTo()->getFrameByWebElement($webElement)->findElement(By::id("txt1")); $webElement->sendKeys("test iframe"); @@ -173,8 +143,6 @@ public function testSwitchToFrameByWebElementShouldGetFrameWebElementGetBackToPa public function testSwitchToGetWindowShouldGetWindowWebElement() { - $this->_driver->get($this->_url); - $this->_driver->findElement(By::id("btnPopUp1"))->click(); $webElement = $this->_driver->switchTo()->getWindow("popup1")->waitForElementUntilIsPresent(By::id("txt1")); @@ -185,8 +153,6 @@ public function testSwitchToGetWindowShouldGetWindowWebElement() public function testSwitchToGetWindowShouldGetWindowWebElementGetBackToParentWindow() { - $this->_driver->get($this->_url); - $window1Handle = $this->_driver->getCurrentWindowHandle(); $this->_driver->findElement(By::id("btnPopUp1"))->click(); @@ -215,8 +181,6 @@ public function testSwitchToGetWindowShouldGetWindowWebElementGetBackToParentWin public function testSwitchToGetActiveElementShouldGetActiveElement() { - $this->_driver->get($this->_url); - $this->_driver->findElement(By::id("txt1"))->sendKeys("test"); $webElement = $this->_driver->switchTo()->getActiveElement(); @@ -226,8 +190,6 @@ public function testSwitchToGetActiveElementShouldGetActiveElement() public function testSwitchToGetAlertShouldGetAlertInstance() { - $this->_driver->get($this->_url); - $this->_driver->findElement(By::id("btnAlert"))->click(); $alert = $this->_driver->switchTo()->getAlert(); @@ -237,8 +199,6 @@ public function testSwitchToGetAlertShouldGetAlertInstance() public function testSwitchToGetAlertShouldGetAlertText() { - $this->_driver->get($this->_url); - $this->_driver->findElement(By::id("btnAlert"))->click(); $alertText = $this->_driver->switchTo()->getAlert()->getText(); @@ -248,8 +208,6 @@ public function testSwitchToGetAlertShouldGetAlertText() public function testSwitchToGetAlertShouldDismissAlert() { - $this->_driver->get($this->_url); - $this->_driver->findElement(By::id("btnConfirm"))->click(); $this->_driver->switchTo()->getAlert()->dismiss(); @@ -261,8 +219,6 @@ public function testSwitchToGetAlertShouldDismissAlert() public function testSwitchToGetAlertShouldAcceptAlert() { - $this->_driver->get($this->_url); - $this->_driver->findElement(By::id("btnConfirm"))->click(); $this->_driver->switchTo()->getAlert()->accept(); @@ -274,8 +230,6 @@ public function testSwitchToGetAlertShouldAcceptAlert() public function testSwitchToGetAlertShouldSendKeysToAlert() { - $this->_driver->get($this->_url); - $this->_driver->findElement(By::id("btnPrompt"))->click(); $alert = $this->_driver->switchTo()->getAlert(); @@ -289,10 +243,12 @@ public function testSwitchToGetAlertShouldSendKeysToAlert() public function testClearCookieShouldClear() { - $this->_driver->get($this->_url); + $url = parse_url( $this->_url ); + $host = strpos( $url['host'], '.' ) !== false ? $url['host'] : null; + $this->_driver->setCookie("test", "1"); $this->_driver->setCookie("test2","2", "/"); - $this->_driver->setCookie("test3", "3", "/", "hostei.com", true, 0); + $this->_driver->setCookie("test3", "3", "/", $host, false, 0); $this->assertEquals(3, count($this->_driver->getCurrentCookies())); $this->_driver->clearCookie("test2"); @@ -302,10 +258,12 @@ public function testClearCookieShouldClear() public function testClearCurrentCookiesShouldClear() { - $this->_driver->get($this->_url); + $url = parse_url( $this->_url ); + $host = strpos( $url['host'], '.' ) !== false ? $url['host'] : null; + $this->_driver->setCookie("test", "1"); $this->_driver->setCookie("test2", "2", "/"); - $this->_driver->setCookie("test3", "3", "/", "hostei.com", true, 0); + $this->_driver->setCookie("test3", "3", "/", $host, false, 0); $this->assertEquals(3, count($this->_driver->getCurrentCookies())); $this->_driver->clearCurrentCookies(); @@ -315,10 +273,12 @@ public function testClearCurrentCookiesShouldClear() public function testSetGetCookiesShouldSetGet() { - $this->_driver->get($this->_url); + $url = parse_url( $this->_url ); + $host = strpos( $url['host'], '.' ) !== false ? $url['host'] : null; + $this->_driver->setCookie("test", "1"); $this->_driver->setCookie("test2", "2", "/"); - $this->_driver->setCookie("test3", "3", "/", "hostei.com", true, 0); + $this->_driver->setCookie("test3", "3", "/", $host, false, 0); $this->assertTrue(is_array($this->_driver->getCurrentCookies())); $this->assertEquals(3, count($this->_driver->getCurrentCookies())); @@ -327,8 +287,6 @@ public function testSetGetCookiesShouldSetGet() public function testScreenshotsShouldCreateFile() { - $this->_driver->get($this->_url); - $screenShotsDirectory = "/tmp/selenium screenshots"; if (!file_exists($screenShotsDirectory)) { mkdir($screenShotsDirectory, 0755, true); } @@ -356,8 +314,6 @@ public function testScreenshotsShouldCreateFile() public function testScreenshotsShouldCreateFile2() { - $this->_driver->get($this->_url); - $screenShotsDirectory = "/tmp/selenium screenshots"; if (!file_exists($screenShotsDirectory)) { @@ -387,8 +343,6 @@ public function testScreenshotsShouldCreateFile2() public function testGetWindowPositionShouldGetArray() { - $this->_driver->get($this->_url); - $window1Handle = $this->_driver->getCurrentWindowHandle(); $position = $this->_driver->getWindowPosition($window1Handle); @@ -399,7 +353,6 @@ public function testGetWindowPositionShouldGetArray() public function testGetCurrentWindowPositionShouldGetArray() { - $this->_driver->get($this->_url); $position = $this->_driver->getCurrentWindowPosition(); $this->assertTrue(is_numeric($position["x"])); @@ -408,7 +361,6 @@ public function testGetCurrentWindowPositionShouldGetArray() public function testSetWindowPositionShouldGetArray() { - $this->_driver->get($this->_url); $window1Handle = $this->_driver->getCurrentWindowHandle(); $this->_driver->setWindowSize($window1Handle, 200,200); @@ -423,8 +375,6 @@ public function testSetWindowPositionShouldGetArray() public function testSetCurrentWindowPositionShouldGetArray() { - $this->_driver->get($this->_url); - $this->_driver->setCurrentWindowSize(200,200); $this->_driver->setCurrentWindowPosition(50, 60); @@ -437,7 +387,6 @@ public function testSetCurrentWindowPositionShouldGetArray() public function testGetWindowSizeShouldGetArray() { - $this->_driver->get($this->_url); $window1Handle = $this->_driver->getCurrentWindowHandle(); $dimensions = $this->_driver->getWindowSize($window1Handle); @@ -447,7 +396,6 @@ public function testGetWindowSizeShouldGetArray() public function testGetCurrentWindowSizeShouldGetArray() { - $this->_driver->get($this->_url); $dimensions = $this->_driver->getCurrentWindowSize(); $this->assertTrue(is_numeric($dimensions["width"])); @@ -456,7 +404,6 @@ public function testGetCurrentWindowSizeShouldGetArray() public function testSetWindowSizeShouldGetArray() { - $this->_driver->get($this->_url); $window1Handle = $this->_driver->getCurrentWindowHandle(); $this->_driver->setWindowSize($window1Handle, 432, 520); @@ -468,7 +415,6 @@ public function testSetWindowSizeShouldGetArray() public function testSetCurrentWindowSizeShouldGetArray() { - $this->_driver->get($this->_url); $this->_driver->setCurrentWindowSize(432, 520); $dimensions = $this->_driver->getCurrentWindowSize(); @@ -478,7 +424,6 @@ public function testSetCurrentWindowSizeShouldGetArray() public function testGetWindowShouldNavigateAcrossWindows() { - $this->_driver->get($this->_url); $this->_driver->setImplicitWait(5000); $window1Handle = $this->_driver->getCurrentWindowHandle(); @@ -501,13 +446,11 @@ public function testGetWindowShouldNavigateAcrossWindows() public function testGetCurrentWindowHandleSholdGetHandle() { - $this->_driver->get($this->_url); $this->assertTrue(is_string($this->_driver->getCurrentWindowHandle())); } public function testGetCurrentWindowHandlesSholdGet3Handles() { - $this->_driver->get($this->_url); $this->_driver->findElement(By::id("btnPopUp1"))->click(); $this->_driver->findElement(By::id("btnPopUp2"))->click(); @@ -516,7 +459,6 @@ public function testGetCurrentWindowHandlesSholdGet3Handles() public function testCloseCurrentWindowShouldClose() { - $this->_driver->get($this->_url); $this->_driver->findElement(By::id("btnPopUp1"))->click(); $this->_driver->switchTo()->getWindow("popup1"); $this->_driver->closeCurrentWindow(); @@ -526,7 +468,6 @@ public function testCloseCurrentWindowShouldClose() public function testGetWindowShouldAccessContent() { - $this->_driver->get($this->_url); $this->_driver->findElement(By::id("btnPopUp1"))->click(); $this->_driver->switchTo()->getWindow("popup1"); @@ -538,7 +479,6 @@ public function testGetWindowShouldAccessContent() public function testGetFrameShouldAccessContent() { - $this->_driver->get($this->_url); $this->_driver->getFrame("iframe1"); $webElement = $this->_driver->findElement(By::id("txt1")); @@ -549,7 +489,6 @@ public function testGetFrameShouldAccessContent() public function testGetFrameShouldAccessContentGetBackParentWindow() { - $this->_driver->get($this->_url); $window1Handle = $this->_driver->getCurrentWindowHandle(); $this->_driver->getFrame("iframe1"); @@ -557,21 +496,23 @@ public function testGetFrameShouldAccessContentGetBackParentWindow() $webElement->sendKeys("test iframe"); $this->assertEquals("test iframe", $webElement->getAttribute("value")); - sleep(5); + //sleep(5); // doesn't appear to be required $this->_driver->switchTo()->getWindow($window1Handle); $webElementParentWindow = $this->_driver->findElement(By::id("txt1")); $webElementParentWindow->sendKeys("test parent window 1"); $this->assertEquals("test parent window 1", $webElementParentWindow->getAttribute("value")); - sleep(5); + //sleep(5); // doesn't appear to be required } - - public function testGetCurrentSessionsShouldGetArray() { $this->assertTrue(is_array($this->_driver->getCurrentSessions())); } + + public function testGetCurrentSessionsShouldGetArray() + { + $this->assertTrue(is_array($this->_driver->getCurrentSessions())); + } public function testExecuteScriptShouldSetInputText() { - $this->_driver->get($this->_url); $this->_driver->executeScript("document.getElementById('txt2').value='TEST!';"); $webElement = $this->_driver->findElement(By::id("txt2")); @@ -580,13 +521,11 @@ public function testExecuteScriptShouldSetInputText() public function testExecuteScriptShouldGetPageTitle() { - $this->_driver->get($this->_url); $this->assertEquals("Nearsoft SeleniumClient SandBox", $this->_driver->executeScript("return document.title")); } public function testExecuteScriptShouldSetInputTextUsingArguments() { - $this->_driver->get($this->_url); $this->_driver->executeScript("document.getElementById(arguments[0]).value=arguments[1];", array("txt1", "TEST2!")); $webElement = $this->_driver->findElement(By::id("txt1")); @@ -595,29 +534,29 @@ public function testExecuteScriptShouldSetInputTextUsingArguments() public function testSetAsyncScriptTimeout() { - $this->_driver->get($this->_url); $this->_driver->setAsyncScriptTimeout(10000); $this->assertNotEquals(null, $this->_driver); } public function testExecuteAsyncScriptShouldShowAlertKeepDriverInstance() { - $this->_driver->get($this->_url); $this->_driver->executeAsyncScript("arguments[arguments.length - 1](document.body);"); $this->assertNotEquals(null, $this->_driver); } - public function testGetCapabilitiesShouldGetInfo() { $this->assertTrue(is_array($this->_driver->getCapabilities())); } + public function testGetCapabilitiesShouldGetInfo() { + $this->assertTrue(is_array($this->_driver->getCapabilities())); + } public function testStartSessionShouldHaveSessionId() { $this->assertNotEquals(null, $this->_driver->getSessionId()); - $this->assertTrue(count($this->_driver->getSessionId())>0); + // SessionID appears to be a 36 character GUID + $this->assertGreaterThan(0, strlen($this->_driver->getSessionId())); } public function testGetShouldNavigateToUrl() { - $this->_driver->get($this->_url); $this->assertEquals($this->_url, $this->_driver->getCurrentPageUrl()); } @@ -629,32 +568,28 @@ public function testSetImplicitWait() public function testStatus() { - $this->assertTrue(is_array($this->_driver->status())); + $this->assertTrue(is_array($this->_driver->status())); } public function testRefresh() { - $this->assertNotEquals(null, $this->_driver); + $this->assertNotEquals(null, $this->_driver); } public function testPageSource() { - $this->_driver->get($this->_url); $this->assertTrue(is_string($this->_driver->pageSource())); $this->assertTrue(count($this->_driver->pageSource())>0); } public function testTitle() { - $this->_driver->get($this->_url); $this->assertTrue(is_string($this->_driver->title())); $this->assertTrue(count($this->_driver->title())>0); } public function testFindElement() { - $this->_driver->get($this->_url); - $webElement = $this->_driver->findElement(By::id("txt1")); $this->assertTrue($webElement instanceof WebElement); @@ -666,11 +601,17 @@ public function testFindElement() $this->assertEquals("9999", $webElement->getAttribute("value")); } + + public function testFindElementByJsSelector() + { + $input = $this->_driver->findElement(By::jsSelector('input','document.querySelectorAll')); + $this->assertTrue($input instanceof WebElement); + $this->setExpectedException('SeleniumClient\Http\SeleniumInvalidSelectorException'); + $this->_driver->findElement(By::jsSelector('input')); + } public function testFindElements() { - $this->_driver->get($this->_url); - $webElements = $this->_driver->findElements(By::tagName("input")); foreach($webElements as $webElement) { $this->assertTrue($webElement instanceof WebElement); } @@ -678,11 +619,21 @@ public function testFindElements() $this->assertTrue(is_array($webElements)); $this->assertTrue(count($webElements)>0); } + + public function testFindElementsByJsSelector() + { + $inputs = $this->_driver->findElements(By::jsSelector('input','document.querySelectorAll')); + $self = $this; + array_walk($inputs, function($input) use ($self) { + $self->assertTrue($input instanceof WebElement); + }); + $this->assertGreaterThan(0, count($inputs)); + $this->setExpectedException('SeleniumClient\Http\SeleniumInvalidSelectorException'); + $this->_driver->findElements(By::jsSelector('input')); + } public function testBack() { - $this->_driver->get($this->_url); - $expectedTitle = $this->_driver->title(); $this->_driver->get($this->_url."/free-tools/"); @@ -694,8 +645,6 @@ public function testBack() public function testForward() { - $this->_driver->get($this->_url); - $this->_driver->get($this->_url."/formReceptor.php"); $expectedTitle = $this->_driver->title(); @@ -709,8 +658,6 @@ public function testForward() public function testWaitForElementUntilIsPresent() { - $this->_driver->get($this->_url); - $this->_driver->findElement(By::id("btnAppendDiv"))->click(); $this->_driver->waitForElementUntilIsPresent(By::id("dDiv1-0"),10); @@ -720,8 +667,6 @@ public function testWaitForElementUntilIsPresent() public function testWaitForElementUntilIsNotPresent() { - $this->_driver->get($this->_url); - $webElement = $this->_driver->findElement(By::id("btnHideThis")); $webElement->click(); diff --git a/SeleniumClientTest/Tests/WebDriverWaitTest.php b/SeleniumClientTest/Tests/WebDriverWaitTest.php index 89cae35..e4ab2b0 100644 --- a/SeleniumClientTest/Tests/WebDriverWaitTest.php +++ b/SeleniumClientTest/Tests/WebDriverWaitTest.php @@ -1,33 +1,17 @@ _driver = new WebDriver(); - $this->_driver->get($this->_url); - } - - public function tearDown() - { - if($this->_driver != null) - $this->_driver->quit(); - } - public function testUntilShouldWait() { - $this->_driver->findElement(By::id("btnAppendDiv"))->click(); + $this->_driver->findElement(By::id("btnAppendDiv"))->click(); $wait = new WebDriverWait(8); - $label = $wait->until($this->_driver,"findElement",array(By::id("dDiv1-0"),true)); + $label = $wait->until($this->_driver,"findElement",array(By::id("dDiv1-0"),true)); $this->assertEquals("Some content",$label->getText()); } @@ -35,7 +19,7 @@ public function testUntilShouldWaitShouldThrowException() { $this->setExpectedException('SeleniumClient\WebDriverWaitTimeoutException'); - $this->_driver->findElement(By::id("btnAppendDiv"))->click(); + $this->_driver->findElement(By::id("btnAppendDiv"))->click(); $wait = new WebDriverWait(3); $label = $wait->until($this->_driver,"findElement",array(By::id("dDiv1-0"),true)); diff --git a/SeleniumClientTest/Tests/WebElementTest.php b/SeleniumClientTest/Tests/WebElementTest.php index f354308..d354a19 100644 --- a/SeleniumClientTest/Tests/WebElementTest.php +++ b/SeleniumClientTest/Tests/WebElementTest.php @@ -1,66 +1,51 @@ _driver = new WebDriver(); - $this->_driver->get($this->_url); - } - - public function tearDown() +class WebElementTest extends AbstractTest +{ + public function testGetCoordinatesInViewShouldGetLocationOnScreenOnceScrolledIntoView() { - if($this->_driver != null) - $this->_driver->quit(); - } - - public function testGetCoordinatesInViewShouldGetLocationOnScreenOnceScrolledIntoView() - { - $element = $this->_driver->findElement(By::id("txt1")); + $element = $this->_driver->findElement(By::id("txt1")); $coordinates = $element->getLocationOnScreenOnceScrolledIntoView(); - - $this->assertTrue(is_numeric($coordinates["x"]) ); - $this->assertTrue(is_numeric($coordinates["y"]) ); + + $this->assertTrue(is_numeric($coordinates["x"]) ); + $this->assertTrue(is_numeric($coordinates["y"]) ); } - public function testGetCoordinatesShouldGetCoordinates() - { - $element = $this->_driver->findElement(By::id("txt1")); + public function testGetCoordinatesShouldGetCoordinates() + { + $element = $this->_driver->findElement(By::id("txt1")); $coordinates = $element->getCoordinates(); - + $this->assertTrue(is_numeric($coordinates["x"]) ); - $this->assertTrue(is_numeric($coordinates["y"]) ); + $this->assertTrue(is_numeric($coordinates["y"]) ); } public function testIsDisplayedShouldDetermineIfDisplayed() { $button1 = $this->_driver->findElement(By::id("btnNoAction")); $this->assertEquals( true, $button1->isDisplayed()); - $this->_driver->executeScript("document.getElementById('btnNoAction').style.display = 'none';"); + $this->_driver->executeScript("document.getElementById('btnNoAction').style.display = 'none';"); $this->assertEquals( false, $button1->isDisplayed()); } public function testGetAttributeShouldGetData() { - $chk = $this->_driver->findElement(By::id("chk3")); + $chk = $this->_driver->findElement(By::id("chk3")); $this->assertEquals( "chk3",strtolower($chk->getAttribute("name"))); } public function testIsEnabledShouldDetermineIfEnabled() { - $button1 = $this->_driver->findElement(By::id("btnNoAction")); + $button1 = $this->_driver->findElement(By::id("btnNoAction")); $this->assertEquals( true, $button1->isEnabled()); - $this->_driver->executeScript("document.getElementById('btnNoAction').disabled = true;"); + $this->_driver->executeScript("document.getElementById('btnNoAction').disabled = true;"); $this->assertEquals( false, $button1->isEnabled()); } @@ -78,7 +63,23 @@ public function testIsSelectedShouldDetermineIfSelected() $this->assertEquals( true, $selectBoxOption->isSelected()); } - + + public function testClassMethodsAffectElementClassName() + { + $element = $this->_driver->findElement(By::id("sel1")); + $this->assertEmpty($element->getClassName()); + $element->setClassName("select x-small"); + $this->assertEquals("select x-small", $element->getClassName()); + $this->assertContains('class="select x-small"', $element->getOuterHTML()); + // test method chaining + $element->addClass("foo")->addClass("bar"); + $this->assertEquals("select x-small foo bar", $element->getClassName()); + // we shouldn't be able to add a duplicate class + $element->addClass("foo"); + $this->assertEquals("select x-small foo bar", $element->getClassName()); + $element->removeClass("foo"); + $this->assertEquals("select x-small bar", $element->getClassName()); + } public function testClearShouldSetValueEmpty() { @@ -90,8 +91,23 @@ public function testClearShouldSetValueEmpty() $this->assertEquals("", trim($webElement->getAttribute("value"))); } - - + + public function testGetInnerHTMLShouldGetInnerHTML() + { + $selectBox = $this->_driver->findElement(By::id("sel1")); + $text = $selectBox->getInnerHTML(); + $this->assertContains('assertStringEndsNotWith('', $text); + } + + public function testGetOuterHTMLShouldGetOuterHTML() + { + $selectBox = $this->_driver->findElement(By::id("sel1")); + $text = $selectBox->getOuterHTML(); + $this->assertContains('assertStringEndsWith('', $text); + } + public function testGetTagNameShouldGetTagName() { $webElement = $this->_driver->findElement(By::id("txt1")); @@ -108,6 +124,13 @@ public function testDescribeShouldGetElementId() $this->assertEquals( $webElement->getElementId(), trim($webElementDescription["id"])); } + + public function testFindElementByJsSelectorShouldGetChildElement() + { + $selectBox = $this->_driver->findElement(By::id("sel1")); + $option = $selectBox->findElement(By::jsSelector('option[selected="selected"]', 'document.querySelector')); + $this->assertEquals('Orange', $option->getText()); + } public function testFindElementShouldGetFoundElementText() { @@ -148,14 +171,14 @@ public function testFindElementsShouldGetOneOfFoundElementsText() } } } - + public function testClickShouldSubmitForm() { $button = $this->_driver->findElement(By::id("btnSubmit")); $button->click(); - $this->assertTrue(strstr($this->_driver->getCurrentPageUrl(), "formReceptor") >= 0); + $this->assertTrue(strstr($this->_driver->getCurrentPageUrl(), "formReceptor") >= 0); } public function testSubmitShouldSubmitForm() diff --git a/SeleniumClientTest/bootstrap.php b/SeleniumClientTest/bootstrap.php index 77386ce..74c698e 100644 --- a/SeleniumClientTest/bootstrap.php +++ b/SeleniumClientTest/bootstrap.php @@ -1,17 +1,10 @@ - - - Tests/AlertTest.php - Tests/DesiredCapabilitiesTest.php - Tests/SelectElementTest.php - Tests/TargetLocatorTest.php - Tests/WebDriverTest.php - Tests/WebDriverWaitTest.php - Tests/WebElementTest.php - - - \ No newline at end of file diff --git a/SeleniumClientTest/phpunit.xml.dist b/SeleniumClientTest/phpunit.xml.dist new file mode 100644 index 0000000..014be32 --- /dev/null +++ b/SeleniumClientTest/phpunit.xml.dist @@ -0,0 +1,32 @@ + + + + + + + + + + Tests + Tests/AbstractTest.php + + + + + ../SeleniumClient + + ../SeleniumClient/Exceptions.php + ../SeleniumClient/Http/Exceptions.php + + + + + + + + + + \ No newline at end of file