All Downloads are FREE. Search and download functionalities are using the official Maven repository.

php-slim4-server.openapi_data_mocker_middleware_test.mustache Maven / Gradle / Ivy

assertInstanceOf(OpenApiDataMockerMiddleware::class, $middleware);
        $this->assertNotNull($middleware);
    }

    public function provideConstructCorrectArguments()
    {
        $getMockResponseCallback = function () {
            return false;
        };
        $afterCallback = function () {
            return false;
        };
        return [
            [new OpenApiDataMocker(), [], null, null],
            [new OpenApiDataMocker(), [], $getMockResponseCallback, $afterCallback],
        ];
    }

    /**
     * @covers ::__construct
     * @dataProvider provideConstructInvalidArguments
     * @expectedException \InvalidArgumentException
     * @expectedException \TypeError
     */
    public function testConstructorWithInvalidArguments(
        $mocker,
        $responses,
        $getMockResponseCallback,
        $afterCallback
    ) {
        $middleware = new OpenApiDataMockerMiddleware($mocker, $responses, $getMockResponseCallback, $afterCallback);
    }

    public function provideConstructInvalidArguments()
    {
        return [
            'getMockResponseCallback not callable' => [
                new OpenApiDataMocker(), [], 'foobar', null,
            ],
            'afterCallback not callable' => [
                new OpenApiDataMocker(), [], null, 'foobar',
            ],
        ];
    }

    /**
     * @covers ::process
     * @dataProvider provideProcessArguments
     */
    public function testProcess(
        $mocker,
        $responses,
        $getMockResponseCallback,
        $afterCallback,
        $request,
        $expectedStatusCode,
        $expectedHeaders,
        $notExpectedHeaders,
        $expectedBody
    ) {

        // Create a stub for the RequestHandlerInterface interface.
        $handler = $this->createMock(RequestHandlerInterface::class);
        $handler->method('handle')
             ->willReturn(AppFactory::determineResponseFactory()->createResponse());

        $middleware = new OpenApiDataMockerMiddleware(
            $mocker,
            $responses,
            $getMockResponseCallback,
            $afterCallback
        );
        $response = $middleware->process($request, $handler);

        // check status code
        $this->assertSame($expectedStatusCode, $response->getStatusCode());

        // check http headers in request
        foreach ($expectedHeaders as $expectedHeader => $expectedHeaderValue) {
            $this->assertTrue($response->hasHeader($expectedHeader));
            if ($expectedHeaderValue !== '*') {
                $this->assertSame($expectedHeaderValue, $response->getHeader($expectedHeader)[0]);
            }
        }
        foreach ($notExpectedHeaders as $notExpectedHeader) {
            $this->assertFalse($response->hasHeader($notExpectedHeader));
        }

        // check body
        if (is_array($expectedBody)) {
            // random values, check keys only
            foreach ($expectedBody as $attribute => $value) {
                $this->assertObjectHasAttribute($attribute, json_decode((string) $response->getBody(), false));
            }
        } else {
            $this->assertEquals($expectedBody, (string) $response->getBody());
        }
    }

    public function provideProcessArguments()
    {
        $mocker = new OpenApiDataMocker();
        $isMockResponseRequired = function (ServerRequestInterface $request) {
            $mockHttpHeader = 'X-{{invokerPackage}}-Mock';
            return $request->hasHeader($mockHttpHeader)
                && $request->getHeader($mockHttpHeader)[0] === 'ping';
        };

        $getMockResponseCallback = function (ServerRequestInterface $request, array $responses) use ($isMockResponseRequired) {
            if ($isMockResponseRequired($request)) {
                if (array_key_exists('default', $responses)) {
                    return $responses['default'];
                }

                // return first response
                return $responses[array_key_first($responses)];
            }

            return false;
        };

        $afterCallback = function ($request, $response) use ($isMockResponseRequired) {
            if ($isMockResponseRequired($request)) {
                $response = $response->withHeader('X-{{invokerPackage}}-Mock', 'pong');
            }

            return $response;
        };

        $responses = [
            '400' => [
                'code' => 400,
                'jsonSchema' => json_encode([
                    'description' => 'Bad Request Response',
                    'content' => new StdClass(),
                ]),
            ],
            'default' => [
                'code' => 201,
                'jsonSchema' => json_encode([
                    'description' => 'Success Response',
                    'headers' => [
                        'X-Location' => ['schema' => ['type' => 'string']],
                        'X-Created-Id' => ['schema' => ['type' => 'integer']],
                    ],
                    'content' => [
                        'application/json;encoding=utf-8' => ['schema' => ['type' => 'object', 'properties' => ['id' => ['type' => 'integer'], 'className' => ['type' => 'string'], 'declawed' => ['type' => 'boolean']]]],
                    ],
                ]),
            ],
        ];

        $responsesXmlOnly = [
            'default' => [
                'code' => 201,
                'jsonSchema' => json_encode([
                    'description' => 'Success Response',
                    'content' => [
                        'application/xml' => [
                            'schema' => [
                                'type' => 'string',
                            ],
                        ],
                    ],
                ]),
            ],
        ];

        $requestFactory = ServerRequestCreatorFactory::create();

        return [
            'callbacks null' => [
                $mocker,
                $responses,
                null,
                null,
                $requestFactory->createServerRequestFromGlobals(),
                200,
                [],
                ['X-{{invokerPackage}}-Mock', 'x-location', 'x-created-id'],
                '',
            ],
            'xml not supported' => [
                $mocker,
                $responsesXmlOnly,
                $getMockResponseCallback,
                $afterCallback,
                $requestFactory
                    ->createServerRequestFromGlobals()
                    ->withHeader('X-{{invokerPackage}}-Mock', 'ping'),
                201,
                ['X-{{invokerPackage}}-Mock' => 'pong', 'content-type' => '*/*'],
                ['x-location', 'x-created-id'],
                'Mock feature supports only "application/json" content-type!',
            ],
            'mock response default schema' => [
                $mocker,
                $responses,
                $getMockResponseCallback,
                $afterCallback,
                $requestFactory
                    ->createServerRequestFromGlobals()
                    ->withHeader('X-{{invokerPackage}}-Mock', 'ping'),
                201,
                ['X-{{invokerPackage}}-Mock' => 'pong', 'content-type' => 'application/json', 'x-location' => '*', 'x-created-id' => '*'],
                [],
                [
                    'id' => 1,
                    'className' => 'cat',
                    'declawed' => false,
                ],
            ],
        ];
    }
}
{{/apiInfo}}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy