first version
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\UserModel;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Modules\SystemUser\Models\SysUserModel;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 订货采购系统功能测试基类
|
||||
*
|
||||
* - SQLite :memory: + RefreshDatabase,每个测试方法独立迁移
|
||||
* - 双端认证辅助:createToken 签发 Sanctum token,withToken 注入 Authorization 头,
|
||||
* 走真实链路(auth:sanctum → AuthGuardMiddleware 双端隔离 → abilities 校验)
|
||||
*/
|
||||
abstract class ProcurementTestCase extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private static int $userSeq = 0;
|
||||
|
||||
/**
|
||||
* 创建后台系统用户并以该用户身份发起后续请求
|
||||
*
|
||||
* @param array<int, string> $abilities 权限点列表,['*'] 为全部权限
|
||||
*/
|
||||
protected function actingAsSysUser(array $abilities = ['*'], array $attributes = []): SysUserModel
|
||||
{
|
||||
// 清除 guard 缓存:Sanctum RequestGuard 会在 app 单例上缓存已认证用户,
|
||||
// 同一测试内切换身份时必须重置,否则后续请求仍用旧用户做 abilities 校验
|
||||
$this->app['auth']->forgetGuards();
|
||||
|
||||
$seq = ++self::$userSeq;
|
||||
$user = SysUserModel::create(array_merge([
|
||||
// id 避开 1:SysAccessToken::can() 对 tokenable_id==1(超管)直接放行全部权限,
|
||||
// 测试用户从 101 起编号,保证 abilities 校验真实生效
|
||||
'id' => 100 + $seq,
|
||||
'username' => 'tester' . str_pad((string) $seq, 4, '0', STR_PAD_LEFT) . random_int(10, 99),
|
||||
'password' => bcrypt('password'),
|
||||
'nickname' => '测试员' . $seq,
|
||||
'email' => 'tester' . $seq . '_' . random_int(100, 999) . '@example.com',
|
||||
'mobile' => '',
|
||||
'dept_id' => 0,
|
||||
'sex' => 0,
|
||||
'status' => 1,
|
||||
], $attributes));
|
||||
|
||||
$this->withToken($user->createToken('testing', $abilities)->plainTextToken);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* 以小程序用户身份发起后续请求(token abilities 默认 ['mini'])
|
||||
*
|
||||
* @param array<int, string> $abilities
|
||||
*/
|
||||
protected function actingAsMiniUser(UserModel $user, array $abilities = ['mini']): UserModel
|
||||
{
|
||||
$this->app['auth']->forgetGuards();
|
||||
|
||||
$this->withToken($user->createToken('mini', $abilities)->plainTextToken);
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user