Commit 7580a055 authored by Bertrand Gauthier's avatar Bertrand Gauthier
Browse files

Quelques tests unitaires dans le module Import.

parent ed02b9dd
Loading
Loading
Loading
Loading
+5 −2
Changes for composer.json: 5 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -12,6 +12,7 @@
        "zendframework/zend-developer-tools":   "^1.0"
    },
    "require": {
        "ext-json":                             "*",
        "unicaen/app":                          "^1.3",
        "unicaen/auth":                         "^1.2",
        "unicaen/faq":                          "^1.0",
@@ -31,14 +32,16 @@
        "psr-0": {
            "Application\\": "module/Application/src",
            "Retraitement\\": "module/Retraitement/src",
            "Notification\\": "module/Notification/src"
            "Notification\\": "module/Notification/src",
            "Import\\": "module/Import/src"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "ApplicationUnitTest\\":        "module/Application/tests/ApplicationUnitTest",
            "ApplicationFunctionalTest\\":  "module/Application/tests/ApplicationFunctionalTest",
            "RetraitementTest\\":           "module/Retraitement/test/RetraitementTest"
            "RetraitementTest\\":           "module/Retraitement/test/RetraitementTest",
            "ImportTest\\":                 "module/Import/tests/ImportTest"
        }
    }
}
+82 −72
Changes for module/Import/src/Import/Service/CallService.php: 82 added lines, 72 removed lines.
Original line number Diff line number Diff line
@@ -4,13 +4,14 @@ namespace Import\Service;

use Assert\Assertion;
use Assert\AssertionFailedException;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ServerException;
use UnicaenApp\Exception\RuntimeException;
use Import\Exception\CallException;
use Import\Exception\ServiceNotFoundException;
use Zend\Http\Response;
use Zend\Log\LoggerAwareTrait;

@@ -26,6 +27,11 @@ class CallService
     */
    protected $config;

    /**
     * @var Client
     */
    protected $client;

    /**
     * @var string         $url      : le chemin d'acces au web service
     * @var string         $user     : l'identifiant pour l'authentification
@@ -47,7 +53,11 @@ class CallService
     */
    public function setConfig(array $config)
    {
        $this->config = $config;
        try {
            $this->loadConfig($config);
        } catch (AssertionFailedException $e) {
            throw CallException::badConfig($e);
        }

        return $this;
    }
@@ -55,116 +65,104 @@ class CallService
    /**
     * @return \stdClass
     */
    public function version()
    public function getVersion()
    {
        $uri = 'version/current';

        $response = $this->sendRequest($uri);
        if ($response->getStatusCode() != 200) {
            throw CallException::unexpectedResponse($uri, $response);
        }

        $json = json_decode($response->getBody());
        if ($json === null) {
            // NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
            throw CallException::invalidJSONResponse($uri, (string)$response->getBody());
        }

        return $json;
        return $this->get('version/current');
    }

    /**
     * Envoie une requête au web service, à l'URI spécifiée.
     *
     * @param string $uri
     * @return \stdClass
     */
    public function get($uri)
    {
        try {
            $response = $this->sendRequest($uri);
        } catch (CallException $ce) {
            throw $ce;
        } catch (\Exception $e) {
            throw CallException::unexpectedError($uri, $e);
        }
        if ($response->getStatusCode() !== Response::STATUS_CODE_200) {
            throw CallException::unexpectedResponse($uri, $response);
        }

        $json = json_decode($response->getBody());
        if ($json === null) {
            // NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
            throw CallException::invalidJSONResponse($uri, (string)$response->getBody());
        }
        $json = $this->sendRequest($uri);

        return $json;
    }

    /**
     * @throws \Assert\AssertionFailedException
     * @param array $config
     * @throws AssertionFailedException
     */
    private function loadConfig()
    private function loadConfig(array $config)
    {
        Assertion::keyIsset($this->config, 'url');
        Assertion::keyIsset($this->config, 'user');
        Assertion::keyIsset($this->config, 'password');
        Assertion::keyIsset($config, 'url');
        Assertion::keyIsset($config, 'user');
        Assertion::keyIsset($config, 'password');

        $this->url = $this->config['url'];
        $this->user = $this->config['user'];
        $this->password = $this->config['password'];
        $this->config = [
            'base_uri' => $config['url'],
            'headers' => [
                'Accept' => 'application/json',
            ],
            'auth' => [
                $config['user'],
                $config['password'],
            ],
        ];

        if (array_key_exists('proxy', $this->config)) {
            $this->proxy = $this->config['proxy'];
        if (array_key_exists('verify', $config)) {
            $this->config['verify'] = $config['verify'];
        }
        if (array_key_exists('verify', $this->config)) {
            $this->verify = $this->config['verify'];
        if (array_key_exists('timeout', $config)) {
            $this->config['timeout'] = $config['timeout'];
        }
        if (array_key_exists('timeout', $this->config)) {
            $this->timeout = $this->config['timeout'];
        if (array_key_exists('proxy', $config)) {
            $this->config['proxy'] = $config['proxy'];
        } else {
            $this->config['proxy'] = ['no' => 'localhost'];
        }
    }

    private function createClient()
    /**
     * @param Client $client
     * @return self
     */
    public function setClient(Client $client)
    {
        try {
            $this->loadConfig();
        } catch (AssertionFailedException $e) {
            throw CallException::badConfig($e);
        }
        $this->client = $client;

        $options = [
            'base_uri' => $this->url,
            'headers'  => [
                'Accept' => 'application/json',
            ],
            'auth'     => [$this->user, $this->password],
        ];
        return $this;
    }

        if ($this->proxy !== null) {
            $options['proxy'] = $this->proxy;
        } else {
            $options['proxy'] = ['no' => 'localhost'];
    /**
     * @return Client
     */
    public function getClient()
    {
        if ($this->client === null) {
            $this->client = $this->createClient();
        }
        if ($this->verify !== null) {
            $options['verify'] = $this->verify;

        return $this->client;
    }
        if ($this->timeout !== null) {
            $options['timeout'] = $this->timeout;

    /**
     * @return Client
     */
    private function createClient()
    {
        if ($this->config === null) {
            throw new RuntimeException("Une config doit être fournie au préalable.");
        }

        return new Client($options);
        return new Client($this->config);
    }

    /**
     * Appel du Web Service d'import de données.
     *
     * @param string $uri : la "page" du Web Service à interroger
     * @return Response la réponse du Web Service
     * @return \stdClass Réponse du Web Service décodé en JSON
     *
     * RMQ le client est configuré en utilisant les propriétés du FetcherService
     */
    private function sendRequest($uri)
    {
        $client = $this->createClient();
        $client = $this->getClient();

        try {
            $_debut = microtime(true);
@@ -179,8 +177,20 @@ class CallService
            throw CallException::networkError($e);
        } catch (GuzzleException $e) {
            throw CallException::unexpectedError($uri, $e);
        } catch (Exception $e) {
            throw CallException::unexpectedError($uri, $e);
        }

        if ($response->getStatusCode() !== Response::STATUS_CODE_200) {
            throw CallException::unexpectedResponse($uri, $response);
        }

        return $response;
        $json = json_decode($response->getBody());
        if ($json === null) {
            // NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
            throw CallException::invalidJSONResponse($uri, (string)$response->getBody());
        }

        return $json;
    }
}
 No newline at end of file
+1 −1
Changes for module/Import/src/Import/Service/FetcherService.php: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -96,7 +96,7 @@ class FetcherService
    {
        $config = $this->getConfigForEtablissement();

        return $this->callService->setConfig($config)->version();
        return $this->callService->setConfig($config)->getVersion();
    }

    /**
+172 −0
Changes for module/Import/tests/Import/Service/CallServiceTest.php: 172 added lines, 0 removed lines.
Original line number Diff line number Diff line
<?php

namespace ImportTest\Service;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\TransferException;
use Import\Service\CallService;
use Zend\Http\Response;
use Exception;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ServerException;
use UnicaenApp\Exception\RuntimeException;
use Import\Exception\CallException;
use Zend\Log\LoggerInterface;

class CallServiceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Client|\PHPUnit_Framework_MockObject_MockObject
     */
    private $client;

    /**
     * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    private $logger;

    protected function setUp()
    {
        $this->client = $this->createMock(Client::class);
        $this->logger = $this->createMock(LoggerInterface::class);
    }

    /**
     * @expectedException \Import\Exception\CallException
     */
    public function testSettingIncompleteConfigThrowsException()
    {
        $config = [];
        $service = new CallService();
        $service->setConfig($config);
    }

    public function testSettingConfigWithMandatoryKeys()
    {
        $config = [
            'url' => 'set',
            'user' => 'set',
            'password' => 'set',
        ];
        $service = new CallService();
        try {
            $service->setConfig($config);
        } catch (\Exception $e) {
            $this->fail("Aucune exception ne devrait être lancée.");
        }
    }

    public function testSettingConfigPopulatesConfig()
    {
        $populatedConfig = [
            'base_uri' => 'url value',
            'headers' => [
                'Accept' => 'application/json',
            ],
            'auth' => [
                'user value',
                'password value',
            ],
            'proxy' => 'proxy value',
            'verify' => 'verify ifyvalue',
            'timeout' => 'timeout value',
        ];

        $service = new CallService();
        $service->setConfig([
            'url' => 'url value',
            'user' => 'user value',
            'password' => 'password value',
            'proxy' => 'proxy value',
            'verify' => 'verify ifyvalue',
            'timeout' => 'timeout value',
        ]);

        $this->assertEquals($populatedConfig, $this->getObjectAttribute($service, 'config'));
    }

    public function testSettingConfigPopulatesDefaultProxyValue()
    {
        $populatedConfig = [
            'base_uri' => 'url value',
            'headers' => [
                'Accept' => 'application/json',
            ],
            'auth' => [
                'user value',
                'password value',
            ],
            'proxy' => ['no' => 'localhost'], // proxy default value
        ];

        $service = new CallService();
        $service->setConfig([
            'url' => 'url value',
            'user' => 'user value',
            'password' => 'password value',
            //'proxy' => 'proxy value', // no 'proxy' key
        ]);

        $this->assertEquals($populatedConfig, $this->getObjectAttribute($service, 'config'));
    }

    /**
     * @expectedException \UnicaenApp\Exception\RuntimeException
     */
    public function testCreateClientThrowsExceptionWhenNoConfigAvailable()
    {
        $service = new CallService();
        $service->get('peu/importe');
    }

    public function testCanInjectClient()
    {
        $service = new CallService();
        $service->setClient($this->client);

        $this->assertSame($this->client, $service->getClient());
    }

    public function getSendRequestPossibleError()
    {
        return [
            [$this->createMock(ClientException::class)],
            [$this->createMock(ServerException::class)],
            [$this->createMock(RequestException::class)],
            [$this->createMock(TransferException::class)], // implémente GuzzleException
            [$this->createMock(Exception::class)],
        ];
    }

    /**
     * @dataProvider getSendRequestPossibleError
     * @expectedException \Import\Exception\CallException
     * @param Exception $ex
     */
    public function testSendRequestThrowsCallExceptionForAnyRequestError($ex)
    {
        $this->client->expects($this->once())->method('request')->willThrowException($ex);

        $service = new CallService();
        $service->setClient($this->client);
        $service->get('peu/importe');
    }

    /**
     * @expectedException \Import\Exception\CallException
     */
    public function testSendRequestThrowsCallExceptionWhenResponseStatusCodeIsNot200()
    {
        $response = $this->createMock(Response::class);
        $response->expects($this->any())->method('getStatusCode')->willReturn(123);

        $this->client->expects($this->once())->method('request')->willReturn($response);

        $service = new CallService();
        $service->setClient($this->client);
        $service->setLogger($this->logger);
        $service->get('peu/importe');
    }
}
+9 −6
Changes for phpunit.xml: 9 added lines, 6 removed lines.
Original line number Diff line number Diff line
<?xml version="1.0" encoding="UTF-8"?>

<phpunit bootstrap="init_autoloader.php" colors="true">
<phpunit bootstrap="./vendor/autoload.php" colors="true">
    <testsuites>
        <testsuite name="Application">
            <directory>./module/Application/tests</directory>
@@ -8,6 +8,9 @@
        <testsuite name="Retraitement">
            <directory>./module/Retraitement/test</directory>
        </testsuite>
        <testsuite name="Import">
            <directory>./module/Import/tests/Import</directory>
        </testsuite>
        <testsuite name="Rule">
            <directory>./module/Application/tests/ApplicationUnitTest/Rule</directory>
        </testsuite>
@@ -22,11 +25,11 @@
        <!--<log type="coverage-html" target="/tmp/phpunit/coverage" />-->
    </logging>

    <!--<filter>-->
        <!--<whitelist processUncoveredFilesFromWhitelist="true">-->
            <!--<directory suffix=".php">../src</directory>-->
        <!--</whitelist>-->
    <!--</filter>-->
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./module</directory>
        </whitelist>
    </filter>

    <groups>