Guards BjyAuthorize Always 200 (which should be 403) Status Code in Unit Test

161 Views Asked by At

I'm trying to create unit test using BjyAuthorize, the guard works well in browser ( return 403 ) but it doesn't work in unit test because it's always return 200 (which should be 403).

here are my codes :

Bjyauthohrize.global.php

<?php

return [
'bjyauthorize' => [

    // set the 'guest' role as default (must be defined in a role provider)
    'default_role' => 'guest',

    'identity_provider' => \BjyAuthorize\Provider\Identity\ZfcUserZendDb::class,

    // Using the authentication identity provider, which basically reads the roles from the auth service's identity
//        'identity_provider' =>    \BjyAuthorize\Provider\Identity\AuthenticationIdentityProvider::class,

    'role_providers'        => array(

        \BjyAuthorize\Provider\Role\ZendDb::class => [
            'table'                 => 'user_role',
            'identifier_field_name' => 'id',
            'role_id_field'         => 'role_id',
            'parent_role_field'     => 'parent_id',
        ],

        // using an object repository (entity repository) to load all roles into our ACL
//            BjyAuthorize\Provider\Role\ObjectRepositoryProvider::class => array(
//                'object_manager'    => 'doctrine.entitymanager.orm_default',
//                'role_entity_class' => 'User\Entity\Role',
//            ),
    ),

    /* Currently, only controller and route guards exist
     *
     * Consider enabling either the controller or the route guard depending on your needs.
     */
   'guards' => [
       \BjyAuthorize\Guard\Route::class => [
           ['route' => 'zfcuser', 'roles' => ['user']],
           ['route' => 'zfcuser/logout', 'roles' => ['user','administrator']],
           ['route' => 'zfcuser/login', 'roles' => ['guest']],
           ['route' => 'zfcuser/register', 'roles' => ['guest']],
           // Below is the default index action used by the ZendSkeletonApplication
           ['route' => 'home', 'roles' => ['guest', 'user']],
           ['route' => 'user/default', 'roles' => ['user']],
       ],
    ],
],

];

Bootstrap :

public static function init()
{
    $zf2ModulePaths = array(dirname(dirname(__DIR__)));
    if (($path = static::findParentPath('vendor'))) {
        $zf2ModulePaths[] = $path;
    }
    if (($path = static::findParentPath('module')) !== $zf2ModulePaths[0]) {
        $zf2ModulePaths[] = $path;
    }

    static::initAutoloader();

    // use ModuleManager to load this module and it's dependencies
    $testConfig = include __DIR__ . '/TestConfig.php';

    $baseConfig = array(
        'module_listener_options' => array(
            'module_paths' => $zf2ModulePaths,
        ),
    );

    $config = ArrayUtils::merge($testConfig, $baseConfig);

    $serviceManager = new ServiceManager(new ServiceManagerConfig());
    $serviceManager->setService('ApplicationConfig', $config);
    $serviceManager->get('ModuleManager')->loadModules();

    static::$serviceManager = $serviceManager;
    static::$config = $config;
}

setUp() :

 protected $serviceManager;
protected $controller;
protected $event;
protected $routeMatch;
protected $request;


public function setUp()
{
    $this->serviceManager = Bootstrap::getServiceManager();
    $this->controller = new IndexController($this->serviceManager->get('doctrine.entitymanager.orm_default'));
    $this->routeMatch = new RouteMatch(array('controller' => 'User\Controller\Index'));
    $this->request    = new Request();
    $this->event      = new MvcEvent();
    $config = $this->serviceManager->get('Config');
    $routerConfig = isset($config['router']) ? $config['router'] : array();
    $router = HttpRouter::factory($routerConfig);
    $this->event->setRouter($router);
    $this->event->setRouteMatch($this->routeMatch);
    $this->controller->setEvent($this->event);
    $this->controller->setServiceLocator($this->serviceManager);

    $this->mockZfcLogin();
    $this->mockBjy();

    parent::setUp();
}

TestAction:

 public function testUpdateProfileActionCanBeAccessed()
{
    $this->mockBjy('dodol');

    $this->routeMatch->setParam('action', 'updateProfile');

    $result   = $this->controller->dispatch($this->request);
    $response = $this->controller->getResponse();

    $this->assertEquals(403, $response->getStatusCode());
}

here is mockBjy and mockzfc :

protected function mockBjy($role = 'guest')
{
    $authorizeMock = $this
        ->getMockBuilder('BjyAuthorize\Provider\Identity\ProviderInterface')
        ->disableOriginalConstructor()
        ->getMock();

    $authorizeMock
        ->expects($this->any())
        ->method('getIdentityRoles')
        ->will($this->returnValue($role));

    $this->serviceManager->setAllowOverride(true)
        ->setService('BjyAuthorize\Provider\Identity\ProviderInterface', $authorizeMock);
}

protected function mockZfcLogin()
{
    $ZfcUserMock = $this->getMock('ZfcUser\Entity\User');

    $ZfcUserMock->expects($this->any())
        ->method('getId')
        ->will($this->returnValue('10'));

    $authMock = $this->getMock('ZfcUser\Controller\Plugin\ZfcUserAuthentication');

    $authMock->expects($this->any())
        ->method('hasIdentity')
        -> will($this->returnValue(true));

    $authMock->expects($this->any())
        ->method('getIdentity')
        -> will($this->returnValue($ZfcUserMock));

    $this->controller->getPluginManager()
        ->setService('zfcUserAuthentication', $authMock);
}

controller:

   public function updateProfileAction()
{
    Debug::dump($this->zfcUserAuthentication()->getIdentity()->getId());
    $authorize = $this->getServiceLocator()->get('BjyAuthorize\Provider\Identity\ProviderInterface');
    $roles = $authorize->getIdentityRoles();
    Debug::dump($roles);
 }

result :

Configuration read from /home/mockie/importants/htdocs/hommate/module/User/test/phpunit.xml

string(2) "10"

string(5) "guest"

Time: 122 ms, Memory: 7.00Mb

OK (1 test, 5 assertions)
0

There are 0 best solutions below