App.php 16.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
<?php
/**
 * PHP Unit test suite for 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
 *
 * @category   EcomDev
 * @package    EcomDev_PHPUnit
 * @copyright  Copyright (c) 2011 Ecommerce Developers (http://www.ecomdev.org)
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 * @author     Ivan Chepurnyi <ivan.chepurnyi@ecomdev.org>
 */

/**
 * Application model for phpunit tests
 *
 */
class EcomDev_PHPUnit_Model_App extends Mage_Core_Model_App
{
    // Run types constants,
    // Don't know why
    // they are not defined in core application
    const RUN_TYPE_STORE = 'store';
    const RUN_TYPE_WEBSITE = 'website';
    const RUN_TYPE_GROUP = 'group';

    // Admin store code
    const ADMIN_STORE_CODE = 'admin';

35 36 37 38 39 40 41 42 43 44 45 46
    const AREA_ADMINHTML = EcomDev_PHPUnit_Model_App_Area::AREA_ADMINHTML;
    const AREA_ADMIN = EcomDev_PHPUnit_Model_App_Area::AREA_ADMIN;
    const AREA_FRONTEND = EcomDev_PHPUnit_Model_App_Area::AREA_FRONTEND;
    const AREA_GLOBAL = EcomDev_PHPUnit_Model_App_Area::AREA_GLOBAL;
    const AREA_TEST = EcomDev_PHPUnit_Model_App_Area::AREA_TEST;

    const AREA_PART_EVENTS = EcomDev_PHPUnit_Model_App_Area::PART_EVENTS;
    const AREA_PART_DESIGN = EcomDev_PHPUnit_Model_App_Area::PART_DESIGN;
    const AREA_PART_TRANSLATE = EcomDev_PHPUnit_Model_App_Area::PART_TRANSLATE;
    const AREA_PART_CONFIG = EcomDev_PHPUnit_Model_App_Area::PART_CONFIG;

    const INTERFACE_ISOLATION = 'EcomDev_PHPUnit_Isolation_Interface';
47

48
    const REGISTRY_PATH_LAYOUT_SINGLETON = '_singleton/core/layout';
49 50
    const REGISTRY_PATH_DESIGN_PACKAGE_SINGLETON = '_singleton/core/design_package';

Ivan Chepurnyi's avatar
Ivan Chepurnyi committed
51 52
    const REGISTRY_PATH_SHARED_STORAGE = 'test_suite_shared_storage';

53
    const XML_PATH_LAYOUT_MODEL_FOR_TEST = 'phpunit/suite/layout/model';
54 55 56 57 58 59
    const XML_PATH_DESIGN_PACKAGE_MODEL_FOR_TEST = 'phpunit/suite/design/package/model';

    const XML_PATH_APP_AREA = 'phpunit/suite/app/area/class';
    const XML_PATH_CONTROLLER_FRONT = 'phpunit/suite/controller/front/class';
    const XML_PATH_CONTROLLER_REQUEST = 'phpunit/suite/controller/request/class';
    const XML_PATH_CONTROLLER_RESPONSE = 'phpunit/suite/controller/response/class';
60

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    /**
     * Old configuration model to be returned back
     * after unit tests are finished
     *
     * @var Mage_Core_Model_Config
     */
    protected static $_oldConfig = null;

    /**
     * Old application model to be returned back
     * after unit tests are finished
     *
     * @var Mage_Core_Model_App
     */
    protected static $_oldApplication = null;

    /**
     * Old event collection to be returned back
     * after the unit tests are finished
     *
     * @var Varien_Event_Collection
     */
    protected static $_oldEventCollection = null;

85 86 87 88 89 90 91
    /**
     * List of singletons in original application
     *
     * @var array
     */
    protected static $_oldRegistry = null;

92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
    /**
     * Configuration model class name for unit tests
     *
     * @var string
     */
    protected static $_configClass = 'EcomDev_PHPUnit_Model_Config';

    /**
     * Configuration model class name for unit tests
     *
     * @var string
     */
    protected static $_eventCollectionClass = 'Varien_Event_Collection';

    /**
107
     * List of areas that will be ignored in resetAreas() method
108
     *
109
     * @var array
110
     */
111 112 113 114
    protected $_resetIgnoreAreas = array(
        self::AREA_GLOBAL,
        self::AREA_TEST
    );
115

116 117 118 119 120 121 122
    /**
     * Enabled events flag
     *
     * @var boolean
     */
    protected $_eventsEnabled = true;

123 124 125 126 127 128 129
    /**
     * Dispatched events array
     *
     * @var array
     */
    protected $_dispatchedEvents = array();

130 131 132 133 134 135 136
    /**
     * List of module names stored by class name
     *
     * @var array
     */
    protected $_moduleNameByClassName = array();

137 138 139 140 141 142 143 144 145 146 147
    /**
     * This method replaces application, event and config objects
     * in Mage to perform unit tests in separate Magento steam
     *
     */
    public static function applyTestScope()
    {
        // Save old environment variables
        self::$_oldApplication = EcomDev_Utils_Reflection::getRestrictedPropertyValue('Mage', '_app');
        self::$_oldConfig = EcomDev_Utils_Reflection::getRestrictedPropertyValue('Mage', '_config');
        self::$_oldEventCollection = EcomDev_Utils_Reflection::getRestrictedPropertyValue('Mage', '_events');
148
        self::$_oldRegistry = EcomDev_Utils_Reflection::getRestrictedPropertyValue('Mage', '_registry');
149 150 151 152 153 154


        // Setting environment variables for unit tests
        EcomDev_Utils_Reflection::setRestrictedPropertyValue('Mage', '_config', new self::$_configClass);
        EcomDev_Utils_Reflection::setRestrictedPropertyValue('Mage', '_app', new self);
        EcomDev_Utils_Reflection::setRestrictedPropertyValue('Mage', '_events', new self::$_eventCollectionClass);
155
        EcomDev_Utils_Reflection::setRestrictedPropertyValue('Mage', '_registry', array());
156 157 158 159 160 161 162 163 164 165 166 167

        // All unit tests will be runned in admin scope, to get rid of frontend restrictions
        Mage::app()->initTest();
    }

    /**
     * Initializes test scope for PHPUnit
     *
     * @return EcomDev_PHPUnit_Model_App
     */
    public function initTest()
    {
168 169 170 171 172 173 174 175
        if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
            // If garbage collector is not enabled,
            // we enable it for tests
            if (!gc_enabled()) {
                gc_enable();
            }
        }

176 177 178
        $this->_config = Mage::getConfig();
        $this->_initBaseConfig();
        $this->_initCache();
179 180 181 182 183 184 185 186 187 188 189 190 191 192

        // Set using cache
        // for things that shouldn't be reloaded each time
        EcomDev_Utils_Reflection::setRestrictedPropertyValue(
            $this->_cache,
            '_allowedCacheOptions',
            array(
                'eav' => 1,
                'layout' => 1,
                'translate' => 1
            )
        );

        // Clean cache before the whole suite is running
193
        $this->getCache()->clean();
194

195 196 197
        // Init modules runs install proccess for table structures,
        // It is required for setting up proper setup script
        $this->_initModules();
198 199 200

        $this->loadAreaPart(self::AREA_GLOBAL, self::AREA_PART_EVENTS);

201 202 203 204 205 206
        if ($this->_config->isLocalConfigLoaded()) {
            $this->_initCurrentStore(self::ADMIN_STORE_CODE, self::RUN_TYPE_STORE);
            $this->_initRequest();
            Mage_Core_Model_Resource_Setup::applyAllDataUpdates();
        }

207 208 209 210 211 212 213 214 215 216 217 218 219
        $layoutModel = $this->_getModelFromConfig(
            self::XML_PATH_LAYOUT_MODEL_FOR_TEST,
            self::INTERFACE_ISOLATION,
            'Layout model'
        );

        $this->replaceRegistry(self::REGISTRY_PATH_LAYOUT_SINGLETON,
                               $layoutModel);

        $designPackageModel = $this->_getModelFromConfig(
            self::XML_PATH_DESIGN_PACKAGE_MODEL_FOR_TEST,
            self::INTERFACE_ISOLATION,
            'Design package model'
220 221
        );

222 223
        $this->replaceRegistry(self::REGISTRY_PATH_DESIGN_PACKAGE_SINGLETON,
                               $designPackageModel);
224

225
        $this->loadAreaPart(self::AREA_TEST, self::AREA_PART_EVENTS);
Ivan Chepurnyi's avatar
Ivan Chepurnyi committed
226 227

        $this->replaceRegistry(self::REGISTRY_PATH_SHARED_STORAGE, new Varien_Object());
228 229 230
        return $this;
    }

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
    /**
     * Retrieves a model from config and checks it on interface implementation
     *
     * @param string $configPath
     * @param string $interface
     * @param string $modelName
     * @return Mage_Core_Model_Abstract
     */
    protected function _getModelFromConfig($configPath, $interface, $modelName = 'Model')
    {
        $model = Mage::getModel(
            (string)$this->getConfig()->getNode($configPath)
        );

        if (!$model instanceof $interface) {
           throw new RuntimeException(
               sprintf('%s should implement %s to make possible running tests in isolation',
                       $modelName, $interface)
           );
        }

        return $model;
    }

    /**
     * Initialize front controller for test suite
     *
     * @return EcomDev_PHPUnit_Model_App
     */
    protected function _initFrontController()
    {
        $frontControllerClass = $this->_getClassNameFromConfig(self::XML_PATH_CONTROLLER_FRONT);
        $this->_frontController = new $frontControllerClass();
        Mage::register('controller', $this->_frontController);
        $this->_frontController->init();
        return $this;
    }

    /**
     * Retrieve application area
     *
     * @param   string $code
     * @return  EcomDev_PHPUnit_Model_App_Area
     */
    public function getArea($code)
    {
        if (!isset($this->_areas[$code])) {
            $appAreaClass = $this->_getClassNameFromConfig(
                self::XML_PATH_APP_AREA, self::INTERFACE_ISOLATION
            );
            $this->_areas[$code] = new $appAreaClass($code, $this);
        }
        return $this->_areas[$code];
    }

    /**
     * Resets areas parts, like events, translations, design
     *
     * @return EcomDev_PHPUnit_Model_App
     */
    public function resetAreas()
    {
        /* @var $area EcomDev_PHPUnit_Model_App_Area */
        foreach ($this->_areas as $code => $area) {
            if (!in_array($code, $this->_resetIgnoreAreas)) {
                $area->reset();
            }
        }
        return $this;
    }

    /**
     * Replace registry item value
     *
     * @param string $key
     * @param string $value
     */
    public function replaceRegistry($key, $value)
    {
        $registry = EcomDev_Utils_Reflection::getRestrictedPropertyValue('Mage', '_registry');
        $registry[$key] = $value;
        EcomDev_Utils_Reflection::setRestrictedPropertyValue('Mage', '_registry', $registry);
        return $this;
    }

    /**
     * Removes event area
     *
     * @param string $code area code
     * @return EcomDev_PHPUnit_Model_App
     */
    public function removeEventArea($code)
    {
        if (isset($this->_events[$code])) {
            unset($this->_events[$code]);
        }

        return $this;
    }

    /**
     * Returns request for test suite
     * (non-PHPdoc)
     * @see Mage_Core_Model_App::getRequest()
     * @return EcomDev_PHPUnit_Controller_Request_Http
     */
    public function getRequest()
    {
        if ($this->_request === null) {
            $requestClass = $this->_getClassNameFromConfig(
                self::XML_PATH_CONTROLLER_REQUEST, self::INTERFACE_ISOLATION
            );
            $this->_request = new $requestClass;
        }

        return $this->_request;
    }

    /**
     * Returns response for test suite
     * (non-PHPdoc)
     * @see Mage_Core_Model_App::getResponse()
     * @return EcomDev_PHPUnit_Controller_Response_Http
     */
    public function getResponse()
    {
        if ($this->_response === null) {
            $responseClass = $this->_getClassNameFromConfig(
                self::XML_PATH_CONTROLLER_RESPONSE, self::INTERFACE_ISOLATION
            );
            $this->_response = new $responseClass;
        }

        return $this->_response;
    }

    /**
     * Returns class name from configuration path,
     * If $interface is specified, then it additionaly checks it for implementation
     *
     *
     * @param string $configPath
     * @param string $interface
     * @return string
     */
    protected function _getClassNameFromConfig($configPath, $interface = null)
    {
        $className = (string)$this->getConfig()->getNode($configPath);

        $reflection = EcomDev_Utils_Reflection::getRelflection($className);
        if ($interface !== null && !$reflection->implementsInterface($interface)) {
            throw new RuntimeException(
                sprintf('Invalid class name defined in configuration path %s, because %s does not implement %s interface',
                        $configPath, $interface)
            );
        }
        return $className;
    }

390 391 392 393 394 395 396 397 398 399 400 401
    /**
     * Overriden to fix issue with stores loading
     * (non-PHPdoc)
     * @see Mage_Core_Model_App::_initStores()
     */
    protected function _initStores()
    {
        $this->_store = null;
        parent::_initStores();
        return $this;
    }

402 403 404 405 406 407 408 409 410 411
    /**
     * Discard test scope for application, returns all the objects from live version
     *
     */
    public static function discardTestScope()
    {
        // Setting environment variables for unit tests
        EcomDev_Utils_Reflection::setRestrictedPropertyValue('Mage', '_app', self::$_oldApplication);
        EcomDev_Utils_Reflection::setRestrictedPropertyValue('Mage', '_config', self::$_oldConfig);
        EcomDev_Utils_Reflection::setRestrictedPropertyValue('Mage', '_events', self::$_oldEventCollection);
412 413 414
        EcomDev_Utils_Reflection::setRestrictedPropertyValue('Mage', '_registry', self::$_oldRegistry);
    }

415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
    /**
     * Returns module name for a particular object
     *
     * @param string|object $className
     * @throws RuntimeException if module name was not found for the passed class name
     * @return string
     */
    public function getModuleNameByClassName($className)
    {
        if (is_object($className)) {
            $className = get_class($className);
        }

        if (!isset($this->_moduleNameByClassName[$className])) {
            // Try to find the module name by class name
            $moduleName = false;
            foreach ($this->getConfig()->getNode('modules')->children() as $module) {
                if (strpos($className, $module->getName()) === 0) {
                   $moduleName = $module->getName();
                   break;
                }
            }

            if (!$moduleName) {
                throw new RuntimeException('Cannot to find the module name for class name: ' . $className);
            }

            $this->setModuleNameForClassName($className, $moduleName);
        }

        return $this->_moduleNameByClassName[$className];
    }

    /**
     * Set associated module name for a class name,
     * Usually used for making possible dependency injection in the test cases
     *
     *
     * @param string $className
     * @param string $moduleName
     * @return EcomDev_PHPUnit_Model_App
     */
    public function setModuleNameForClassName($className, $moduleName)
    {
        $this->_moduleNameByClassName[$className] = $moduleName;
        return $this;
    }

463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
    /**
     * Overriden for typehinting
     *
     * @return EcomDev_PHPUnit_Model_Config
     * (non-PHPdoc)
     * @see Mage_Core_Model_App::getConfig()
     */
    public function getConfig()
    {
        return parent::getConfig();
    }

    /**
     * Overriden for typehinting
     *
     * @return EcomDev_PHPUnit_Model_Layout
     * (non-PHPdoc)
     * @see Mage_Core_Model_App::getLayout()
     */
    public function getLayout()
    {
        return parent::getLayout();
    }

487 488 489 490 491 492 493 494 495
    /**
     * Disables events fire
     *
     * @return EcomDev_PHPUnit_Model_App
     */
    public function disableEvents()
    {
        $this->_eventsEnabled = false;
        return $this;
496 497
    }

498 499 500 501 502 503
    /**
     * Enable events fire
     *
     * @return EcomDev_PHPUnit_Model_App
     */
    public function enableEvents()
504
    {
505 506
        $this->_eventsEnabled = true;
        return $this;
507 508
    }

509 510 511 512 513 514 515 516 517 518 519
    /**
     * Overriden for disabling events
     * fire during fixutre loading
     *
     * (non-PHPdoc)
     * @see Mage_Core_Model_App::dispatchEvent()
     */
    public function dispatchEvent($eventName, $args)
    {
        if ($this->_eventsEnabled) {
            parent::dispatchEvent($eventName, $args);
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541

            if (!isset($this->_dispatchedEvents[$eventName])) {
                $this->_dispatchedEvents[$eventName] = 0;
            }

            $this->_dispatchedEvents[$eventName]++;
        }

        return $this;
    }


    /**
     * Returns number of times when the event was dispatched
     *
     * @param string $eventName
     * @return int
     */
    public function getDispatchedEventCount($eventName)
    {
        if (isset($this->_dispatchedEvents[$eventName])) {
            return $this->_dispatchedEvents[$eventName];
542 543
        }

544 545 546 547 548 549 550 551 552 553 554 555
        return 0;
    }


    /**
     * Resets dispatched events information
     *
     * @return EcomDev_PHPUnit_Model_App
     */
    public function resetDispatchedEvents()
    {
        $this->_dispatchedEvents = array();
556 557
        return $this;
    }
558
}