rouxtaccess/laravel-openapi-test

1.4.0 2024-07-01 07:59 UTC

This package is auto-updated.

Last update: 2024-10-01 00:06:45 UTC


README

底层逻辑使用来自 byjgPHP Swagger Test,用于与 L5-Swagger 一起使用。这是基于 pionlLaravel Swagger Test 开发的。

使用 Laravel 的底层请求测试来测试您的 API 架构。

支持

有关断言如何针对您的文档进行工作的信息,请查看 PHP Swagger Test

目前,此工具仅支持 JSON API,覆盖任何所需功能应该非常简单。

安装

  1. 需要此包

    composer require --dev rouxtaccess/laravel-openapi-test
    

用法

使用 Laravel 的 TestCase 并添加 ImplementsOpenApiFunctions 特性。

$this->setUpOpenApiTester(); 添加到测试的 setUp 函数中

使用与 ApiRequester 相同的 "请求构建"。有关更多详细信息,请参阅 PHP Swagger Test

对于验证和测试,有 validateRequest()validateRequestFails()sendRequest()validateResponse(Response::HTTP_OK); 等方法。

要在 OpenApi 所需规范之上断言响应数据,可以使用 assertResponseHas() 辅助方法。下面是示例。

<?php

namespace Tests\Feature\Api;

use App\User;
use RouxtAccess\OpenApi\Testing\Laravel\Traits\ImplementsOpenApiFunctions;
use Symfony\Component\HttpFoundation\Response;
use Tests\TestCase;

class AuthLoginTest extends TestCase
{
   use ImplementsOpenApiFunctions;
   
   protected function setUp(): void
   {
       parent::setUp();
       $this->setUpOpenApiTester();
   }

   public function testLoginWithoutDetails()
   {
       $this->requester->withMethod('POST')
           ->withPath('/api/auth/login');

       $this->validateRequestFails()
           ->sendRequest()
           ->validateResponse(Response::HTTP_UNPROCESSABLE_ENTITY);

       $this->assertResponseHas('errors.email');
       $this->assertResponseHas('errors.password');
   }

   public function testLoginIncorrectDetails()
   {
       $this->requester->withMethod('POST')
           ->withPath('/api/auth/login')
           ->withRequestBody(['email' => 'not_a_real_users_email@notreal.com', 'password' => 'not_a_valid_password']);

       $this->validateRequestFails()
           ->sendRequest()
           ->validateResponse(Response::HTTP_UNAUTHORIZED);
   }

   public function testLoginSuccess()
   {
       $user = factory(User::class)->create(['name' => 'test-user', 'email' => 'testemail@example.com', 'password' => bcrypt('bestpassword')]);

       $this->requester->withMethod('POST')
           ->withPath('/api/auth/login')
           ->withRequestBody(['email' => $user->email, 'password' => 'bestpassword']);

       $this->validateRequest()
           ->sendRequest()
           ->validateResponse(Response::HTTP_OK);
   }
}