Commit 0dac91d4 authored by Bertrand Gauthier's avatar Bertrand Gauthier
Browse files

Suite correction des tests unitaires.

parent bcd2532e
Loading
Loading
Loading
Loading

tests/Bootstrap.php

0 → 100644
+88 −0
Original line number Diff line number Diff line
<?php
namespace UnicaenAppTest;

use Zend\Loader\AutoloaderFactory;
use Zend\Mvc\Service\ServiceManagerConfig;
use Zend\ServiceManager\ServiceManager;
use RuntimeException;

error_reporting(E_ALL | E_STRICT);
chdir(__DIR__);

/**
 * Test bootstrap, for setting up autoloading
 */
class Bootstrap
{
    protected static $serviceManager;

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

        static::initAutoloader();

        static::$serviceManager = new ServiceManager(new ServiceManagerConfig());
    }

    public static function getServiceManager()
    {
        return static::$serviceManager;
    }

    protected static function initAutoloader()
    {
        $vendorPath = static::findParentPath('vendor');

        if (is_readable($vendorPath . '/autoload.php')) {
            include $vendorPath . '/autoload.php';
            return;
        }

        $zf2Path = getenv('ZF2_PATH');
        if (!$zf2Path) {
            if (defined('ZF2_PATH')) {
                $zf2Path = ZF2_PATH;
            } elseif (is_dir($vendorPath . '/ZF2/library')) {
                $zf2Path = $vendorPath . '/ZF2/library';
            } elseif (is_dir($vendorPath . '/zendframework/zendframework/library')) {
                $zf2Path = $vendorPath . '/zendframework/zendframework/library';
            }
        }

        if (!$zf2Path) {
            throw new RuntimeException('Unable to load ZF2. Run `php composer.phar install` or define a ZF2_PATH environment variable.');
        }

        include $zf2Path . '/Zend/Loader/AutoloaderFactory.php';
        AutoloaderFactory::factory([
            'Zend\Loader\StandardAutoloader' => [
                'autoregister_zf' => true,
                'namespaces' => [
                    __NAMESPACE__ => __DIR__ . '/' . __NAMESPACE__,
                ],
            ],
        ]);
    }

    protected static function findParentPath($path)
    {
        $dir = __DIR__;
        $previousDir = '.';
        while (!is_dir($dir . '/' . $path)) {
            $dir = dirname($dir);
            if ($previousDir === $dir) return false;
            $previousDir = $dir;
        }
        return $dir . '/' . $path;
    }
}

Bootstrap::init();
 No newline at end of file
+2 −2
Original line number Diff line number Diff line
<?php
namespace UnicaenAuthTest\Acl;

use PHPUnit\Framework\TestCase;
use PHPUnit_Framework_TestCase;
use UnicaenAuth\Acl\NamedRole;

/**
@@ -9,7 +9,7 @@ use UnicaenAuth\Acl\NamedRole;
 *
 * @author Bertrand GAUTHIER <bertrand.gauthier at unicaen.fr>
 */
class NamedRoleTest extends TestCase
class NamedRoleTest extends PHPUnit_Framework_TestCase
{
    public function testCanConstructWithoutName()
    {
+8 −5
Original line number Diff line number Diff line
<?php
namespace UnicaenAuthTest\Authentication\Adapter;

use PHPUnit\Framework\TestCase;
use PHPUnit_Framework_TestCase;
use UnicaenAuth\Authentication\Adapter\AbstractFactory;
use UnicaenAuth\Service\User;
use Zend\EventManager\EventManager;
@@ -13,8 +13,11 @@ use Zend\ServiceManager\ServiceManager;
 *
 * @author Bertrand GAUTHIER <bertrand.gauthier at unicaen.fr>
 */
class AbstractFactoryTest extends TestCase
class AbstractFactoryTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var AbstractFactory
     */
    protected $factory;

    protected function setUp()
@@ -59,7 +62,7 @@ class AbstractFactoryTest extends TestCase

    /**
     * @dataProvider getInvalidServiceClassName
     * @expectedException \UnicaenApp\Exception
     * @expectedException \UnicaenApp\Exception\RuntimeException
     * @param string $serviceClassName
     */
    public function testCreateServiceWithNameThrowsExceptionIfInvalidServiceSpecified($serviceClassName)
@@ -75,14 +78,14 @@ class AbstractFactoryTest extends TestCase
    {
        $eventManager = new EventManager();

        $serviceLocator = $this->getMock('Zend\ServiceManager\ServiceManager', ['get']);
        $serviceLocator = $this->createMock('Zend\ServiceManager\ServiceManager'/*, ['get']*/);
        $serviceLocator->expects($this->any())
                       ->method('get')
                       ->will($this->returnCallback(function($serviceName) use ($eventManager) {
                           if ('unicaen-auth_user_service' === $serviceName) {
                               return new User();
                           }
                           if ('EventManager' === $serviceName) {
                           if ('event_manager' === $serviceName) {
                               return $eventManager;
                           }
                           return null;
+26 −65
Original line number Diff line number Diff line
<?php

namespace UnicaenAuthTest\Authentication\Adapter;

use CAS_GracefullTerminationException;
use PHPUnit\Framework\TestCase;
use UnicaenApp\Exception;
use PHPUnit_Framework_TestCase;
use UnicaenApp\Exception\RuntimeException;
use UnicaenAuth\Authentication\Adapter\Cas;
use UnicaenAuth\Authentication\Adapter\phpCASWrapper;
use UnicaenAuth\Options\ModuleOptions;
use Zend\EventManager\EventManager;
use ZfcUser\Authentication\Adapter\AdapterChainEvent;
use Zend\Authentication\Result;

define ('__VENDOR_DIR__', __DIR__ . '/../../../../vendor');

require_once __VENDOR_DIR__ . '/intouch/phpcas/CAS.php';

/**
 * Description of CasTest
 *
 * @author Bertrand GAUTHIER <bertrand.gauthier at unicaen.fr>
 */
class CasTest extends TestCase
class CasTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var Cas
     */
    protected $adapter;

    /**
     * @var ModuleOptions
     */
    protected $moduleOptions;

    /**
@@ -29,7 +34,7 @@ class CasTest extends TestCase
     */
    protected function setUp()
    {
        $this->moduleOptions = $moduleOptions = new \UnicaenAuth\Options\ModuleOptions([
        $this->moduleOptions = $moduleOptions = new ModuleOptions([
            'cas' => [
                'connection' => [
                    'default' => [
@@ -45,7 +50,7 @@ class CasTest extends TestCase
            ],
        ]);

        $serviceManager = $this->getMock('Zend\ServiceManager\ServiceManager', ['get']);
        $serviceManager = $this->createMock('Zend\ServiceManager\ServiceManager'/*, ['get']*/);
        $serviceManager->expects($this->any())
                       ->method('get')
                       ->will($this->returnCallback(function($serviceName) use ($moduleOptions) {
@@ -56,7 +61,7 @@ class CasTest extends TestCase
                               return $moduleOptions;
                           }
                           if ('router' === $serviceName) {
                               $router = new \Zend\Router\Http\TreeRouteStack();
                               $router = new \Zend\Mvc\Router\Http\TreeRouteStack();
                               $router->setBaseUrl('/appli')->setRequestUri(new \Zend\Uri\Http('/request'));
                               return $router;
                           }
@@ -80,7 +85,7 @@ class CasTest extends TestCase

    /**
     * @dataProvider getInvalidCasOptions
     * @expectedException Exception
     * @expectedException RuntimeException
     */
    public function testThrowsExceptionIfNoCasParamSpecified($config)
    {
@@ -95,54 +100,11 @@ class CasTest extends TestCase
        $this->assertNull($result);
    }

    public function testCanActivateCasDebugMode()
    {
        $this->moduleOptions->setCas([
            'connection' => [
                'default' => [
                    'params' => [
                        'hostname' => 'cas.unicaen.fr',
                        'port' => 443,
                        'version' => "2.0",
                        'uri' => "",
                        'debug' => true, // debug mode
                    ],
                ],
            ],
        ]);

        $casClient = $this->getMock('phpCAS', ['setDebug', 'client', 'setNoCasServerValidation']);
        $casClient->staticExpects($this->once())
                  ->method('setDebug');
        $this->adapter->setCasClient($casClient);

        $this->adapter->getCasClient();
    }

    public function testCanRedirectToCasIfNotAuthenticated()
    {
        CAS_GracefullTerminationException::throwInsteadOfExiting();

        ob_start();
        try {
            $result = $this->adapter->authenticate(new AdapterChainEvent());
            $this->fail("Exception CAS_GracefullTerminationException non levée.");
        }
        catch (CAS_GracefullTerminationException $e) {

        }
        $result = ob_get_clean();

        $expected = <<<EOS
<html><head><title>CAS Authentication wanted!</title></head><body><h1>CAS Authentication wanted!</h1><p>You should already have been redirected to the CAS server. Click <a href="https://cas.unicaen.fr/login?service=http%3A%2F%2F%3A">here</a> to continue.</p><hr><address>phpCAS 1.3.2+ using server <a href="https://cas.unicaen.fr/">https://cas.unicaen.fr/</a> (CAS 2.0)</a></address></body></html>
EOS;
        $this->assertEquals($expected, $result);
    }

    public function testAuthenticateReturnsTrueWhenAuthenticationSucceeds()
    public function testAuthenticatePopulatesEventWhenAuthenticationSucceeds()
    {
        $casClient = $this->getMock('phpCAS', ['client', 'forceAuthentication', 'getUser']);
        $casClient->staticExpects($this->once())
        /** @var phpCASWrapper|\PHPUnit_Framework_MockObject_MockObject $casClient */
        $casClient = $this->createMock(phpCASWrapper::class);
        $casClient->expects($this->once())
                  ->method('getUser')
                  ->will($this->returnValue($username = 'username'));

@@ -150,16 +112,14 @@ EOS;

        $event = new AdapterChainEvent();

        $result = $this->adapter->authenticate($event);
        $this->adapter->authenticate($event);

        $this->assertTrue($result);
        $this->assertTrue($this->adapter->isSatisfied());
        $this->assertEquals(['is_satisfied' => true, 'identity' => $username], $this->adapter->getStorage()->read());

        $this->assertEquals("userAuthenticated", $event->getName());
        $this->assertEquals(Result::SUCCESS, $event->getCode());
        $this->assertEquals($username, $event->getIdentity());
        $this->assertTrue($event->propagationIsStopped());
    }

    public function testLogoutReturnsNullIfNoCasConfigSpecified()
@@ -171,11 +131,12 @@ EOS;

    public function testCanLogoutFromCasWithRedirectService()
    {
        $casClient = $this->getMock('phpCAS', ['client', 'isAuthenticated', 'logoutWithRedirectService']);
        $casClient->staticExpects($this->once())
        /** @var phpCASWrapper|\PHPUnit_Framework_MockObject_MockObject $casClient */
        $casClient = $this->createMock(phpCASWrapper::class);
        $casClient->expects($this->once())
                  ->method('isAuthenticated')
                  ->will($this->returnValue(true));
        $casClient->staticExpects($this->once())
        $casClient->expects($this->once())
                  ->method('logoutWithRedirectService');

        $this->adapter->setCasClient($casClient);
+4 −4
Original line number Diff line number Diff line
@@ -2,7 +2,7 @@
namespace UnicaenAuthTest\Authentication\Adapter;

use PDOException;
use PHPUnit\Framework\TestCase;
use PHPUnit_Framework_TestCase;
use UnicaenAuth\Authentication\Adapter\Db;
use UnicaenAuth\Options\ModuleOptions;
use Zend\Http\PhpEnvironment\Request;
@@ -15,7 +15,7 @@ use ZfcUser\Authentication\Adapter\AdapterChainEvent;
 *
 * @author Bertrand GAUTHIER <bertrand.gauthier at unicaen.fr>
 */
class DbTest extends TestCase
class DbTest extends PHPUnit_Framework_TestCase
{
    protected $adapter;
    protected $moduleOptions;
@@ -43,9 +43,9 @@ class DbTest extends TestCase
            ],
        ]);

        $this->mapper = $mapper = $this->getMock('ZfcUser\Mapper\User', ['findByUsername', 'findByEmail']);
        $this->mapper = $mapper = $this->createMock('ZfcUser\Mapper\User'/*, ['findByUsername', 'findByEmail']*/);

        $serviceManager = $this->getMock('Zend\ServiceManager\ServiceManager', ['get']);
        $serviceManager = $this->createMock('Zend\ServiceManager\ServiceManager'/*, ['get']*/);
        $serviceManager->expects($this->any())
                       ->method('get')
                       ->will($this->returnCallback(function($serviceName) use ($moduleOptions, $mapper) {
Loading