gertjuhh/symfony-openapi-validator

Symfony应用程序测试的OpenAPI验证器

0.2.6 2024-04-09 14:23 UTC

This package is auto-updated.

Last update: 2024-09-11 10:58:32 UTC


README

此包可以根据Symfony的WebTestCase,基于OpenAPI规范验证应用程序测试中发出的请求。这是通过使用PSR-7桥接器HttpFoundation对象转换为OpenAPI规范,并传递给OpenAPI PSR-7消息验证器来实现的。

安装

composer require --dev gertjuhh/symfony-openapi-validator

使用方法

  • OpenApiValidator特性添加到您的WebTestCase
  • 通过调用self::createClient()创建客户端
    • 或者使用您自己的自定义逻辑创建一个KernelBrowser实例
  • 使用客户端执行您想要验证的请求
  • 调用self::assertOpenApiSchema(<schema>, <client>);
    • schema:对应OpenAPI yaml架构的路径
    • client:用于发出请求的客户端
  • 或者可选地使用self::assertResponseAgainstOpenApiSchema(<schema>, <client>);仅验证响应
    • 此函数可以传递operationAddress作为第三个参数,但默认情况下将从client检索操作。

设置缓存

底层库可以使用PSR-6缓存。在运行多个测试针对单个架构时,这可以显著提高速度,因为它可以解析一次并重用。

为了激活此缓存,您可以将PSR-6缓存实例传递到静态属性\Gertjuhh\SymfonyOpenapiValidator\StaticOpenApiValidatorCache::$validatorCache。例如

<?php

use Gertjuhh\SymfonyOpenapiValidator\StaticOpenApiValidatorCache;
use Symfony\Component\Cache\Adapter\ArrayAdapter;

StaticOpenApiValidatorCache::$validatorCache = new ArrayAdapter(storeSerialized: false);

建议将storeSerialized设置为false在ArrayAdapter实例上,因为它通过存储实际对象来降低内存使用量;否则,Symfony将存储OpenAPI架构的序列化表示形式,并在每次测试运行时进行反序列化。

此片段可以嵌入到PHPUnit的bootstrap脚本中。

示例

<?php
declare(strict_types=1);

namespace App\ApplicationTests;

use Gertjuhh\SymfonyOpenapiValidator\OpenApiValidator;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

final class HelloWorldTest extends WebTestCase
{
    use OpenApiValidator;

    public function testHelloWorldReturnsSuccessfulResponse(): void
    {
        $client = self::createClient();

        $client->xmlHttpRequest('GET', '/hello-world');

        self::assertResponseIsSuccessful();
        self::assertOpenApiSchema('public/openapi.yaml', $client);
    }
}