wubbleyou/boundaries

自动生成测试,用于验证路由中间件和政策边界

v1.0.2 2024-04-24 13:26 UTC

This package is auto-updated.

Last update: 2024-09-24 14:24:12 UTC


README

Boundaries 是一个 DX 工具,用于生成单元测试,以自动测试您的路由是否与开发者确定的规则相匹配。

Boundaries 随带两个规则,即 MiddlewareRulePolicyRule

安装

通过 Composer 正常安装此包

composer require wubbleyou/boundaries

用法

要开始,您需要运行以下命令以生成基本测试文件

php/sail artisan wubbleyou:generate-test

配置

现在您已经生成了测试并保存到 tests\Feature\Boundaries\BoundaryTest.php,您可能会注意到一个 trait 被放置在 app\Traits\BoundaryRouteTrait.php 中,它包含两个方法,请阅读下面的附加信息以了解为什么需要提供这些。

getWhitelist()

getWhitelist() 方法允许您返回一个数组,其中包含所有希望 Wubbleyou\Boundaries 忽略的路由。

return [
    'login',
    'register',
    'homepage',
    'about',
];

getRoutes()

getRoutes() 方法允许您返回一个数组,以指定应在每个路由上运行的精确断言,以下是一个示例

$admin = User::factory()->create(['is_admin', true]);
$userOne = User::factory()->create();
$userTwo = User::factory()->create();

return [
    'users.change-password' => [
        new MiddlewareRule(['web', 'auth', 'incorrect']),
        new PolicyRule('get', 403, $userOne, ['user' => $userTwo]),
    ]
];

MiddlewareRule

中间件规则测试您的路由是否与一组特定的中间件匹配,如果它不匹配这些中间件中的所有中间件,则测试将失败。

MiddlewareRule 还有一个可选的第二个参数 $strict(默认:false)。如果启用 strict,则提供的预期中间件数组必须与路由上存在的中间件完全匹配。如果未启用 strict,则路由上存在的中间件必须包含所有预期的中间件,但也可以包含我们未测试的其他中间件。

new MiddlewareRule(['web', 'auth'], true),

PolicyRule

策略规则针对特定路由执行测试以测试 HTTP 状态代码。您向它提供

  • 请求类型(get/post等)
  • 预期的 HTTP 状态代码响应(200、404、403等)
  • 要测试的路由的用户(这可以设置为 NULL 以测试未认证的用户)(默认:null)
  • 路由期望的参数(可选)(默认:[])

然后它将测试该路由,如果响应代码与您提供的代码不匹配,则返回错误。

自定义 BoundaryRules

您还可以使用以下命令生成自定义 BoundaryRules

php/sail artisan wubbleyou:generate-rule RuleName

一个示例 BoundaryRule 可能如下所示

<?php

namespace App\BoundaryRules;

use Wubbleyou\Boundaries\BoundaryRules\BoundaryRule;
use Illuminate\Routing\Route;
use Tests\TestCase;

class TestingRule extends BoundaryRule {
    public function handle(Route $route, TestCase $test, string $routeName): array
    {
        return ['This test failed because this array is not empty'];
    }
}

Closures

您还可以提供 Closure 作为 BoundaryRule

function(Route $route) {
    if($route->getName() !== 'hello') {
        return ['Route name is not hello'];
    }

    return [];
},

附加信息

如果每个路由都没有在 getWhitelist()getRoutes() 中进行记录,Boundaries 测试将失败,如果您想生成不在其中之一的路由列表,请运行以下命令

php/sail artisan wubbleyou:missing-routes

请注意,此命令需要您已生成 BoundaryRouteTrait 才能正常工作,如果您只需生成 trait 而不包含任何测试,可以运行

php/sail artisan wubbleyou:generate-route-trait