Giter Site home page Giter Site logo

swaggerassertions's Introduction

Swagger Assertions

Test any API requests and responses match with the models described in the documentation.

This project is compatible with Swagger 2 spec definitions.

Installing via Composer

You can use Composer .

composer require fr3d/swagger-assertions

Usage in PHPUnit

There are two traits for provide predefined helper functions for different assertions.

See examples at examples/PhpUnit

FAQ

Q: Can this library validate my Swagger definition?
A: No. This library validate your API requests and responses match your Swagger definition.

License

Code licensed under BSD 2 clauses terms & conditions.

See LICENSE.txt for more information.

swaggerassertions's People

Contributors

jessedc avatar maks3w avatar masonm avatar nicofuma avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swaggerassertions's Issues

Possible issue in resolving recursive references

I think I found an issue with the way references are resolved by the SchemaManager::fromUri() method.
If I use a call to SchemaManager::fromUri() to initialize the SchemaManager and then use that manager to validate a response whose schema involves recursive references, the validation goes off into an infinite loop.
However, if I use the SchemaStorage to import the json schema first (thereby pre-resolving all references) and then create the SchemaManager manually from the resolved schema, everything works fine.

Attached is a test case that I built starting from the example reported by @MaikWagner in #53 . Depending on which way the SchemaManager is instanciated (the test includes both ways, one comment and the other not), the test either is green or goes into an infinite loop.

test.zip

json-schema breaks for URI now

It looks like justinrainbow/json-schema has recently been updated and it now breaks SwaggerAssertions, if you try and pass SchemaManager a URL, like so:

$this->schemaManager = new SchemaManager('http://petstore.swagger.io/v2/swagger.json');

This commit has caused the recent issue:

jsonrainbow/json-schema@780dd6f

If you try and use a URL now, it will fail on:

./vendor/justinrainbow/json-schema/src/JsonSchema/Uri/Retrievers/FileGetContents.php

30 if (!file_exists($uri)) {
31 throw new ResourceNotFoundException('JSON schema not found at ' . $uri);
32 }

A temporary fix is to tell SwaggerAssertions composer.json to use 2.0.2 of justinrainbow/json-schema, but probably not the best solution long term?

Pattern mathing in URLs

Hi,

Do you have a suggestion how to handle URLs that use variables and look similar to URLs that have paths that kind of match those variables, e.g.

/some/path/{var}
vs.
/some/path/non-var

In our case {var} is a placeholder for an id with only digits. The application routing allows to make this distinction. However when validating the second path's URL also matches the first path (when not considering pattern matching). Then the swagger assertion fails because the second path's response is validated against the specification of the first URL.

Tests are always pass

Tests are always pass. Even if I manually corrupt fixtures/pet_store.json tests are still pass. Steps to reproduce:

  1. cd ~/Desktop
  2. git clone https://github.com/Maks3w/SwaggerAssertions.git
  3. cd SwaggerAssertions
  4. composer install
  5. phpunit examples/PhpUnit/LocalFileTest.php
  6. Manually corrupt fixtures/pet_store.json -> #/definitions/Pet -> set properties.category to properties.catego*1*ry
  7. phpunit examples/PhpUnit/LocalFileTest.php Test passes but should fail.

Is any way to fix it?

"Request URI does not match with any swagger path definition"

Hi

First thanks for a great package.

If I add query string paramaters to the test URL the error "Request URI does not match with any swagger path definition" shows up. Without the query string parameters, the request hits the API.

Here is the test method:


    /**
     * Get publications by category
     */
    public function testFetchPublicationsByCategory()
    {

        /** Configure your end point and request parameters */
        $requestType = 'GET';
        $endPoint = '/publications';

        $parameters = [
            "request.category" => "001"
        ];

        /** Make the request */
        $response = $this->guzzleHttpClient->request($requestType, $this->baseURI.$endPoint, [
            'query' => $parameters
        ]);

        $responseBody = json_decode((string) $response->getBody());

        /** Do your assertions */
        $this->assertResponseBodyMatch($responseBody, self::$schemaManager, '/publications', 'get', 200);

    }

Here is the path definition from the swagger schema:

"/publications":{
      "get":{
        "tags":[
          "Publications"
        ],
        "operationId":"Publications_ListPublications",
        "consumes":[

        ],
        "produces":[
          "application/json",
          "text/json",
          "application/xml",
          "text/xml"
        ],
        "parameters":[
          {
            "name":"request.publisher.id",
            "in":"query",
            "required":false,
            "type":"integer",
            "format":"int32"
          },
          {
            "name":"request.publisher.name",
            "in":"query",
            "required":false,
            "type":"string"
          },
          {
            "name":"request.publisher.processingLocation",
            "in":"query",
            "required":false,
            "type":"string"
          },
          {
            "name":"request.category",
            "in":"query",
            "required":false,
            "type":"string"
          },
          {
            "name":"request.pageSize",
            "in":"query",
            "required":false,
            "type":"integer",
            "format":"int32"
          },
          {
            "name":"request.pageNo",
            "in":"query",
            "required":false,
            "type":"integer",
            "format":"int32"
          }
        ],
        "responses":{
          "200":{
            "description":"OK",
            "schema":{
              "$ref":"#/definitions/ListPublicationsResponse"
            }
          }
        }
      },
      "post":{
        "tags":[
          "Publications"
        ],
        "operationId":"Publications_CreatePublication",
        "consumes":[

        ],
        "produces":[
          "application/json",
          "text/json",
          "application/xml",
          "text/xml"
        ],
        "parameters":[

        ],
        "responses":{
          "200":{
            "description":"OK",
            "schema":{
              "$ref":"#/definitions/CreatePublicationResponse"
            }
          }
        }
      }
    },

If I remove the "query" => [....] from the Guzzle ->get() call, the API is hit.

Clearly these query string parameters are changing the query URL but then it is failing to find the /publications path in the schema?

Am I doing something entirely stupid?

Thanks.

SchemaStorage::expandRefs() loops infinitely on recursive $ref definition

Hi,

I was trying to validate a response with a json schema that has circular $ref definitions. This is basically allowed (https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03#section-7) but leads to an php error after looping infinitely:

PHP Fatal error: Maximum execution time of 30 seconds exceeded in vendor/justinrainbow/json-schema/src/JsonSchema/SchemaStorage.php on line 85

With xdebug enabled it exits after a while and throws this backtrace:

PHP Fatal error: Uncaught Error: Maximum function nesting level of '256' reached, aborting! in /vendor/justinrainbow/json-schema/src/JsonSchema/SchemaStorage.php:86
Stack trace:
#0 vendor/justinrainbow/json-schema/src/JsonSchema/SchemaStorage.php(86): is_object('id')
#1 vendor/justinrainbow/json-schema/src/JsonSchema/SchemaStorage.php(89): JsonSchema\SchemaStorage->expandRefs('id', 'internal://prov...')
#2 vendor/justinrainbow/json-schema/src/JsonSchema/SchemaStorage.php(107): JsonSchema\SchemaStorage->expandRefs(Array, 'internal://prov...')
#3 vendor/justinrainbow/json-schema/src/JsonSchema/SchemaStorage.php(107): JsonSchema\SchemaStorage->expandRefs(Object(stdClass), 'internal://prov...')
#4 vendor/justinrainbow/json-schema/src/JsonSchema/SchemaSto in vendor/justinrainbow/json-schema/src/JsonSchema/SchemaStorage.php on line 86

schema-loop-debug

You can reproduce the issue with the following code:

test.php

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Response.php';
require_once __DIR__ . '/SwaggerSchemaManager.php';
require_once __DIR__ . '/SwaggerValidator.php';
require_once __DIR__ . '/Validator.php';

$definition =  __DIR__ . '/swagger.json';
if (!is_readable($definition)) {
        throw new Exception("Could not read '$definition'.");
}

//$header = getHeader((array) ([]));
//$body = $filename === '' ? '' : readFromFile($filename);
$response = new Response(200, [], "", "/ps?hash=123", 'GET');

$validator = new SwaggerValidator('file://' . $definition);

if ($result = $validator->validateResponse($response)) {
        print("ok\n");
} else {
        fprintf(STDERR, implode(', ', $validator->getErrors()) . "\n");
        exit(1);
}

swagger.json

{
  "swagger": "2.0",
  "info": {
    "title": "Test",
    "version": "0.0.1"
  },
  "paths": {
    "/ps": {
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "hash",
            "type": "string"
          }
        ],
        "responses": {
          "200": {
            "description": "foo",
            "schema": {
              "$ref": "#/definitions/actionItem"
            }
          }
        }
      }
    }
  },
  "definitions": {
    "response": {
    },
    "actionItem": {
      "type": "object",
      "properties": {
        "value": {
          "type": "string"
        },
        "refs": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/actionItem"
          }
        }
      }
    }
  }
}

Mapper fails to recognise endpoint with variable file extension

Let me say first, great library and thank you for providing/supporting it!

I have following endpoint: https://site.com/v1/company/us/123456.json and that mapps to following Swagger spcification: /v1/company/{country}/{companyId}.{format} where format can be either XML or JSON.

So my problem is that the code sees the path as like there is no file extension and the companyId=123456.json because the . is deemed as a valid character and not a separator as is the case with /

So my question is there any way around that problem?

Your requirements could not be resolved to an installable set of packages.

Hi
I tried to install it, based on your documentation, by using :
composer require Maks3w/SwaggerAssertions
it then asks for entering the version, below is the message:

Please provide a version constraint for the Maks3w/SwaggerAssertions requirement :
I tried 0.1.2, and some other like 0.1.1

and below is the error that I get :

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package maks3w/swaggerassertions could not be found in any version, there may be a typo in the package name.

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://groups.google.com/d/topic/composer-dev/_g3ASeIFlrc/discussion> for more details.

Read <http://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

Installation failed, reverting ./composer.json to its original content.

I also tried to clone the project and run it locally, but then I get the below error:

  [RuntimeException]
  Could not load package fr3d/swagger-assertions in http://packagist.org: [UnexpectedValueException] Could not parse version constraint ^0.3.1: Invalid ver
  sion string "^0.3.1"



  [UnexpectedValueException]
  Could not parse version constraint ^0.3.1: Invalid version string "^0.3.1"

Assertion of required fields by definition does not work

It seems that assertion of required fields is not working properly, while test ends fine without fields in response. Api is not available publicly so I include full Swagger file.

swagger.conf:

{
    "swagger": "2.0",
    "info": {
        "title": "Blabla",
        "description": "Bla bla"
    },
    "host": "api.blablaxyz.com",
    "basePath": "/v1",
    "schemes": [
        "http"
    ],
    "paths": {
        "/user/{user_id}": {
            "get": {
                "tags": [
                    "User"
                ],
                "description": "Get user data.",
                "consumes": [
                    "application/json"
                ],
                "produces": [
                    "application/json"
                ],
                "parameters": [
                    {
                        "name": "user_id",
                        "in": "path",
                        "description": "Expected user_id",
                        "required": true,
                        "type": "integer"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "Gets user object.",
                        "schema": {
                            "$ref": "#/definitions/User"
                        }
                    },
                    "404": {
                        "description": "Provided user_id doesn't exist.",
                        "headers": {
                            "404": {}
                        }
                    }
                }
            }
        }
    },
    "definitions": {
        "User": {
            "required": [
                "email",
                "name",
                "surname",
                "dupa"
            ],
            "properties": {
                "email": {
                    "description": "User e-mail address",
                    "type": "string"
                },
                "name": {
                    "description": "User name",
                    "type": "string"
                },
                "surname": {
                    "description": "User surname",
                    "type": "string"
                },
                "dupa": {
                    "type": "string"
                }
            }
        }
    }
}

Property dupa is fake and will not be returned by API.

test.php:

<?php

use FR3D\SwaggerAssertions\PhpUnit\Psr7AssertsTrait;
use FR3D\SwaggerAssertions\SchemaManager;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;

class AssertTest extends \PHPUnit_Framework_TestCase {
    use Psr7AssertsTrait;

    protected static $schemaManager;
    protected $guzzleHttpClient;

    public static function setUpBeforeClass() {
        self::$schemaManager = new SchemaManager(json_decode(file_get_contents('http://api.blablaxyz.com/v1/swagger.conf')));
        // tested that definitions are parsed properly
    }

    protected function setUp() {
        $this->guzzleHttpClient = new Client(['headers' => ['User-Agent' => 'Unit tests']]);
    }

    public function test_get_user() {
        $request = new Request('GET', 'http://api.blablaxyz.com/v1/user/1');
        $request->withHeader('Accept', 'application/json');
        $response = $this->guzzleHttpClient->send($request);
        $this->assertResponseMatch($response, self::$schemaManager, '/v1/user/1', 'get');
    }
}

Response body in this example is exactly:

{"status":"success","data":{"email":"kontakt@s...","user_id":1,"name":"Michał","surname":"Semeniuk","avatar":""}}

Assertion goes well while it should not:

  1. Generally whole format is not OK, while we return Jsend which returns User under data index and not directly as it's expected by User definition.
  2. Mentioned dupa which is required by definition is not returned.
  3. Field avatar is not defined but this is expected to pass without additionalProperties nulled.

Am I missing something or required fields are not parsed?

Thanks in advance.

Dependency on phpunit instead of symfony/validator

I have noticed that you added phpunit/phpunit to require section in composer.json. I think it should be changed and the code should be rebuilt to use an alternative like symfony/validator and it's Constraints instead of using phpunit's version.

The reason I would change is that all dev libraries (phpunit is one of them) has no security guarantee so it should not be used in production env at all.

Structure validation error.

Schema

"responses": {
                    "200": {
                        "description": "",
                        "schema": {
                            "type": "object",
                            "properties": {
                                "booking_events": {
                                    "$ref": "#/definitions/booking_event"
                                },
                                "event_creators": {
                                    "$ref": "#/definitions/event_creator"
                                },
                                "venues": {
                                    "$ref": "#/definitions/venue"
                                },
                                "booking_event_details": {
                                    "$ref": "#/definitions/booking_event_details"
                                },
                                "booking_event_packages": {
                                    "type": "array",
                                    "items": {
                                        "type": "object"
                                    }
                                },
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>      <------------ this section
                                "downloads": {
                                    "type": "array",
                                    "items": {
                                        "$ref": "#/definitions/download_file"
                                    }
                                },
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 
                                "highlights": {
                                    "type": "array",
                                    "items": {
                                        "type": "string"
                                    }
                                },
                                "to_brings": {
                                    "type": "array",
                                    "items": {
                                        "type": "string"
                                    }
                                },
                                "to_wears": {
                                    "type": "array",
                                    "items": {
                                        "type": "string"
                                    }
                                },
                                "pricings": {
                                    "type": "object",
                                    "properties": {
                                        "low": {
                                            "type": "boolean"
                                        },
                                        "high": {
                                            "type": "boolean"
                                        },
                                        "total": {
                                            "type": [
                                                "integer",
                                                "string"
                                            ]
                                        }
                                    }
                                }
                            }
                        }
                    },
                    "201": {
                        "$ref": "#/responses/trait:success:201"
                    },
                    "401": {
                        "$ref": "#/responses/trait:success:401"
                    }
                }

Response

{
    "success": true,
   ...........................................................................
    "booking_event_packages": [],
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>    <---------- this section
    "downloads": [
        {
            "Doc": {
                "id": "123",
                "owner_id": "100",
                "active": "1",
                "type": "doc",
                "key": "dg46bv1i36uekrjq",
                "is_main": "0",
                "name": "bookings endpoint",
                "filename": "aus39y0rqvrzxsj8u423.txt",
                "created": "2016-10-17 15:50:50",
                "modified": "2016-10-17 15:50:50",
                "encrypted_key": "S9vLirwnAZB2WoSuVsnfOksSJ96zUdI9EuN31zQ_t1M5dA_W8F4GWOUGDEwGLzSho74ZaSL_9KrpJWM5r1e5osFBlwOrYB6Vyin-F2X4qAVGY57oV8wEPitQ25dGckTt",
                "filepath": "https:\/\/s3-ap-southeast-2.amazonaws.com\/emc-dev\/e0a64-docs\/100\/aus39y0rqvrzxsj8u423.txt",
                "path": "s3:\/\/emc-dev\/e0a64-docs\/100\/aus39y0rqvrzxsj8u423.txt",
                "url": "https:\/\/s3-ap-southeast-2.amazonaws.com\/emc-dev\/e0a64-docs\/100\/aus39y0rqvrzxsj8u423.txt",
                "exists": false,
                "size": 0,
                "size_string": "0 bytes",
                "extension": "txt"
            }
        }
    ],
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    "highlights": [
        "one",
        "two"
    ],
    "to_brings": [
        "hello",
        "goodbye"
    ],
    "to_wears": [
        "apples",
        "pears"
    ],
    "pricings": {
        "low": false,
        "high": false,
        "total": 0
    }
}

As you can see above, the download section's structure is definately different. In the schema, downloads have an array of object while the response have an object with key name Doc. Thus, I believe that json-schema library should detect this error. But it seems to only detect the data type errors.

How can I detect this type of error? or is this type of error impossible to detect in json-schema library?

Please give me a small clue to resolve this issue.

Thank you.

Dependency clash with json_schema

Hey there, this looks like just the thing I was looking for.
However, the tie to the outdated version of justinrainbow/json_schema is preventing me from using the package.

I took a closer look at the code and by just replacing the class RefResolver in SchemaManager with SchemaStorage, I was able to make all but 11 tests pass with the newest version of json_schema(5.0.2).

The remaining failing tests seem to be related to the document tree not beeing traversed correctly, however, I'm unsure of how to fix it.
Is there any reason why the package is pinned at 2.0.1 or is it viable to keep pushing for this?

Incompatible with PHP 8.1 due to "justinrainbow/json-schema"

Running this under PHP 8.1 will give deprecation warnings, since 8.1 is now enforcing return type compatibility for internal classes (source):

[03-Nov-2023 20:09:50 UTC] PHP Fatal error:  During inheritance of Iterator: Uncaught Behat\Testwork\Call\Exception\CallErrorException: 8192: Return type of JsonSchema\Iterator\ObjectIterator::current() should either be compatible with Iterator::current(): mixed, or the
 #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /app/vendor/justinrainbow/json-schema/src/JsonSchema/Iterator/ObjectIterator.php line 42 in /app/vendor/behat/behat/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php:90
Stack trace:
#0 /app/vendor/justinrainbow/json-schema/src/JsonSchema/Iterator/ObjectIterator.php(17): Behat\Testwork\Call\Handler\RuntimeCallHandler->handleError(8192, 'Return type of ...', '/app/ven...', 42)
#1 /app/vendor/composer/ClassLoader.php(571): include('/app/ven...')
#2 /app/vendor/composer/ClassLoader.php(428): Composer\Autoload\includeFile('/app/ven...')
#3 /app/vendor/fr3d/swagger-assertions/src/JsonSchema/RefResolver.php(86): Composer\Autoload\ClassLoader->loadClass('JsonSchema\\Iter...')                                                                                                                             #4 /app/vendor/fr3d/swagger-assertions/src/JsonSchema/RefResolver.php(70): FR3D\SwaggerAssertions\JsonSchema\RefResolver->resolveSchemas(Object(stdClass), 'https://adobest...', Array)
#5 /app/vendor/fr3d/swagger-assertions/src/JsonSchema/RefResolver.php(54): FR3D\SwaggerAssertions\JsonSchema\RefResolver->resolveCached('https://adobest...', Array)
#6 /app/include/app/Swagger.php(110): FR3D\SwaggerAssertions\JsonSchema\RefResolver->resolve('https://adobest...')
#7 /app/tests/behat/context/ApiContext.php(858): app\Swagger::getSchemaManager()

There's a PR to fix this: jsonrainbow/json-schema#682

Error when using primitive data type "file"

The Swagger 2.0 spec supports having a Schema object with root type "file", which is an extension to JSON Schema:

As an extension to the Schema Object, its root type value may also be "file". This SHOULD be accompanied by a relevant produces mime-type.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#responseObject

Doing this results in an assertion failure with the message "is an invalid type for file". Here's a branch with a test case showing that: master...MasonM:bug-with-schema-file

Output on my machine:

$  ./vendor/bin/phpunit      
PHPUnit 6.2.4 by Sebastian Bergmann and contributors.

.E............................................................... 65 / 93 ( 69%)
............................                                      93 / 93 (100%)

Time: 93 ms, Memory: 10.00MB

There was 1 error:

1) FR3D\SwaggerAssertions\PhpUnit\AssertsTraitTest::testAssertResponseBodyMatchWithFile
JsonSchema\Exception\InvalidArgumentException: GIF89a,; is an invalid type for file

/Users/mmalone/src/SwaggerAssertions/vendor/justinrainbow/json-schema/src/JsonSchema/Constraints/TypeConstraint.php:143
/Users/mmalone/src/SwaggerAssertions/vendor/justinrainbow/json-schema/src/JsonSchema/Constraints/TypeConstraint.php:73
/Users/mmalone/src/SwaggerAssertions/vendor/justinrainbow/json-schema/src/JsonSchema/Constraints/Constraint.php:201
/Users/mmalone/src/SwaggerAssertions/vendor/justinrainbow/json-schema/src/JsonSchema/Constraints/UndefinedConstraint.php:130
/Users/mmalone/src/SwaggerAssertions/vendor/justinrainbow/json-schema/src/JsonSchema/Constraints/UndefinedConstraint.php:36
/Users/mmalone/src/SwaggerAssertions/vendor/justinrainbow/json-schema/src/JsonSchema/Constraints/Constraint.php:217
/Users/mmalone/src/SwaggerAssertions/vendor/justinrainbow/json-schema/src/JsonSchema/Constraints/SchemaConstraint.php:29
/Users/mmalone/src/SwaggerAssertions/vendor/justinrainbow/json-schema/src/JsonSchema/Validator.php:36
/Users/mmalone/src/SwaggerAssertions/src/PhpUnit/JsonSchemaConstraint.php:41
/Users/mmalone/src/SwaggerAssertions/src/PhpUnit/AssertsTrait.php:37
/Users/mmalone/src/SwaggerAssertions/tests/PhpUnit/AssertsTraitTest.php:43

ERRORS!
Tests: 93, Assertions: 211, Errors: 1.

Compatibility with OpenAPI 3.0

Hi,

A few weeks ago has been delivered the third major version of OpenAPI.
Did you plan to upgrade SwaggerAssertions to be compatible with?

Regards,
Ben

Strict mode for comparison

Currently there is no strict mode in comparison of the response body and the given definition. This results in the strange behavior, that the test goes green, even if there are more parameters in response as defined. The strict mode should check the amount of given parameters against the amount of parameters in definition.

Nullable extension not taken into consideration ?

Hi, I have this nullable property :

"archived": {
    "type": "integer",
    "minimum": 0,
    "x-nullable": true
},

when I'm testing , it fails when the property is null, here's the assertion error message :
[archived] NULL value found, but an integer is required

is it due to swagger-assertions not supporting vendor extensions or what ? any help.

Trouble with validating required query parameter

Hello, first of all thank you for your great library.

I have this API endpoint, it includes a required query parameter called type :

"/users": {
            "post": {
			"parameters": [
				{
					"name": "type",
					"in": "query",
					"required": true,
					"type": "string"
				}
			],
			"responses": {
				//...
			}
		}
	}

I'm testing it using the following method :

public function testPostTextElement(){

        $path = '/users?type=x';
        $httpMethod = 'POST';

        $request = new Request($httpMethod,self::HOST.$path);
        
        try{
            $this->assertRequestMatch($request,self::$schemaManager);
            $response = $this->guzzleHttpClient->send($request);

        }catch (ClientException $e){
            $response = $e->getResponse();
        }catch (ServerException $e){
            $response = $e->getResponse();
        }

        $this->assertResponseMatch($response,self::$schemaManager,$path,$httpMethod);
    }

but I keep getting the following error :

Failed asserting that {"type":"x"} is a valid request query. [] Object value found, but a string is required

any idea on how to solve this problem ?

Nullable response fields

And another question, is there a possibility to implement fields in response which can be null?

Different implementations of SymfonyAssertsTrait::assertRequestMatch() and SymfonyAssertsTrait::assertResponseMatch() methods

These two methods have different implementation and it affects some cases, for example when you try to test endpoint with query parameters. When URI has query parameters The assertRequestMatch succeeded, but assertResponseMatch fails, because they use different values for $path variable:
assertRequestMatch - $request->getPathInfo()
assertResponseMatch - $request->getRequestUri()

Can you confirm that it has been implemented in this way intentionally?

How to check non-JSON requests with SymfonyAssertsTrait

In the function assertResponseMatch of SymfonyAssertsTrait, it looks like it assumes that the body is always json, given that it is always calling json_decode.

For the oauth service I use regular POST parameters, which are not available under
$request->getContent()
but under
$request->request->all()

Is SwaggerAssertions also capable of checking these requests?

assertResponseBodyMatch ignores definition

Hi there.
I am failing at validating that the response body matches the definition defined in swagger definition.
I used your very same example.
For the sake of reproducing it, here's what I did:
I requested

$request = new Request('GET', 'http://petstore.swagger.io/v2/pet/findByStatus?status=available');

which, according to http://petstore.swagger.io/v2/swagger.json, the 200 response schema is:

"schema": {
    "type": "array",
    "items": {
        "$ref": "#/definitions/Pet"
    }
}

Where Pet is:

"Pet": {
    "type": "object",
    "required": ["name", "photoUrls"],
    "properties": {
        "id": {
            "type": "integer",
            "format": "int64"
        },
        "category": {
            "$ref": "#/definitions/Category"
        },
        "name": {
            "type": "string",
            "example": "doggie"
        },
        "photoUrls": {
            "type": "array",
            "xml": {
                "name": "photoUrl",
                "wrapped": true
            },
            "items": {
                "type": "string"
            }
        },
        "tags": {
            "type": "array",
            "xml": {
                "name": "tag",
                "wrapped": true
            },
            "items": {
                "$ref": "#/definitions/Tag"
            }
        },
        "status": {
            "type": "string",
            "description": "pet status in the store",
            "enum": ["available", "pending", "sold"]
        }
    },
    "xml": {
        "name": "Pet"
    }
}

Test gives OK.
Now, if I were to change the name property to integer it should fail, but it doesn't.

"name": {
    "type": "integer"
},

Is this the intended behaviour? What is then the library validating?
I'm running php 7.1.

Cheers

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.