/framework/Mage/Selenium/TestCase.php
PHP | 3668 lines | 2361 code | 215 blank | 1092 comment | 282 complexity | 9a032bdf8a5c7e4b071e2f310c654569 MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- <?php
- /**
- * Magento
- *
- * NOTICE OF LICENSE
- *
- * This source file is subject to the Open Software License (OSL 3.0)
- * that is bundled with this package in the file LICENSE.txt.
- * It is also available through the world-wide-web at this URL:
- * http://opensource.org/licenses/osl-3.0.php
- * If you did not receive a copy of the license and are unable to
- * obtain it through the world-wide-web, please send an email
- * to license@magentocommerce.com so we can send you a copy immediately.
- *
- * DISCLAIMER
- *
- * Do not edit or add to this file if you wish to upgrade Magento to newer
- * versions in the future. If you wish to customize Magento for your
- * needs please refer to http://www.magentocommerce.com for more information.
- *
- * @category tests
- * @package selenium
- * @subpackage Mage_Selenium
- * @author Magento Core Team <core@magentocommerce.com>
- * @copyright Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
- */
- /**
- * An extended test case implementation that adds useful helper methods
- *
- * @package selenium
- * @subpackage Mage_Selenium
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
- * @method Core_Mage_AdminUser_Helper adminUserHelper()
- * @method Core_Mage_AttributeSet_Helper attributeSetHelper()
- * @method Core_Mage_Category_Helper categoryHelper()
- * @method Core_Mage_CheckoutMultipleAddresses_Helper checkoutMultipleAddressesHelper()
- * @method Core_Mage_CheckoutOnePage_Helper checkoutOnePageHelper()
- * @method Core_Mage_CmsPages_Helper cmsPagesHelper()
- * @method Core_Mage_CmsPolls_Helper cmsPollsHelper()
- * @method Core_Mage_CmsStaticBlocks_Helper cmsStaticBlocksHelper()
- * @method Core_Mage_CmsWidgets_Helper cmsWidgetsHelper()
- * @method Core_Mage_CompareProducts_Helper compareProductsHelper()
- * @method Core_Mage_CustomerGroups_Helper customerGroupsHelper()
- * @method Core_Mage_Customer_Helper customerHelper()
- * @method Core_Mage_Installation_Helper installationHelper()
- * @method Core_Mage_Newsletter_Helper newsletterHelper()
- * @method Core_Mage_OrderCreditMemo_Helper orderCreditMemoHelper()
- * @method Core_Mage_OrderInvoice_Helper orderInvoiceHelper()
- * @method Core_Mage_OrderShipment_Helper orderShipmentHelper()
- * @method Core_Mage_Order_Helper orderHelper()
- * @method Core_Mage_Paypal_Helper paypalHelper()
- * @method Core_Mage_PriceRules_Helper priceRulesHelper()
- * @method Core_Mage_ProductAttribute_Helper productAttributeHelper()
- * @method Core_Mage_Product_Helper productHelper()
- * @method Core_Mage_Rating_Helper ratingHelper()
- * @method Core_Mage_Review_Helper reviewHelper()
- * @method Core_Mage_ShoppingCart_Helper shoppingCartHelper()
- * @method Core_Mage_Store_Helper storeHelper()
- * @method Core_Mage_SystemConfiguration_Helper systemConfigurationHelper()
- * @method Core_Mage_Tags_Helper tagsHelper()
- * @method Core_Mage_Tax_Helper taxHelper()
- * @method Core_Mage_Wishlist_Helper wishlistHelper()
- */
- class Mage_Selenium_TestCase extends PHPUnit_Extensions_SeleniumTestCase
- {
- ################################################################################
- # Framework variables and constant #
- ################################################################################
- /**
- * Configuration object instance
- * @var Mage_Selenium_TestConfiguration
- */
- protected $_testConfig;
- /**
- * Config helper instance
- * @var Mage_Selenium_Helper_Config
- */
- protected $_configHelper;
- /**
- * UIMap helper instance
- * @var Mage_Selenium_Helper_Uimap
- */
- protected $_uimapHelper;
- /**
- * Data helper instance
- * @var Mage_Selenium_Helper_Data
- */
- protected $_dataHelper;
- /**
- * Params helper instance
- * @var Mage_Selenium_Helper_Params
- */
- protected $_paramsHelper;
- /**
- * Data Generator helper instance
- * @var Mage_Selenium_Helper_DataGenerator
- */
- protected $_dataGeneratorHelper;
- /**
- * Array of Test Helper instances
- * @var array
- */
- protected static $_testHelpers = array();
- /**
- * Framework setting
- * @var array
- */
- public $frameworkConfig;
- /**
- * Saves HTML content of the current page if the test failed
- * @var bool
- */
- protected $_saveHtmlPageOnFailure = false;
- /**
- * Timeout in ms
- * @var int
- */
- protected $_browserTimeoutPeriod = 40000;
- /**
- * Name of the first page after logging into the back-end
- * @var string
- */
- protected $_firstPageAfterAdminLogin = 'dashboard';
- /**
- * Array of messages on page
- * @var array
- */
- protected static $_messages = array();
- /**
- * Name of run Test Class
- * @var null
- */
- public static $_testClass = null;
- /**
- * Name of last testcase in test class
- * @var array
- */
- protected static $_lastTestNameInClass = null;
- /**
- * Additional params for navigation URL
- * @var string
- */
- private $_urlPostfix;
- /**
- * Testcase error
- * @var boolean
- * @deprecated
- */
- protected $_error = false;
- /**
- * Type of uimap elements
- * @var string
- */
- const FIELD_TYPE_MULTISELECT = 'multiselect';
- /**
- * Type of uimap elements
- * @var string
- */
- const FIELD_TYPE_DROPDOWN = 'dropdown';
- /**
- * Type of uimap elements
- * @var string
- */
- const FIELD_TYPE_CHECKBOX = 'checkbox';
- /**
- * Type of uimap elements
- * @var string
- */
- const FIELD_TYPE_RADIOBUTTON = 'radiobutton';
- /**
- * Type of uimap elements
- * @var string
- */
- const FIELD_TYPE_INPUT = 'field';
- ################################################################################
- # Selenium variables(do not rename) #
- ################################################################################
- /**
- * @var PHPUnit_Extensions_SeleniumTestCase_Driver[]
- */
- protected $drivers = array();
- /**
- * @var string
- */
- protected $coverageScriptUrl = '';
- /**
- * @var bool
- */
- protected $captureScreenshotOnFailure = false;
- ################################################################################
- # Else variables #
- ################################################################################
- /**
- * Loading holder XPath
- * @staticvar string
- */
- protected static $xpathLoadingHolder = "//div[@id='loading-mask'][not(contains(@style,'display:') and contains(@style,'none'))]";
- /**
- * Constructs a test case with the given name and browser to test execution
- *
- * @param string $name Test case name(by default = null)
- * @param array $data Test case data array(by default = array())
- * @param string $dataName Name of Data set(by default = '')
- */
- public function __construct($name = null, array $data = array(), $dataName = '')
- {
- $this->_testConfig = Mage_Selenium_TestConfiguration::getInstance();
- $this->_configHelper = $this->_testConfig->getHelper('config');
- $this->_uimapHelper = $this->_testConfig->getHelper('uimap');
- $this->_dataHelper = $this->_testConfig->getHelper('data');
- $this->_paramsHelper = $this->_testConfig->getHelper('params');
- $this->_dataGeneratorHelper = $this->_testConfig->getHelper('dataGenerator');
- $this->frameworkConfig = $this->_configHelper->getConfigFramework();
- parent::__construct($name, $data, $dataName);
- $this->captureScreenshotOnFailure = $this->frameworkConfig['captureScreenshotOnFailure'];
- $this->_saveHtmlPageOnFailure = $this->frameworkConfig['saveHtmlPageOnFailure'];
- $this->coverageScriptUrl = $this->frameworkConfig['coverageScriptUrl'];
- $this->screenshotPath = $this->screenshotUrl = $this->getDefaultScreenshotPath();
- }
- /**
- * Delegate method calls to the driver. Overridden to load test helpers
- *
- * @param string $command Command (method) name to call
- * @param array $arguments Arguments to be sent to the called command (method)
- *
- * @return mixed
- */
- public function __call($command, $arguments)
- {
- $helper = substr($command, 0, strpos($command, 'Helper'));
- if ($helper) {
- $helper = $this->_loadHelper($helper);
- if ($helper) {
- return $helper;
- }
- }
- return parent::__call($command, $arguments);
- }
- /**
- * Loads a specific driver for the specified browser
- *
- * @param array $browser Defines what kind of driver, for a what browser will be loaded
- *
- * @return Mage_Selenium_Driver
- */
- protected function getDriver(array $browser)
- {
- if (!isset($browser['name'])) {
- $browser['name'] = '';
- }
- if (!isset($browser['browser'])) {
- $browser['browser'] = '';
- }
- if (!isset($browser['host'])) {
- $browser['host'] = 'localhost';
- }
- if (!isset($browser['port'])) {
- $browser['port'] = 4444;
- }
- if (!isset($browser['timeout'])) {
- $browser['timeout'] = 30;
- }
- if (!isset($browser['httpTimeout'])) {
- $browser['httpTimeout'] = 45;
- }
- $driver = new Mage_Selenium_Driver();
- $driver->setName($browser['name']);
- $driver->setBrowser($browser['browser']);
- $driver->setHost($browser['host']);
- $driver->setPort($browser['port']);
- $driver->setTimeout($browser['timeout']);
- $driver->setHttpTimeout($browser['httpTimeout']);
- $driver->setTestCase($this);
- $driver->setTestId($this->testId);
- $driver->setLogHandle($this->_testConfig->getLogFile());
- $driver->setBrowserUrl($this->_configHelper->getBaseUrl());
- $this->_browserTimeoutPeriod = $browser['timeout'] * 1000;
- $this->drivers[0] = $driver;
- return $driver;
- }
- /**
- * Implementation of setUpBeforeClass() method in the object context, called as setUpBeforeTests()<br>
- * Used ONLY one time before execution of each class (tests in test class)
- * @throws Exception
- */
- private function setUpBeforeTestClass()
- {
- $currentTestClass = get_class($this);
- static $setUpBeforeTestsError = null;
- if (self::$_testClass != $currentTestClass) {
- self::$_testClass = $currentTestClass;
- //work with xpath for IE
- $browser = $this->getBrowserSettings();
- if (strstr($browser['browser'], '*ie') !== false) {
- $this->useXpathLibrary('javascript-xpath');
- $this->allowNativeXpath(true);
- }
- $this->setLastTestNameInClass();
- try {
- $setUpBeforeTestsError = null;
- $this->setUpBeforeTests();
- } catch (Exception $e) {
- $setUpBeforeTestsError =
- "\nError in setUpBeforeTests method for '" . $currentTestClass . "' class:\n" . $e->getMessage();
- }
- if (isset($e)) {
- throw $e;
- }
- }
- if ($setUpBeforeTestsError !== null) {
- $this->markTestSkipped($setUpBeforeTestsError);
- }
- }
- /**
- * Prepare browser session
- */
- public function prepareBrowserSession()
- {
- $browsers = $this->_configHelper->getConfigBrowsers();
- if ($this->frameworkConfig['shareSession'] && empty(self::$browsers)) {
- $this->setupSpecificBrowser($browsers['default']);
- $this->shareSession($this->prepareTestSession());
- } elseif (empty(self::$browsers)) {
- $this->setupSpecificBrowser($browsers['default']);
- $this->prepareTestSession();
- } else {
- $this->frameworkConfig['shareSession'] = false;
- $this->prepareTestSession();
- }
- }
- final function setUp()
- {
- $this->clearMessages();
- $this->prepareBrowserSession();
- $this->setUpBeforeTestClass();
- }
- /**
- * Function is called before all tests in a test class
- * and can be used for some precondition(s) for all tests
- */
- public function setUpBeforeTests()
- {
- }
- /**
- * Define name of last testcase in test class
- */
- private function setLastTestNameInClass()
- {
- $testMethods = array();
- $class = new ReflectionClass(self::$_testClass);
- foreach ($class->getMethods() as $method) {
- if (PHPUnit_Framework_TestSuite::isPublicTestMethod($method)) {
- $testMethods[] = $method->getName();
- }
- }
- $testName = end($testMethods);
- $data = PHPUnit_Util_Test::getProvidedData(self::$_testClass, $testName);
- if ($data) {
- $testName .= sprintf(' with data set #%d', count($data) - 1);
- }
- self::$_lastTestNameInClass = $testName;
- }
- /**
- * Implementation of tearDownAfterAllTests() method in the object context, called as tearDownAfterTestClass()<br>
- * Used ONLY one time after execution of last test in test class
- * Implementation of tearDownAfterEachTest() method in the object context, called as tearDownAfterTest()<br>
- * Used after execution of each test in test class
- * @throws Exception
- */
- final function tearDown()
- {
- if ($this->hasFailed()) {
- if ($this->_saveHtmlPageOnFailure) {
- $this->saveHtmlPage();
- }
- if ($this->captureScreenshotOnFailure) {
- $this->takeScreenshot();
- }
- } else {
- $this->assertEmptyVerificationErrors();
- }
- $annotations = $this->getAnnotations();
- if (!isset($annotations['method']['skipTearDown'])) {
- try {
- $this->tearDownAfterTest();
- } catch (Exception $e) {
- }
- }
- try {
- if ($this->getName() == self::$_lastTestNameInClass) {
- $this->tearDownAfterTestClass();
- }
- } catch (Exception $_e) {
- if (!isset($e)) {
- $e = $_e;
- }
- }
- if (isset($e) && !$this->hasFailed()) {
- if ($this->_saveHtmlPageOnFailure) {
- $this->saveHtmlPage();
- }
- if ($this->captureScreenshotOnFailure) {
- $this->takeScreenshot();
- }
- }
- if (!$this->frameworkConfig['shareSession']) {
- $this->stop();
- }
- if (isset($e)) {
- throw $e;
- }
- }
- protected function tearDownAfterTestClass()
- {
- }
- protected function tearDownAfterTest()
- {
- }
- /**
- * Access/load helpers from the tests. Helper class name should be like "TestScope_HelperName"
- *
- * @param string $testScope Part of the helper class name which refers to the file with the needed helper
- *
- * @return object
- * @throws UnexpectedValueException
- */
- protected function _loadHelper($testScope)
- {
- if (empty($testScope)) {
- throw new UnexpectedValueException('Helper name can\'t be empty');
- }
- $helpers = $this->_testConfig->getTestHelperClassNames();
- if (!isset($helpers[ucwords($testScope)])) {
- throw new UnexpectedValueException('Cannot load helper "' . $testScope . '"');
- }
- $helperClassName = $helpers[ucwords($testScope)];
- if (!isset(self::$_testHelpers[$helperClassName])) {
- if (class_exists($helperClassName)) {
- self::$_testHelpers[$helperClassName] = new $helperClassName();
- } else {
- return false;
- }
- }
- if (self::$_testHelpers[$helperClassName] instanceof Mage_Selenium_TestCase) {
- foreach (get_object_vars($this) as $name => $value) {
- self::$_testHelpers[$helperClassName]->$name = $value;
- }
- }
- return self::$_testHelpers[$helperClassName];
- }
- /**
- * Retrieve instance of helper
- * @deprecated
- * @see _loadHelper()
- *
- * @param string $className
- *
- * @return Mage_Selenium_TestCase
- */
- public function helper($className)
- {
- $className = str_replace('/', '_', $className);
- if (strpos($className, '_Helper') === false) {
- $className .= '_Helper';
- }
- if (!isset(self::$_testHelpers[$className])) {
- if (class_exists($className)) {
- self::$_testHelpers[$className] = new $className;
- } else {
- return false;
- }
- }
- if (self::$_testHelpers[$className] instanceof Mage_Selenium_TestCase) {
- foreach (get_object_vars($this) as $name => $value) {
- self::$_testHelpers[$className]->$name = $value;
- }
- }
- return self::$_testHelpers[$className];
- }
- /**
- * Checks if there was error during last operations
- * @return boolean
- * @deprecated
- */
- public function hasError()
- {
- return $this->_error;
- }
- ################################################################################
- # #
- # Assertions Methods #
- # #
- ################################################################################
- /**
- * Asserts that $condition is true. Reports an error $message if $condition is false.
- * @static
- *
- * @param bool $condition Condition to assert
- * @param string|array $message Message to report if the condition is false (by default = '')
- */
- public static function assertTrue($condition, $message = '')
- {
- $message = self::messagesToString($message);
- if (is_object($condition)) {
- $condition = (false === $condition->hasError());
- }
- self::assertThat($condition, self::isTrue(), $message);
- }
- /**
- * Asserts that $condition is false. Reports an error $message if $condition is true.
- * @static
- *
- * @param bool $condition Condition to assert
- * @param string $message Message to report if the condition is true (by default = '')
- */
- public static function assertFalse($condition, $message = '')
- {
- $message = self::messagesToString($message);
- if (is_object($condition)) {
- $condition = (false === $condition->hasError());
- }
- self::assertThat($condition, self::isFalse(), $message);
- }
- ################################################################################
- # #
- # Parameter helper methods #
- # #
- ################################################################################
- /**
- * Append parameters decorator object
- *
- * @param Mage_Selenium_Helper_Params $paramsHelperObject Parameters decorator object
- *
- * @return Mage_Selenium_TestCase
- */
- public function appendParamsDecorator($paramsHelperObject)
- {
- $this->_paramsHelper = $paramsHelperObject;
- return $this;
- }
- /**
- * Add parameter to params object instance
- *
- * @param string $name
- * @param string $value
- *
- * @return Mage_Selenium_Helper_Params
- */
- public function addParameter($name, $value)
- {
- $this->_paramsHelper->setParameter($name, $value);
- return $this;
- }
- /**
- * Get parameter from params object instance
- *
- * @param string $name
- *
- * @return string
- */
- public function getParameter($name)
- {
- return $this->_paramsHelper->getParameter($name);
- }
- /**
- * Define parameter %$paramName% from URL
- *
- * @param string $paramName
- * @param null|string $url
- *
- * @return null|string
- */
- public function defineParameterFromUrl($paramName, $url = null)
- {
- if (is_null($url)) {
- $url = self::_getMcaFromCurrentUrl($this->_configHelper->getConfigAreas(), $this->getLocation());
- }
- $title_arr = explode('/', $url);
- if (in_array($paramName, $title_arr) && isset($title_arr[array_search($paramName, $title_arr) + 1])) {
- return $title_arr[array_search($paramName, $title_arr) + 1];
- }
- foreach ($title_arr as $key => $value) {
- if (preg_match("#$paramName$#i", $value) && isset($title_arr[$key + 1])) {
- return $title_arr[$key + 1];
- }
- }
- return null;
- }
- /**
- * Define parameter %id% from attribute @title by XPath
- *
- * @param string $xpath
- *
- * @return null|string
- */
- public function defineIdFromTitle($xpath)
- {
- $urlFromTitleAttribute = $this->getValue($xpath . '/@title');
- if (is_numeric($urlFromTitleAttribute)) {
- return $urlFromTitleAttribute;
- }
- return $this->defineIdFromUrl($urlFromTitleAttribute);
- }
- /**
- * Define parameter %id% from URL
- *
- * @param null|string $url
- *
- * @return null|string
- */
- public function defineIdFromUrl($url = null)
- {
- return $this->defineParameterFromUrl('id', $url);
- }
- /**
- * Adds field ID to Message Xpath (sets %fieldId% parameter)
- *
- * @param string $fieldType Field type
- * @param string $fieldName Field name from UIMap
- */
- public function addFieldIdToMessage($fieldType, $fieldName)
- {
- $fieldXpath = $this->_getControlXpath($fieldType, $fieldName);
- if ($this->isElementPresent($fieldXpath . '/@id')) {
- $fieldId = $this->getAttribute($fieldXpath . '/@id');
- $fieldId = empty($fieldId)
- ? $this->getAttribute($fieldXpath . '/@name')
- : $fieldId;
- } else {
- $fieldId = $this->getAttribute($fieldXpath . '/@name');
- }
- $this->addParameter('fieldId', $fieldId);
- }
- ################################################################################
- # #
- # Data helper methods #
- # #
- ################################################################################
- /**
- * Generates random value as a string|text|email $type, with specified $length.<br>
- * Available $modifier:
- * <li>if $type = string - alnum|alpha|digit|lower|upper|punct
- * <li>if $type = text - alnum|alpha|digit|lower|upper|punct
- * <li>if $type = email - valid|invalid
- *
- * @param string $type Available types are 'string', 'text', 'email' (by default = 'string')
- * @param int $length Generated value length (by default = 100)
- * @param null|string $modifier Value modifier, e.g. PCRE class (by default = null)
- * @param null|string $prefix Prefix to prepend the generated value (by default = null)
- *
- * @return string
- */
- public function generate($type = 'string', $length = 100, $modifier = null, $prefix = null)
- {
- $result = $this->_dataGeneratorHelper->generate($type, $length, $modifier, $prefix);
- return $result;
- }
- /**
- * Loads test data.
- *
- * @param string $dataFile - File name or full path to file in fixture folder
- * (for example: 'default\core\Mage\AdminUser\data\AdminUsers') in which DataSet is specified
- * @param string $dataSource - DataSet name(for example: 'test_data')
- * or part of DataSet (for example: 'test_data/product')
- * @param array|null $overrideByKey
- * @param array|null $overrideByValueParam
- *
- * @throws PHPUnit_Framework_Exception
- * @return array
- */
- public function loadDataSet($dataFile, $dataSource, $overrideByKey = null, $overrideByValueParam = null)
- {
- $data = $this->_dataHelper->getDataValue($dataSource);
- if ($data === false) {
- $dataSetName = array_shift(explode('/', $dataSource));
- $this->_dataHelper->loadTestDataSet($dataFile, $dataSetName);
- $data = $this->_dataHelper->getDataValue($dataSource);
- }
- if (!is_array($data)) {
- throw new PHPUnit_Framework_Exception('Data "' . $dataSource . '" is not specified.');
- }
- if ($overrideByKey) {
- $data = $this->overrideArrayData($overrideByKey, $data, 'byFieldKey');
- }
- if ($overrideByValueParam) {
- $data = $this->overrideArrayData($overrideByValueParam, $data, 'byValueParam');
- }
- array_walk_recursive($data, array($this, 'setDataParams'));
- return $this->clearDataArray($data);
- }
- /**
- * Override data in array.
- *
- * @param array $dataForOverride
- * @param array $overrideArray
- * @param string $overrideType
- *
- * @return array
- * @throws RuntimeException
- */
- public function overrideArrayData(array $dataForOverride, array $overrideArray, $overrideType)
- {
- $errorMessages = array();
- $messageParam = strtolower(substr_replace(str_replace('by', '', $overrideType), ' ', 5, 0));
- foreach ($dataForOverride as $fieldKey => $fieldValue) {
- if (!$this->overrideDataByCondition($fieldKey, $fieldValue, $overrideArray, $overrideType)) {
- $errorMessages[] =
- "Value for '" . $fieldKey . "' " . $messageParam . " is not changed: [There is no this "
- . $messageParam . " in dataset]";
- }
- }
- if ($errorMessages) {
- throw new RuntimeException(implode("\n", $errorMessages));
- }
- return $overrideArray;
- }
- /**
- * Change in array value by condition.
- *
- * @param string $overrideKey
- * @param string $overrideValue
- * @param array $overrideArray
- * @param string $condition byFieldKey|byValueParam
- *
- * @return bool
- * @throws OutOfRangeException
- */
- public function overrideDataByCondition($overrideKey, $overrideValue, &$overrideArray, $condition)
- {
- $isOverridden = false;
- foreach ($overrideArray as $currentKey => &$currentValue) {
- switch ($condition) {
- case 'byFieldKey':
- $isFound = ($currentKey === $overrideKey);
- break;
- case 'byValueParam':
- $isFound = ($currentValue === '%' . $overrideKey . '%');
- break;
- default:
- throw new OutOfRangeException('Wrong condition');
- break;
- }
- if ($isFound) {
- $currentValue = $overrideValue;
- $isOverridden = true;
- } elseif (is_array($currentValue)) {
- $isOverridden = $this->overrideDataByCondition($overrideKey, $overrideValue, $currentValue, $condition)
- || $isOverridden;
- }
- }
- return $isOverridden;
- }
- /**
- * Set data params
- *
- * @param string $value
- * @param string $key Index of the target to randomize
- */
- public function setDataParams(&$value, $key)
- {
- if (preg_match('/%randomize%/', $value)) {
- $value = preg_replace('/%randomize%/', $this->generate('string', 5, ':lower:'), $value);
- }
- if (preg_match('/^%longValue[0-9]+%$/', $value)) {
- $length = preg_replace('/[^0-9]/', '', $value);
- $value = preg_replace('/%longValue[0-9]+%/', $this->generate('string', $length, ':alpha:'), $value);
- }
- if (preg_match('/^%specialValue[0-9]+%$/', $value)) {
- $length = preg_replace('/[^0-9]/', '', $value);
- $value = preg_replace('/%specialValue[0-9]+%/', $this->generate('string', $length, ':punct:'), $value);
- }
- if (preg_match('/%currentDate%/', $value)) {
- $fallbackOrderHelper = $this->_configHelper->getFixturesFallbackOrder();
- switch (end($fallbackOrderHelper)) {
- case 'enterprise':
- $value = preg_replace('/%currentDate%/', date("n/j/Y"), $value);
- break;
- default:
- $value = preg_replace('/%currentDate%/', date("n/j/y"), $value);
- break;
- }
- }
- }
- /**
- * Delete field in array with special values(for example: %noValue%)
- *
- * @param array $dataArray
- *
- * @return array|bool
- */
- public function clearDataArray($dataArray)
- {
- if (!is_array($dataArray)) {
- return false;
- }
- foreach ($dataArray as $key => $value) {
- if (is_array($value)) {
- $dataArray[$key] = $this->clearDataArray($value);
- if (count($dataArray[$key]) == false) {
- unset($dataArray[$key]);
- }
- } elseif (preg_match('/^\%(\w)+\%$/', $value)) {
- unset($dataArray[$key]);
- }
- }
- return $dataArray;
- }
- ################################################################################
- # Deprecated data helper methods #
- ################################################################################
- /**
- * Loads test data from DataSet, specified in the $dataSource
- *
- * @deprecated
- * @see loadDataSet()
- *
- * @param string $dataSource Data source (e.g. filename in ../data without .yml extension)
- * @param null|array $override value to override in original data from data source
- * @param null|array|string $randomize Value to randomize
- *
- * @return array
- */
- public function loadData($dataSource, $override = null, $randomize = null)
- {
- $data = $this->_dataHelper->getDataValue($dataSource);
- if (!is_array($data)) {
- $this->fail('Data \'' . $dataSource . '\' is not loaded');
- }
- array_walk_recursive($data, array($this, 'setDataParams'));
- if (!empty($randomize)) {
- $randomize = (!is_array($randomize))
- ? array($randomize)
- : $randomize;
- array_walk_recursive($data, array($this, 'randomizeData'), $randomize);
- }
- if (!empty($override) && is_array($override)) {
- $withSubArray = array();
- $withOutSubArray = array();
- foreach ($override as $key => $value) {
- if (preg_match('|/|', $key)) {
- $withSubArray[$key]['subArray'] = preg_replace('#/[a-z0-9_]+$#i', '', $key);
- $withSubArray[$key]['name'] = preg_replace('#^[a-z0-9_]+/#i', '', $key);
- $withSubArray[$key]['value'] = $value;
- } else {
- $withOutSubArray[$key] = $value;
- }
- }
- foreach ($withOutSubArray as $key => $value) {
- if (!$this->overrideData($key, $value, $data)) {
- $data[$key] = $value;
- }
- }
- foreach ($withSubArray as $value) {
- if (!$this->overrideDataInSubArray($value['subArray'], $value['name'], $value['value'], $data)) {
- $data[$value['subArray']][$value['name']] = $value['value'];
- }
- }
- }
- return $data;
- }
- /**
- * Remove array elements that have '%noValue%' value
- *
- * @deprecated
- * @see clearDataArray()
- *
- * @param array $array
- *
- * @return array
- */
- public function arrayEmptyClear(array $array)
- {
- foreach ($array as $k => $v) {
- if (is_array($v)) {
- $array[$k] = $this->arrayEmptyClear($v);
- if (count($array[$k]) == false) {
- unset($array[$k]);
- }
- } else {
- if ($v === '%noValue%') {
- unset($array[$k]);
- }
- }
- }
- return $array;
- }
- /**
- * Override data with index $key on-fly in the $overrideArray by new value (&$value)
- * @deprecated
- * @see overrideDataByCondition()
- *
- * @param string $overrideKey Index of the target to override
- * @param string $overrideValue Value for override
- * @param array $overrideArray Target array, which contains some index(es) to override
- *
- * @return bool
- */
- public function overrideData($overrideKey, $overrideValue, &$overrideArray)
- {
- $overrideResult = false;
- foreach ($overrideArray as $key => &$value) {
- if ($key === $overrideKey) {
- $overrideArray[$key] = $overrideValue;
- $overrideResult = true;
- } elseif (is_array($value)) {
- $result = $this->overrideData($overrideKey, $overrideValue, $value);
- if ($result || $overrideResult) {
- $overrideResult = true;
- }
- }
- }
- return $overrideResult;
- }
- /**
- * @deprecated
- * @see overrideDataByCondition()
- *
- * @param string $subArray
- * @param string $overrideKey
- * @param string $overrideValue
- * @param array $overrideArray
- *
- * @return bool
- */
- public function overrideDataInSubArray($subArray, $overrideKey, $overrideValue, &$overrideArray)
- {
- $overrideResult = false;
- foreach ($overrideArray as $key => &$value) {
- if (is_array($value)) {
- if ($key === $subArray) {
- foreach ($value as $k => $v) {
- if ($k === $overrideKey) {
- $value[$k] = $overrideValue;
- $overrideResult = true;
- }
- if (is_array($v)) {
- $result = $this->overrideDataInSubArray($subArray, $overrideKey, $overrideValue, $value);
- if ($result || $overrideResult) {
- $overrideResult = true;
- }
- }
- }
- } else {
- $result = $this->overrideDataInSubArray($subArray, $overrideKey, $overrideValue, $value);
- if ($result || $overrideResult) {
- $overrideResult = true;
- }
- }
- }
- }
- return $overrideResult;
- }
- /**
- * Randomize data with index $key on-fly in the $randomizeArray by new value (&$value)
- *
- * @deprecated
- * @see setDataParams()
- *
- * @param string $value Value for randomization (in this case - value will be as a suffix)
- * @param string $key Index of the target to randomize
- * @param array $randomizeArray Target array, which contains some index(es) to randomize
- */
- public function randomizeData(&$value, $key, $randomizeArray)
- {
- foreach ($randomizeArray as $randomizeField) {
- if ($randomizeField === $key) {
- $value = $this->generate('string', 5, ':lower:') . '_' . $value;
- }
- }
- }
- ################################################################################
- # #
- # Messages helper methods #
- # #
- ################################################################################
- /**
- * Removes all added messages
- *
- * @param null|string $type
- */
- public function clearMessages($type = null)
- {
- if ($type && array_key_exists($type, self::$_messages)) {
- unset(self::$_messages[$type]);
- } elseif ($type == null) {
- self::$_messages = null;
- }
- }
- /**
- * Gets all messages on the pages
- */
- protected function _parseMessages()
- {
- $area = $this->getArea();
- $page = $this->getCurrentUimapPage();
- if ($area == 'admin' || $area == 'frontend') {
- $fieldNameWithMessage = $page->findPageelement('fieldNameWithValidationMessage');
- self::$_messages['notice'] = $this->getElementsByXpath($page->findMessage('general_notice'));
- self::$_messages['validation'] =
- $this->getElementsByXpath($page->findMessage('general_validation'), 'text', $fieldNameWithMessage);
- } else {
- self::$_messages['validation'] = $this->getElementsByXpath($page->findMessage('general_validation'));
- }
- self::$_messages['success'] = $this->getElementsByXpath($page->findMessage('general_success'));
- self::$_messages['error'] = $this->getElementsByXpath($page->findMessage('general_error'));
- }
- /**
- * Returns all messages (or messages of the specified type) on the page
- *
- * @param null|string $type Message type: validation|error|success
- *
- * @return array
- */
- public function getMessagesOnPage($type = null)
- {
- $this->_parseMessages();
- if ($type) {
- return self::$_messages[$type];
- }
- return self::$_messages;
- }
- /**
- * Returns all parsed messages (or messages of the specified type)
- *
- * @param null|string $type Message type: validation|error|success (default = null, for all messages)
- *
- * @return array|null
- */
- public function getParsedMessages($type = null)
- {
- if ($type) {
- return (isset(self::$_messages[$type]))
- ? self::$_messages[$type]
- : null;
- }
- return self::$_messages;
- }
- /**
- * Adds validation|error|success message(s)
- *
- * @param string $type Message type: validation|error|success
- * @param string|array $message Message text
- */
- public function addMessage($type, $message)
- {
- if (is_array($message)) {
- foreach ($message as $value) {
- self::$_messages[$type][] = $value;
- }
- } else {
- self::$_messages[$type][] = $message;
- }
- }
- /**
- * Adds a verification message
- *
- * @param string|array $message Message text
- */
- public function addVerificationMessage($message)
- {
- $this->addMessage('verification', $message);
- }
- /**
- * Verifies messages count
- *
- * @param int $count Expected number of message(s) on the page
- * @param null|string $xpath XPath of a message(s) that should be evaluated (default = null)
- *
- * @return int Number of nodes that match the specified $xpath
- */
- public function verifyMessagesCount($count = 1, $xpath = null)
- {
- if ($xpath === null) {
- $xpath = $this->_getMessageXpath('general_validation');
- }
- $this->_parseMessages();
- return $this->getXpathCount($xpath) == $count;
- }
- /**
- * Check if the specified message exists on the page
- *
- * @param string $message Message ID from UIMap
- *
- * @return array
- */
- public function checkMessage($message)
- {
- $messageLocator = $this->_getMessageXpath($message);
- return $this->checkMessageByXpath($messageLocator);
- }
- /**
- * Checks if message with the specified XPath exists on the page
- *
- * @param string $xpath XPath of message to checking
- *
- * @return array
- */
- public function checkMessageByXpath($xpath)
- {
- $this->_parseMessages();
- if ($xpath && $this->isElementPresent($xpath)) {
- return array("success" => true);
- }
- return array("success" => false,
- "xpath" => $xpath,
- "found" => self::messagesToString($this->getMessagesOnPage()));
- }
- /**
- * Checks if any 'error' message exists on the page
- *
- * @param null|string $message Error message ID from UIMap OR XPath of the error message (by default = null)
- *
- * @return array
- */
- public function errorMessage($message = null)
- {
- return (!empty($message))
- ? $this->checkMessage($message)
- : $this->checkMessageByXpath($this->_getMessageXpath('general_error'));
- }
- /**
- * Checks if any 'success' message exists on the page
- *
- * @param null|string $message Success message ID from UIMap OR XPath of the success message (by default = null)
- *
- * @return array
- */
- public function successMessage($message = null)
- {
- return (!empty($message))
- ? $this->checkMessage($message)
- : $this->checkMessageByXpath($this->_getMessageXpath('general_success'));
- }
- /**
- * Checks if any 'validation' message exists on the page
- *
- * @param null|string $message Validation message ID from UIMap OR XPath of the validation message (by default = null)
- *
- * @return array
- */
- public function validationMessage($message = null)
- {
- return (!empty($message))
- ? $this->checkMessage($message)
- : $this->checkMessageByXpath($this->_getMessageXpath('general_validation'));
- }
- /**
- * Asserts that the specified message of the specified type is present on the current page
- *
- * @param string $type success|validation|error
- * @param null|string $message Message ID from UIMap
- */
- public function assertMessagePresent($type, $message = null)
- {
- $method = strtolower($type) . 'Message';
- $result = $this->$method($message);
- if (!$result['success']) {
- if (is_null($message)) {
- $error = "Failed looking for '" . $type . "' message.\n";
- } else {
- $error = "Failed looking for '" . $message . "' message.\n[xpath: " . $result['xpath'] . "]\n";
- }
- if ($result['found']) {
- $error .= "Found messages instead:\n" . $result['found'];
- }
- $this->fail($error);
- }
- }
- /**
- * Asserts that the specified message of the specified type is not present on the current page
- *
- * @param string $type success|validation|error
- * @param null|string $message Message ID from UIMap
- */
- public function assertMessageNotPresent($type, $message = null)
- {
- $method = strtolower($type) . 'Message';
- $result = $this->$method($message);
- if ($result['success']) {
- if (is_null($message)) {
- $error = "'" . $type . "' message is on the page.";
- } else {
- $error = "'" . $message . "' message is on the page.";
- }
- $messagesOnPage = self::messagesToString($this->getMessagesOnPage());
- if ($messagesOnPage) {
- $error .= "\n" . $messagesOnPage;
- }
- $this->fail($error);
- }
- }
- /**
- * Assert there are no verification errors
- */
- public function assertEmptyVerificationErrors()
- {
- $verificationErrors = $this->getParsedMessages('verification');
- if ($verificationErrors) {
- $this->clearMessages('verification');
- $this->fail(implode("\n", $verificationErrors));
- }
- }
- /**
- * @param string $type
- *
- * @return array|string
- * @throws RuntimeException
- */
- public function getBasicXpathMessage($type = 'all')
- {
- $xpath = null;
- $types = array('success', 'error', 'validation', 'notice');
- $currentPage = $this->getCurrentPage();
- $currentArea = $this->getArea();
- $this->setArea('admin');
- $this->setCurrentPage('dashboard');
- if ($type != 'all') {
- if (in_array($type, $types)) {
- $xpath = $this->_getMessageXpath('general_' . $type);
- } else {
- throw new RuntimeException('Incorrect message type');
- }
- } else {
- foreach ($types as $value) {
- $xpath[$value] = $this->_getMessageXpath('general_' . $value);
- }
- }
- $this->setArea($currentArea);
- $this->setCurrentPage($currentPage);
- return $xpath;
- }
- /**
- * Returns a string representation of the messages.
- *
- * @static
- *
- * @param array|string $message
- *
- * @return string
- */
- protected static function messagesToString($message)
- {
- if (is_array($message) && $message) {
- $message = implode("\n", call_user_func_array('array_merge', $message));
- }
- return $message;
- }
- ################################################################################
- # #
- # Navigation helper methods #
- # #
- ################################################################################
- /**
- * Set additional params for navigation
- *
- * @param string $params your params to add to URL (?paramName1=paramValue1¶mName2=paramValue2)
- */
- public function setUrlPostfix($params)
- {
- $this->_urlPostfix = $params;
- }
- /**
- * Navigates to the specified page in specified area.<br>
- * Page identifier must be described in the UIMap.
- *
- * @param string $area Area identifier (by default = 'frontend')
- * @param string $page Page identifier
- * @param bool $validatePage
- *
- * @return Mage_Selenium_TestCase
- */
- public function goToArea($area = 'frontend', $page = '', $validatePage = true)
- {
- $this->_configHelper->setArea($area);
- if ($page == '') {
- $areaConfig = $this->_configHelper->getAreaConfig();
- $page = $areaConfig['base_page_uimap'];
- }
- $this->navigate($page, $validatePage);
- return $this;
- }
- /**
- * Navigates to the specified page in the current area.<br>
- * Page identifier must be described in the UIMap.
- *
- * @param string $page Page identifier
- * @param bool $validatePage
- *
- * @return Mage_Selenium_TestCase
- */
- public function navigate($page, $validatePage = true)
- {
- $area = $this->_configHelper->getArea();
- $clickXpath = $this->_uimapHelper->getPageClickXpath($area, $page, $this->_paramsHelper);
- if ($clickXpath && $this->isElementPresent($clickXpath)) {
- $this->click($clickXpath);
- $this->waitForPageToLoad($this->_browserTimeoutPeriod);
- } elseif (isset($this->_urlPostfix)) {
- $this->open($this->_uimapHelper->getPageUrl($area, $page, $this->_paramsHelper) . $this->_urlPostfix);
- } else {
- $this->open($this->_uimapHelper->getPageUrl($area, $page, $this->_paramsHelper));
- }
- if ($validatePage) {
- $this->validatePage($page);
- }
- return $this;
- }
- /**
- * Navigate to the specified admin page.<br>
- * Page identifier must be described in the UIMap. Opens "Dashboard" page by default.
- *
- * @param string $page Page identifier (by default = 'dashboard')
- * @param bool $validatePage
- *
- * @return Mage_Selenium_TestCase
- */
- public function admin($page = 'dashboard', $validatePage = true)
- {
- $this->goToArea('admin', $page, $validatePage);
- return $this;
- }
- /**
- * Navigate to the specified frontend page<br>
- * Page identifier must be described in the UIMap. Opens "Home page" by default.
- *
- * @param string $page Page identifier (by default = 'home_page')
- * @param bool $validatePage
- *
- * @return Mage_Selenium_TestCase
- */
- public function frontend($page = 'home_page', $validatePage = true)
- {
- $this->goToArea('frontend', $page, $validatePage);
- return $this;
- }
- ################################################################################
- # #
- # Area helper methods #
- # #
- ################################################################################
- /**
- * Gets current location area<br>
- * Usage: define area currently operating.
- * <li>Possible areas: frontend | admin
- * @return string
- */
- public function getCurrentLocationArea()
- {
- $currentArea = self::_getAreaFromCurrentUrl($this->_configHelper->getConfigAreas(), $this->getLocation());
- $this->_configHelper->setArea($currentArea);
- return $currentArea;
- }
- /**
- * Find area in areasConfig using full page URL
- * @static
- *
- * @param array $areasConfig Full area config
- * @param string $cu…
Large files files are truncated, but you can click here to view the full file