Git Product home page Git Product logo

php-openapi-test's Introduction

PHP Swagger Test

Opensource ByJG GitHub source GitHub license GitHub release Build Status Scrutinizer Code Quality

A set of tools for testing in your REST calls based on the OpenApi specification using PHPUnit. Currently, this library supports the OpenApi specifications 2.0 (formerly swagger) and 3.0. Some features like callbacks, links and references to external documents/objects weren't implemented.

PHP Swagger Test can help you to test your REST Api. You can use this tool both for Unit Tests or Functional Tests.

This tool reads a previously Swagger JSON file (not YAML) and enables you to test the request and response. You can use the tool "https://github.com/zircote/swagger-php" for creating the JSON file when you are developing your rest API.

The ApiTestCase's assertion process is based on throwing exceptions if some validation or test failed.

Use cases for PHP Swagger test

You can use the Swagger Test library as:

  • Functional test cases
  • Unit test cases
  • Runtime parameters validator
  • Validate your specification

Functional Test cases

Swagger Test provides the class SwaggerTestCase for you extend and create a PHPUnit test case. The code will try to make a request to your API Method and check if the request parameters, status and object returned are OK.

/**
 * Create a TestCase inherited from SwaggerTestCase
 */
class MyTestCase extends \GoreSakuraba\OpenAPI\ApiTestCase
{
    public function setUp()
    {
        $schema = \GoreSakuraba\OpenAPI\Base\Schema::getInstance(file_get_contents('/path/to/json/definition'));
        $this->setSchema($schema);
    }
    
    /**
     * Test if the REST address /path/for/get/ID with the method GET returns what is
     * documented on the "swagger.json"
     */
    public function testGet()
    {
        $request = new \GoreSakuraba\OpenAPI\ApiRequester();
        $request->withMethod('GET')
                ->withPath("/path/for/get/1");

        $this->assertRequest($request);
    }

    /**
     * Test if the REST address /path/for/get/NOTFOUND returns a status code 404.
     */
    public function testGetNotFound()
    {
        $request = new \GoreSakuraba\OpenAPI\ApiRequester();
        $request->withMethod('GET')
                ->withPath("/path/for/get/NOTFOUND")
                ->assertResponseCode(404);

        $this->assertRequest($request);
    }

    /**
     * Test if the REST address /path/for/post/ID with the method POST  
     * and the request object ['name'=>'new name', 'field' => 'value'] will return an object
     * as is documented in the "swagger.json" file
     */
    public function testPost()
    {
        $request = new \GoreSakuraba\OpenAPI\ApiRequester();
        $request->withMethod('POST')
                ->withPath("/path/for/post/2")
                ->withRequestBody(['name' => 'new name', 'field' => 'value']);

        $this->assertRequest($request);
    }

    /**
     * Test if the REST address /another/path/for/post/{id} with the method POST  
     * and the request object ['name'=>'new name', 'field' => 'value'] will return an object
     * as is documented in the "swagger.json" file
     */
    public function testPost2()
    {
        $request = new \GoreSakuraba\OpenAPI\ApiRequester();
        $request->withMethod('POST')
                ->withPath("/path/for/post/3")
                ->withQuery(['id' => 10])
                ->withRequestBody(['name' => 'new name', 'field' => 'value']);

        $this->assertRequest($request);
    }

}

Functional Tests without a Webserver

Sometimes, you want to run functional tests without making the actual HTTP requests and without setting up a webserver for that. Instead, you forward the requests to the routing of your application kernel which lives in the same process as the functional tests. In order to do that, you need a bit of glue code based on the AbstractRequester baseclass:

class MyAppRequester extends \GoreSakuraba\OpenAPI\AbstractRequester
{
    private MyAppKernel $app;

    public function __construct(MyAppKernel $app)
    {
        parent::construct();
        $this->app = $app;
    }

    protected function handleRequest(RequestInterface $request)
    {
        return $this->app->handle($request);
    }
}

You now use an instance of this class in place of the ApiRequester class from the examples above. Of course, if you need to apply changes to the request, or the response in order to fit your framework, this is exactly the right place to do it.

@todo: Explain in the Docs sections the RestServer component

Using it as Unit Test cases

If you want mock the request API and just test the expected parameters, you are sending and receiving you have to:

1. Create the Swagger or OpenAPI Test Schema

$schema = \GoreSakuraba\OpenAPI\Base\Schema::getInstance($contentsOfSchemaJson);

2. Get the definitions for your path

$path = '/path/to/method';
$statusExpected = 200;
$method = 'POST';

// Returns a SwaggerRequestBody instance
$bodyRequestDef = $schema->getRequestParameters($path, $method);

// Returns a SwaggerResponseBody instance
$bodyResponseDef = $schema->getResponseParameters($path, $method, $statusExpected);

3. Match the result

if (!empty($requestBody)) {
    $bodyRequestDef->match($requestBody);
}
$bodyResponseDef->match($responseBody);

If the request or response body does not match with the definition an exception NotMatchException will be thrown.

Runtime parameters validator

This tool was not developed only for unit and functional tests. You can use to validate if the required body parameters is the expected.

So, before your API Code you can validate the request body using:

$schema = \GoreSakuraba\OpenAPI\Base\Schema::getInstance($contentsOfSchemaJson);
$bodyRequestDef = $schema->getRequestParameters($path, $method);
$bodyRequestDef->match($requestBody);

Validate your Specification

PHP Swagger has the class MockRequester with exact the same functionalities of ApiRequester class. The only difference is the MockRequester don't need to request to a real endpoint.

This is used to validate request and response against your OpenAPI spec without running any server code.

class MyTest extends ApiTestCase
{
    public function testExpectOK()
    {
        $expectedResponse = new \GuzzleHttp\Psr7\Response(
            200,
            [],
            \GuzzleHttp\Psr7\Utils::streamFor(json_encode([
                "id" => 1,
                "name" => "Spike",
                "photoUrls" => []
            ]))
        );

        // The MockRequester does not send the request to a real endpoint
        // Just returning the expected Response object sent in the constructor 
        $request = new \GoreSakuraba\OpenAPI\MockRequester($expectedResponse);
        $request->withMethod('GET')
                ->withPath("/pet/1");

        $this->assertRequest($request); // That should be "True" based on the specification
    }
}

Integration with PSR7

You can populate the ApiRequester/MockRequester with the information provided by the RequestInterface PSR7 interface.

e.g.

$psr7Request = new \GuzzleHttp\Psr7\Request(
    'get',
    '/method_to_be_tested?param1=value1',
    [],
    \GuzzleHttp\Psr7\Utils::streamFor('{"foo":"bar"}')
);

$request = new \GoreSakuraba\OpenAPI\ApiRequester();
$request->withPsr7Request($psr7Request);

// Return a ResponseInterface PSR7 component 
$response = $request->send();

Install

composer require "byjg/swagger-test=3.1.*"

Questions?

Please raise your issue on Github issue.

References

This project uses the byjg/webrequest component. It implements the PSR-7 specification, and a HttpClient / MockClient to do the requests. Check it out to get more information.


Open source ByJG

php-openapi-test's People

Contributors

byjg avatar ulricheckhardt avatar vitormattos avatar goresakuraba avatar odael avatar malinink avatar hordev avatar antonio-rylke-vgl avatar domingojimenez avatar artjomsimon avatar thepanz avatar steveplevno avatar gustavoporcides avatar 89409 avatar

Watchers

 avatar

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.