General Coding Convention Changes

This commit is contained in:
Sriram Venkatesh 2014-01-27 10:50:20 +13:00
parent f5957a0586
commit 26f47d9d58

View File

@ -3,15 +3,15 @@
namespace SilverStripe\BehatExtension\Context; namespace SilverStripe\BehatExtension\Context;
use Behat\Behat\Context\Step, use Behat\Behat\Context\Step,
Behat\Behat\Event\FeatureEvent, Behat\Behat\Event\FeatureEvent,
Behat\Behat\Event\ScenarioEvent, Behat\Behat\Event\ScenarioEvent,
Behat\Behat\Event\SuiteEvent; Behat\Behat\Event\SuiteEvent;
use Behat\Gherkin\Node\PyStringNode; use Behat\Gherkin\Node\PyStringNode;
use Behat\MinkExtension\Context\MinkContext; use Behat\MinkExtension\Context\MinkContext;
use Behat\Mink\Driver\GoutteDriver, use Behat\Mink\Driver\GoutteDriver,
Behat\Mink\Driver\Selenium2Driver, Behat\Mink\Driver\Selenium2Driver,
Behat\Mink\Exception\UnsupportedDriverActionException, Behat\Mink\Exception\UnsupportedDriverActionException,
Behat\Mink\Exception\ElementNotFoundException; Behat\Mink\Exception\ElementNotFoundException;
use SilverStripe\BehatExtension\Context\SilverStripeAwareContextInterface; use SilverStripe\BehatExtension\Context\SilverStripeAwareContextInterface;
@ -27,309 +27,288 @@ require_once 'vendor/autoload.php';
*/ */
class SilverStripeContext extends MinkContext implements SilverStripeAwareContextInterface class SilverStripeContext extends MinkContext implements SilverStripeAwareContextInterface
{ {
protected $databaseName; protected $databaseName;
/** /**
* @var Array Partial string match for step names * @var Array Partial string match for step names
* that are considered to trigger Ajax request in the CMS, * that are considered to trigger Ajax request in the CMS,
* and hence need special timeout handling. * and hence need special timeout handling.
* @see \SilverStripe\BehatExtension\Context\BasicContext->handleAjaxBeforeStep(). * @see \SilverStripe\BehatExtension\Context\BasicContext->handleAjaxBeforeStep().
*/ */
protected $ajaxSteps; protected $ajaxSteps;
/** /**
* @var Int Timeout in milliseconds, after which the interface assumes * @var Int Timeout in milliseconds, after which the interface assumes
* that an Ajax request has timed out, and continues with assertions. * that an Ajax request has timed out, and continues with assertions.
*/ */
protected $ajaxTimeout; protected $ajaxTimeout;
/** /**
* @var String Relative URL to the SilverStripe admin interface. * @var String Relative URL to the SilverStripe admin interface.
*/ */
protected $adminUrl; protected $adminUrl;
/** /**
* @var String Relative URL to the SilverStripe login form. * @var String Relative URL to the SilverStripe login form.
*/ */
protected $loginUrl; protected $loginUrl;
/** /**
* @var String Relative path to a writeable folder where screenshots can be stored. * @var String Relative path to a writeable folder where screenshots can be stored.
* If set to NULL, no screenshots will be stored. * If set to NULL, no screenshots will be stored.
*/ */
protected $screenshotPath; protected $screenshotPath;
protected $context; protected $context;
/** /**
* Initializes context. * Initializes context.
* Every scenario gets it's own context object. * Every scenario gets it's own context object.
* *
* @param array $parameters context parameters (set them up through behat.yml) * @param array $parameters context parameters (set them up through behat.yml)
*/ */
public function __construct(array $parameters) public function __construct(array $parameters) {
{ // Initialize your context here
// Initialize your context here $this->context = $parameters;
$this->context = $parameters; }
}
public function setDatabase($databaseName) public function setDatabase($databaseName) {
{ $this->databaseName = $databaseName;
$this->databaseName = $databaseName; }
}
public function setAjaxSteps($ajaxSteps) public function setAjaxSteps($ajaxSteps) {
{ if($ajaxSteps) $this->ajaxSteps = $ajaxSteps;
if($ajaxSteps) $this->ajaxSteps = $ajaxSteps; }
}
public function getAjaxSteps() public function getAjaxSteps() {
{ return $this->ajaxSteps;
return $this->ajaxSteps; }
}
public function setAjaxTimeout($ajaxTimeout) public function setAjaxTimeout($ajaxTimeout) {
{ $this->ajaxTimeout = $ajaxTimeout;
$this->ajaxTimeout = $ajaxTimeout; }
}
public function getAjaxTimeout() public function getAjaxTimeout() {
{ return $this->ajaxTimeout;
return $this->ajaxTimeout; }
}
public function setAdminUrl($adminUrl) public function setAdminUrl($adminUrl) {
{ $this->adminUrl = $adminUrl;
$this->adminUrl = $adminUrl; }
}
public function getAdminUrl() public function getAdminUrl() {
{ return $this->adminUrl;
return $this->adminUrl; }
}
public function setLoginUrl($loginUrl) public function setLoginUrl($loginUrl) {
{ $this->loginUrl = $loginUrl;
$this->loginUrl = $loginUrl; }
}
public function getLoginUrl() public function getLoginUrl() {
{ return $this->loginUrl;
return $this->loginUrl; }
}
public function setScreenshotPath($screenshotPath) public function setScreenshotPath($screenshotPath) {
{ $this->screenshotPath = $screenshotPath;
$this->screenshotPath = $screenshotPath; }
}
public function getScreenshotPath() public function getScreenshotPath() {
{ return $this->screenshotPath;
return $this->screenshotPath; }
}
/** /**
* @BeforeScenario * @BeforeScenario
*/ */
public function before(ScenarioEvent $event) public function before(ScenarioEvent $event) {
{ if (!isset($this->databaseName)) {
if (!isset($this->databaseName)) { throw new \LogicException(
throw new \LogicException( 'Context\'s $databaseName has to be set when implementing SilverStripeAwareContextInterface.'
'Context\'s $databaseName has to be set when implementing ' );
. 'SilverStripeAwareContextInterface.' }
);
}
$url = $this->joinUrlParts($this->getBaseUrl(), '/dev/testsession/start'); $url = $this->joinUrlParts($this->getBaseUrl(), '/dev/testsession/start');
$url .= '?' . http_build_query($this->getTestSessionState()); $url .= '?' . http_build_query($this->getTestSessionState());
$this->getSession()->visit($url); $this->getSession()->visit($url);
$page = $this->getSession()->getPage(); $page = $this->getSession()->getPage();
$content = $page->getContent(); $content = $page->getContent();
if(!preg_match('/<!-- +SUCCESS: +DBNAME=([^ ]+)/i', $content, $matches)) { if(!preg_match('/<!-- +SUCCESS: +DBNAME=([^ ]+)/i', $content, $matches)) {
throw new \LogicException("Could not create a test session. Details below:\n" . $content); throw new \LogicException("Could not create a test session. Details below:\n" . $content);
} else if($matches[1] != $this->databaseName) { } elseif($matches[1] != $this->databaseName) {
throw new \LogicException("Test session is using the database $matches[1]; it should be using $this->databaseName."); throw new \LogicException("Test session is using the database $matches[1]; it should be using $this->databaseName.");
} }
$loginForm = $page->find('css', '#MemberLoginForm_LoginForm'); $loginForm = $page->find('css', '#MemberLoginForm_LoginForm');
} }
/** /**
* Returns a parameter map of state to set within the test session. * Returns a parameter map of state to set within the test session.
* Takes TESTSESSION_PARAMS environment variable into account for run-specific configurations. * Takes TESTSESSION_PARAMS environment variable into account for run-specific configurations.
* *
* @return array * @return array
*/ */
public function getTestSessionState() { public function getTestSessionState() {
$extraParams = array(); $extraParams = array();
parse_str(getenv('TESTSESSION_PARAMS'), $extraParams); parse_str(getenv('TESTSESSION_PARAMS'), $extraParams);
return array_merge( return array_merge(
array( array(
'database' => $this->databaseName, 'database' => $this->databaseName,
'mailer' => 'SilverStripe\BehatExtension\Utility\TestMailer', 'mailer' => 'SilverStripe\BehatExtension\Utility\TestMailer',
), ),
$extraParams $extraParams
); );
} }
/** /**
* Parses given URL and returns its components * Parses given URL and returns its components
* *
* @param $url * @param $url
* @return array|mixed Parsed URL * @return array|mixed Parsed URL
*/ */
public function parseUrl($url) public function parseUrl($url) {
{ $url = parse_url($url);
$url = parse_url($url); $url['vars'] = array();
$url['vars'] = array(); if (!isset($url['fragment'])) {
if (!isset($url['fragment'])) { $url['fragment'] = null;
$url['fragment'] = null; }
} if (isset($url['query'])) {
if (isset($url['query'])) { parse_str($url['query'], $url['vars']);
parse_str($url['query'], $url['vars']); }
}
return $url; return $url;
} }
/** /**
* Checks whether current URL is close enough to the given URL. * Checks whether current URL is close enough to the given URL.
* Unless specified in $url, get vars will be ignored * Unless specified in $url, get vars will be ignored
* Unless specified in $url, fragment identifiers will be ignored * Unless specified in $url, fragment identifiers will be ignored
* *
* @param $url string URL to compare to current URL * @param $url string URL to compare to current URL
* @return boolean Returns true if the current URL is close enough to the given URL, false otherwise. * @return boolean Returns true if the current URL is close enough to the given URL, false otherwise.
*/ */
public function isCurrentUrlSimilarTo($url) public function isCurrentUrlSimilarTo($url) {
{ $current = $this->parseUrl($this->getSession()->getCurrentUrl());
$current = $this->parseUrl($this->getSession()->getCurrentUrl()); $test = $this->parseUrl($url);
$test = $this->parseUrl($url);
if ($current['path'] !== $test['path']) { if ($current['path'] !== $test['path']) {
return false; return false;
} }
if (isset($test['fragment']) && $current['fragment'] !== $test['fragment']) { if (isset($test['fragment']) && $current['fragment'] !== $test['fragment']) {
return false; return false;
} }
foreach ($test['vars'] as $name => $value) { foreach ($test['vars'] as $name => $value) {
if (!isset($current['vars'][$name]) || $current['vars'][$name] !== $value) { if (!isset($current['vars'][$name]) || $current['vars'][$name] !== $value) {
return false; return false;
} }
} }
return true; return true;
} }
/** /**
* Returns base URL parameter set in MinkExtension. * Returns base URL parameter set in MinkExtension.
* It simplifies configuration by allowing to specify this parameter * It simplifies configuration by allowing to specify this parameter
* once but makes code dependent on MinkExtension. * once but makes code dependent on MinkExtension.
* *
* @return string * @return string
*/ */
public function getBaseUrl() public function getBaseUrl() {
{ return $this->getMinkParameter('base_url') ?: '';
return $this->getMinkParameter('base_url') ?: ''; }
}
/** /**
* Joins URL parts into an URL using forward slash. * Joins URL parts into an URL using forward slash.
* Forward slash usages are normalised to one between parts. * Forward slash usages are normalised to one between parts.
* This method takes variable number of parameters. * This method takes variable number of parameters.
* *
* @param $... * @param $...
* @return string * @return string
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*/ */
public function joinUrlParts() public function joinUrlParts() {
{ if (0 === func_num_args()) {
if (0 === func_num_args()) { throw new \InvalidArgumentException('Need at least one argument');
throw new \InvalidArgumentException('Need at least one argument'); }
}
$parts = func_get_args(); $parts = func_get_args();
$trimSlashes = function(&$part) { $trimSlashes = function(&$part) {
$part = trim($part, '/'); $part = trim($part, '/');
}; };
array_walk($parts, $trimSlashes); array_walk($parts, $trimSlashes);
return implode('/', $parts); return implode('/', $parts);
} }
public function canIntercept() public function canIntercept() {
{ $driver = $this->getSession()->getDriver();
$driver = $this->getSession()->getDriver(); if ($driver instanceof GoutteDriver) {
if ($driver instanceof GoutteDriver) { return true;
return true; }
} else {
else { if ($driver instanceof Selenium2Driver) {
if ($driver instanceof Selenium2Driver) { return false;
return false; }
} }
}
throw new UnsupportedDriverActionException('You need to tag the scenario with "@mink:goutte" or "@mink:symfony". Intercepting the redirections is not supported by %s', $driver); throw new UnsupportedDriverActionException('You need to tag the scenario with "@mink:goutte" or
} "@mink:symfony". Intercepting the redirections is not supported by %s', $driver);
}
/** /**
* @Given /^(.*) without redirection$/ * @Given /^(.*) without redirection$/
*/ */
public function theRedirectionsAreIntercepted($step) public function theRedirectionsAreIntercepted($step) {
{ if ($this->canIntercept()) {
if ($this->canIntercept()) { $this->getSession()->getDriver()->getClient()->followRedirects(false);
$this->getSession()->getDriver()->getClient()->followRedirects(false); }
}
return new Step\Given($step); return new Step\Given($step);
} }
/** /**
* Fills in form field with specified id|name|label|value. * Fills in form field with specified id|name|label|value.
* Overwritten to select the first *visible* element, see https://github.com/Behat/Mink/issues/311 * Overwritten to select the first *visible* element, see https://github.com/Behat/Mink/issues/311
*/ */
public function fillField($field, $value) public function fillField($field, $value) {
{ $value = $this->fixStepArgument($value);
$value = $this->fixStepArgument($value); $fields = $this->getSession()->getPage()->findAll('named', array(
$fields = $this->getSession()->getPage()->findAll('named', array( 'field', $this->getSession()->getSelectorsHandler()->xpathLiteral($field)
'field', $this->getSession()->getSelectorsHandler()->xpathLiteral($field) ));
)); if($fields) foreach($fields as $field) {
if($fields) foreach($fields as $field) { if($field->isVisible()) {
if($field->isVisible()) { $field->setValue($value);
$field->setValue($value); return;
return; }
} }
}
throw new ElementNotFoundException(
throw new ElementNotFoundException( $this->getSession(), 'form field', 'id|name|label|value', $field
$this->getSession(), 'form field', 'id|name|label|value', $field );
); }
}
/** /**
* Overwritten to click the first *visable* link the DOM. * Overwritten to click the first *visable* link the DOM.
*/ */
public function clickLink($link) public function clickLink($link) {
{ $link = $this->fixStepArgument($link);
$link = $this->fixStepArgument($link); $links = $this->getSession()->getPage()->findAll('named', array(
$links = $this->getSession()->getPage()->findAll('named', array( 'link', $this->getSession()->getSelectorsHandler()->xpathLiteral($link)
'link', $this->getSession()->getSelectorsHandler()->xpathLiteral($link) ));
)); if($links) foreach($links as $l) {
if($links) foreach($links as $l) { if($l->isVisible()) {
if($l->isVisible()) { $l->click();
$l->click(); return;
return; }
} }
} throw new ElementNotFoundException(
throw new ElementNotFoundException( $this->getSession(), 'link', 'id|name|label|value', $link
$this->getSession(), 'link', 'id|name|label|value', $link );
); }
}
} }