初始提交:卡密授权管理系统
This commit is contained in:
commit
59586775c4
202 files changed
+25427
No files matched your search
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
namespace Tests\Benchmark;
|
||||
|
||||
use App\Services\JwtService;
|
||||
|
||||
/**
|
||||
* 黑名单接口压力测试脚本
|
||||
* 并发请求 /api/auth/me,验证黑名单拦截性能与稳定性
|
||||
*/
|
||||
class BlacklistBenchmark
|
||||
{
|
||||
private string $baseUrl;
|
||||
private string $token;
|
||||
private int $concurrency;
|
||||
private int $total;
|
||||
|
||||
public function __construct(string $baseUrl, int $concurrency = 20, int $total = 200)
|
||||
{
|
||||
$this->baseUrl = $baseUrl;
|
||||
$this->concurrency = $concurrency;
|
||||
$this->total = $total;
|
||||
|
||||
$jwtService = new JwtService();
|
||||
$this->token = $jwtService->generateToken([
|
||||
'id' => 8888,
|
||||
'username' => 'bench_user',
|
||||
'role' => 'admin',
|
||||
])['access_token'];
|
||||
}
|
||||
|
||||
public function run(): array
|
||||
{
|
||||
$completed = 0;
|
||||
$success = 0;
|
||||
$errors = 0;
|
||||
$start = microtime(true);
|
||||
|
||||
$mh = curl_multi_init();
|
||||
$active = [];
|
||||
|
||||
// 初始化一批请求
|
||||
for ($i = 0; $i < $this->concurrency && $i < $this->total; $i++) {
|
||||
$ch = $this->createHandle();
|
||||
$active[] = $ch;
|
||||
curl_multi_add_handle($mh, $ch);
|
||||
}
|
||||
|
||||
$sent = count($active);
|
||||
$running = null;
|
||||
|
||||
do {
|
||||
curl_multi_exec($mh, $running);
|
||||
curl_multi_select($mh, 0.1);
|
||||
|
||||
while ($info = curl_multi_info_read($mh)) {
|
||||
$completed++;
|
||||
$handle = $info['handle'];
|
||||
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
|
||||
|
||||
if ($httpCode >= 200 && $httpCode < 500) {
|
||||
$success++;
|
||||
} else {
|
||||
$errors++;
|
||||
}
|
||||
|
||||
curl_multi_remove_handle($mh, $handle);
|
||||
|
||||
if ($sent < $this->total) {
|
||||
$newHandle = $this->createHandle();
|
||||
$sent++;
|
||||
curl_multi_add_handle($mh, $newHandle);
|
||||
}
|
||||
}
|
||||
} while ($running > 0);
|
||||
|
||||
curl_multi_close($mh);
|
||||
$duration = microtime(true) - $start;
|
||||
|
||||
return [
|
||||
'total' => $completed,
|
||||
'success' => $success,
|
||||
'errors' => $errors,
|
||||
'duration' => round($duration, 4),
|
||||
'rps' => $duration > 0 ? round($completed / $duration, 2) : 0,
|
||||
];
|
||||
}
|
||||
|
||||
private function createHandle()
|
||||
{
|
||||
$ch = curl_init();
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_URL => $this->baseUrl . '/api/auth/me',
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 5,
|
||||
CURLOPT_HTTPHEADER => [
|
||||
'Authorization: Bearer ' . $this->token,
|
||||
],
|
||||
]);
|
||||
return $ch;
|
||||
}
|
||||
}
|
||||
|
||||
// 命令行入口
|
||||
if (PHP_SAPI === 'cli' && basename($argv[0]) === basename(__FILE__)) {
|
||||
define('BASE_PATH', dirname(dirname(__DIR__)));
|
||||
define('APP_PATH', BASE_PATH . '/app');
|
||||
define('CONFIG_PATH', BASE_PATH . '/config');
|
||||
define('ROUTES_PATH', BASE_PATH . '/routes');
|
||||
define('STORAGE_PATH', BASE_PATH . '/storage');
|
||||
|
||||
require BASE_PATH . '/vendor/autoload.php';
|
||||
require APP_PATH . '/Helpers/functions.php';
|
||||
|
||||
if (file_exists(BASE_PATH . '/.env')) {
|
||||
$lines = file(BASE_PATH . '/.env', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
||||
foreach ($lines as $line) {
|
||||
if (strpos(trim($line), '#') === 0) continue;
|
||||
if (strpos($line, '=') !== false) {
|
||||
list($key, $value) = explode('=', $line, 2);
|
||||
putenv(trim($key) . '=' . trim($value, " \t\n\r\0\x0B\"'"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$baseUrl = $argv[1] ?? 'http://127.0.0.1:8080';
|
||||
$concurrency = (int)($argv[2] ?? 20);
|
||||
$total = (int)($argv[3] ?? 200);
|
||||
|
||||
$bench = new BlacklistBenchmark($baseUrl, $concurrency, $total);
|
||||
$result = $bench->run();
|
||||
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . PHP_EOL;
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
namespace Tests\Integration;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use App\Services\JwtService;
|
||||
|
||||
/**
|
||||
* 管理员个人信息接口集成测试
|
||||
*/
|
||||
class AuthProfileApiTest extends TestCase
|
||||
{
|
||||
private static string $baseUrl;
|
||||
private static $serverProcess;
|
||||
private static string $token;
|
||||
|
||||
public static function setUpBeforeClass(): void
|
||||
{
|
||||
self::$baseUrl = 'http://127.0.0.1:8091';
|
||||
$cmd = 'php -S 127.0.0.1:8091 -t ' . BASE_PATH . '/public';
|
||||
self::$serverProcess = proc_open($cmd, [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes);
|
||||
sleep(1);
|
||||
|
||||
// 直接生成管理员 JWT
|
||||
$jwtService = new JwtService();
|
||||
self::$token = $jwtService->generateToken([
|
||||
'id' => 1,
|
||||
'username' => 'admin',
|
||||
'role' => 'admin',
|
||||
])['access_token'];
|
||||
}
|
||||
|
||||
public static function tearDownAfterClass(): void
|
||||
{
|
||||
if (self::$serverProcess) {
|
||||
proc_terminate(self::$serverProcess);
|
||||
proc_close(self::$serverProcess);
|
||||
}
|
||||
}
|
||||
|
||||
private static function request(string $method, string $path, array $body = [], array $headers = []): array
|
||||
{
|
||||
$url = self::$baseUrl . $path;
|
||||
$ch = curl_init();
|
||||
$opts = [
|
||||
CURLOPT_URL => $url,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 10,
|
||||
CURLOPT_CUSTOMREQUEST => $method,
|
||||
];
|
||||
if (!empty($headers)) {
|
||||
$opts[CURLOPT_HTTPHEADER] = $headers;
|
||||
}
|
||||
if (!empty($body)) {
|
||||
$opts[CURLOPT_POSTFIELDS] = json_encode($body, JSON_UNESCAPED_UNICODE);
|
||||
}
|
||||
curl_setopt_array($ch, $opts);
|
||||
$response = curl_exec($ch);
|
||||
curl_close($ch);
|
||||
return json_decode($response, true) ?? [];
|
||||
}
|
||||
|
||||
public function testGetCurrentUserProfile(): void
|
||||
{
|
||||
$resp = self::request('GET', '/api/auth/me', [], [
|
||||
'Authorization: Bearer ' . self::$token,
|
||||
]);
|
||||
|
||||
$this->assertSame(200, $resp['code']);
|
||||
$this->assertSame('admin', $resp['data']['username']);
|
||||
$this->assertArrayHasKey('nickname', $resp['data']);
|
||||
}
|
||||
|
||||
public function testUpdateProfile(): void
|
||||
{
|
||||
$uniqueNickname = 'Admin_' . time();
|
||||
$resp = self::request('PUT', '/api/auth/profile', [
|
||||
'nickname' => $uniqueNickname,
|
||||
'email' => 'admin_' . time() . '@example.com',
|
||||
'phone' => '1380000' . mt_rand(1000, 9999),
|
||||
], [
|
||||
'Authorization: Bearer ' . self::$token,
|
||||
'Content-Type: application/json',
|
||||
]);
|
||||
|
||||
$this->assertSame(200, $resp['code']);
|
||||
|
||||
$me = self::request('GET', '/api/auth/me', [], [
|
||||
'Authorization: Bearer ' . self::$token,
|
||||
]);
|
||||
$this->assertSame($uniqueNickname, $me['data']['nickname']);
|
||||
|
||||
// 恢复昵称
|
||||
self::request('PUT', '/api/auth/profile', [
|
||||
'nickname' => '超级管理员',
|
||||
'email' => '',
|
||||
'phone' => '',
|
||||
], [
|
||||
'Authorization: Bearer ' . self::$token,
|
||||
'Content-Type: application/json',
|
||||
]);
|
||||
}
|
||||
|
||||
public function testUpdateProfileWithInvalidEmail(): void
|
||||
{
|
||||
$resp = self::request('PUT', '/api/auth/profile', [
|
||||
'email' => 'invalid-email',
|
||||
], [
|
||||
'Authorization: Bearer ' . self::$token,
|
||||
'Content-Type: application/json',
|
||||
]);
|
||||
|
||||
$this->assertSame(400, $resp['code']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
<?php
|
||||
namespace Tests\Integration;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use App\Services\JwtService;
|
||||
|
||||
/**
|
||||
* 黑名单接口集成测试
|
||||
*/
|
||||
class BlacklistApiTest extends TestCase
|
||||
{
|
||||
private static string $baseUrl;
|
||||
private static $serverProcess;
|
||||
private static string $token;
|
||||
|
||||
public static function setUpBeforeClass(): void
|
||||
{
|
||||
self::$baseUrl = 'http://127.0.0.1:8092';
|
||||
$cmd = 'php -S 127.0.0.1:8092 -t ' . BASE_PATH . '/public';
|
||||
self::$serverProcess = proc_open($cmd, [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes);
|
||||
sleep(1);
|
||||
|
||||
$jwtService = new JwtService();
|
||||
self::$token = $jwtService->generateToken([
|
||||
'id' => 1,
|
||||
'username' => 'admin',
|
||||
'role' => 'admin',
|
||||
])['access_token'];
|
||||
}
|
||||
|
||||
public static function tearDownAfterClass(): void
|
||||
{
|
||||
if (self::$serverProcess) {
|
||||
proc_terminate(self::$serverProcess);
|
||||
proc_close(self::$serverProcess);
|
||||
}
|
||||
}
|
||||
|
||||
private static function request(string $method, string $path, array $body = [], array $headers = []): array
|
||||
{
|
||||
$url = self::$baseUrl . $path;
|
||||
$ch = curl_init();
|
||||
$opts = [
|
||||
CURLOPT_URL => $url,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 10,
|
||||
CURLOPT_CUSTOMREQUEST => $method,
|
||||
];
|
||||
if (!empty($headers)) {
|
||||
$opts[CURLOPT_HTTPHEADER] = $headers;
|
||||
}
|
||||
if (!empty($body)) {
|
||||
$opts[CURLOPT_POSTFIELDS] = json_encode($body, JSON_UNESCAPED_UNICODE);
|
||||
}
|
||||
curl_setopt_array($ch, $opts);
|
||||
$response = curl_exec($ch);
|
||||
curl_close($ch);
|
||||
return json_decode($response, true) ?? [];
|
||||
}
|
||||
|
||||
public function testCreateAndListBlacklist(): void
|
||||
{
|
||||
$uniqueIp = '10.0.0.' . mt_rand(2, 254);
|
||||
$createResp = self::request('POST', '/api/blacklists', [
|
||||
'target_type' => 'ip',
|
||||
'target_value' => $uniqueIp,
|
||||
'remark' => 'integration test',
|
||||
], [
|
||||
'Authorization: Bearer ' . self::$token,
|
||||
'Content-Type: application/json',
|
||||
]);
|
||||
$this->assertSame(200, $createResp['code']);
|
||||
|
||||
$listResp = self::request('GET', '/api/blacklists?target_type=ip&keyword=' . $uniqueIp, [], [
|
||||
'Authorization: Bearer ' . self::$token,
|
||||
]);
|
||||
$this->assertSame(200, $listResp['code']);
|
||||
$this->assertGreaterThan(0, $listResp['data']['total']);
|
||||
$this->assertSame($uniqueIp, $listResp['data']['list'][0]['target_value']);
|
||||
}
|
||||
|
||||
public function testUpdateBlacklistStatus(): void
|
||||
{
|
||||
$createResp = self::request('POST', '/api/blacklists', [
|
||||
'target_type' => 'user',
|
||||
'target_value' => (string)mt_rand(100000, 999999),
|
||||
], [
|
||||
'Authorization: Bearer ' . self::$token,
|
||||
'Content-Type: application/json',
|
||||
]);
|
||||
$this->assertSame(200, $createResp['code']);
|
||||
|
||||
$listResp = self::request('GET', '/api/blacklists?target_type=user', [], [
|
||||
'Authorization: Bearer ' . self::$token,
|
||||
]);
|
||||
$id = $listResp['data']['list'][0]['id'];
|
||||
|
||||
$updateResp = self::request('PUT', '/api/blacklists/' . $id, [
|
||||
'status' => 0,
|
||||
], [
|
||||
'Authorization: Bearer ' . self::$token,
|
||||
'Content-Type: application/json',
|
||||
]);
|
||||
$this->assertSame(200, $updateResp['code']);
|
||||
}
|
||||
|
||||
public function testNonAdminCannotAccessBlacklist(): void
|
||||
{
|
||||
$jwtService = new JwtService();
|
||||
$token = $jwtService->generateToken([
|
||||
'id' => 2,
|
||||
'username' => 'agent',
|
||||
'role' => 'agent',
|
||||
])['access_token'];
|
||||
|
||||
$resp = self::request('GET', '/api/blacklists', [], [
|
||||
'Authorization: Bearer ' . $token,
|
||||
]);
|
||||
$this->assertSame(403, $resp['code']);
|
||||
}
|
||||
|
||||
public function testBlockedUserCannotAccessApi(): void
|
||||
{
|
||||
// 将用户 9999 加入黑名单
|
||||
self::request('POST', '/api/blacklists', [
|
||||
'target_type' => 'user',
|
||||
'target_value' => '9999',
|
||||
], [
|
||||
'Authorization: Bearer ' . self::$token,
|
||||
'Content-Type: application/json',
|
||||
]);
|
||||
|
||||
$jwtService = new JwtService();
|
||||
$token = $jwtService->generateToken([
|
||||
'id' => 9999,
|
||||
'username' => 'blocked_user',
|
||||
'role' => 'admin',
|
||||
])['access_token'];
|
||||
|
||||
$resp = self::request('GET', '/api/auth/me', [], [
|
||||
'Authorization: Bearer ' . $token,
|
||||
]);
|
||||
$this->assertSame(403, $resp['code']);
|
||||
$this->assertStringContainsString('黑名单', $resp['message']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
<?php
|
||||
namespace Tests\Integration;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use App\Services\JwtService;
|
||||
|
||||
/**
|
||||
* 系统设置接口集成测试
|
||||
*/
|
||||
class SystemApiTest extends TestCase
|
||||
{
|
||||
private static string $baseUrl;
|
||||
private static $serverProcess;
|
||||
private static string $token;
|
||||
|
||||
public static function setUpBeforeClass(): void
|
||||
{
|
||||
// 启动独立测试服务器
|
||||
self::$baseUrl = 'http://127.0.0.1:8090';
|
||||
$cmd = 'php -S 127.0.0.1:8090 -t ' . BASE_PATH . '/public';
|
||||
self::$serverProcess = proc_open($cmd, [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes);
|
||||
// 等待服务器就绪
|
||||
sleep(1);
|
||||
|
||||
// 直接生成管理员 JWT,避免依赖登录密码
|
||||
$jwtService = new JwtService();
|
||||
self::$token = $jwtService->generateToken([
|
||||
'id' => 1,
|
||||
'username' => 'admin',
|
||||
'role' => 'admin',
|
||||
])['access_token'];
|
||||
}
|
||||
|
||||
public static function tearDownAfterClass(): void
|
||||
{
|
||||
if (self::$serverProcess) {
|
||||
proc_terminate(self::$serverProcess);
|
||||
proc_close(self::$serverProcess);
|
||||
}
|
||||
}
|
||||
|
||||
private static function request(string $method, string $path, array $body = [], array $headers = []): array
|
||||
{
|
||||
$url = self::$baseUrl . $path;
|
||||
$ch = curl_init();
|
||||
$opts = [
|
||||
CURLOPT_URL => $url,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 10,
|
||||
CURLOPT_CUSTOMREQUEST => $method,
|
||||
];
|
||||
if (!empty($headers)) {
|
||||
$opts[CURLOPT_HTTPHEADER] = $headers;
|
||||
}
|
||||
if (!empty($body)) {
|
||||
$opts[CURLOPT_POSTFIELDS] = json_encode($body, JSON_UNESCAPED_UNICODE);
|
||||
}
|
||||
curl_setopt_array($ch, $opts);
|
||||
$response = curl_exec($ch);
|
||||
curl_close($ch);
|
||||
return json_decode($response, true) ?? [];
|
||||
}
|
||||
|
||||
public function testGetSystemConfigs(): void
|
||||
{
|
||||
$resp = self::request('GET', '/api/system/configs?keys=site_name,card_key_prefix', [], [
|
||||
'Authorization: Bearer ' . self::$token,
|
||||
]);
|
||||
|
||||
$this->assertSame(200, $resp['code']);
|
||||
$this->assertArrayHasKey('data', $resp);
|
||||
$this->assertArrayHasKey('site_name', $resp['data']);
|
||||
}
|
||||
|
||||
public function testSaveAndGetSiteName(): void
|
||||
{
|
||||
$uniqueName = 'TestSite_' . time();
|
||||
$saveResp = self::request('POST', '/api/system/configs', [
|
||||
'configs' => [
|
||||
'site_name' => $uniqueName,
|
||||
],
|
||||
], [
|
||||
'Authorization: Bearer ' . self::$token,
|
||||
'Content-Type: application/json',
|
||||
]);
|
||||
$this->assertSame(200, $saveResp['code']);
|
||||
|
||||
$getResp = self::request('GET', '/api/system/configs?keys=site_name', [], [
|
||||
'Authorization: Bearer ' . self::$token,
|
||||
]);
|
||||
$this->assertSame(200, $getResp['code']);
|
||||
$this->assertSame($uniqueName, $getResp['data']['site_name']);
|
||||
|
||||
// 恢复默认站点名称
|
||||
self::request('POST', '/api/system/configs', [
|
||||
'configs' => ['site_name' => 'CardAuth授权管理系统'],
|
||||
], [
|
||||
'Authorization: Bearer ' . self::$token,
|
||||
'Content-Type: application/json',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
namespace Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use App\Services\BlacklistService;
|
||||
use App\Core\Database;
|
||||
|
||||
/**
|
||||
* 黑名单服务单元测试
|
||||
*/
|
||||
class BlacklistServiceTest extends TestCase
|
||||
{
|
||||
private BlacklistService $service;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->service = new BlacklistService();
|
||||
$this->service->clearCache();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->service->clearCache();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function testIsBlockedWithUserId(): void
|
||||
{
|
||||
$this->service->refreshCache();
|
||||
// 默认数据库为空,应未被拉黑
|
||||
$this->assertFalse($this->service->isBlocked(1, null));
|
||||
}
|
||||
|
||||
public function testIsBlockedWithIp(): void
|
||||
{
|
||||
$this->service->refreshCache();
|
||||
$this->assertFalse($this->service->isBlocked(null, '127.0.0.1'));
|
||||
$this->assertFalse($this->service->isBlocked(null, null));
|
||||
}
|
||||
|
||||
public function testCacheRefreshAndClear(): void
|
||||
{
|
||||
$list = $this->service->refreshCache();
|
||||
$this->assertIsArray($list);
|
||||
|
||||
$activeList = $this->service->getActiveList();
|
||||
$this->assertSame($list, $activeList);
|
||||
|
||||
$this->service->clearCache();
|
||||
$this->assertFalse(file_exists(STORAGE_PATH . '/cache/blacklist.json'));
|
||||
}
|
||||
|
||||
public function testIsBlockedWithExpiredItem(): void
|
||||
{
|
||||
// 构造一个包含过期记录的缓存文件
|
||||
$cache = [
|
||||
[
|
||||
'target_type' => 'ip',
|
||||
'target_value' => '192.168.1.100',
|
||||
'status' => 1,
|
||||
'expire_time' => date('Y-m-d H:i:s', time() - 3600),
|
||||
],
|
||||
];
|
||||
$file = STORAGE_PATH . '/cache/blacklist.json';
|
||||
$dir = dirname($file);
|
||||
if (!is_dir($dir)) mkdir($dir, 0755, true);
|
||||
file_put_contents($file, json_encode($cache));
|
||||
|
||||
$this->assertFalse($this->service->isBlocked(null, '192.168.1.100'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
namespace Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use App\Services\JwtService;
|
||||
|
||||
/**
|
||||
* JWT 服务单元测试
|
||||
*/
|
||||
class JwtServiceTest extends TestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
// 设置 JWT 密钥,保证测试与生产使用相同配置入口
|
||||
putenv('JWT_SECRET=test-secret-key-for-unit-tests');
|
||||
$_ENV['JWT_SECRET'] = 'test-secret-key-for-unit-tests';
|
||||
}
|
||||
|
||||
public function testGenerateAndVerifyToken(): void
|
||||
{
|
||||
$service = new JwtService();
|
||||
$user = ['id' => 1, 'username' => 'admin', 'role' => 'admin'];
|
||||
$tokens = $service->generateToken($user);
|
||||
|
||||
$this->assertArrayHasKey('access_token', $tokens);
|
||||
$this->assertArrayHasKey('refresh_token', $tokens);
|
||||
$this->assertArrayHasKey('expires_in', $tokens);
|
||||
$this->assertSame('Bearer', $tokens['token_type']);
|
||||
|
||||
$decoded = $service->verifyToken($tokens['access_token']);
|
||||
$this->assertNotNull($decoded);
|
||||
$this->assertSame(1, $decoded['id']);
|
||||
$this->assertSame('admin', $decoded['username']);
|
||||
$this->assertSame('admin', $decoded['role']);
|
||||
}
|
||||
|
||||
public function testVerifyExpiredToken(): void
|
||||
{
|
||||
$service = new JwtService();
|
||||
// 构造一个已过期 token:签发时间一年前,过期时间一天前
|
||||
$payload = [
|
||||
'iss' => 'cardauth',
|
||||
'iat' => time() - 86400 * 365,
|
||||
'exp' => time() - 86400,
|
||||
'nbf' => time() - 86400 * 365,
|
||||
'sub' => 1,
|
||||
'data' => ['id' => 1, 'username' => 'admin', 'role' => 'admin'],
|
||||
];
|
||||
|
||||
$reflection = new \ReflectionClass($service);
|
||||
$encodeMethod = $reflection->getMethod('encode');
|
||||
$encodeMethod->setAccessible(true);
|
||||
$expiredToken = $encodeMethod->invoke($service, $payload);
|
||||
|
||||
$this->assertNull($service->verifyToken($expiredToken));
|
||||
}
|
||||
|
||||
public function testVerifyInvalidToken(): void
|
||||
{
|
||||
$service = new JwtService();
|
||||
$this->assertNull($service->verifyToken('not.a.token'));
|
||||
$this->assertNull($service->verifyToken(''));
|
||||
}
|
||||
|
||||
public function testRefreshTokenFlow(): void
|
||||
{
|
||||
$service = new JwtService();
|
||||
$user = ['id' => 2, 'username' => 'operator', 'role' => 'project_admin'];
|
||||
$tokens = $service->generateToken($user);
|
||||
|
||||
$refreshed = $service->refreshToken($tokens['refresh_token']);
|
||||
$this->assertNotNull($refreshed);
|
||||
$this->assertArrayHasKey('access_token', $refreshed);
|
||||
|
||||
// 使用 access_token 验证身份
|
||||
$decoded = $service->verifyToken($refreshed['access_token']);
|
||||
$this->assertSame(2, $decoded['id']);
|
||||
$this->assertSame('project_admin', $decoded['role']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
namespace Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use App\Core\Validator;
|
||||
|
||||
/**
|
||||
* 输入验证器单元测试
|
||||
*/
|
||||
class ValidatorTest extends TestCase
|
||||
{
|
||||
public function testRequiredValidation(): void
|
||||
{
|
||||
$validator = new Validator(['name' => '']);
|
||||
$this->assertFalse($validator->validate(['name' => 'required']));
|
||||
|
||||
$validator = new Validator(['name' => 'CardAuth']);
|
||||
$this->assertTrue($validator->validate(['name' => 'required']));
|
||||
}
|
||||
|
||||
public function testEmailValidation(): void
|
||||
{
|
||||
$validator = new Validator(['email' => 'admin@example.com']);
|
||||
$this->assertTrue($validator->validate(['email' => 'email']));
|
||||
|
||||
$validator = new Validator(['email' => 'not-an-email']);
|
||||
$this->assertFalse($validator->validate(['email' => 'email']));
|
||||
}
|
||||
|
||||
public function testMinMaxLength(): void
|
||||
{
|
||||
$validator = new Validator(['site_name' => 'CA']);
|
||||
$this->assertFalse($validator->validate(['site_name' => 'min:3']));
|
||||
|
||||
$validator = new Validator(['site_name' => 'CardAuth']);
|
||||
$this->assertTrue($validator->validate(['site_name' => 'min:3|max:50']));
|
||||
|
||||
$validator = new Validator(['site_name' => str_repeat('a', 51)]);
|
||||
$this->assertFalse($validator->validate(['site_name' => 'max:50']));
|
||||
}
|
||||
|
||||
public function testIntegerValidation(): void
|
||||
{
|
||||
$validator = new Validator(['expire' => '15']);
|
||||
$this->assertTrue($validator->validate(['expire' => 'integer']));
|
||||
|
||||
$validator = new Validator(['expire' => '15.5']);
|
||||
$this->assertFalse($validator->validate(['expire' => 'integer']));
|
||||
}
|
||||
|
||||
public function testInValidation(): void
|
||||
{
|
||||
$validator = new Validator(['status' => 'unused']);
|
||||
$this->assertTrue($validator->validate(['status' => 'in:unused,used,disabled']));
|
||||
|
||||
$validator = new Validator(['status' => 'expired']);
|
||||
$this->assertFalse($validator->validate(['status' => 'in:unused,used,disabled']));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
// PHPUnit 测试引导文件
|
||||
define('BASE_PATH', dirname(__DIR__));
|
||||
define('APP_PATH', BASE_PATH . '/app');
|
||||
define('CONFIG_PATH', BASE_PATH . '/config');
|
||||
define('ROUTES_PATH', BASE_PATH . '/routes');
|
||||
define('STORAGE_PATH', BASE_PATH . '/storage');
|
||||
|
||||
require BASE_PATH . '/vendor/autoload.php';
|
||||
require APP_PATH . '/Helpers/functions.php';
|
||||
|
||||
// 加载环境变量
|
||||
if (file_exists(BASE_PATH . '/.env')) {
|
||||
$lines = file(BASE_PATH . '/.env', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
||||
foreach ($lines as $line) {
|
||||
if (strpos(trim($line), '#') === 0) continue;
|
||||
if (strpos($line, '=') !== false) {
|
||||
list($key, $value) = explode('=', $line, 2);
|
||||
$key = trim($key);
|
||||
$value = trim($value, " \t\n\r\0\x0B\"'");
|
||||
putenv("$key=$value");
|
||||
$_ENV[$key] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user