Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue/19 json oas compat #20

Merged
merged 5 commits into from
Dec 18, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
#19 Handle nullable value in 3.0.x by modifying type
  • Loading branch information
hotmeteor committed Dec 11, 2020
commit 62f7531d88d2c06fb6332d83af432b5ac51d6089
7 changes: 5 additions & 2 deletions src/Assertions.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Illuminate\Support\Arr;
use PHPUnit\Framework\Assert as PHPUnit;
use Spectator\Exceptions\InvalidPathException;
use Spectator\Exceptions\MissingSpecException;
use Spectator\Exceptions\RequestValidationException;
use Spectator\Exceptions\ResponseValidationException;
use cebe\openapi\exceptions\UnresolvableReferenceException;
Expand All @@ -18,9 +19,10 @@ public function assertValidRequest()

PHPUnit::assertFalse(
in_array(Arr::get($contents, 'exception'), [
InvalidPathException::class,
MissingSpecException::class,
RequestValidationException::class,
UnresolvableReferenceException::class,
InvalidPathException::class,
]),
$this->decodeExceptionMessage($contents)
);
Expand All @@ -36,9 +38,10 @@ public function assertInvalidRequest()

PHPUnit::assertTrue(
in_array(Arr::get($contents, 'exception'), [
InvalidPathException::class,
MissingSpecException::class,
RequestValidationException::class,
UnresolvableReferenceException::class,
InvalidPathException::class,
]),
$this->decodeExceptionMessage($contents)
);
Expand Down
6 changes: 5 additions & 1 deletion src/Middleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ class Middleware
{
protected $spectator;

protected $version = '3.0';

public function __construct(RequestFactory $spectator)
{
$this->spectator = $spectator;
Expand Down Expand Up @@ -73,7 +75,7 @@ protected function validate(Request $request, Closure $next)

$response = $next($request);

ResponseValidator::validate($request_path, $response, $operation);
ResponseValidator::validate($request_path, $response, $operation, $this->version);

$this->spectator->reset();

Expand All @@ -88,6 +90,8 @@ protected function operation($request_path, $request_method)

$openapi = $this->spectator->resolve();

$this->version = $openapi->openapi;

foreach ($openapi->paths as $path => $pathItem) {
if ($this->resolvePath($path) === $request_path) {
$methods = array_keys($pathItem->getOperations());
Expand Down
35 changes: 31 additions & 4 deletions src/Validation/ResponseValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace Spectator\Validation;

use Exception;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use cebe\openapi\spec\Schema;
use Opis\JsonSchema\Validator;
use cebe\openapi\spec\Response;
Expand All @@ -19,16 +21,19 @@ class ResponseValidator

protected $operation;

public function __construct(string $uri, $response, Operation $operation)
protected $version;

public function __construct(string $uri, $response, Operation $operation, $version = '3.0')
{
$this->uri = $uri;
$this->response = $response;
$this->operation = $operation;
$this->version = $version;
}

public static function validate(string $uri, $response, Operation $operation)
public static function validate(string $uri, $response, Operation $operation, $version = '3.0')
{
$instance = new self($uri, $response, $operation);
$instance = new self($uri, $response, $operation, $version);

$instance->handle();
}
Expand Down Expand Up @@ -75,7 +80,7 @@ protected function validateResponse(Schema $schema, $body)
$shortHandler = $this->shortHandler();

try {
$result = $validator->dataValidation($body, $schema->getSerializableData(), -1);
$result = $validator->dataValidation($body, $this->prepareData($schema->getSerializableData()), -1);
} catch (SchemaKeywordException $exception) {
throw ResponseValidationException::withError("{$shortHandler} has invalid schema: [ {$exception->getMessage()} ]");
} catch (Exception $exception) {
Expand Down Expand Up @@ -154,4 +159,26 @@ protected function validator(): Validator

return $validator;
}

protected function prepareData($data)
{
if (!isset($data->properties)) {
return $data;
}

$clone = clone $data;

$v30 = Str::startsWith($this->version, '3.0');

foreach ($clone->properties as $key => $attributes) {
if ($v30 && isset($attributes->nullable)) {
$type = Arr::wrap($attributes->type);
$type[] = 'null';
$attributes->type = array_unique($type);
unset($attributes->nullable);
}
}

return $clone;
}
}
4 changes: 2 additions & 2 deletions tests/Fixtures/Nullable.3.0.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@
"type": "string",
"example": "Bloggs"
},
"favourite_colour": {
"email": {
"type": "string",
"example": "Red",
"example": "[email protected]",
"nullable": true
}
}
Expand Down
60 changes: 60 additions & 0 deletions tests/Fixtures/Nullable.3.1.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
{
"openapi": "3.1.0",
"info": {
"title": "Nullable.3.1",
"version": "1.0"
},
"servers": [
{
"url": "http:https://localhost:3000"
}
],
"paths": {
"/users/{user}": {
"parameters": [
{
"schema": {
"type": "string"
},
"name": "user",
"in": "path",
"required": true
}
],
"get": {
"summary": "Get single user",
"tags": [],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"first_name": {
"type": "string",
"example": "Joe"
},
"last_name": {
"type": "string",
"example": "Bloggs"
},
"email": {
"type": ["string", "null"],
"example": "[email protected]"
}
}
}
}
}
}
},
"operationId": "get-users-user"
}
}
},
"components": {
"schemas": {}
}
}
133 changes: 120 additions & 13 deletions tests/ResponseValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@

class ResponseValidatorTest extends TestCase
{
const NULLABLE_MISSING = 0;
const NULLABLE_EMPTY = 1;
const NULLABLE_VALID = 2;
const NULLABLE_INVALID = 3;
const NULLABLE_NULL = 4;

public function setUp(): void
{
parent::setUp();
Expand Down Expand Up @@ -107,21 +113,122 @@ public function test_cannot_locate_path_without_path_prefix()
->assertValidResponse(200);
}

public function test_handle_nullable_in_oa3dot0()
{
Spectator::using('Nullable.3.0.json');

Route::get('/api/v1/users/1', function () {
return [
[
'first_name' => 'Joe',
'last_name' => 'Bloggs',
],
/**
* @dataProvider nullableProvider
*/
public function test_handle_nullables(
$version,
$state,
$is_valid
) {
Spectator::using("Nullable.{$version}.json");

Route::get('/users/{user}', function () use ($state) {
$return = [
'first_name' => 'Joe',
'last_name' => 'Bloggs',
];

if ($state === self::NULLABLE_EMPTY) {
$return['email'] = '';
}

if ($state === self::NULLABLE_VALID) {
$return['email'] = '[email protected]';
}

if ($state === self::NULLABLE_INVALID) {
$return['email'] = [1, 2, 3];
}

if ($state === self::NULLABLE_NULL) {
$return['email'] = null;
}

return $return;
})->middleware(Middleware::class);

$this->getJson('/api/v1/users/1')
->assertValidRequest()
->assertValidResponse();
if ($is_valid) {
$this->getJson('/users/1')
->assertValidRequest()
->assertValidResponse();
} else {
$this->getJson('/users/1')
->assertValidRequest()
->assertInvalidResponse();
}
}

public function nullableProvider()
{
$validResponse = true;
$invalidResponse = false;

$v30 = '3.0';
$v31 = '3.1';

return [
// OA 3.0.0
'3.0, missing' => [
$v30,
self::NULLABLE_MISSING,
$validResponse,
],

'3.0, empty' => [
$v30,
self::NULLABLE_EMPTY,
$validResponse,
],

'3.0, null' => [
$v30,
self::NULLABLE_NULL,
$validResponse,
],

'3.0, valid' => [
$v30,
self::NULLABLE_VALID,
$validResponse,
],

'3.0, invalid' => [
$v30,
self::NULLABLE_INVALID,
$invalidResponse,
],

// OA 3.1.0
'3.1, missing' => [
$v31,
self::NULLABLE_MISSING,
$validResponse,
],

'3.1, empty' => [
$v31,
self::NULLABLE_EMPTY,
$validResponse,
],

'3.1, null' => [
$v31,
self::NULLABLE_NULL,
$validResponse,
],

'3.1, valid' => [
$v31,
self::NULLABLE_VALID,
$validResponse,
],

'3.1, invalid' => [
$v31,
self::NULLABLE_INVALID,
$invalidResponse,
],
];
}
}