Ver Fonte

rest operations: minor improvements and unit tests

Olivier Massot há 3 anos atrás
pai
commit
94f321e4ae

+ 0 - 0
dolibarr-sync_preview.log


+ 17 - 15
src/Service/Rest/Operation/BaseRestOperation.php

@@ -5,6 +5,7 @@ namespace App\Service\Rest\Operation;
 
 use App\Service\Rest\ApiRequestInterface;
 use App\Service\Rest\ApiRequestService;
+use JetBrains\PhpStorm\Pure;
 use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
 use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
 use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
@@ -89,49 +90,49 @@ abstract class BaseRestOperation
     /**
      * @return string
      */
-    public function getMethod(): string
+    public function getErrorMessage(): string
     {
-        return $this->method;
+        return $this->errorMessage;
     }
 
     /**
      * @return string
      */
-    public function getPath(): string
+    public function getMethod(): string
     {
-        return $this->path;
+        return $this->method;
     }
 
     /**
-     * @return array
+     * @return string
      */
-    public function getParameters(): array
+    public function getPath(): string
     {
-        return $this->parameters;
+        return $this->path;
     }
 
     /**
      * @return array
      */
-    public function getOptions(): array
+    public function getCurrentData(): array
     {
-        return $this->options;
+        return $this->currentData;
     }
 
     /**
-     * @return string
+     * @return array
      */
-    public function getErrorMessage(): string
+    public function getParameters(): array
     {
-        return $this->errorMessage;
+        return $this->parameters;
     }
 
     /**
      * @return array
      */
-    public function getCurrentData(): array
+    public function getOptions(): array
     {
-        return $this->currentData;
+        return $this->options;
     }
 
     /**
@@ -142,7 +143,8 @@ abstract class BaseRestOperation
      */
     abstract public function getChangeLog(): array;
 
+    #[Pure]
     public function __toString(): string {
-        return $this->getMethod() . " " . $this->getPath() . " " . json_encode($this->getParameters());
+        return $this->getMethod() . " " . $this->getPath();
     }
 }

+ 16 - 0
src/Service/Rest/Operation/CreateOperation.php

@@ -28,6 +28,22 @@ class CreateOperation extends BaseRestOperation
         $this->entity = $entity;
     }
 
+    /**
+     * @return string
+     */
+    public function getEntity(): string
+    {
+        return $this->entity;
+    }
+
+    /**
+     * @return array
+     */
+    public function getData(): array
+    {
+        return $this->data;
+    }
+
     /**
      * Return an array of messages describing the change that this operation will bring
      *

+ 8 - 0
src/Service/Rest/Operation/DeleteOperation.php

@@ -30,6 +30,14 @@ class DeleteOperation extends BaseRestOperation
         $this->id = $id;
     }
 
+    /**
+     * @return string
+     */
+    public function getEntity(): string
+    {
+        return $this->entity;
+    }
+
     /**
      * Return an array of messages describing the change that this operation will bring
      *

+ 15 - 0
src/Service/Rest/Operation/UpdateOperation.php

@@ -33,6 +33,21 @@ class UpdateOperation extends BaseRestOperation
         $this->id = $id;
     }
 
+    /**
+     * @return string
+     */
+    public function getEntity(): string
+    {
+        return $this->entity;
+    }
+
+    /**
+     * @return array
+     */
+    public function getData(): array
+    {
+        return $this->data;
+    }
 
     /**
      * Return an array of messages describing the change that this operation will bring

+ 7 - 8
tests/Service/Rest/ApiRequestServiceTest.php

@@ -9,11 +9,10 @@ use Symfony\Contracts\HttpClient\ResponseInterface;
 
 class ApiRequestServiceTest extends TestCase
 {
-    private HttpClientInterface $client;
     private ApiRequestService $apiRequestService;
 
     public function setUp(): void {
-        $this->client = $this->getMockBuilder(HttpClientInterface::class)
+        $client = $this->getMockBuilder(HttpClientInterface::class)
             ->disableOriginalConstructor()
             ->getMock();
 
@@ -22,26 +21,26 @@ class ApiRequestServiceTest extends TestCase
             ->getMock();
         $response->method('getContent')->willReturn('{"a": 1}');
 
-        $this->client
+        $client
             ->expects($this->once())
             ->method('request')
             ->with("GET", "my_url.org")
             ->willReturn($response);
 
-        $this->apiRequestService = new ApiRequestService($this->client);
+        $this->apiRequestService = new ApiRequestService($client);
     }
 
     public function testGetJsonContent() {
         $this->assertEquals(
-            $this->apiRequestService->getJsonContent('my_url.org'),
-            ['a' => 1]
+            ['a' => 1],
+            $this->apiRequestService->getJsonContent('my_url.org')
         );
     }
 
     public function testGetContent() {
         $this->assertEquals(
-            $this->apiRequestService->getContent('my_url.org'),
-            '{"a": 1}'
+            '{"a": 1}',
+            $this->apiRequestService->getContent('my_url.org')
         );
     }
 }

+ 126 - 0
tests/Service/Rest/Operation/BaseRestOperationTest.php

@@ -0,0 +1,126 @@
+<?php
+
+use App\Service\Rest\ApiRequestService;
+use App\Service\Rest\Operation\BaseRestOperation;
+use PHPUnit\Framework\TestCase;
+use Symfony\Component\HttpClient\Exception\ClientException;
+use Symfony\Contracts\HttpClient\ResponseInterface;
+
+class ForTestsBaseRestOperation extends BaseRestOperation {
+    public function getChangeLog(): array { return []; }
+}
+
+class BaseRestOperationTest extends TestCase
+{
+    private ApiRequestService $apiRequestService;
+
+    public function setUp(): void {
+        $this->apiRequestService = $this->getMockBuilder(ApiRequestService::class)
+            ->disableOriginalConstructor()
+            ->getMock();
+    }
+
+    public function testGetters() {
+        $operation = new ForTestsBaseRestOperation(
+            'a label',
+            'GET',
+            '/a/path',
+            ['data' => 1],
+            ['param' => 2],
+            ['option' => 3]
+        );
+
+        $this->assertEquals('a label', $operation->getLabel());
+        $this->assertEquals('GET', $operation->getMethod());
+        $this->assertEquals('/a/path', $operation->getPath());
+        $this->assertEquals(['data' => 1], $operation->getCurrentData());
+        $this->assertEquals(['param' => 2], $operation->getParameters());
+        $this->assertEquals(['option' => 3], $operation->getOptions());
+
+        $this->assertEquals('GET /a/path', (string)$operation);
+    }
+
+    /**
+     * Test execution with a valid request
+     */
+    public function testExecuteValid()
+    {
+        $operation = new ForTestsBaseRestOperation(
+            'Update entity 1', 'PUT', 'entity/1', [], [], ['json' => '{"a":1}']
+        );
+
+        $responseOk = $this->getMockBuilder(ResponseInterface::class)->getMock();
+        $responseOk->method('getStatusCode')->willReturn(200);
+
+        $this->apiRequestService
+            ->expects($this->once())
+            ->method('request')
+            ->with('PUT', 'entity/1', [], ['json' => '{"a":1}'])
+            ->willReturn($responseOk);
+
+        $operation->setApiRequestService($this->apiRequestService);
+
+        $operation->execute();
+        $this->assertEquals(BaseRestOperation::STATUS_DONE, $operation->getStatus());
+        $this->assertEquals("", $operation->getErrorMessage());
+    }
+
+    /**
+     * Test execution with an invalid request (api returns an error 404 for example)
+     */
+    public function testExecuteInvalid()
+    {
+        $operation = new ForTestsBaseRestOperation(
+            'Update entity 1', 'PUT', 'entity/2'
+        );
+
+        $responseError = $this->getMockBuilder(ResponseInterface::class)->getMock();
+        $responseError->method('getStatusCode')->willReturn(404);
+        $responseError->method('getContent')->willReturn('Not found');
+
+        $this->apiRequestService
+            ->expects($this->once())
+            ->method('request')
+            ->with('PUT', 'entity/2')
+            ->willReturn($responseError);
+
+        $operation->setApiRequestService($this->apiRequestService);
+
+        $operation->execute();
+        $this->assertEquals(BaseRestOperation::STATUS_ERROR, $operation->getStatus());
+        $this->assertEquals('Error 404 : Not found', $operation->getErrorMessage());
+    }
+
+    /**
+     * Test execution if the request throw an HTTP exception
+     */
+    public function testExecutionError() {
+        $operation = new ForTestsBaseRestOperation(
+            'Update entity 1', 'PUT', 'entity/3'
+        );
+
+        $responseException = $this->getMockBuilder(ResponseInterface::class)->getMock();
+        $responseException->method('getStatusCode')->willReturn(500);
+        $responseException->method('getContent')->willReturn('The server said the request is bad');
+        $responseException->method('getInfo')->willReturnMap([
+            ['http_code', 500],
+            ['url', 'entity/3'],
+            ['response_headers', ['content-type: json']]
+        ]);
+
+        $this->apiRequestService
+            ->expects($this->once())
+            ->method('request')
+            ->with('PUT', 'entity/3')
+            ->willThrowException(new ClientException($responseException));
+
+        $operation->setApiRequestService($this->apiRequestService);
+
+        $operation->execute();
+        $this->assertEquals(BaseRestOperation::STATUS_ERROR, $operation->getStatus());
+        $this->assertMatchesRegularExpression(
+            '/.*ClientException: HTTP 500 returned for "entity\/3".*/',
+            $operation->getErrorMessage()
+        );
+    }
+}

+ 42 - 0
tests/Service/Rest/Operation/CreateOperationTest.php

@@ -0,0 +1,42 @@
+<?php
+
+use App\Service\Rest\Operation\CreateOperation;
+use PHPUnit\Framework\TestCase;
+
+class CreateOperationTest extends TestCase
+{
+    public function testGetters() {
+        $operation = new CreateOperation(
+            'Create a dinosaur',
+            'dinosaur',
+            ['name' => 'denver']
+        );
+
+        $this->assertEquals('POST', $operation->getMethod());
+        $this->assertEquals('dinosaur', $operation->getEntity());
+        $this->assertEquals('dinosaur', $operation->getPath());
+        $this->assertEquals(['name' => 'denver'], $operation->getData());
+
+        $this->assertEquals('POST dinosaur', (string)$operation);
+    }
+
+    public function testGetChangeLog() {
+        $operation = new CreateOperation(
+            'Create a dinosaur',
+            'dinosaur',
+            ['name' => 'denver', 'color' => 'green', 'objects' => ['glasses' => 'pink', 'guitar' => 'electric']]
+        );
+
+        $this->assertEquals(
+            [
+                '[POST dinosaur]',
+                'name : `denver`',
+                'color : `green`',
+                'objects.glasses : `pink`',
+                'objects.guitar : `electric`',
+            ],
+            $operation->getChangeLog()
+        );
+    }
+
+}

+ 36 - 0
tests/Service/Rest/Operation/DeleteOperationTest.php

@@ -0,0 +1,36 @@
+<?php
+
+use App\Service\Rest\Operation\CreateOperation;
+use App\Service\Rest\Operation\DeleteOperation;
+use PHPUnit\Framework\TestCase;
+
+class CreateOperationTest extends TestCase
+{
+    public function testGetters() {
+        $operation = new DeleteOperation(
+            'Delete a dinosaur',
+            'dinosaur',
+            ['id' => 1]
+        );
+
+        $this->assertEquals('DELETE', $operation->getMethod());
+        $this->assertEquals('dinosaur', $operation->getEntity());
+        $this->assertEquals('dinosaur/1', $operation->getPath());
+
+        $this->assertEquals('DELETE dinosaur/1', (string)$operation);
+    }
+
+    public function testGetChangeLog() {
+        $operation = new DeleteOperation(
+            'Delete a dinosaur',
+            'dinosaur',
+            ['id' => 1]
+        );
+
+        $this->assertEquals(
+            ['[DELETE dinosaur/1]'],
+            $operation->getChangeLog()
+        );
+    }
+
+}

+ 44 - 0
tests/Service/Rest/Operation/UpdateOperationTest.php

@@ -0,0 +1,44 @@
+<?php
+
+use App\Service\Rest\Operation\CreateOperation;
+use App\Service\Rest\Operation\UpdateOperation;
+use PHPUnit\Framework\TestCase;
+
+class CreateOperationTest extends TestCase
+{
+    public function testGetters() {
+        $operation = new UpdateOperation(
+            'Update a dinosaur',
+            'dinosaur',
+            ['id' => 1, 'weight' => 1600],
+            ['weight' => 1800]
+        );
+
+        $this->assertEquals('PUT', $operation->getMethod());
+        $this->assertEquals('dinosaur', $operation->getEntity());
+        $this->assertEquals('dinosaur/1', $operation->getPath());
+        $this->assertEquals(['id' => 1, 'weight' => 1600], $operation->getCurrentData());
+        $this->assertEquals(['weight' => 1800], $operation->getData());
+
+        $this->assertEquals('PUT dinosaur/1', (string)$operation);
+    }
+
+    public function testGetChangeLog() {
+        $operation = new UpdateOperation(
+            'Update a dinosaur',
+            'dinosaur',
+            ['id' => 1, 'weight' => 1600, 'attrs' => ['vision' => 'movement-based', 'teeth' => '100']],
+            ['weight' => 1800, 'attrs' => ['vision' => 'movement-based', 'teeth' => '99']]
+        );
+
+        $this->assertEquals(
+            [
+                '[PUT dinosaur/1]',
+                'weight : `1600` => `1800`',
+                'attrs.teeth : `100` => `99`',
+            ],
+            $operation->getChangeLog()
+        );
+    }
+
+}