|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * Matomo - free/libre analytics platform |
| 5 | + * |
| 6 | + * @link https://matomo.org |
| 7 | + * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later |
| 8 | + */ |
| 9 | + |
| 10 | +declare(strict_types=1); |
| 11 | + |
| 12 | +namespace Piwik\Plugins\OpenApiDocs\tests\Unit; |
| 13 | + |
| 14 | +require_once PIWIK_INCLUDE_PATH . '/plugins/OpenApiDocs/vendor/autoload.php'; |
| 15 | + |
| 16 | +use PHPUnit\Framework\TestCase; |
| 17 | +use Piwik\Plugins\OpenApiDocs\API; |
| 18 | + |
| 19 | +/** |
| 20 | + * @group OpenApiDocs |
| 21 | + * @group OpenApiDocs_Unit |
| 22 | + * @group OpenApiDocs_APITest |
| 23 | + */ |
| 24 | +class APITest extends TestCase |
| 25 | +{ |
| 26 | + public function testGetMatomoOpenApiSpecReturnsDecodedJson() |
| 27 | + { |
| 28 | + $expectedSpec = [ |
| 29 | + 'openapi' => '3.1.0', |
| 30 | + 'info' => [ |
| 31 | + 'title' => 'Matomo Reporting API', |
| 32 | + 'version' => '1.0.0', |
| 33 | + ], |
| 34 | + ]; |
| 35 | + |
| 36 | + $api = $this->buildApiMock(true, json_encode($expectedSpec)); |
| 37 | + |
| 38 | + $result = $api->getMatomoOpenApiSpec(); |
| 39 | + |
| 40 | + $this->assertSame($expectedSpec, $result); |
| 41 | + } |
| 42 | + |
| 43 | + public function testGetMatomoOpenApiSpecThrowsExceptionWhenFileMissing() |
| 44 | + { |
| 45 | + $api = $this->buildApiMock(false); |
| 46 | + |
| 47 | + $this->expectException(\Exception::class); |
| 48 | + $this->expectExceptionMessage('OpenAPI spec file was not found'); |
| 49 | + |
| 50 | + $api->getMatomoOpenApiSpec(); |
| 51 | + } |
| 52 | + |
| 53 | + public function testGetMatomoOpenApiSpecThrowsExceptionWhenJsonIsInvalid() |
| 54 | + { |
| 55 | + $api = $this->buildApiMock(true, '{invalid json}'); |
| 56 | + |
| 57 | + $this->expectException(\Exception::class); |
| 58 | + $this->expectExceptionMessage('OpenAPI spec file contains invalid JSON'); |
| 59 | + |
| 60 | + $api->getMatomoOpenApiSpec(); |
| 61 | + } |
| 62 | + |
| 63 | + private function buildApiMock(bool $isReadable, $fileContents = false): API |
| 64 | + { |
| 65 | + $api = $this->getMockBuilder(API::class) |
| 66 | + ->onlyMethods(['getMatomoSpecFilePath', 'isSpecFileReadable', 'readSpecFile']) |
| 67 | + ->getMock(); |
| 68 | + |
| 69 | + $api->method('getMatomoSpecFilePath')->willReturn('/tmp/matomo_openapi_spec_v1.0.0.json'); |
| 70 | + $api->method('isSpecFileReadable')->willReturn($isReadable); |
| 71 | + $api->method('readSpecFile')->willReturn($fileContents); |
| 72 | + |
| 73 | + return $api; |
| 74 | + } |
| 75 | +} |
0 commit comments