| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283 |
- <?php
- namespace App\Module\OpenAPI\Tests;
- use App\Module\OpenAPI\Models\OpenApiApp;
- use App\Module\OpenAPI\Services\OpenApiService;
- use App\Module\OpenAPI\Services\RateLimitService;
- use App\Module\OpenAPI\Services\ScopeService;
- use App\Module\OpenAPI\Services\WebhookService;
- use Illuminate\Foundation\Testing\RefreshDatabase;
- use Illuminate\Foundation\Testing\WithFaker;
- use Tests\TestCase;
- /**
- * OpenAPI模块测试
- */
- class OpenApiModuleTest extends TestCase
- {
- use RefreshDatabase, WithFaker;
- protected OpenApiService $openApiService;
- protected RateLimitService $rateLimitService;
- protected ScopeService $scopeService;
- protected WebhookService $webhookService;
- protected function setUp(): void
- {
- parent::setUp();
-
- $this->openApiService = app(OpenApiService::class);
- $this->rateLimitService = app(RateLimitService::class);
- $this->scopeService = app(ScopeService::class);
- $this->webhookService = app(WebhookService::class);
- }
- /**
- * 测试创建应用
- */
- public function test_create_app()
- {
- $appData = [
- 'name' => 'Test App',
- 'description' => 'This is a test application',
- 'website' => 'https://example.com',
- 'callback_url' => 'https://example.com/callback',
- 'contact_email' => 'test@example.com',
- 'user_id' => 1,
- ];
- $app = $this->openApiService->createApp($appData);
- $this->assertInstanceOf(OpenApiApp::class, $app);
- $this->assertEquals($appData['name'], $app->name);
- $this->assertEquals($appData['description'], $app->description);
- $this->assertNotEmpty($app->app_id);
- $this->assertNotEmpty($app->app_secret);
- $this->assertEquals(32, strlen($app->app_id));
- $this->assertEquals(64, strlen($app->app_secret));
- }
- /**
- * 测试应用认证
- */
- public function test_app_authentication()
- {
- // 创建测试应用
- $app = $this->createTestApp();
- // 测试正确的认证
- $authenticatedApp = $this->openApiService->authenticateApp($app->app_id, $app->app_secret);
- $this->assertInstanceOf(OpenApiApp::class, $authenticatedApp);
- $this->assertEquals($app->app_id, $authenticatedApp->app_id);
- // 测试错误的密钥
- $result = $this->openApiService->authenticateApp($app->app_id, 'wrong_secret');
- $this->assertNull($result);
- // 测试不存在的应用ID
- $result = $this->openApiService->authenticateApp('nonexistent_app_id', $app->app_secret);
- $this->assertNull($result);
- }
- /**
- * 测试权限范围验证
- */
- public function test_scope_validation()
- {
- $app = $this->createTestApp(['scopes' => ['USER_READ', 'GAME_READ']]);
- // 测试拥有的权限
- $this->assertTrue($this->scopeService->hasScope($app, 'USER_READ'));
- $this->assertTrue($this->scopeService->hasScope($app, 'GAME_READ'));
- // 测试没有的权限
- $this->assertFalse($this->scopeService->hasScope($app, 'USER_WRITE'));
- $this->assertFalse($this->scopeService->hasScope($app, 'ADMIN_READ'));
- // 测试管理员权限
- $adminApp = $this->createTestApp(['scopes' => ['ADMIN']]);
- $this->assertTrue($this->scopeService->hasScope($adminApp, 'USER_READ'));
- $this->assertTrue($this->scopeService->hasScope($adminApp, 'USER_WRITE'));
- $this->assertTrue($this->scopeService->hasScope($adminApp, 'ADMIN_READ'));
- }
- /**
- * 测试频率限制
- */
- public function test_rate_limiting()
- {
- $app = $this->createTestApp([
- 'rate_limits' => [
- 'requests_per_minute' => 5,
- 'requests_per_hour' => 100,
- ]
- ]);
- $request = $this->createMockRequest();
- // 测试正常请求
- for ($i = 0; $i < 5; $i++) {
- $result = $this->rateLimitService->checkRateLimit($app, $request);
- $this->assertTrue($result['allowed']);
- }
- // 测试超出限制
- $result = $this->rateLimitService->checkRateLimit($app, $request);
- $this->assertFalse($result['allowed']);
- $this->assertEquals('requests_per_minute', $result['limit_type']);
- }
- /**
- * 测试Webhook创建
- */
- public function test_webhook_creation()
- {
- $app = $this->createTestApp();
- $webhookData = [
- 'name' => 'Test Webhook',
- 'url' => 'https://example.com/webhook',
- 'events' => ['user.created', 'user.updated'],
- 'timeout' => 30,
- 'retry_count' => 3,
- ];
- $webhook = $this->webhookService->createWebhook($app, $webhookData);
- $this->assertEquals($webhookData['name'], $webhook->name);
- $this->assertEquals($webhookData['url'], $webhook->url);
- $this->assertEquals($webhookData['events'], $webhook->events);
- $this->assertEquals($app->app_id, $webhook->app_id);
- $this->assertNotEmpty($webhook->secret);
- }
- /**
- * 测试应用状态检查
- */
- public function test_app_status_checks()
- {
- // 测试激活状态
- $activeApp = $this->createTestApp(['status' => 'ACTIVE']);
- $this->assertTrue($activeApp->isActive());
- $this->assertFalse($activeApp->isSuspended());
- $this->assertFalse($activeApp->isExpired());
- // 测试暂停状态
- $suspendedApp = $this->createTestApp(['status' => 'SUSPENDED']);
- $this->assertFalse($suspendedApp->isActive());
- $this->assertTrue($suspendedApp->isSuspended());
- // 测试过期状态
- $expiredApp = $this->createTestApp([
- 'status' => 'ACTIVE',
- 'expires_at' => now()->subDay()
- ]);
- $this->assertTrue($expiredApp->isActive());
- $this->assertTrue($expiredApp->isExpired());
- }
- /**
- * 测试IP白名单
- */
- public function test_ip_whitelist()
- {
- $app = $this->createTestApp([
- 'ip_whitelist' => ['192.168.1.1', '10.0.0.0/8', '172.16.*']
- ]);
- // 测试精确匹配
- $this->assertTrue($app->isIpAllowed('192.168.1.1'));
- $this->assertFalse($app->isIpAllowed('192.168.1.2'));
- // 测试CIDR匹配
- $this->assertTrue($app->isIpAllowed('10.0.0.1'));
- $this->assertTrue($app->isIpAllowed('10.255.255.255'));
- $this->assertFalse($app->isIpAllowed('11.0.0.1'));
- // 测试通配符匹配
- $this->assertTrue($app->isIpAllowed('172.16.1'));
- $this->assertTrue($app->isIpAllowed('172.16.255'));
- $this->assertFalse($app->isIpAllowed('172.17.1'));
- // 测试无白名单(允许所有)
- $noWhitelistApp = $this->createTestApp(['ip_whitelist' => null]);
- $this->assertTrue($noWhitelistApp->isIpAllowed('1.2.3.4'));
- }
- /**
- * 测试统计数据生成
- */
- public function test_stats_generation()
- {
- $app = $this->createTestApp();
- // 模拟API调用日志
- $this->createTestLogs($app, 10);
- // 获取统计数据
- $stats = $this->openApiService->getAppStats($app->app_id, 'day');
- $this->assertIsArray($stats);
- $this->assertArrayHasKey('total_requests', $stats);
- $this->assertArrayHasKey('total_success', $stats);
- $this->assertArrayHasKey('total_errors', $stats);
- $this->assertArrayHasKey('success_rate', $stats);
- }
- /**
- * 创建测试应用
- */
- protected function createTestApp(array $overrides = []): OpenApiApp
- {
- $defaultData = [
- 'name' => $this->faker->company,
- 'description' => $this->faker->sentence,
- 'website' => $this->faker->url,
- 'callback_url' => $this->faker->url,
- 'contact_email' => $this->faker->email,
- 'user_id' => 1,
- 'status' => 'ACTIVE',
- 'auth_type' => 'API_KEY',
- 'scopes' => ['USER_READ', 'GAME_READ'],
- ];
- $data = array_merge($defaultData, $overrides);
- return $this->openApiService->createApp($data);
- }
- /**
- * 创建模拟请求
- */
- protected function createMockRequest()
- {
- $request = new \Illuminate\Http\Request();
- $request->server->set('REMOTE_ADDR', '127.0.0.1');
- $request->server->set('REQUEST_URI', '/api/test');
- return $request;
- }
- /**
- * 创建测试日志
- */
- protected function createTestLogs(OpenApiApp $app, int $count = 10)
- {
- for ($i = 0; $i < $count; $i++) {
- \App\Module\OpenAPI\Models\OpenApiLog::create([
- 'app_id' => $app->app_id,
- 'user_id' => 1,
- 'method' => 'GET',
- 'uri' => '/api/test',
- 'params' => json_encode(['test' => 'data']),
- 'headers' => json_encode(['User-Agent' => 'Test']),
- 'ip_address' => '127.0.0.1',
- 'user_agent' => 'Test Agent',
- 'response_code' => $i < 8 ? 200 : 400, // 80%成功率
- 'response_time' => rand(100, 1000),
- 'response_size' => rand(1000, 5000),
- 'scope' => 'USER_READ',
- 'rate_limit_hit' => false,
- ]);
- }
- }
- }
|