Files
sam-api/tests/TestCase.php

117 lines
3.2 KiB
PHP
Raw Normal View History

2025-07-17 10:05:47 +09:00
<?php
namespace Tests;
use App\Models\Members\User;
use App\Models\Members\UserTenant;
use App\Models\Tenants\Tenant;
use Illuminate\Foundation\Testing\DatabaseTransactions;
2025-07-17 10:05:47 +09:00
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use DatabaseTransactions;
protected Tenant $tenant;
protected User $user;
protected string $apiKey;
protected string $token;
/**
* 테스트 환경 초기화: API Key + Tenant + User + 로그인 토큰
* 테스트 클래스의 setUp()에서 parent::setUp() 호출
*/
protected function setUpAuthenticatedUser(): void
{
// API Key 생성
$this->apiKey = 'test-api-key-'.uniqid();
\DB::table('api_keys')->insert([
'key' => $this->apiKey,
'description' => 'Test API Key',
'is_active' => true,
'created_at' => now(),
'updated_at' => now(),
]);
// Tenant 생성 (Observer 우회)
$this->tenant = Tenant::withoutEvents(function () {
return Tenant::create([
'company_name' => 'Test Company',
'code' => 'TEST'.uniqid(),
'email' => 'test@example.com',
'phone' => '010-1234-5678',
]);
});
// User 생성
$testUserId = 'testuser'.uniqid();
$this->user = User::create([
'user_id' => $testUserId,
'name' => 'Test User',
'email' => $testUserId.'@example.com',
'password' => bcrypt('password123'),
]);
// UserTenant 관계
UserTenant::create([
'user_id' => $this->user->id,
'tenant_id' => $this->tenant->id,
'is_active' => true,
'is_default' => true,
]);
// 로그인 및 토큰 획득
$response = $this->withHeaders([
'X-API-KEY' => $this->apiKey,
'Accept' => 'application/json',
])->postJson('/api/v1/login', [
'user_id' => $this->user->user_id,
'user_pwd' => 'password123',
]);
$response->assertStatus(200);
$this->token = $response->json('access_token');
}
/**
* 인증된 API 요청
*/
protected function api(string $method, string $uri, array $data = [])
{
return $this->withHeaders([
'X-API-KEY' => $this->apiKey,
'Authorization' => 'Bearer '.$this->token,
'Accept' => 'application/json',
])->{$method.'Json'}($uri, $data);
}
/**
* 성공 응답 구조 검증 (success + message + data)
*/
protected function assertApiSuccess($response, int $status = 200)
{
$response->assertStatus($status)
->assertJsonStructure(['success', 'message', 'data']);
return $response;
}
/**
* 페이지네이션 응답 구조 검증
*/
protected function assertApiPaginated($response)
{
$response->assertStatus(200)
->assertJsonStructure([
'success',
'message',
'data' => ['data', 'current_page', 'total'],
]);
return $response;
}
2025-07-17 10:05:47 +09:00
}