Commit eb3604c0 authored by Ivan Chepurnyi's avatar Ivan Chepurnyi

Merge branch 'feature/test-helpers' into dev

parents 75c27ef3 e5e05b64
...@@ -23,18 +23,18 @@ ...@@ -23,18 +23,18 @@
class EcomDev_PHPUnit_Controller_Front extends Mage_Core_Controller_Varien_Front class EcomDev_PHPUnit_Controller_Front extends Mage_Core_Controller_Varien_Front
{ {
/** /**
* Overriden for getting rid * Resets initialized routers before front controller re-initialization
* of initialization of routers for each test case * on test cases
* *
* (non-PHPdoc) * (non-PHPdoc)
* @see Mage_Core_Controller_Varien_Front::init() * @see Mage_Core_Controller_Varien_Front::init()
*/ */
public function init() public function init()
{ {
if (!$this->_routers) { if ($this->_routers) {;
parent::init(); $this->_routers = array();
} }
return $this; return parent::init();
} }
} }
<?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) 2013 EcomDev BV (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>
*/
class EcomDev_PHPUnit_Model_Observer
{
const XML_PATH_TEST_HELPERS = 'phpunit/suite/helpers';
/**
* Registers default test helpers
*
*/
public function registerDefaultTestHelpers()
{
foreach (Mage::getConfig()->getNode(self::XML_PATH_TEST_HELPERS)->children() as $helperNode) {
$helperClass = (string)$helperNode;
if ($helperClass && class_exists($helperClass)) {
$helper = new $helperClass();
if (!$helper instanceof EcomDev_PHPUnit_Helper_Interface) {
throw new RuntimeException(
sprintf(
'Test helpers should implement %s, but %s is not implementing it.',
'EcomDev_PHPUnit_Helper_Interface',
$helperClass
)
);
}
EcomDev_PHPUnit_Helper::add($helper);
}
}
}
}
\ No newline at end of file
...@@ -17,11 +17,18 @@ ...@@ -17,11 +17,18 @@
*/ */
use EcomDev_PHPUnit_Test_Case_Util as TestUtil; use EcomDev_PHPUnit_Test_Case_Util as TestUtil;
use EcomDev_PHPUnit_Helper as TestHelper;
/** /**
* Basic test case class * Basic test case class, implements test helpers for easy working with Magento
*
* *
* @method EcomDev_PHPUnit_Mock_Proxy mockClassAlias(string $type, $classAlias, array $methods = array(), array $constructorArgs = array())
* @method EcomDev_PHPUnit_Mock_Proxy mockModel($classAlias, array $methods = array(), array $constructorArgs = array())
* @method EcomDev_PHPUnit_Mock_Proxy mockBlock($classAlias, array $methods = array(), array $constructorArgs = array())
* @method EcomDev_PHPUnit_Mock_Proxy mockHelper($classAlias, array $methods = array(), array $constructorArgs = array())
* @method EcomDev_PHPUnit_Mock_Proxy mockSession($classAlias, array $methods = array())
* @method EcomDev_PHPUnit_Mock_Proxy adminSession(array $resources = array())
* @method EcomDev_PHPUnit_Mock_Proxy customerSession(int $customerId)
*/ */
abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase
{ {
...@@ -372,20 +379,18 @@ abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase ...@@ -372,20 +379,18 @@ abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase
* *
* @param string $type block|model|helper * @param string $type block|model|helper
* @param string $classAlias * @param string $classAlias
* @return PHPUnit_Framework_MockObject_MockBuilder * @return EcomDev_PHPUnit_Mock_Proxy
*/ */
public function getGroupedClassMockBuilder($type, $classAlias) public function getGroupedClassMockBuilder($type, $classAlias)
{ {
$className = $this->getGroupedClassName($type, $classAlias); return TestUtil::getGroupedClassMockBuilder($this, $type, $classAlias);
return $this->getMockBuilder($className);
} }
/** /**
* Retrieves a mock builder for a block class alias * Retrieves a mock builder for a block class alias
* *
* @param string $classAlias * @param string $classAlias
* @return PHPUnit_Framework_MockObject_MockBuilder * @return EcomDev_PHPUnit_Mock_Proxy
*/ */
public function getBlockMockBuilder($classAlias) public function getBlockMockBuilder($classAlias)
{ {
...@@ -396,7 +401,7 @@ abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase ...@@ -396,7 +401,7 @@ abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase
* Retrieves a mock builder for a model class alias * Retrieves a mock builder for a model class alias
* *
* @param string $classAlias * @param string $classAlias
* @return PHPUnit_Framework_MockObject_MockBuilder * @return EcomDev_PHPUnit_Mock_Proxy
*/ */
public function getModelMockBuilder($classAlias) public function getModelMockBuilder($classAlias)
{ {
...@@ -407,7 +412,7 @@ abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase ...@@ -407,7 +412,7 @@ abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase
* Retrieves a mock builder for a resource model class alias * Retrieves a mock builder for a resource model class alias
* *
* @param string $classAlias * @param string $classAlias
* @return PHPUnit_Framework_MockObject_MockBuilder * @return EcomDev_PHPUnit_Mock_Proxy
*/ */
public function getResourceModelMockBuilder($classAlias) public function getResourceModelMockBuilder($classAlias)
{ {
...@@ -418,7 +423,7 @@ abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase ...@@ -418,7 +423,7 @@ abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase
* Retrieves a mock builder for a helper class alias * Retrieves a mock builder for a helper class alias
* *
* @param string $classAlias * @param string $classAlias
* @return PHPUnit_Framework_MockObject_MockBuilder * @return EcomDev_PHPUnit_Mock_Proxy
*/ */
public function getHelperMockBuilder($classAlias) public function getHelperMockBuilder($classAlias)
{ {
...@@ -436,7 +441,7 @@ abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase ...@@ -436,7 +441,7 @@ abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase
* @param boolean $callOriginalConstructor * @param boolean $callOriginalConstructor
* @param boolean $callOriginalClone * @param boolean $callOriginalClone
* @param boolean $callAutoload * @param boolean $callAutoload
* @return PHPUnit_Framework_MockObject_MockObject * @return EcomDev_PHPUnit_Mock_Proxy
*/ */
public function getModelMock($classAlias, $methods = array(), $isAbstract = false, public function getModelMock($classAlias, $methods = array(), $isAbstract = false,
array $constructorArguments = array(), array $constructorArguments = array(),
...@@ -460,7 +465,7 @@ abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase ...@@ -460,7 +465,7 @@ abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase
* @param boolean $callOriginalConstructor * @param boolean $callOriginalConstructor
* @param boolean $callOriginalClone * @param boolean $callOriginalClone
* @param boolean $callAutoload * @param boolean $callAutoload
* @return PHPUnit_Framework_MockObject_MockObject * @return EcomDev_PHPUnit_Mock_Proxy
*/ */
public function getResourceModelMock($classAlias, $methods = array(), $isAbstract = false, public function getResourceModelMock($classAlias, $methods = array(), $isAbstract = false,
array $constructorArguments = array(), array $constructorArguments = array(),
...@@ -484,7 +489,7 @@ abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase ...@@ -484,7 +489,7 @@ abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase
* @param boolean $callOriginalConstructor * @param boolean $callOriginalConstructor
* @param boolean $callOriginalClone * @param boolean $callOriginalClone
* @param boolean $callAutoload * @param boolean $callAutoload
* @return PHPUnit_Framework_MockObject_MockObject * @return EcomDev_PHPUnit_Mock_Proxy
*/ */
public function getHelperMock($classAlias, $methods = array(), $isAbstract = false, public function getHelperMock($classAlias, $methods = array(), $isAbstract = false,
array $constructorArguments = array(), array $constructorArguments = array(),
...@@ -508,7 +513,7 @@ abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase ...@@ -508,7 +513,7 @@ abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase
* @param boolean $callOriginalConstructor * @param boolean $callOriginalConstructor
* @param boolean $callOriginalClone * @param boolean $callOriginalClone
* @param boolean $callAutoload * @param boolean $callAutoload
* @return PHPUnit_Framework_MockObject_MockObject * @return EcomDev_PHPUnit_Mock_Proxy
*/ */
public function getBlockMock($classAlias, $methods = array(), $isAbstract = false, public function getBlockMock($classAlias, $methods = array(), $isAbstract = false,
array $constructorArguments = array(), array $constructorArguments = array(),
...@@ -529,11 +534,7 @@ abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase ...@@ -529,11 +534,7 @@ abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase
*/ */
protected function getGroupedClassName($type, $classAlias) protected function getGroupedClassName($type, $classAlias)
{ {
if ($type === 'resource_model') { return TestUtil::getGroupedClassName($type, $classAlias);
return $this->app()->getConfig()->getResourceModelClassName($classAlias);
}
return $this->app()->getConfig()->getGroupedClassName($type, $classAlias);
} }
/** /**
...@@ -705,4 +706,16 @@ abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase ...@@ -705,4 +706,16 @@ abstract class EcomDev_PHPUnit_Test_Case extends PHPUnit_Framework_TestCase
TestUtil::setCurrentStore($store); TestUtil::setCurrentStore($store);
return $this; return $this;
} }
/**
* Calling of the helper method
*
* @param string $method
* @param array $args
* @return mixed
*/
public function __call($method, array $args)
{
return TestUtil::call($method, $args);
}
} }
<?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) 2013 EcomDev BV (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>
*/
use EcomDev_PHPUnit_Helper as TestHelper;
use EcomDev_PHPUnit_Test_Case_Util as TestUtil;
/**
* Helper for stubbing customer session
*
*
*/
class EcomDev_PHPUnit_Test_Case_Helper_Customer extends EcomDev_PHPUnit_Helper_Abstract
{
/**
* Logs in as a customer by customer id and store id
*
* @param int $customerId
* @param string|int|null $storeId
*
* @return EcomDev_PHPUnit_Mock_Proxy
*/
public function helperCustomerSession($customerId, $storeId = null)
{
$customerSessionMock = TestHelper::invoke(
'mockSession',
'customer/session',
array('renewSession')
);
if ($storeId === null) {
$storeId = TestUtil::app()->getAnyStoreView()->getCode();
}
TestUtil::setCurrentStore($storeId);
$customerSessionMock->loginById($customerId);
return $customerSessionMock;
}
}
<?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) 2013 EcomDev BV (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>
*/
use EcomDev_PHPUnit_Test_Case_Util as TestUtil;
/**
* Mock helper for Test Case
*
*/
class EcomDev_PHPUnit_Test_Case_Helper_Mock extends EcomDev_PHPUnit_Helper_Abstract
{
/**
* Creates a mockery for a class alias of particular type
*
* @param string $type
* @param string $classAlias
* @param array $methods
* @param array $constructorArgs
*
* @return EcomDev_PHPUnit_Mock_Proxy
*/
public function helperMockClassAlias($type, $classAlias, array $methods = array(), array $constructorArgs = array())
{
return TestUtil::getGroupedClassMockBuilder($this->testCase, $type, $classAlias)
->setConstructorArgs($constructorArgs)
->setMethods($methods);
}
/**
* Creates a mock for a model by its class alias
*
* @param string $classAlias
* @param array $methods
* @param array $constructorArgs
*
* @return EcomDev_PHPUnit_Mock_Proxy
*/
public function helperMockModel($classAlias, array $methods = array(), array $constructorArgs = array())
{
return $this->helperMockClassAlias('model', $classAlias, $methods, $constructorArgs);
}
/**
* Creates a mock for a block by its class alias
*
* @param string $classAlias
* @param array $methods
* @param array $constructorArgs
*
* @return EcomDev_PHPUnit_Mock_Proxy
*/
public function helperMockBlock($classAlias, array $methods = array(), array $constructorArgs = array())
{
return $this->helperMockClassAlias('block', $classAlias, $methods, $constructorArgs);
}
/**
* Creates a mock for a block by its class alias
*
* @param string $classAlias
* @param array $methods
* @param array $constructorArgs
*
* @return EcomDev_PHPUnit_Mock_Proxy
*/
public function helperMockHelper($classAlias, array $methods = array(), array $constructorArgs = array())
{
return $this->helperMockClassAlias('helper', $classAlias, $methods, $constructorArgs);
}
}
<?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) 2013 EcomDev BV (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>
*/
use EcomDev_PHPUnit_Test_Case_Util as TestUtil;
/**
* Session mocks helper
*
*/
class EcomDev_PHPUnit_Test_Case_Helper_Session
extends EcomDev_PHPUnit_Helper_Abstract
implements EcomDev_PHPUnit_Helper_Listener_Interface
{
/**
* Loaded ACL model for admin session mocks
*
* @var Mage_Admin_Model_Acl
*/
protected $acl;
/**
* Creates a mockery for session
*
* @param string $classAlias
* @param array $methods
*
* @return EcomDev_PHPUnit_Mock_Proxy
*/
public function helperMockSession($classAlias, array $methods = array())
{
$sessionMock = EcomDev_PHPUnit_Helper::invoke('mockModel', $classAlias, $methods)
->disableOriginalConstructor();
TestUtil::replaceByMock('singleton', $classAlias, $sessionMock);
return $sessionMock;
}
/**
* Helper for mocking admin panel session
*
* @param array $resources
* @return EcomDev_PHPUnit_Mock_Proxy
*/
public function helperAdminSession(array $resources = array())
{
$session = $this->helperMockSession('admin/session', array('refreshAcl'));
$user = $this->createUser();
$this->loadRules($user, $this->getAcl(), $resources);
$session->setAcl($this->getAcl());
$session->setUser($user);
return $session;
}
/**
* Returns an instance of ACL object that will be used for all
* admin stubs
*
* @return Mage_Admin_Model_Acl
*/
public function getAcl()
{
if ($this->acl === null) {
$this->acl = Mage::getModel('admin/acl');
Mage::getSingleton('admin/config')->loadAclResources($this->acl);
}
return $this->acl;
}
/**
* Loads role rules into ACL for admin user
*
* @param Mage_Admin_Model_User $user
* @param Mage_Admin_Model_Acl $acl
* @param array $allowedResources
*
* @return $this
*/
public function loadRules(Mage_Admin_Model_User $user, Mage_Admin_Model_Acl $acl, array $allowedResources = array())
{
$userRole = Mage::getModel('admin/acl_role_user', Mage_Admin_Model_Acl::ROLE_TYPE_USER . $user->getId());
$acl->addRole($userRole);
if (empty($allowedResources)) {
$acl->allow($userRole);
$acl->allow($userRole, $acl->getResources());
return $this;
}
$aclResources = $acl->getResources();
$allow = array();
foreach ($allowedResources as $resource) {
$childResources = array_filter(
$aclResources,
function ($entry) use ($resource) {
return strpos($entry, 'admin/' . $resource) === 0;
}
);
$allow = array_merge($allow, $childResources);
}
$deny = array();
foreach ($aclResources as $resource) {
if (!in_array($resource, $allow)) {
$deny[] = $resource;
}
}
$acl->allow($userRole, $allow);
$acl->deny($userRole, $deny);
return $this;
}
/**
* Creates a new instance of user with unique id
*
* Used for stubbing admin user roles
*
* @param int $entropy
* @return Mage_Admin_Model_User
*/
public function createUser($entropy = 3)
{
$userId = floor(microtime(true)*pow(10, $entropy) - floor(time()/100)*100*pow(10, $entropy));
// Fix for EE gws functionality
$userRole = Mage::getModel('admin/roles');
$userRole->setGwsIsAll(1);
$user = Mage::getModel('admin/user');
$user->setId($userId);
EcomDev_Utils_Reflection::setRestrictedPropertyValue($user, '_role', $userRole);
return $user;
}
/**
* Does nothing during test setup
*
*
*/
public function setUp()
{
}
/**
* Clean ups acl roles information after test completed
*
*/
public function tearDown()
{
if ($this->acl !== null) {
$this->acl->removeRoleAll();
}
}
}
...@@ -16,13 +16,14 @@ ...@@ -16,13 +16,14 @@
* @author Ivan Chepurnyi <ivan.chepurnyi@ecomdev.org> * @author Ivan Chepurnyi <ivan.chepurnyi@ecomdev.org>
*/ */
use EcomDev_PHPUnit_Helper as TestHelper;
class EcomDev_PHPUnit_Test_Case_Util class EcomDev_PHPUnit_Test_Case_Util
{ {
const XML_PATH_DEFAULT_FIXTURE_MODEL = 'phpunit/suite/fixture/model'; const XML_PATH_DEFAULT_FIXTURE_MODEL = 'phpunit/suite/fixture/model';
const XML_PATH_DEFAULT_EXPECTATION_MODEL = 'phpunit/suite/expectation/model'; const XML_PATH_DEFAULT_EXPECTATION_MODEL = 'phpunit/suite/expectation/model';
const XML_PATH_DEFAULT_YAML_LOADER_MODEL = 'phpunit/suite/yaml/model'; const XML_PATH_DEFAULT_YAML_LOADER_MODEL = 'phpunit/suite/yaml/model';
/** /**
* List of replaced registry keys for current test case run * List of replaced registry keys for current test case run
* *
...@@ -423,7 +424,9 @@ class EcomDev_PHPUnit_Test_Case_Util ...@@ -423,7 +424,9 @@ class EcomDev_PHPUnit_Test_Case_Util
*/ */
public static function replaceByMock($type, $classAlias, $mock) public static function replaceByMock($type, $classAlias, $mock)
{ {
if ($mock instanceof PHPUnit_Framework_MockObject_MockBuilder) { if ($mock instanceof EcomDev_PHPUnit_Mock_Proxy) {
$mock = $mock->getMockInstance();
} elseif ($mock instanceof PHPUnit_Framework_MockObject_MockBuilder) {
$mock = $mock->getMock(); $mock = $mock->getMock();
} elseif (!$mock instanceof PHPUnit_Framework_MockObject_MockObject) { } elseif (!$mock instanceof PHPUnit_Framework_MockObject_MockObject) {
throw PHPUnit_Util_InvalidArgumentHelper::factory( throw PHPUnit_Util_InvalidArgumentHelper::factory(
...@@ -463,6 +466,36 @@ class EcomDev_PHPUnit_Test_Case_Util ...@@ -463,6 +466,36 @@ class EcomDev_PHPUnit_Test_Case_Util
self::$replacedRegistry[$key] = $oldValue; self::$replacedRegistry[$key] = $oldValue;
} }
/**
* Returns class name by grouped class alias
*
* @param string $type block/model/helper/resource_model
* @param string $classAlias
* @return string
*/
public static function getGroupedClassName($type, $classAlias)
{
if ($type === 'resource_model') {
return self::app()->getConfig()->getResourceModelClassName($classAlias);
}
return self::app()->getConfig()->getGroupedClassName($type, $classAlias);
}
/**
* Retrieve mock builder for grouped class alias
*
* @param PHPUnit_Framework_TestCase $testCase
* @param string $type block|model|helper
* @param string $classAlias
* @return EcomDev_PHPUnit_Mock_Proxy
*/
public static function getGroupedClassMockBuilder(PHPUnit_Framework_TestCase $testCase, $type, $classAlias)
{
$className = self::getGroupedClassName($type, $classAlias);
return new EcomDev_PHPUnit_Mock_Proxy($testCase, $className);
}
/** /**
* Called for each test case * Called for each test case
* *
...@@ -489,4 +522,36 @@ class EcomDev_PHPUnit_Test_Case_Util ...@@ -489,4 +522,36 @@ class EcomDev_PHPUnit_Test_Case_Util
self::app()->replaceRegistry($registryPath, $originalValue); self::app()->replaceRegistry($registryPath, $originalValue);
} }
} }
/**
* Implementation of __call method functionality that can be used from a test case
*
* @param string $method
* @param array $args
*
* @throws ErrorException
* @return bool
*/
public static function call($method, $args)
{
if (TestHelper::has($method)) {
return TestHelper::invokeArgs($method, $args);
}
$backTraceCalls = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 3);
$previousCall = $backTraceCalls[2];
throw new ErrorException(
sprintf(
'Call to undefined function %s%s%s()',
$previousCall['class'],
$previousCall['type'],
$previousCall['function']
),
0,
E_USER_ERROR,
$previousCall['file'],
$previousCall['line']
);
}
} }
...@@ -59,6 +59,8 @@ class EcomDev_PHPUnit_Test_Listener implements PHPUnit_Framework_TestListener ...@@ -59,6 +59,8 @@ class EcomDev_PHPUnit_Test_Listener implements PHPUnit_Framework_TestListener
$this->getAppReflection()->getMethod('applyTestScope')->invoke(null); $this->getAppReflection()->getMethod('applyTestScope')->invoke(null);
} }
$this->firstLevelTestSuite = $suite; $this->firstLevelTestSuite = $suite;
Mage::dispatchEvent('phpunit_suite_start_after', array( Mage::dispatchEvent('phpunit_suite_start_after', array(
'suite' => $suite, 'suite' => $suite,
...@@ -139,6 +141,7 @@ class EcomDev_PHPUnit_Test_Listener implements PHPUnit_Framework_TestListener ...@@ -139,6 +141,7 @@ class EcomDev_PHPUnit_Test_Listener implements PHPUnit_Framework_TestListener
'listener' => $this 'listener' => $this
)); ));
if ($test instanceof PHPUnit_Framework_TestCase) { if ($test instanceof PHPUnit_Framework_TestCase) {
EcomDev_PHPUnit_Helper::setTestCase($test);
EcomDev_PHPUnit_Test_Case_Util::getFixture(get_class($test)) EcomDev_PHPUnit_Test_Case_Util::getFixture(get_class($test))
->setScope(EcomDev_PHPUnit_Model_Fixture_Interface::SCOPE_LOCAL) ->setScope(EcomDev_PHPUnit_Model_Fixture_Interface::SCOPE_LOCAL)
->loadByTestCase($test); ->loadByTestCase($test);
...@@ -148,6 +151,7 @@ class EcomDev_PHPUnit_Test_Listener implements PHPUnit_Framework_TestListener ...@@ -148,6 +151,7 @@ class EcomDev_PHPUnit_Test_Listener implements PHPUnit_Framework_TestListener
->apply(); ->apply();
EcomDev_PHPUnit_Test_Case_Util::setUp(); EcomDev_PHPUnit_Test_Case_Util::setUp();
EcomDev_PHPUnit_Helper::setUp();
} }
Mage::dispatchEvent('phpunit_test_start_after', array( Mage::dispatchEvent('phpunit_test_start_after', array(
'test' => $test, 'test' => $test,
...@@ -178,6 +182,7 @@ class EcomDev_PHPUnit_Test_Listener implements PHPUnit_Framework_TestListener ...@@ -178,6 +182,7 @@ class EcomDev_PHPUnit_Test_Listener implements PHPUnit_Framework_TestListener
} }
EcomDev_PHPUnit_Test_Case_Util::tearDown(); EcomDev_PHPUnit_Test_Case_Util::tearDown();
EcomDev_PHPUnit_Helper::tearDown();
} }
Mage::dispatchEvent('phpunit_test_end_after', array( Mage::dispatchEvent('phpunit_test_end_after', array(
......
...@@ -42,6 +42,16 @@ ...@@ -42,6 +42,16 @@
</ecomdev_phpunit> </ecomdev_phpunit>
</types> </types>
</cache> </cache>
<events>
<phpunit_suite_start_after>
<observers>
<ecomdev_phpunit>
<class>ecomdev_phpunit/observer</class>
<method>registerDefaultTestHelpers</method>
</ecomdev_phpunit>
</observers>
</phpunit_suite_start_after>
</events>
</global> </global>
<phpunit> <phpunit>
<suite> <suite>
...@@ -131,6 +141,12 @@ ...@@ -131,6 +141,12 @@
<Namespace_MyModule /> <Namespace_MyModule />
--> -->
</modules> </modules>
<helpers>
<mock>EcomDev_PHPUnit_Test_Case_Helper_Mock</mock>
<session>EcomDev_PHPUnit_Test_Case_Helper_Session</session>
<customer>EcomDev_PHPUnit_Test_Case_Helper_Customer</customer>
</helpers>
</suite> </suite>
</phpunit> </phpunit>
<test> <test>
......
<?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) 2013 EcomDev BV (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>
*/
class EcomDev_PHPUnitTest_Test_Helper_Call extends EcomDev_PHPUnit_Test_Case
{
/**
* @var EcomDev_PHPUnit_Helper_Interface|PHPUnit_Framework_MockObject_MockObject
*/
protected $helper;
/**
* Creates new helper for test
*/
protected function setUp()
{
$this->helper = $this->getMockForAbstractClass('EcomDev_PHPUnit_Helper_Interface');
$this->helper->expects($this->any())
->method('invoke')
->with($this->equalTo('someCustomHelper'))
->will($this->returnSelf());
$this->helper->expects($this->any())
->method('has')
->will($this->returnValueMap(array(
array('someCustomHelper', true)
)));
EcomDev_PHPUnit_Helper::add($this->helper);
}
/**
* Testing calling of helper via test case
*
*/
public function testCall()
{
$this->assertSame(
$this->helper, $this->someCustomHelper()
);
}
/**
* @expectedException ErrorException
* @expectedExceptionMessage Call to undefined function EcomDev_PHPUnitTest_Test_Helper_Call->unknownHelper()
*/
public function testCallError()
{
$this->unknownHelper('');
}
public function tearDown()
{
EcomDev_PHPUnit_Helper::remove($this->helper);
}
}
\ No newline at end of file
<?php
/**
* Tests for customer session creation
*
* @loadSharedFixture customers
*/
class EcomDev_PHPUnitTest_Test_Helper_Customer extends EcomDev_PHPUnit_Test_Case
{
/**
*
* @dataProvider dataProvider
*/
public function testCustomerSession($customerId)
{
$customerSession = $this->customerSession($customerId);
$expected = $this->expected('auto');
$this->assertEquals($expected->getIsLoggedIn(), $customerSession->isLoggedIn());
if ($expected->getName()) {
$this->assertEquals($expected->getName(), $customerSession->getCustomer()->getName());
}
}
}
<?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) 2013 EcomDev BV (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>
*/
class EcomDev_PHPUnitTest_Test_Helper_Mock extends EcomDev_PHPUnit_Test_Case
{
public function testMockClassAlias()
{
$mock = $this->mockClassAlias('model', 'catalog/product',
array('getId'),
array(array('entity_id' => 1))
);
$this->assertInstanceOf('EcomDev_PHPUnit_Mock_Proxy', $mock);
$this->assertAttributeEquals($this->getGroupedClassName('model', 'catalog/product'), 'className', $mock);
$this->assertAttributeContains('getId', 'methods', $mock);
$this->assertAttributeContains(array('entity_id' => 1), 'constructorArgs', $mock);
}
public function testModelMock()
{
$mock = $this->mockModel('catalog/product',
array('getId'),
array(array('entity_id' => 1))
);
$this->assertInstanceOf('EcomDev_PHPUnit_Mock_Proxy', $mock);
$this->assertAttributeEquals($this->getGroupedClassName('model', 'catalog/product'), 'className', $mock);
$this->assertAttributeContains('getId', 'methods', $mock);
$this->assertAttributeContains(array('entity_id' => 1), 'constructorArgs', $mock);
}
public function testBlockMock()
{
$mock = $this->mockBlock('catalog/product_view',
array('getTemplate'),
array(array('product_id' => 1))
);
$this->assertInstanceOf('EcomDev_PHPUnit_Mock_Proxy', $mock);
$this->assertAttributeEquals($this->getGroupedClassName('block', 'catalog/product_view'), 'className', $mock);
$this->assertAttributeContains('getTemplate', 'methods', $mock);
$this->assertAttributeContains(array('product_id' => 1), 'constructorArgs', $mock);
}
public function testHelperMock()
{
$mock = $this->mockBlock('catalog/category',
array('getStoreCategories'),
array('some_value')
);
$this->assertInstanceOf('EcomDev_PHPUnit_Mock_Proxy', $mock);
$this->assertAttributeEquals($this->getGroupedClassName('block', 'catalog/category'), 'className', $mock);
$this->assertAttributeContains('getStoreCategories', 'methods', $mock);
$this->assertAttributeContains('some_value', 'constructorArgs', $mock);
}
}
\ No newline at end of file
<?php
class EcomDev_PHPUnitTest_Test_Helper_Session extends EcomDev_PHPUnit_Test_Case_Controller
{
/**
* Tests stubbing of any session
*
*/
public function testMockSession()
{
$sessionMock = $this->mockSession('admin/session', array('getUserId'));
$this->assertInstanceOf('EcomDev_PHPUnit_Mock_Proxy', $sessionMock);
$this->assertInstanceOf('Mage_Admin_Model_Session', $sessionMock->getMockInstance());
$this->assertSame($sessionMock->getMockInstance(), Mage::getSingleton('admin/session'));
}
/**
* Tests stubing of admin session
*
*/
public function testAdminSessionAllRights()
{
$this->adminSession();
$this->assertTrue(Mage::getSingleton('admin/session')->isLoggedIn());
$this->assertTrue(Mage::getSingleton('admin/session')->isAllowed('catalog/products'));
$this->assertTrue(Mage::getSingleton('admin/session')->isAllowed('sales/order'));
$this->assertTrue(Mage::getSingleton('admin/session')->isAllowed('system/config'));
}
/**
* Tests creation of admin session
*
*/
public function testAdminSessionOnlyCatalog()
{
$this->adminSession(array('catalog'));
$this->assertTrue(Mage::getSingleton('admin/session')->isLoggedIn());
$this->assertTrue(Mage::getSingleton('admin/session')->isAllowed('catalog/products'));
$this->assertTrue(Mage::getSingleton('admin/session')->isAllowed('catalog/categories'));
$this->assertFalse(Mage::getSingleton('admin/session')->isAllowed('sales/order'));
$this->assertFalse(Mage::getSingleton('admin/session')->isAllowed('system/config'));
}
/**
* Tests creation of admin session
*
*/
public function testAdminSessionOnlyCatalogProduct()
{
$this->adminSession(array('catalog/products'));
$this->assertTrue(Mage::getSingleton('admin/session')->isLoggedIn());
$this->assertTrue(Mage::getSingleton('admin/session')->isAllowed('catalog/products'));
$this->assertFalse(Mage::getSingleton('admin/session')->isAllowed('catalog/categories'));
$this->assertFalse(Mage::getSingleton('admin/session')->isAllowed('sales/order'));
$this->assertFalse(Mage::getSingleton('admin/session')->isAllowed('system/config'));
}
}
john_doe:
- 1
jane_doe:
- 2
unknown_customer:
- 3
\ No newline at end of file
john_doe:
name: John Doe
is_logged_in: true
jane_doe:
name: Jane Doe
is_logged_in: true
unknown_customer:
is_logged_in: false
\ No newline at end of file
eav:
customer:
- entity_id: 1 # Customer with default billing and shipping addresses
attribute_set_id: 0 # Fix issue with customer entity
website_id: 1
store_id: 1
created_in: Default Store
group_id: 1
firstname: John
lastname: Doe
email: john@doe.com
pasword_hash: d1bcc360d05a6bdd7484784f43660c88:hG
default_billing: 1
default_shipping: 1
- entity_id: 2 # Customer without addresses
attribute_set_id: 0 # Fix issue with customer entity
website_id: 1
store_id: 1
created_in: Default Store
group_id: 1
firstname: Jane
lastname: Doe
email: jane@doe.com
pasword_hash: d1bcc360d05a6bdd7484784f43660c88:hG
customer_address:
- entity_id: 1 # Let him to be a guy from Nevada
attribute_set_id: 0 # Fix issue with customer address entity
customer_id: 1
parent_id: 1
firstname: John
lastname: Doe
country_id: US
region_id: 39
region_code: NV
region: Nevada
postcode: 89001
city: Alamo
telephone: 555-55-55
street: Address 123
\ No newline at end of file
<?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) 2013 EcomDev BV (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>
*/
use EcomDev_PHPUnit_Helper as Helper;
class EcomDev_PHPUnitTest_Test_Lib_Helper extends PHPUnit_Framework_TestCase
{
/**
* Preserved array of already set helpers,
* to return them back when test case finished its run
*
* @var EcomDev_PHPUnit_Helper_Interface[]
*/
protected $initializedHelpers;
protected function setUp()
{
// Retrieve existing helpers and store them for future revert
$this->initializedHelpers = EcomDev_Utils_Reflection::getRestrictedPropertyValue(
'EcomDev_PHPUnit_Helper',
'helpers'
);
$this->resetHelpers();
}
/**
* Resets helpers for test
*/
protected function resetHelpers()
{
EcomDev_Utils_Reflection::setRestrictedPropertyValue('EcomDev_PHPUnit_Helper', 'helpers', array());
}
/**
* Returns amount of helpers for test
*
* @param int $count
* @param bool $setThem
* @return EcomDev_PHPUnit_Helper_Interface[]|PHPUnit_Framework_MockObject_MockObject[]
*/
protected function getHelpersForTest($count = 2, $setThem = false)
{
$result = array();
$helperInterfaces = array(
true => 'EcomDev_PHPUnit_Helper_Interface',
false => 'EcomDev_PHPUnit_Helper_Listener_Interface'
);
for ($i = 0; $i < $count; $i ++) {
$helperInterface = $helperInterfaces[$i % 2 === 0];
$result[] = $this->getMockForAbstractClass(
$helperInterface, array(), 'Test_Helper_Name' . $i
);
}
if ($setThem) {
EcomDev_Utils_Reflection::setRestrictedPropertyValue('EcomDev_PHPUnit_Helper', 'helpers', $result);
}
return $result;
}
/**
* Tests regular helper addition
*
*/
public function testAdd()
{
$helpers = $this->getHelpersForTest(3);
Helper::add($helpers[0]);
Helper::add($helpers[1]);
Helper::add($helpers[2]);
$this->assertAttributeSame($helpers, 'helpers', 'EcomDev_PHPUnit_Helper');
}
/**
* Tests addition of helpers to static property
*
*/
public function testAddOrdered()
{
$helpers = $this->getHelpersForTest(6);
Helper::add($helpers[0]);
Helper::add($helpers[1]);
Helper::add($helpers[2], array('before' => $helpers[1]));
$this->assertAttributeSame(
array($helpers[0], $helpers[2], $helpers[1]),
'helpers', 'EcomDev_PHPUnit_Helper'
);
Helper::add($helpers[4], array('after' => $helpers[2]));
$this->assertAttributeSame(
array($helpers[0], $helpers[2], $helpers[4], $helpers[1]),
'helpers', 'EcomDev_PHPUnit_Helper'
);
Helper::add($helpers[3], array('before' => 'Test_Helper_Name2'));
$this->assertAttributeSame(
array($helpers[0], $helpers[3], $helpers[2], $helpers[4], $helpers[1]),
'helpers', 'EcomDev_PHPUnit_Helper'
);
Helper::add($helpers[5], array('after' => 'Test_Helper_Name3'));
$this->assertAttributeSame(
array($helpers[0], $helpers[3], $helpers[5], $helpers[2], $helpers[4], $helpers[1]),
'helpers', 'EcomDev_PHPUnit_Helper'
);
}
/**
* Test wrong helper position
*
* @expectedException RuntimeException
* @expectedExceptionMessage Unknown position specified
*/
public function testAddWrongPosition()
{
$helper = current($this->getHelpersForTest(1));
Helper::add($helper, array('unknown' => 'position'));
}
/**
* Tests removal of each helper
*/
public function testRemove()
{
$helpers = $this->getHelpersForTest(5, true);
// Check helpers are exists before editing
$this->assertAttributeSame($helpers, 'helpers', 'EcomDev_PHPUnit_Helper');
Helper::remove($helpers[1]);
$this->assertAttributeSame(
array($helpers[0], $helpers[2], $helpers[3], $helpers[4]),
'helpers',
'EcomDev_PHPUnit_Helper'
);
Helper::remove($helpers[0]);
$this->assertAttributeSame(
array($helpers[2], $helpers[3], $helpers[4]),
'helpers',
'EcomDev_PHPUnit_Helper'
);
Helper::remove($helpers[4]);
$this->assertAttributeSame(
array($helpers[2], $helpers[3]),
'helpers',
'EcomDev_PHPUnit_Helper'
);
Helper::remove($helpers[2]);
Helper::remove($helpers[3]);
$this->assertAttributeSame(
array(),
'helpers',
'EcomDev_PHPUnit_Helper'
);
}
/**
* Tests removal of each helper
*
*/
public function testRemoveByClassName()
{
$helpers = $this->getHelpersForTest(5, true);
// Check helpers are exists before editing
$this->assertAttributeSame($helpers, 'helpers', 'EcomDev_PHPUnit_Helper');
Helper::add($helpers[4]); // Added two times
Helper::removeByClass('Test_Helper_Name2');
$this->assertAttributeSame(
array($helpers[0], $helpers[1], $helpers[3], $helpers[4], $helpers[4]),
'helpers',
'EcomDev_PHPUnit_Helper'
);
Helper::removeByClass('Test_Helper_Name4');
$this->assertAttributeSame(
array($helpers[0], $helpers[1], $helpers[3]),
'helpers',
'EcomDev_PHPUnit_Helper'
);
}
/**
* Tests getting of helper by action
*
*/
public function testGetByAction()
{
$helpers = $this->getHelpersForTest(3, true);
// Should be used for firstName
$helpers[0]->expects($this->any())
->method('has')
->will($this->returnValueMap(array(
array('firstName', true),
array('secondName', false),
array('thirdName', false),
)));
// Should be used for thirdName
$helpers[1]->expects($this->any())
->method('has')
->will($this->returnValueMap(array(
array('firstName', false),
array('secondName', false),
array('thirdName', true),
)));
// Should be used for secondName
$helpers[2]->expects($this->any())
->method('has')
->will($this->returnValueMap(array(
array('firstName', false),
array('secondName', true),
array('thirdName', true),
)));
$this->assertSame($helpers[0], Helper::getByAction('firstName'));
$this->assertSame($helpers[1], Helper::getByAction('thirdName'));
$this->assertSame($helpers[2], Helper::getByAction('secondName'));
$this->assertSame(false, Helper::getByAction('uknownName'));
}
/**
* Creates invoke method tests stub
*
* @return EcomDev_PHPUnit_Helper_Interface[]|PHPUnit_Framework_MockObject_MockObject[]
*/
protected function invokeStub()
{
$helpers = $this->getHelpersForTest(1, true);
// Should be used for firstName
$helpers[0]->expects($this->any())
->method('has')
->will($this->returnValueMap(array(
array('firstName', true)
)));
// Invocation stub for firstName
$helpers[0]->expects($this->any())
->method('invoke')
->will($this->returnValueMap(array(
array('firstName', array('one'), 'firstName_one'),
array('firstName', array('one', 'two'), 'firstName_one_two'),
array('firstName', array('one', 'two', 'three'), 'firstName_one_two_three')
)));
return $helpers;
}
/**
* Tests invoking of helper by action
*
*/
public function testInvokeArgs()
{
$this->invokeStub();
$this->assertSame('firstName_one', Helper::invokeArgs('firstName', array('one')));
$this->assertSame('firstName_one_two', Helper::invokeArgs('firstName', array('one', 'two')));
$this->assertSame('firstName_one_two_three', Helper::invokeArgs('firstName', array('one', 'two', 'three')));
$this->setExpectedException('RuntimeException', 'Cannot find a helper for action "unknownName"');
Helper::invokeArgs('unknownName', array('argument'));
}
/**
* Tests invoking of helper by action
*
*/
public function testInvoke()
{
$this->invokeStub();
$this->assertSame('firstName_one', Helper::invoke('firstName', 'one'));
$this->assertSame('firstName_one_two', Helper::invoke('firstName', 'one', 'two'));
$this->assertSame('firstName_one_two_three', Helper::invoke('firstName', 'one', 'two', 'three'));
}
/**
* Tests method for checking action existence in the helper
*
*/
public function testHas()
{
$helpers = $this->getHelpersForTest(1, true);
// Should be used for firstName
$helpers[0]->expects($this->any())
->method('has')
->will($this->returnValueMap(array(
array('firstName', true),
array('secondName', true)
)));
$this->assertTrue(Helper::has('firstName'));
$this->assertTrue(Helper::has('secondName'));
$this->assertFalse(Helper::has('unknownName'));
}
/**
* Test that setTestCase method was correctly invoked
*
*/
public function testSetTestCase()
{
$helpers = $this->getHelpersForTest(4, true);
// Initialize mock for test
foreach ($helpers as $helper) {
$helper->expects($this->once())
->method('setTestCase')
->with(new PHPUnit_Framework_Constraint_IsIdentical($this))
->will($this->returnSelf());
}
EcomDev_PHPUnit_Helper::setTestCase($this);
}
/**
* Test that when set up is invoked,
* test helpers that support setUp method invoked as well
*
*/
public function testSetUp()
{
$helpers = $this->getHelpersForTest(4, true);
$helpers[0]->expects($this->never())
->method('setUp');
$helpers[1]->expects($this->once())
->method('setUp');
$helpers[2]->expects($this->never())
->method('setUp');
$helpers[3]->expects($this->once())
->method('setUp');
EcomDev_PHPUnit_Helper::setUp();
}
/**
* Test that when set up is invoked,
* test helpers that support setUp method invoked as well
*
*/
public function testTearDown()
{
$helpers = $this->getHelpersForTest(4, true);
$helpers[0]->expects($this->never())
->method('tearDown');
$helpers[1]->expects($this->once())
->method('tearDown');
$helpers[2]->expects($this->never())
->method('tearDown');
$helpers[3]->expects($this->once())
->method('tearDown');
EcomDev_PHPUnit_Helper::tearDown();
}
protected function tearDown()
{
// Revert helpers in helper class
EcomDev_Utils_Reflection::setRestrictedPropertyValue(
'EcomDev_PHPUnit_Helper',
'helpers',
$this->initializedHelpers
);
}
}
\ No newline at end of file
<?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) 2013 EcomDev BV (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>
*/
class EcomDev_PHPUnitTest_Test_Lib_Helper_Abstract extends PHPUnit_Framework_TestCase
{
/**
*
*
* @var EcomDev_PHPUnit_Helper_Abstract|PHPUnit_Framework_MockObject_MockObject
*/
protected $helper = null;
protected function setUp()
{
$this->helper = $this->getMockBuilder('EcomDev_PHPUnit_Helper_Abstract')
->setMethods(array('hasMethod', 'callMethod'))
->enableArgumentCloning()
->getMockForAbstractClass();
}
/**
* Creates stub for phpunit method
*
* @param $map
* @return $this
*/
protected function hasMethodStub($map)
{
$stubMap = array();
$stubResult = array();
foreach ($map as $method => $result) {
$stubMap[] = array($method, $result !== false);
if ($result instanceof PHPUnit_Framework_MockObject_Stub) {
$stubResult[$method] = $result;
}
}
$this->helper->expects($this->any())
->method('hasMethod')
->will($this->returnValueMap($stubMap));
$helper = $this->helper;
$this->helper->expects($this->any())
->method('callMethod')
->will($this->returnCallback(function ($method, array $args) use ($helper, $stubResult) {
$invocation = new PHPUnit_Framework_MockObject_Invocation_Object(
get_class($helper), $method, $args, $helper
);
return $stubResult[$method]->invoke($invocation);
}));
return $this;
}
public function testHasAction()
{
$this->hasMethodStub(array(
'helperName' => true,
'helperCamelName' => true,
'helperUnknownName' => false
));
$this->assertTrue($this->helper->has('name'));
$this->assertTrue($this->helper->has('camelName'));
$this->assertFalse($this->helper->has('unknownName'));
}
public function testInvokeAction()
{
$this->hasMethodStub(array(
'helperName' => $this->returnArgument(0),
'helperCamelName' => $this->returnArgument(1),
'helperUnknownName' => false
));
$this->assertSame('value1', $this->helper->invoke('name', array('value1', 'value2')));
$this->assertSame('value2', $this->helper->invoke('camelName', array('value1', 'value2')));
$this->setExpectedException('RuntimeException', 'Helper "unknownName" is not invokable.');
$this->helper->invoke('unknownName', array());
}
public function testSetTestCase()
{
$this->assertObjectHasAttribute('testCase', $this->helper);
$this->helper->setTestCase($this);
$this->assertAttributeSame($this, 'testCase', $this->helper);
}
}
<?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) 2013 EcomDev BV (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>
*/
class EcomDev_PHPUnitTest_Test_Lib_Mock_Proxy extends PHPUnit_Framework_TestCase
{
/**
* @var EcomDev_PHPUnit_Mock_Proxy
*/
protected $mockProxy;
/**
*
*/
protected function setUp()
{
$this->mockProxy = new EcomDev_PHPUnit_Mock_Proxy($this, 'EcomDev_PHPUnit_Constraint_Abstract');
$this->mockProxy->disableOriginalConstructor();
}
/**
* Test addition of the method into mock proxy
*
*
*/
public function testAddMethod()
{
$this->assertAttributeEquals(array(), 'methods', $this->mockProxy);
$this->mockProxy->addMethod('methodName');
$this->assertAttributeEquals(array('methodName'), 'methods', $this->mockProxy);
$this->mockProxy->addMethod('methodName2');
$this->assertAttributeEquals(array('methodName', 'methodName2'), 'methods', $this->mockProxy);
}
public function testRemoveMethod()
{
EcomDev_Utils_Reflection::setRestrictedPropertyValue($this->mockProxy, 'methods', array(
'methodName', 'methodName2', 'methodName3',
));
$this->mockProxy->removeMethod('methodName2');
$this->assertAttributeEquals(array('methodName', 'methodName3'), 'methods', $this->mockProxy);
$this->mockProxy->removeMethod('methodName');
$this->assertAttributeEquals(array('methodName3'), 'methods', $this->mockProxy);
}
public function testPreserveMethods()
{
$this->assertAttributeSame(array(), 'methods', $this->mockProxy);
$this->mockProxy->preserveMethods();
$this->assertAttributeSame(null, 'methods', $this->mockProxy);
}
public function testGetMockInstance()
{
$mockInstance = $this->mockProxy->getMockInstance();
$this->assertInstanceOf(
'PHPUnit_Framework_MockObject_MockObject',
$mockInstance
);
$this->assertInstanceOf(
'EcomDev_PHPUnit_Constraint_Abstract',
$mockInstance
);
$this->assertSame($mockInstance, $this->mockProxy->getMockInstance());
}
public function testGetMockClass()
{
$this->assertSame(
get_class($this->mockProxy->getMockInstance()),
$this->mockProxy->getMockClass()
);
}
public function testExpects()
{
$this->assertAttributeEmpty('mockInstance', $this->mockProxy);
$this->assertInstanceOf(
'PHPUnit_Framework_MockObject_Builder_InvocationMocker',
$this->mockProxy->expects($this->any())->method('compareValues')
);
$this->assertAttributeInstanceOf('EcomDev_PHPUnit_Constraint_Abstract', 'mockInstance', $this->mockProxy);
}
public function testStaticExpects()
{
$this->setExpectedException('RuntimeException', 'staticExpectsProxy');
$this->mockProxy->staticExpects($this->any());
}
public function testStaticExpectsProxy()
{
$this->assertAttributeEmpty('mockInstance', $this->mockProxy);
$this->assertInstanceOf(
'PHPUnit_Framework_MockObject_Builder_InvocationMocker',
$this->mockProxy->staticExpectsProxy($this->any())->method('compareValues')
);
$this->assertAttributeInstanceOf('EcomDev_PHPUnit_Constraint_Abstract', 'mockInstance', $this->mockProxy);
}
public function testGetInvocationMocker()
{
$this->assertAttributeEmpty('mockInstance', $this->mockProxy);
$this->setExpectedException('RuntimeException', 'getMockInstance');
$this->mockProxy->__phpunit_getInvocationMocker();
}
public function testGetStaticInvocationMocker()
{
$this->assertAttributeEmpty('mockInstance', $this->mockProxy);
$this->setExpectedException('RuntimeException', 'getMockInstance');
$this->mockProxy->__phpunit_getStaticInvocationMocker();
}
public function testVerify()
{
$this->assertAttributeEmpty('mockInstance', $this->mockProxy);
$this->setExpectedException('RuntimeException', 'getMockInstance');
$this->mockProxy->__phpunit_verify();
}
public function testCall()
{
// Just checks that call is forwarded to mocked class functionality
$this->assertEquals(false, $this->mockProxy->compareValues('value1', 'value2'));
$this->assertEquals(true, $this->mockProxy->compareValues('value1', 'value1'));
}
}
<?php
/**
* Test Helpers Factory
*
*/
class EcomDev_PHPUnit_Helper
{
/**
* Helpers container
*
* @var EcomDev_PHPunit_Helper_Interface[]
*/
protected static $helpers = array();
/**
* Adds a new helper instance to helpers registry
*
* If $position is specified, it will use value
* from before or after key as related helper
*
* @param EcomDev_PHPunit_Helper_Interface $helper
* @param bool|array $position
*
* @throws RuntimeException
*/
public static function add(EcomDev_PHPunit_Helper_Interface $helper, $position = false)
{
if ($position === false) {
self::$helpers[] = $helper;
} elseif (isset($position['after']) || isset($position['before'])) {
$isBefore = isset($position['before']);
$relatedHelper = $isBefore ? $position['before'] : $position['after'];
if (is_string($relatedHelper)) {
// Retrieving of helper by class name
$relatedHelper = current(self::getHelpersByClass($relatedHelper));
}
$helperPosition = array_search($relatedHelper, self::$helpers, true);
if ($helperPosition !== false) {
array_splice(
self::$helpers,
$helperPosition + ($isBefore ? 0 : 1),
null,
array($helper)
);
}
} else {
throw new RuntimeException('Unknown position specified for helper addition');
}
}
/**
* Removes helper by instance
*
* @param EcomDev_PHPUnit_Helper_Interface $helper
*/
public static function remove(EcomDev_PHPUnit_Helper_Interface $helper)
{
$helperPosition = array_search($helper, self::$helpers, true);
if ($helperPosition !== false) {
array_splice(self::$helpers, $helperPosition, 1);
}
}
/**
* Removes all helpers by class name from helpers array
*
* @param string $helperClass
*/
public static function removeByClass($helperClass)
{
$helpersByClass = self::getHelpersByClass($helperClass);
foreach ($helpersByClass as $helper) {
self::remove($helper);
}
}
/**
* Returns helper by action,
* if helper for action was not found it returns false
*
* @param $action
* @return bool|EcomDev_PHPunit_Helper_Interface
*/
public static function getByAction($action)
{
foreach (self::$helpers as $helper) {
if ($helper->has($action)) {
return $helper;
}
}
return false;
}
/**
* Checks existence of a helper for an action
*
* @param string $action
* @return bool
*/
public static function has($action)
{
return self::getByAction($action) !== false;
}
/**
* Invokes a helper action with arguments as an array
*
* @param string $action
* @param array $args
*
* @throws RuntimeException
* @return mixed
*/
public static function invokeArgs($action, array $args)
{
$helper = self::getByAction($action);
if (!$helper) {
throw new RuntimeException(sprintf('Cannot find a helper for action "%s"', $action));
}
return $helper->invoke($action, $args);
}
/**
* Invokes helper action with flat arguments
*
* @param string $action
* @return mixed
*/
public static function invoke($action /*, $arg1, $arg2, $arg3 ... $argN */)
{
$args = func_get_args();
array_shift($args);
return self::invokeArgs($action, $args);
}
/**
* Sets test case to each helper instance
*
* @param PHPUnit_Framework_TestCase $testCase
*/
public static function setTestCase(PHPUnit_Framework_TestCase $testCase)
{
foreach (self::$helpers as $helper) {
$helper->setTestCase($testCase);
}
}
/**
* Calls setUp method on helper,
* that implements EcomDev_PHPUnit_Helper_Listener_Interface
*
*/
public static function setUp()
{
foreach (self::$helpers as $helper) {
if ($helper instanceof EcomDev_PHPUnit_Helper_Listener_Interface) {
$helper->setUp();
}
}
}
/**
* Calls tearDown method on helper,
* that implements EcomDev_PHPUnit_Helper_Listener_Interface
*
*/
public static function tearDown()
{
foreach (self::$helpers as $helper) {
if ($helper instanceof EcomDev_PHPUnit_Helper_Listener_Interface) {
$helper->tearDown();
}
}
}
/**
* Finds a helper instance by class name
*
* @param string $className
* @return array
*/
protected static function getHelpersByClass($className)
{
return array_filter(self::$helpers, function ($item) use ($className) {
return get_class($item) === $className;
});
}
}
\ No newline at end of file
<?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) 2013 EcomDev BV (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>
*/
/**
* Base helper implementation
*/
abstract class EcomDev_PHPUnit_Helper_Abstract implements EcomDev_PHPunit_Helper_Interface
{
/**
* @var PHPUnit_Framework_TestCase
*/
protected $testCase;
/**
* Checks existence of helper action
*
* @param string $action
* @return bool
*/
public function has($action)
{
return $this->hasMethod('helper' . ucfirst($action));
}
/**
* Invokes defined helper action
*
* @param string $action
* @param array $args
*
* @throws RuntimeException
* @return mixed
*/
public function invoke($action, array $args)
{
if (!$this->has($action)) {
throw new RuntimeException(sprintf('Helper "%s" is not invokable.', $action));
}
$methodName = 'helper' . ucfirst($action);
return $this->callMethod($methodName, $args);
}
/**
* Call method to make testable of the invoke method
*
* @param $method
* @param $args
* @return mixed
*/
protected function callMethod($method, $args)
{
return call_user_func_array(array($this, $method), $args);
}
/**
* Has method for making abstract testable
*
* @param array $method
* @return bool
*/
protected function hasMethod($method)
{
$reflection = EcomDev_Utils_Reflection::getReflection($this);
return $reflection->hasMethod($method);
}
/**
* Sets test case property for helper
*
* @param PHPUnit_Framework_TestCase $testCase
*
* @return $this
*/
public function setTestCase(PHPUnit_Framework_TestCase $testCase)
{
$this->testCase = $testCase;
return $this;
}
}
\ No newline at end of file
<?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) 2013 EcomDev BV (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>
*/
/**
* Interface for PHPUnit Test Helpers
*/
interface EcomDev_PHPunit_Helper_Interface
{
/**
* Checks if helper has action for invocation
*
* @param string $action
* @return bool
*/
public function has($action);
/**
* Invokes helper action
*
* @param string $action
* @param array $args
*
* @return mixed
*/
public function invoke($action, array $args);
/**
* Sets test case for usage in helper
*
* @param PHPUnit_Framework_TestCase $testCase
* @return $this
*/
public function setTestCase(PHPUnit_Framework_TestCase $testCase);
}
<?php
/**
* Interface for helpers that support setUp() and tearDown() methods
*
* These methods are invoked when test setUp() or tearDown() is executed
*
*/
interface EcomDev_PHPUnit_Helper_Listener_Interface extends EcomDev_PHPunit_Helper_Interface
{
public function setUp();
public function tearDown();
}
<?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) 2013 EcomDev BV (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>
*/
/**
* PHPUnit Mock Object Proxy
*
* Used to support mock builder auto-apply as soon as expects method is called.
*/
class EcomDev_PHPUnit_Mock_Proxy
extends PHPUnit_Framework_MockObject_MockBuilder
implements PHPUnit_Framework_MockObject_MockObject
{
protected $mockInstance;
/**
* Adds method name to a mock builder
*
* @param string $methodName
* @return $this
*/
public function addMethod($methodName)
{
$this->methods[] = $methodName;
return $this;
}
/**
* Removes method name from a mock builder
*
* @param string $methodName
* @return $this
*/
public function removeMethod($methodName)
{
$methodIndex = array_search($methodName, $this->methods);
if ($methodIndex !== false) {
array_splice($this->methods, $methodIndex, 1);
}
return $this;
}
/**
* Preserves methods from override in mocked object
*
* @return $this
*/
public function preserveMethods()
{
$this->setMethods(null);
return $this;
}
/**
* Proxied mock instance retrieval
*
* @return PHPUnit_Framework_MockObject_MockObject
*/
public function getMockInstance()
{
if ($this->mockInstance === null) {
$reflection = EcomDev_Utils_Reflection::getReflection($this->className);
$this->mockInstance = ($reflection->isAbstract() || $reflection->isInterface())
? $this->getMockForAbstractClass() : $this->getMock();
}
return $this->mockInstance;
}
/**
* Returns mock class name for generated mock instance
*
* @return string
*/
public function getMockClass()
{
return get_class($this->getMockInstance());
}
/**
* Registers a new expectation in the mock object and returns the match
* object which can be infused with further details.
*
* @param PHPUnit_Framework_MockObject_Matcher_Invocation $matcher
* @return PHPUnit_Framework_MockObject_Builder_InvocationMocker
*/
public function expects(PHPUnit_Framework_MockObject_Matcher_Invocation $matcher)
{
return $this->getMockInstance()->expects($matcher);
}
/**
* Registers a new static expectation in the mock object and returns the
* match object which can be infused with further details.
*
* @param PHPUnit_Framework_MockObject_Matcher_Invocation $matcher
* @return PHPUnit_Framework_MockObject_Builder_InvocationMocker
* @throws RuntimeException in case if you call it
*/
public static function staticExpects(PHPUnit_Framework_MockObject_Matcher_Invocation $matcher)
{
throw new RuntimeException(
'This method cannot be called on mock proxy, use staticExpectsProxy instead'
);
}
/**
* Registers a new static expectation in the mock object and returns the
* match object which can be infused with further details.
*
* @param PHPUnit_Framework_MockObject_Matcher_Invocation $matcher
* @return PHPUnit_Framework_MockObject_Builder_InvocationMocker
*/
public function staticExpectsProxy(PHPUnit_Framework_MockObject_Matcher_Invocation $matcher)
{
return $this->getMockInstance()->staticExpects($matcher);
}
/**
* Returns invocation mocker for
*
* @return PHPUnit_Framework_MockObject_InvocationMocker
*/
public function __phpunit_getInvocationMocker()
{
throw new RuntimeException(
'Mock object proxy cannot be used for retrieving invocation mockers, '
. 'use getMockInstance method for real mock object'
);
}
/**
* @return PHPUnit_Framework_MockObject_InvocationMocker
*/
public static function __phpunit_getStaticInvocationMocker()
{
throw new RuntimeException(
'Mock object proxy cannot be used for retrieving invocation mockers, '
. 'use getMockInstance method for real mock object'
);
}
/**
* Verifies that the current expectation is valid. If everything is OK the
* code should just return, if not it must throw an exception.
*
* @throws PHPUnit_Framework_ExpectationFailedException
*/
public function __phpunit_verify()
{
throw new RuntimeException(
'Mock object proxy cannot be used for verifying mock'
. 'use getMockInstance method for real mock object'
);
}
/**
* Forwards all method calls to mock instance
*
* @param string $name
* @param array $arguments
* @return mixed
*/
public function __call($name, $arguments)
{
return call_user_func_array(
array($this->getMockInstance(), $name),
$arguments
);
}
}
\ No newline at end of file
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment