tunezilla / openapi-test-validation
为Laravel测试提供简单的OpenAPI验证
v1.1.1
2022-08-02 23:57 UTC
Requires
- php: >=7.4
- league/openapi-psr7-validator: ^0.17.0
- nyholm/psr7: ^1.3
- symfony/psr-http-message-bridge: ^2.0
Requires (Dev)
- orchestra/testbench: ^6.17
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-08-30 01:14:47 UTC
README
此包允许您在Laravel测试中使用常规的$this->get()
、$this->json()
和$this->call()
函数来执行OpenAPI请求和响应验证。
此包目前没有Laravel版本限制。它已在Laravel 8上进行了测试。
安装
composer require --dev tunezilla/openapi-test-validation
注意事项
使用symfony/psr-http-message-bridge来消耗响应体,以便验证它是否符合OpenAPI模式。
如果您正在测试只发送一次内容的响应(如Symfony StreamedResponse),但在测试中尝试检索此内容:OpenAPI验证已经发生,内容已被读取,您将收到一个空体。
常规的非流式响应不受此问题的影响。
用法
- 将
MakesOpenAPIRequests
特质添加到您的TestCase
- 在发送请求之前,调用
$this->openAPI('./path/to/your/openapi.yaml')
(可链式调用)
单个模式
<?php namespace Tests\Feature; use TuneZilla\OpenAPITestValidation\MakesOpenAPIRequests; use Tests\TestCase; class ExampleTest extends TestCase { use MakesOpenAPIRequests; public function testShow() { $this->openAPI(resource_path('openapi.yaml')) ->json('GET', '/api/settings') ->assertSuccessful(); } }
一次设置
<?php namespace Tests\Feature; use TuneZilla\OpenAPITestValidation\MakesOpenAPIRequests; use Tests\TestCase; class ExampleTest extends TestCase { use MakesOpenAPIRequests; public function setUp() { parent::setUp(); // if all requests in this testcase use the same schema, you can configure it once in `setUp` // see https://phpunit.readthedocs.io/en/9.3/fixtures.html for information about `setUp` $this->openAPI(resource_path('openapi.yaml')); } public function testShow() { $this->json('GET', '/api/settings') ->assertSuccessful(); } }
多个模式
<?php namespace Tests\Feature; use TuneZilla\OpenAPITestValidation\MakesOpenAPIRequests; use Tests\TestCase; class ExampleTest extends TestCase { use MakesOpenAPIRequests; public function testShow() { // if your requests use different schemas, you can configure them as needed // this one uses settings/openapi.yaml $this->openAPI(resource_path('settings/openapi.yaml')) ->json('GET', '/api/settings') ->assertSuccessful(); // this one uses other/openapi.yaml $this->openAPI(resource_path('other/openapi.yaml')) ->json('GET', '/api/other') ->assertSuccessful(); } }
发送无效请求
<?php namespace Tests\Feature; use TuneZilla\OpenAPITestValidation\MakesOpenAPIRequests; use Tests\TestCase; class ExampleTest extends TestCase { use MakesOpenAPIRequests; public function testInvalidRequest() { // you can use `ignoreNextOpenAPIRequest` to allow invalid requests to pass through to your backend. // this is useful if you're making sure 422 validation errors are thrown: $this->openAPI(resource_path('openapi.yaml')) ->ignoreNextOpenAPIRequest() ->json('GET', '/api/settings?invalid-param=12345') ->assertJsonValidationError(['invalid-param']); } }