v7.0.0-beta.2 release
This commit is contained in:
1 parent
6595fd0eb5
commit
fa8eba7a0d
1165 files changed
+107118
-762127
No files matched your search
@@ -0,0 +1,190 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use App\Services\GeoIpDatabaseService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* POST /api/admin/settings/geoip/update 통합 테스트.
|
||||
*
|
||||
* GeoIpDatabaseService를 모킹하여 컨트롤러가 상태 코드를
|
||||
* 올바른 HTTP 상태/메시지 키로 매핑하는지 검증합니다.
|
||||
* 권한 설정 패턴은 SettingsControllerTest 와 동일합니다.
|
||||
*/
|
||||
class GeoIpControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $admin;
|
||||
|
||||
private string $token;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->admin = $this->createAdminUser();
|
||||
$this->token = $this->admin->createToken('test-token')->plainTextToken;
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Mockery::close();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* core.settings.update 권한을 가진 관리자 사용자를 생성합니다.
|
||||
*
|
||||
* @return User 생성된 관리자 사용자
|
||||
*/
|
||||
private function createAdminUser(): User
|
||||
{
|
||||
$user = User::factory()->create([
|
||||
'password' => Hash::make('password123'),
|
||||
]);
|
||||
|
||||
$permission = Permission::firstOrCreate(
|
||||
['identifier' => 'core.settings.update'],
|
||||
[
|
||||
'name' => json_encode(['ko' => '설정 업데이트', 'en' => 'Settings Update']),
|
||||
'description' => json_encode(['ko' => '설정 업데이트 권한', 'en' => 'Settings Update Permission']),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'type' => 'admin',
|
||||
]
|
||||
);
|
||||
|
||||
$adminBaseRole = Role::firstOrCreate(
|
||||
['identifier' => 'admin'],
|
||||
[
|
||||
'name' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
|
||||
'description' => json_encode(['ko' => '시스템 관리자', 'en' => 'System Administrator']),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
|
||||
$roleIdentifier = 'admin_test_'.uniqid();
|
||||
$testRole = Role::create([
|
||||
'identifier' => $roleIdentifier,
|
||||
'name' => json_encode(['ko' => '테스트 관리자', 'en' => 'Test Administrator']),
|
||||
'description' => json_encode(['ko' => '테스트 관리자', 'en' => 'Test Administrator']),
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$testRole->permissions()->sync([$permission->id]);
|
||||
|
||||
$user->roles()->attach($adminBaseRole->id, ['assigned_at' => now(), 'assigned_by' => null]);
|
||||
$user->roles()->attach($testRole->id, ['assigned_at' => now(), 'assigned_by' => null]);
|
||||
|
||||
return $user->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* Bearer 토큰 헤더를 포함하여 API 엔드포인트를 호출합니다.
|
||||
*
|
||||
* @return \Illuminate\Testing\TestResponse HTTP 응답
|
||||
*/
|
||||
private function postUpdate(): \Illuminate\Testing\TestResponse
|
||||
{
|
||||
return $this->withHeader('Authorization', 'Bearer '.$this->token)
|
||||
->postJson('/api/admin/settings/geoip/update');
|
||||
}
|
||||
|
||||
public function test_unauthenticated_request_returns_401(): void
|
||||
{
|
||||
$response = $this->postJson('/api/admin/settings/geoip/update');
|
||||
$response->assertStatus(401);
|
||||
}
|
||||
|
||||
public function test_missing_license_key_returns_400(): void
|
||||
{
|
||||
$mockService = Mockery::mock(GeoIpDatabaseService::class);
|
||||
$mockService->shouldReceive('updateDatabase')
|
||||
->once()
|
||||
->with(true)
|
||||
->andReturn([
|
||||
'success' => false,
|
||||
'status' => 'missing_license_key',
|
||||
'message' => 'MaxMind 라이선스 키가 설정되지 않았습니다.',
|
||||
]);
|
||||
$this->app->instance(GeoIpDatabaseService::class, $mockService);
|
||||
|
||||
$response = $this->postUpdate();
|
||||
|
||||
$response->assertStatus(400);
|
||||
$this->assertFalse($response->json('success'));
|
||||
}
|
||||
|
||||
public function test_successful_update_returns_200_with_data(): void
|
||||
{
|
||||
$mockService = Mockery::mock(GeoIpDatabaseService::class);
|
||||
$mockService->shouldReceive('updateDatabase')
|
||||
->once()
|
||||
->with(true)
|
||||
->andReturn([
|
||||
'success' => true,
|
||||
'status' => 'updated',
|
||||
'message' => 'GeoIP DB 업데이트가 완료되었습니다.',
|
||||
'data' => [
|
||||
'database_path' => '/fake/path/GeoLite2-City.mmdb',
|
||||
'file_size_bytes' => 62_000_000,
|
||||
'elapsed_seconds' => 5.2,
|
||||
'last_updated_at' => '2026-04-16T03:00:00+00:00',
|
||||
],
|
||||
]);
|
||||
$this->app->instance(GeoIpDatabaseService::class, $mockService);
|
||||
|
||||
$response = $this->postUpdate();
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertTrue($response->json('success'));
|
||||
$this->assertEquals(62_000_000, $response->json('data.file_size_bytes'));
|
||||
}
|
||||
|
||||
public function test_unauthorized_status_returns_401_code(): void
|
||||
{
|
||||
$mockService = Mockery::mock(GeoIpDatabaseService::class);
|
||||
$mockService->shouldReceive('updateDatabase')
|
||||
->once()
|
||||
->with(true)
|
||||
->andReturn([
|
||||
'success' => false,
|
||||
'status' => 'unauthorized',
|
||||
'message' => '라이선스 키가 유효하지 않습니다. (HTTP 401)',
|
||||
]);
|
||||
$this->app->instance(GeoIpDatabaseService::class, $mockService);
|
||||
|
||||
$response = $this->postUpdate();
|
||||
|
||||
$response->assertStatus(401);
|
||||
}
|
||||
|
||||
public function test_download_failed_returns_500_code(): void
|
||||
{
|
||||
$mockService = Mockery::mock(GeoIpDatabaseService::class);
|
||||
$mockService->shouldReceive('updateDatabase')
|
||||
->once()
|
||||
->with(true)
|
||||
->andReturn([
|
||||
'success' => false,
|
||||
'status' => 'download_failed',
|
||||
'message' => '다운로드 실패: HTTP 503',
|
||||
]);
|
||||
$this->app->instance(GeoIpDatabaseService::class, $mockService);
|
||||
|
||||
$response = $this->postUpdate();
|
||||
|
||||
$response->assertStatus(500);
|
||||
}
|
||||
}
|
||||
@@ -1,597 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Enums\MailSendStatus;
|
||||
use App\Models\MailSendLog;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* MailSendLogController 테스트
|
||||
*
|
||||
* 메일 발송 이력 API 엔드포인트를 테스트합니다.
|
||||
*/
|
||||
class MailSendLogControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $admin;
|
||||
|
||||
private string $token;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->admin = $this->createAdminUser();
|
||||
$this->token = $this->admin->createToken('test-token')->plainTextToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자 역할 생성 및 할당
|
||||
*
|
||||
* @param array $permissions 사용자에게 부여할 권한 식별자 목록
|
||||
* @return User
|
||||
*/
|
||||
private function createAdminUser(array $permissions = ['core.mail-send-logs.read']): User
|
||||
{
|
||||
$user = User::factory()->create([
|
||||
'password' => Hash::make('password123'),
|
||||
]);
|
||||
|
||||
// 권한 생성
|
||||
$permissionIds = [];
|
||||
foreach ($permissions as $permIdentifier) {
|
||||
$permission = Permission::firstOrCreate(
|
||||
['identifier' => $permIdentifier],
|
||||
[
|
||||
'name' => json_encode(['ko' => $permIdentifier, 'en' => $permIdentifier]),
|
||||
'description' => json_encode(['ko' => $permIdentifier.' 권한', 'en' => $permIdentifier.' Permission']),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'type' => 'admin',
|
||||
]
|
||||
);
|
||||
$permissionIds[] = $permission->id;
|
||||
}
|
||||
|
||||
// 고유한 식별자로 역할 생성
|
||||
$roleIdentifier = 'admin_test_'.uniqid();
|
||||
$adminRole = Role::create([
|
||||
'identifier' => $roleIdentifier,
|
||||
'name' => json_encode(['ko' => '테스트 관리자', 'en' => 'Test Administrator']),
|
||||
'description' => json_encode(['ko' => '테스트 관리자', 'en' => 'Test Administrator']),
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
// admin 역할 (admin 미들웨어 통과용)
|
||||
$adminBaseRole = Role::firstOrCreate(
|
||||
['identifier' => 'admin'],
|
||||
[
|
||||
'name' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
|
||||
'description' => json_encode(['ko' => '시스템 관리자', 'en' => 'System Administrator']),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
|
||||
// 테스트용 역할에 권한 할당
|
||||
$adminRole->permissions()->sync($permissionIds);
|
||||
|
||||
// 사용자에게 admin 역할과 테스트용 역할 모두 할당
|
||||
$user->roles()->attach($adminBaseRole->id, [
|
||||
'assigned_at' => now(),
|
||||
'assigned_by' => null,
|
||||
]);
|
||||
$user->roles()->attach($adminRole->id, [
|
||||
'assigned_at' => now(),
|
||||
'assigned_by' => null,
|
||||
]);
|
||||
|
||||
return $user->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* 인증 헤더와 함께 요청
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
private function authRequest(): static
|
||||
{
|
||||
return $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$this->token,
|
||||
'Accept' => 'application/json',
|
||||
]);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// 인증/권한 테스트
|
||||
// ========================================================================
|
||||
|
||||
public function test_index_returns_401_without_authentication(): void
|
||||
{
|
||||
$response = $this->getJson('/api/admin/mail-send-logs');
|
||||
$response->assertStatus(401);
|
||||
}
|
||||
|
||||
public function test_index_returns_403_without_permission(): void
|
||||
{
|
||||
$user = $this->createAdminUser([]);
|
||||
$token = $user->createToken('test-token')->plainTextToken;
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$token,
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/mail-send-logs');
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// index 엔드포인트 - 응답 구조
|
||||
// ========================================================================
|
||||
|
||||
public function test_index_returns_data_and_pagination_structure(): void
|
||||
{
|
||||
MailSendLog::factory()->count(3)->create();
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-send-logs');
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonStructure([
|
||||
'success',
|
||||
'message',
|
||||
'data' => [
|
||||
'data',
|
||||
'pagination' => [
|
||||
'current_page',
|
||||
'last_page',
|
||||
'per_page',
|
||||
'total',
|
||||
'from',
|
||||
'to',
|
||||
'has_more_pages',
|
||||
],
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_index_data_items_have_correct_fields(): void
|
||||
{
|
||||
MailSendLog::factory()->create();
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-send-logs');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$data = $response->json('data.data');
|
||||
$this->assertCount(1, $data);
|
||||
|
||||
$item = $data[0];
|
||||
$this->assertArrayHasKey('id', $item);
|
||||
$this->assertArrayHasKey('recipient_email', $item);
|
||||
$this->assertArrayHasKey('recipient_name', $item);
|
||||
$this->assertArrayHasKey('subject', $item);
|
||||
$this->assertArrayHasKey('template_type', $item);
|
||||
$this->assertArrayHasKey('extension_type', $item);
|
||||
$this->assertArrayHasKey('extension_identifier', $item);
|
||||
$this->assertArrayHasKey('status', $item);
|
||||
$this->assertArrayHasKey('sent_at', $item);
|
||||
$this->assertArrayHasKey('body', $item);
|
||||
$this->assertArrayHasKey('sender_email', $item);
|
||||
$this->assertArrayHasKey('sender_name', $item);
|
||||
$this->assertArrayHasKey('number', $item);
|
||||
}
|
||||
|
||||
public function test_index_data_items_include_body_content(): void
|
||||
{
|
||||
$body = '<p>Test email body</p>';
|
||||
MailSendLog::factory()->create(['body' => $body]);
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-send-logs');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$data = $response->json('data.data');
|
||||
$this->assertEquals($body, $data[0]['body']);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// index 엔드포인트 - 필터
|
||||
// ========================================================================
|
||||
|
||||
public function test_index_filters_by_single_extension_type(): void
|
||||
{
|
||||
MailSendLog::factory()->forExtension(ExtensionOwnerType::Core, 'core')->count(2)->create();
|
||||
MailSendLog::factory()->forExtension(ExtensionOwnerType::Module, 'sirsoft-ecommerce')->create();
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-send-logs?extension_type[]=core');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertCount(2, $response->json('data.data'));
|
||||
}
|
||||
|
||||
public function test_index_filters_by_multiple_extension_types(): void
|
||||
{
|
||||
MailSendLog::factory()->forExtension(ExtensionOwnerType::Core, 'core')->count(2)->create();
|
||||
MailSendLog::factory()->forExtension(ExtensionOwnerType::Module, 'sirsoft-board')->create();
|
||||
MailSendLog::factory()->forExtension(ExtensionOwnerType::Plugin, 'sirsoft-payment')->create();
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-send-logs?extension_type[]=core&extension_type[]=module');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertCount(3, $response->json('data.data'));
|
||||
}
|
||||
|
||||
public function test_index_filters_by_single_status(): void
|
||||
{
|
||||
MailSendLog::factory()->count(3)->create(['status' => MailSendStatus::Sent->value]);
|
||||
MailSendLog::factory()->failed()->count(2)->create();
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-send-logs?status[]=failed');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertCount(2, $response->json('data.data'));
|
||||
}
|
||||
|
||||
public function test_index_filters_by_multiple_statuses(): void
|
||||
{
|
||||
MailSendLog::factory()->count(2)->create(['status' => MailSendStatus::Sent->value]);
|
||||
MailSendLog::factory()->failed()->count(1)->create();
|
||||
MailSendLog::factory()->create(['status' => MailSendStatus::Skipped->value]);
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-send-logs?status[]=sent&status[]=failed');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertCount(3, $response->json('data.data'));
|
||||
}
|
||||
|
||||
public function test_index_filters_by_search(): void
|
||||
{
|
||||
MailSendLog::factory()->create(['recipient_email' => 'findme@example.com']);
|
||||
MailSendLog::factory()->create(['recipient_email' => 'other@example.com']);
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-send-logs?search=findme');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertCount(1, $response->json('data.data'));
|
||||
}
|
||||
|
||||
public function test_index_filters_by_search_type_recipient_email(): void
|
||||
{
|
||||
MailSendLog::factory()->create([
|
||||
'recipient_email' => 'findme@example.com',
|
||||
'recipient_name' => '다른이름',
|
||||
'subject' => '다른제목',
|
||||
]);
|
||||
MailSendLog::factory()->create([
|
||||
'recipient_email' => 'other@example.com',
|
||||
'recipient_name' => 'findme',
|
||||
'subject' => '기타',
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-send-logs?search=findme&search_type=recipient_email');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertCount(1, $response->json('data.data'));
|
||||
$this->assertEquals('findme@example.com', $response->json('data.data.0.recipient_email'));
|
||||
}
|
||||
|
||||
public function test_index_filters_by_search_type_subject(): void
|
||||
{
|
||||
MailSendLog::factory()->create([
|
||||
'recipient_email' => 'a@example.com',
|
||||
'subject' => '주문 완료 안내',
|
||||
]);
|
||||
MailSendLog::factory()->create([
|
||||
'recipient_email' => 'b@example.com',
|
||||
'subject' => '비밀번호 재설정',
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-send-logs?search=주문&search_type=subject');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertCount(1, $response->json('data.data'));
|
||||
}
|
||||
|
||||
public function test_index_search_type_all_searches_all_fields(): void
|
||||
{
|
||||
MailSendLog::factory()->create(['recipient_email' => 'keyword@example.com', 'subject' => '기타']);
|
||||
MailSendLog::factory()->create(['recipient_email' => 'a@example.com', 'subject' => 'keyword 포함']);
|
||||
MailSendLog::factory()->create(['recipient_email' => 'b@example.com', 'recipient_name' => 'keyword맨', 'subject' => '기타']);
|
||||
MailSendLog::factory()->create(['recipient_email' => 'c@example.com', 'subject' => '관련없음']);
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-send-logs?search=keyword&search_type=all');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertCount(3, $response->json('data.data'));
|
||||
}
|
||||
|
||||
public function test_index_filters_by_date_range(): void
|
||||
{
|
||||
MailSendLog::factory()->create(['sent_at' => Carbon::parse('2026-01-15')]);
|
||||
MailSendLog::factory()->create(['sent_at' => Carbon::parse('2026-03-15')]);
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-send-logs?date_from=2026-03-01&date_to=2026-03-31');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertCount(1, $response->json('data.data'));
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// index 엔드포인트 - 페이지네이션
|
||||
// ========================================================================
|
||||
|
||||
public function test_index_respects_per_page(): void
|
||||
{
|
||||
MailSendLog::factory()->count(10)->create();
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-send-logs?per_page=5');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertCount(5, $response->json('data.data'));
|
||||
$this->assertEquals(10, $response->json('data.pagination.total'));
|
||||
$this->assertEquals(5, $response->json('data.pagination.per_page'));
|
||||
$this->assertTrue($response->json('data.pagination.has_more_pages'));
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// index 엔드포인트 - 정렬
|
||||
// ========================================================================
|
||||
|
||||
public function test_index_sorts_by_sent_at_desc_by_default(): void
|
||||
{
|
||||
MailSendLog::factory()->create(['sent_at' => Carbon::parse('2026-03-01')]);
|
||||
MailSendLog::factory()->create(['sent_at' => Carbon::parse('2026-03-05')]);
|
||||
MailSendLog::factory()->create(['sent_at' => Carbon::parse('2026-03-03')]);
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-send-logs');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$data = $response->json('data.data');
|
||||
$this->assertCount(3, $data);
|
||||
// 기본 정렬: sent_at desc (최신순)
|
||||
$this->assertGreaterThanOrEqual(
|
||||
$data[1]['sent_at'],
|
||||
$data[0]['sent_at']
|
||||
);
|
||||
}
|
||||
|
||||
public function test_index_sorts_by_recipient_email_asc(): void
|
||||
{
|
||||
MailSendLog::factory()->create(['recipient_email' => 'charlie@example.com']);
|
||||
MailSendLog::factory()->create(['recipient_email' => 'alice@example.com']);
|
||||
MailSendLog::factory()->create(['recipient_email' => 'bob@example.com']);
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-send-logs?sort_by=recipient_email&sort_order=asc');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$data = $response->json('data.data');
|
||||
$this->assertEquals('alice@example.com', $data[0]['recipient_email']);
|
||||
$this->assertEquals('bob@example.com', $data[1]['recipient_email']);
|
||||
$this->assertEquals('charlie@example.com', $data[2]['recipient_email']);
|
||||
}
|
||||
|
||||
public function test_index_rejects_invalid_sort_by(): void
|
||||
{
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-send-logs?sort_by=invalid_column');
|
||||
|
||||
$response->assertStatus(422);
|
||||
}
|
||||
|
||||
public function test_index_rejects_invalid_sort_order(): void
|
||||
{
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-send-logs?sort_order=invalid');
|
||||
|
||||
$response->assertStatus(422);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// index 엔드포인트 - abilities
|
||||
// ========================================================================
|
||||
|
||||
public function test_index_includes_abilities_in_response(): void
|
||||
{
|
||||
$user = $this->createAdminUser(['core.mail-send-logs.read', 'core.mail-send-logs.delete']);
|
||||
$token = $user->createToken('test-token')->plainTextToken;
|
||||
|
||||
MailSendLog::factory()->create();
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$token,
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/mail-send-logs');
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('data.abilities.can_delete', true);
|
||||
}
|
||||
|
||||
public function test_index_abilities_can_delete_false_without_permission(): void
|
||||
{
|
||||
MailSendLog::factory()->create();
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-send-logs');
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('data.abilities.can_delete', false);
|
||||
}
|
||||
|
||||
public function test_index_data_items_include_abilities(): void
|
||||
{
|
||||
$user = $this->createAdminUser(['core.mail-send-logs.read', 'core.mail-send-logs.delete']);
|
||||
$token = $user->createToken('test-token')->plainTextToken;
|
||||
|
||||
MailSendLog::factory()->create();
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$token,
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/mail-send-logs');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$data = $response->json('data.data');
|
||||
$this->assertArrayHasKey('abilities', $data[0]);
|
||||
$this->assertTrue($data[0]['abilities']['can_delete']);
|
||||
}
|
||||
|
||||
public function test_index_data_items_abilities_can_delete_false_without_permission(): void
|
||||
{
|
||||
MailSendLog::factory()->create();
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-send-logs');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$data = $response->json('data.data');
|
||||
$this->assertArrayHasKey('abilities', $data[0]);
|
||||
$this->assertFalse($data[0]['abilities']['can_delete']);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// destroy 엔드포인트
|
||||
// ========================================================================
|
||||
|
||||
public function test_destroy_returns_401_without_authentication(): void
|
||||
{
|
||||
$log = MailSendLog::factory()->create();
|
||||
|
||||
$response = $this->deleteJson("/api/admin/mail-send-logs/{$log->id}");
|
||||
$response->assertStatus(401);
|
||||
}
|
||||
|
||||
public function test_destroy_returns_403_without_permission(): void
|
||||
{
|
||||
$log = MailSendLog::factory()->create();
|
||||
|
||||
$response = $this->authRequest()->deleteJson("/api/admin/mail-send-logs/{$log->id}");
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
public function test_destroy_deletes_mail_send_log(): void
|
||||
{
|
||||
$user = $this->createAdminUser(['core.mail-send-logs.read', 'core.mail-send-logs.delete']);
|
||||
$token = $user->createToken('test-token')->plainTextToken;
|
||||
|
||||
$log = MailSendLog::factory()->create();
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$token,
|
||||
'Accept' => 'application/json',
|
||||
])->deleteJson("/api/admin/mail-send-logs/{$log->id}");
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('success', true);
|
||||
|
||||
$this->assertDatabaseMissing('mail_send_logs', ['id' => $log->id]);
|
||||
}
|
||||
|
||||
public function test_destroy_returns_404_for_nonexistent_log(): void
|
||||
{
|
||||
$user = $this->createAdminUser(['core.mail-send-logs.read', 'core.mail-send-logs.delete']);
|
||||
$token = $user->createToken('test-token')->plainTextToken;
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$token,
|
||||
'Accept' => 'application/json',
|
||||
])->deleteJson('/api/admin/mail-send-logs/99999');
|
||||
|
||||
$response->assertStatus(404);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// bulkDestroy 엔드포인트
|
||||
// ========================================================================
|
||||
|
||||
public function test_bulk_destroy_returns_401_without_authentication(): void
|
||||
{
|
||||
$response = $this->postJson('/api/admin/mail-send-logs/bulk-delete', [
|
||||
'ids' => [1],
|
||||
]);
|
||||
$response->assertStatus(401);
|
||||
}
|
||||
|
||||
public function test_bulk_destroy_returns_403_without_permission(): void
|
||||
{
|
||||
$logs = MailSendLog::factory()->count(2)->create();
|
||||
|
||||
$response = $this->authRequest()->postJson('/api/admin/mail-send-logs/bulk-delete', [
|
||||
'ids' => $logs->pluck('id')->toArray(),
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
public function test_bulk_destroy_deletes_multiple_logs(): void
|
||||
{
|
||||
$user = $this->createAdminUser(['core.mail-send-logs.read', 'core.mail-send-logs.delete']);
|
||||
$token = $user->createToken('test-token')->plainTextToken;
|
||||
|
||||
$logs = MailSendLog::factory()->count(3)->create();
|
||||
$idsToDelete = $logs->take(2)->pluck('id')->toArray();
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$token,
|
||||
'Accept' => 'application/json',
|
||||
])->postJson('/api/admin/mail-send-logs/bulk-delete', [
|
||||
'ids' => $idsToDelete,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('success', true)
|
||||
->assertJsonPath('data.deleted_count', 2);
|
||||
|
||||
foreach ($idsToDelete as $id) {
|
||||
$this->assertDatabaseMissing('mail_send_logs', ['id' => $id]);
|
||||
}
|
||||
// 삭제되지 않은 항목은 여전히 존재
|
||||
$this->assertDatabaseHas('mail_send_logs', ['id' => $logs->last()->id]);
|
||||
}
|
||||
|
||||
public function test_bulk_destroy_validates_ids_required(): void
|
||||
{
|
||||
$user = $this->createAdminUser(['core.mail-send-logs.read', 'core.mail-send-logs.delete']);
|
||||
$token = $user->createToken('test-token')->plainTextToken;
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$token,
|
||||
'Accept' => 'application/json',
|
||||
])->postJson('/api/admin/mail-send-logs/bulk-delete', []);
|
||||
|
||||
$response->assertStatus(422)
|
||||
->assertJsonValidationErrors(['ids']);
|
||||
}
|
||||
|
||||
public function test_bulk_destroy_validates_ids_must_exist(): void
|
||||
{
|
||||
$user = $this->createAdminUser(['core.mail-send-logs.read', 'core.mail-send-logs.delete']);
|
||||
$token = $user->createToken('test-token')->plainTextToken;
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$token,
|
||||
'Accept' => 'application/json',
|
||||
])->postJson('/api/admin/mail-send-logs/bulk-delete', [
|
||||
'ids' => [99999],
|
||||
]);
|
||||
|
||||
$response->assertStatus(422)
|
||||
->assertJsonValidationErrors(['ids.0']);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// statistics 라우트 제거 확인
|
||||
// ========================================================================
|
||||
|
||||
public function test_statistics_route_does_not_exist(): void
|
||||
{
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-send-logs/statistics');
|
||||
|
||||
// statistics 라우트가 제거되었으므로 404 또는 405 반환
|
||||
// (DELETE {mailSendLog} 라우트가 'statistics'를 파라미터로 매칭하여 405 반환 가능)
|
||||
$this->assertTrue(in_array($response->status(), [404, 405]));
|
||||
}
|
||||
}
|
||||
@@ -1,350 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Models\MailTemplate;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* MailTemplateController Feature 테스트
|
||||
*
|
||||
* 메일 템플릿 API 엔드포인트의 인증, 권한, CRUD 동작을 검증합니다.
|
||||
*/
|
||||
class MailTemplateControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $admin;
|
||||
|
||||
private string $token;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->admin = $this->createAdminUser();
|
||||
$this->token = $this->admin->createToken('test-token')->plainTextToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자 역할 생성 및 할당
|
||||
*
|
||||
* @param array $permissions 사용자에게 부여할 권한 식별자 목록
|
||||
* @return User
|
||||
*/
|
||||
private function createAdminUser(array $permissions = ['core.settings.read', 'core.settings.update']): User
|
||||
{
|
||||
$user = User::factory()->create([
|
||||
'password' => Hash::make('password123'),
|
||||
]);
|
||||
|
||||
$permissionIds = [];
|
||||
foreach ($permissions as $permIdentifier) {
|
||||
$permission = Permission::firstOrCreate(
|
||||
['identifier' => $permIdentifier],
|
||||
[
|
||||
'name' => json_encode(['ko' => $permIdentifier, 'en' => $permIdentifier]),
|
||||
'description' => json_encode(['ko' => $permIdentifier.' 권한', 'en' => $permIdentifier.' Permission']),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'type' => 'admin',
|
||||
]
|
||||
);
|
||||
$permissionIds[] = $permission->id;
|
||||
}
|
||||
|
||||
$roleIdentifier = 'admin_test_'.uniqid();
|
||||
$adminRole = Role::create([
|
||||
'identifier' => $roleIdentifier,
|
||||
'name' => json_encode(['ko' => '테스트 관리자', 'en' => 'Test Administrator']),
|
||||
'description' => json_encode(['ko' => '테스트 관리자', 'en' => 'Test Administrator']),
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$adminBaseRole = Role::firstOrCreate(
|
||||
['identifier' => 'admin'],
|
||||
[
|
||||
'name' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
|
||||
'description' => json_encode(['ko' => '시스템 관리자', 'en' => 'System Administrator']),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
|
||||
$adminRole->permissions()->sync($permissionIds);
|
||||
|
||||
$user->roles()->attach($adminBaseRole->id, [
|
||||
'assigned_at' => now(),
|
||||
'assigned_by' => null,
|
||||
]);
|
||||
$user->roles()->attach($adminRole->id, [
|
||||
'assigned_at' => now(),
|
||||
'assigned_by' => null,
|
||||
]);
|
||||
|
||||
return $user->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* 인증 헤더와 함께 요청
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
private function authRequest(): static
|
||||
{
|
||||
return $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$this->token,
|
||||
'Accept' => 'application/json',
|
||||
]);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// 인증/권한 테스트
|
||||
// ========================================================================
|
||||
|
||||
public function test_index_returns_401_without_authentication(): void
|
||||
{
|
||||
$response = $this->getJson('/api/admin/mail-templates');
|
||||
$response->assertStatus(401);
|
||||
}
|
||||
|
||||
public function test_index_returns_403_without_permission(): void
|
||||
{
|
||||
$user = $this->createAdminUser([]);
|
||||
$token = $user->createToken('test-token')->plainTextToken;
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$token,
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/mail-templates');
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
public function test_update_returns_403_without_update_permission(): void
|
||||
{
|
||||
$user = $this->createAdminUser(['core.settings.read']);
|
||||
$token = $user->createToken('test-token')->plainTextToken;
|
||||
$template = MailTemplate::factory()->withType('welcome')->create();
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$token,
|
||||
'Accept' => 'application/json',
|
||||
])->putJson("/api/admin/mail-templates/{$template->id}", [
|
||||
'subject' => ['ko' => '제목'],
|
||||
'body' => ['ko' => '<p>본문</p>'],
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// index
|
||||
// ========================================================================
|
||||
|
||||
public function test_index_returns_paginated_template_list(): void
|
||||
{
|
||||
MailTemplate::factory()->withType('welcome')->create();
|
||||
MailTemplate::factory()->withType('reset_password')->create();
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-templates');
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonStructure([
|
||||
'success',
|
||||
'message',
|
||||
'data' => [
|
||||
'data',
|
||||
'pagination' => [
|
||||
'current_page',
|
||||
'last_page',
|
||||
'per_page',
|
||||
'total',
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->assertCount(2, $response->json('data.data'));
|
||||
$this->assertEquals(2, $response->json('data.pagination.total'));
|
||||
}
|
||||
|
||||
public function test_index_paginates_with_per_page(): void
|
||||
{
|
||||
MailTemplate::factory()->count(5)->create();
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-templates?per_page=2');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertCount(2, $response->json('data.data'));
|
||||
$this->assertEquals(5, $response->json('data.pagination.total'));
|
||||
$this->assertEquals(3, $response->json('data.pagination.last_page'));
|
||||
}
|
||||
|
||||
public function test_index_filters_by_subject_search(): void
|
||||
{
|
||||
MailTemplate::factory()->withType('welcome')->create([
|
||||
'subject' => ['ko' => '환영 메일', 'en' => 'Welcome'],
|
||||
]);
|
||||
MailTemplate::factory()->withType('reset_password')->create([
|
||||
'subject' => ['ko' => '비밀번호 재설정', 'en' => 'Reset Password'],
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-templates?search=환영&search_type=subject');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertCount(1, $response->json('data.data'));
|
||||
}
|
||||
|
||||
public function test_index_filters_by_body_search(): void
|
||||
{
|
||||
MailTemplate::factory()->withType('welcome')->create([
|
||||
'body' => ['ko' => '<p>가입을 축하합니다</p>', 'en' => '<p>Congratulations</p>'],
|
||||
]);
|
||||
MailTemplate::factory()->withType('reset_password')->create([
|
||||
'body' => ['ko' => '<p>비밀번호를 재설정하세요</p>', 'en' => '<p>Reset your password</p>'],
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-templates?search=축하&search_type=body');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertCount(1, $response->json('data.data'));
|
||||
}
|
||||
|
||||
public function test_index_filters_by_all_search_type(): void
|
||||
{
|
||||
MailTemplate::factory()->withType('welcome')->create([
|
||||
'subject' => ['ko' => '환영', 'en' => 'Welcome'],
|
||||
'body' => ['ko' => '<p>본문</p>', 'en' => '<p>Body</p>'],
|
||||
]);
|
||||
MailTemplate::factory()->withType('reset_password')->create([
|
||||
'subject' => ['ko' => '재설정', 'en' => 'Reset'],
|
||||
'body' => ['ko' => '<p>환영합니다</p>', 'en' => '<p>Welcome</p>'],
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/mail-templates?search=환영&search_type=all');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertCount(2, $response->json('data.data'));
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// update
|
||||
// ========================================================================
|
||||
|
||||
public function test_update_saves_template(): void
|
||||
{
|
||||
$template = MailTemplate::factory()->withType('welcome')->create();
|
||||
|
||||
$response = $this->authRequest()->putJson("/api/admin/mail-templates/{$template->id}", [
|
||||
'subject' => ['ko' => '수정된 제목', 'en' => 'Updated Subject'],
|
||||
'body' => ['ko' => '<p>수정된 본문</p>', 'en' => '<p>Updated Body</p>'],
|
||||
]);
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('success', true);
|
||||
|
||||
$template->refresh();
|
||||
$this->assertEquals('수정된 제목', $template->subject['ko']);
|
||||
}
|
||||
|
||||
public function test_update_validates_required_subject_ko(): void
|
||||
{
|
||||
$template = MailTemplate::factory()->withType('welcome')->create();
|
||||
|
||||
$response = $this->authRequest()->putJson("/api/admin/mail-templates/{$template->id}", [
|
||||
'subject' => ['en' => 'Only English'],
|
||||
'body' => ['ko' => '<p>본문</p>'],
|
||||
]);
|
||||
|
||||
$response->assertStatus(422)
|
||||
->assertJsonValidationErrors(['subject.ko']);
|
||||
}
|
||||
|
||||
public function test_update_validates_required_body_ko(): void
|
||||
{
|
||||
$template = MailTemplate::factory()->withType('welcome')->create();
|
||||
|
||||
$response = $this->authRequest()->putJson("/api/admin/mail-templates/{$template->id}", [
|
||||
'subject' => ['ko' => '제목'],
|
||||
'body' => ['en' => '<p>English only</p>'],
|
||||
]);
|
||||
|
||||
$response->assertStatus(422)
|
||||
->assertJsonValidationErrors(['body.ko']);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// toggleActive
|
||||
// ========================================================================
|
||||
|
||||
public function test_toggle_active_flips_state(): void
|
||||
{
|
||||
$template = MailTemplate::factory()->create(['is_active' => true]);
|
||||
|
||||
$response = $this->authRequest()->patchJson("/api/admin/mail-templates/{$template->id}/toggle-active");
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('success', true);
|
||||
|
||||
$template->refresh();
|
||||
$this->assertFalse($template->is_active);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// preview
|
||||
// ========================================================================
|
||||
|
||||
public function test_preview_returns_rendered_result(): void
|
||||
{
|
||||
$response = $this->authRequest()->postJson('/api/admin/mail-templates/preview', [
|
||||
'subject' => 'Hello {name}',
|
||||
'body' => '<p>Welcome to {app_name}</p>',
|
||||
'variables' => [
|
||||
['key' => 'name'],
|
||||
['key' => 'app_name'],
|
||||
],
|
||||
]);
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('success', true)
|
||||
->assertJsonStructure(['data' => ['subject', 'body']]);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// reset
|
||||
// ========================================================================
|
||||
|
||||
public function test_reset_restores_default_data(): void
|
||||
{
|
||||
$template = MailTemplate::factory()->withType('welcome')->create([
|
||||
'subject' => ['ko' => '사용자 수정'],
|
||||
'body' => ['ko' => '<p>수정됨</p>'],
|
||||
'is_default' => false,
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->postJson("/api/admin/mail-templates/{$template->id}/reset");
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('success', true);
|
||||
|
||||
$template->refresh();
|
||||
$this->assertTrue($template->is_default);
|
||||
}
|
||||
|
||||
public function test_reset_returns_404_for_unknown_type(): void
|
||||
{
|
||||
$template = MailTemplate::factory()->withType('nonexistent_type')->create();
|
||||
|
||||
$response = $this->authRequest()->postJson("/api/admin/mail-templates/{$template->id}/reset");
|
||||
|
||||
$response->assertStatus(404);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Http\Requests\Module\InstallModuleRequest;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 모듈 설치 API 의 vendor_mode 파라미터 검증.
|
||||
*
|
||||
* `POST /api/admin/modules/install` 엔드포인트가 `vendor_mode` 를 올바르게 받아
|
||||
* FormRequest 검증을 통과하고, Service 레이어로 전달하는지 검증한다.
|
||||
*
|
||||
* 실제 모듈 설치는 마이그레이션/composer install 등 사이드 이펙트가 크므로
|
||||
* FormRequest 규칙 검증 + 컨트롤러 파라미터 수신만 격리 검증한다.
|
||||
*/
|
||||
class ModuleInstallWithVendorModeTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_install_request_accepts_valid_vendor_modes(): void
|
||||
{
|
||||
foreach (['auto', 'composer', 'bundled'] as $mode) {
|
||||
$request = new InstallModuleRequest;
|
||||
$request->replace([
|
||||
'module_name' => 'test-valid-module',
|
||||
'vendor_mode' => $mode,
|
||||
]);
|
||||
$request->setContainer($this->app);
|
||||
|
||||
$validator = \Validator::make($request->all(), $request->rules());
|
||||
|
||||
$this->assertTrue(
|
||||
$validator->passes() || ! in_array('vendor_mode', array_keys($validator->failed()), true),
|
||||
"vendor_mode={$mode} 는 유효해야 합니다"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_install_request_rejects_invalid_vendor_mode(): void
|
||||
{
|
||||
$request = new InstallModuleRequest;
|
||||
$request->replace([
|
||||
'module_name' => 'test-module',
|
||||
'vendor_mode' => 'invalid-mode',
|
||||
]);
|
||||
$request->setContainer($this->app);
|
||||
|
||||
$validator = \Validator::make($request->all(), $request->rules());
|
||||
|
||||
$this->assertTrue($validator->fails());
|
||||
$this->assertArrayHasKey('vendor_mode', $validator->errors()->toArray());
|
||||
}
|
||||
|
||||
public function test_install_request_allows_nullable_vendor_mode(): void
|
||||
{
|
||||
// vendor_mode 를 생략해도 검증 통과 — 기본값 auto 사용
|
||||
$request = new InstallModuleRequest;
|
||||
$request->replace(['module_name' => 'test-module']);
|
||||
$request->setContainer($this->app);
|
||||
|
||||
$validator = \Validator::make($request->all(), $request->rules());
|
||||
|
||||
$failed = $validator->failed();
|
||||
$this->assertArrayNotHasKey('vendor_mode', $failed);
|
||||
}
|
||||
|
||||
public function test_module_service_install_signature_accepts_vendor_mode(): void
|
||||
{
|
||||
$reflection = new \ReflectionClass(\App\Services\ModuleService::class);
|
||||
$method = $reflection->getMethod('installModule');
|
||||
$params = $method->getParameters();
|
||||
|
||||
$vendorParam = collect($params)->first(fn ($p) => $p->getName() === 'vendorMode');
|
||||
$this->assertNotNull($vendorParam, 'ModuleService::installModule 에 vendorMode 파라미터가 있어야 합니다');
|
||||
$this->assertSame(
|
||||
\App\Extension\Vendor\VendorMode::class,
|
||||
$vendorParam->getType()?->getName()
|
||||
);
|
||||
}
|
||||
|
||||
public function test_module_service_update_signature_accepts_vendor_mode(): void
|
||||
{
|
||||
$reflection = new \ReflectionClass(\App\Services\ModuleService::class);
|
||||
$method = $reflection->getMethod('updateModule');
|
||||
$params = $method->getParameters();
|
||||
|
||||
$vendorParam = collect($params)->first(fn ($p) => $p->getName() === 'vendorMode');
|
||||
$this->assertNotNull($vendorParam, 'ModuleService::updateModule 에 vendorMode 파라미터가 있어야 합니다');
|
||||
}
|
||||
|
||||
public function test_vendor_mode_from_request_input_parses_correctly(): void
|
||||
{
|
||||
// Controller 측에서 VendorMode::fromStringOrAuto() 사용 — 그 동작 검증
|
||||
$this->assertSame(
|
||||
\App\Extension\Vendor\VendorMode::Auto,
|
||||
\App\Extension\Vendor\VendorMode::fromStringOrAuto(null)
|
||||
);
|
||||
$this->assertSame(
|
||||
\App\Extension\Vendor\VendorMode::Auto,
|
||||
\App\Extension\Vendor\VendorMode::fromStringOrAuto('')
|
||||
);
|
||||
$this->assertSame(
|
||||
\App\Extension\Vendor\VendorMode::Composer,
|
||||
\App\Extension\Vendor\VendorMode::fromStringOrAuto('composer')
|
||||
);
|
||||
$this->assertSame(
|
||||
\App\Extension\Vendor\VendorMode::Bundled,
|
||||
\App\Extension\Vendor\VendorMode::fromStringOrAuto('bundled')
|
||||
);
|
||||
// 유효하지 않은 값은 Auto 로 폴백
|
||||
$this->assertSame(
|
||||
\App\Extension\Vendor\VendorMode::Auto,
|
||||
\App\Extension\Vendor\VendorMode::fromStringOrAuto('invalid')
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -229,7 +229,7 @@ class ModuleUpdateTest extends TestCase
|
||||
{
|
||||
$mockService = Mockery::mock(ModuleService::class);
|
||||
$mockService->shouldReceive('updateModule')
|
||||
->with('test-module')
|
||||
->with('test-module', Mockery::any(), 'overwrite')
|
||||
->once()
|
||||
->andReturn([
|
||||
'success' => true,
|
||||
@@ -288,7 +288,7 @@ class ModuleUpdateTest extends TestCase
|
||||
{
|
||||
$mockService = Mockery::mock(ModuleService::class);
|
||||
$mockService->shouldReceive('updateModule')
|
||||
->with('test-module')
|
||||
->with('test-module', Mockery::any(), 'overwrite')
|
||||
->once()
|
||||
->andReturn([
|
||||
'success' => true,
|
||||
@@ -332,7 +332,7 @@ class ModuleUpdateTest extends TestCase
|
||||
{
|
||||
$mockService = Mockery::mock(ModuleService::class);
|
||||
$mockService->shouldReceive('updateModule')
|
||||
->with('nonexistent-module')
|
||||
->with('nonexistent-module', Mockery::any(), 'overwrite')
|
||||
->once()
|
||||
->andThrow(
|
||||
ValidationException::withMessages([
|
||||
@@ -353,7 +353,7 @@ class ModuleUpdateTest extends TestCase
|
||||
{
|
||||
$mockService = Mockery::mock(ModuleService::class);
|
||||
$mockService->shouldReceive('updateModule')
|
||||
->with('test-module')
|
||||
->with('test-module', Mockery::any(), 'overwrite')
|
||||
->once()
|
||||
->andThrow(new \RuntimeException('Unexpected error'));
|
||||
$this->app->instance(ModuleService::class, $mockService);
|
||||
@@ -404,4 +404,96 @@ class ModuleUpdateTest extends TestCase
|
||||
'Route api.admin.modules.update should exist'
|
||||
);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// layout_strategy 파라미터 전달 검증
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* performUpdate 가 layout_strategy='keep' 을 Service 에 전달하는지 확인
|
||||
*/
|
||||
public function test_perform_update_sends_layout_strategy_keep_to_service(): void
|
||||
{
|
||||
$mockService = Mockery::mock(ModuleService::class);
|
||||
$mockService->shouldReceive('updateModule')
|
||||
->with('test-module', Mockery::any(), 'keep')
|
||||
->once()
|
||||
->andReturn([
|
||||
'success' => true,
|
||||
'from_version' => '1.0.0',
|
||||
'to_version' => '2.0.0',
|
||||
'module_info' => null,
|
||||
]);
|
||||
$this->app->instance(ModuleService::class, $mockService);
|
||||
|
||||
$response = $this->authRequest()->postJson('/api/admin/modules/test-module/update', [
|
||||
'layout_strategy' => 'keep',
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* performUpdate 는 유효하지 않은 layout_strategy 를 거부 (422)
|
||||
*/
|
||||
public function test_perform_update_rejects_invalid_layout_strategy(): void
|
||||
{
|
||||
$response = $this->authRequest()->postJson('/api/admin/modules/test-module/update', [
|
||||
'layout_strategy' => 'garbage',
|
||||
]);
|
||||
|
||||
$response->assertStatus(422);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// checkModifiedLayouts 엔드포인트 테스트
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* checkModifiedLayouts 는 Service 결과를 그대로 반환한다
|
||||
*/
|
||||
public function test_check_modified_layouts_returns_result_from_service(): void
|
||||
{
|
||||
$mockService = Mockery::mock(ModuleService::class);
|
||||
$mockService->shouldReceive('checkModifiedLayouts')
|
||||
->with('test-module')
|
||||
->once()
|
||||
->andReturn([
|
||||
'has_modified_layouts' => true,
|
||||
'modified_count' => 2,
|
||||
'modified_layouts' => [
|
||||
['id' => 1, 'name' => 'test-module.home', 'updated_at' => '2026-04-19 10:00:00', 'size_diff' => 128],
|
||||
['id' => 2, 'name' => 'test-module.list', 'updated_at' => '2026-04-19 10:05:00', 'size_diff' => -64],
|
||||
],
|
||||
]);
|
||||
$this->app->instance(ModuleService::class, $mockService);
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/modules/test-module/check-modified-layouts');
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('success', true)
|
||||
->assertJsonPath('data.has_modified_layouts', true)
|
||||
->assertJsonPath('data.modified_count', 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* checkModifiedLayouts 는 인증이 없으면 401 반환
|
||||
*/
|
||||
public function test_check_modified_layouts_returns_401_without_authentication(): void
|
||||
{
|
||||
$response = $this->getJson('/api/admin/modules/test-module/check-modified-layouts');
|
||||
|
||||
$response->assertStatus(401);
|
||||
}
|
||||
|
||||
/**
|
||||
* check-modified-layouts 라우트 네임 확인
|
||||
*/
|
||||
public function test_check_modified_layouts_route_name_exists(): void
|
||||
{
|
||||
$this->assertTrue(
|
||||
\Illuminate\Support\Facades\Route::has('api.admin.modules.check-modified-layouts'),
|
||||
'Route api.admin.modules.check-modified-layouts should exist'
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 알림 채널 API 컨트롤러 테스트
|
||||
*/
|
||||
class NotificationChannelControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $admin;
|
||||
|
||||
private string $token;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->admin = $this->createAdminWithPermissions();
|
||||
$this->token = $this->admin->createToken('test-token')->plainTextToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* 채널 목록이 기본 채널(mail, database)을 포함하는지 확인
|
||||
*/
|
||||
public function test_index_returns_default_channels(): void
|
||||
{
|
||||
$response = $this->authRequest()->getJson('/api/admin/notification-channels');
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('success', true);
|
||||
|
||||
$channels = $response->json('data.channels');
|
||||
$channelIds = array_column($channels, 'id');
|
||||
|
||||
$this->assertContains('mail', $channelIds);
|
||||
$this->assertContains('database', $channelIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* 각 채널에 id, name, icon이 포함되는지 확인
|
||||
*/
|
||||
public function test_channels_have_required_fields(): void
|
||||
{
|
||||
$response = $this->authRequest()->getJson('/api/admin/notification-channels');
|
||||
|
||||
$channels = $response->json('data.channels');
|
||||
|
||||
foreach ($channels as $channel) {
|
||||
$this->assertArrayHasKey('id', $channel);
|
||||
$this->assertArrayHasKey('name', $channel);
|
||||
$this->assertArrayHasKey('icon', $channel);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 비인증 사용자 접근 거부
|
||||
*/
|
||||
public function test_unauthenticated_returns_401(): void
|
||||
{
|
||||
$response = $this->getJson('/api/admin/notification-channels');
|
||||
|
||||
$response->assertStatus(401);
|
||||
}
|
||||
|
||||
/**
|
||||
* 인증된 요청 헬퍼.
|
||||
*
|
||||
* @return static
|
||||
*/
|
||||
private function authRequest(): static
|
||||
{
|
||||
return $this->withHeaders([
|
||||
'Authorization' => 'Bearer ' . $this->token,
|
||||
'Accept' => 'application/json',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자 생성 헬퍼.
|
||||
*
|
||||
* @return User
|
||||
*/
|
||||
private function createAdminWithPermissions(): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$role = Role::create([
|
||||
'name' => ['ko' => '최고관리자'],
|
||||
'identifier' => 'super_admin',
|
||||
'is_admin' => true,
|
||||
]);
|
||||
|
||||
$perm = Permission::firstOrCreate(
|
||||
['identifier' => 'core.settings.read'],
|
||||
['name' => ['ko' => '환경설정 조회'], 'type' => 'admin', 'order' => 1]
|
||||
);
|
||||
$role->permissions()->attach($perm->id);
|
||||
$user->roles()->attach($role->id);
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Models\NotificationDefinition;
|
||||
use App\Models\NotificationTemplate;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 관리자 알림 정의 API 테스트
|
||||
*/
|
||||
class NotificationDefinitionControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $admin;
|
||||
|
||||
private string $token;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->admin = $this->createAdminWithPermissions();
|
||||
$this->token = $this->admin->createToken('test-token')->plainTextToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록 조회 성공 — pagination + abilities 포함
|
||||
*/
|
||||
public function test_index_returns_definitions_with_pagination_and_abilities(): void
|
||||
{
|
||||
NotificationDefinition::create([
|
||||
'type' => 'welcome',
|
||||
'hook_prefix' => 'core.auth',
|
||||
'extension_type' => 'core',
|
||||
'extension_identifier' => 'core',
|
||||
'name' => ['ko' => '환영', 'en' => 'Welcome'],
|
||||
'channels' => ['mail'],
|
||||
'hooks' => ['core.auth.after_register'],
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/notification-definitions');
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('success', true)
|
||||
->assertJsonStructure([
|
||||
'data' => [
|
||||
'data' => [['id', 'type', 'name', 'channels', 'is_active']],
|
||||
'pagination' => ['current_page', 'last_page', 'total'],
|
||||
'abilities' => ['can_update'],
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록 조회 — templates 없는 definition은 빈 배열 반환 (json 직렬화 에러 없음)
|
||||
*/
|
||||
public function test_index_serializes_with_empty_templates(): void
|
||||
{
|
||||
NotificationDefinition::create([
|
||||
'type' => 'test_no_templates',
|
||||
'hook_prefix' => 'core',
|
||||
'extension_type' => 'core',
|
||||
'extension_identifier' => 'core',
|
||||
'name' => ['ko' => '테스트'],
|
||||
'channels' => ['mail'],
|
||||
'hooks' => [],
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/notification-definitions');
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('data.data.0.templates', []);
|
||||
}
|
||||
|
||||
/**
|
||||
* 상세 조회 — templates 관계 로드됨
|
||||
*/
|
||||
public function test_show_returns_definition_with_templates(): void
|
||||
{
|
||||
$definition = NotificationDefinition::create([
|
||||
'type' => 'welcome',
|
||||
'hook_prefix' => 'core.auth',
|
||||
'extension_type' => 'core',
|
||||
'extension_identifier' => 'core',
|
||||
'name' => ['ko' => '환영', 'en' => 'Welcome'],
|
||||
'channels' => ['mail'],
|
||||
'hooks' => ['core.auth.after_register'],
|
||||
]);
|
||||
|
||||
NotificationTemplate::create([
|
||||
'definition_id' => $definition->id,
|
||||
'channel' => 'mail',
|
||||
'subject' => ['ko' => '환영합니다', 'en' => 'Welcome'],
|
||||
'body' => ['ko' => '본문', 'en' => 'Body'],
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->getJson("/api/admin/notification-definitions/{$definition->id}");
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('data.type', 'welcome')
|
||||
->assertJsonStructure([
|
||||
'data' => ['id', 'type', 'name', 'templates'],
|
||||
]);
|
||||
|
||||
$this->assertNotNull($response->json('data.templates'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성/비활성 토글
|
||||
*/
|
||||
public function test_toggle_active(): void
|
||||
{
|
||||
$definition = NotificationDefinition::create([
|
||||
'type' => 'test_toggle',
|
||||
'hook_prefix' => 'core',
|
||||
'extension_type' => 'core',
|
||||
'extension_identifier' => 'core',
|
||||
'name' => ['ko' => '토글 테스트'],
|
||||
'channels' => ['mail'],
|
||||
'hooks' => [],
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->patchJson("/api/admin/notification-definitions/{$definition->id}/toggle-active");
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertFalse($definition->fresh()->is_active);
|
||||
}
|
||||
|
||||
/**
|
||||
* 정의 리셋 — 소속 템플릿 일괄 기본값 복원 + 정의도 기본 상태로 복구
|
||||
*/
|
||||
public function test_reset_restores_all_templates_to_defaults(): void
|
||||
{
|
||||
$definition = NotificationDefinition::create([
|
||||
'type' => 'welcome',
|
||||
'hook_prefix' => 'core.auth',
|
||||
'extension_type' => 'core',
|
||||
'extension_identifier' => 'core',
|
||||
'name' => ['ko' => '환영'],
|
||||
'channels' => ['mail'],
|
||||
'hooks' => ['core.auth.after_register'],
|
||||
'is_default' => false,
|
||||
]);
|
||||
|
||||
$template = NotificationTemplate::create([
|
||||
'definition_id' => $definition->id,
|
||||
'channel' => 'mail',
|
||||
'subject' => ['ko' => '커스터마이징된 제목'],
|
||||
'body' => ['ko' => '커스터마이징된 본문'],
|
||||
'is_default' => false,
|
||||
'user_overrides' => ['subject' => true],
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->postJson("/api/admin/notification-definitions/{$definition->id}/reset");
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('success', true);
|
||||
|
||||
$this->assertTrue($definition->fresh()->is_default, '리셋 후 정의는 기본 상태로 복구되어야 함');
|
||||
$this->assertTrue($template->fresh()->is_default, '리셋 후 템플릿도 기본 상태로 복구되어야 함');
|
||||
}
|
||||
|
||||
/**
|
||||
* 정의 리셋 — 권한 없는 사용자 403
|
||||
*/
|
||||
public function test_reset_requires_settings_update_permission(): void
|
||||
{
|
||||
$definition = NotificationDefinition::create([
|
||||
'type' => 'test_reset_perm',
|
||||
'hook_prefix' => 'core',
|
||||
'extension_type' => 'core',
|
||||
'extension_identifier' => 'core',
|
||||
'name' => ['ko' => '테스트'],
|
||||
'channels' => ['mail'],
|
||||
'hooks' => [],
|
||||
]);
|
||||
|
||||
$user = User::factory()->create();
|
||||
$role = Role::create(['name' => ['ko' => '일반'], 'identifier' => 'user_reset_test']);
|
||||
$user->roles()->attach($role->id);
|
||||
$token = $user->createToken('test')->plainTextToken;
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$token,
|
||||
'Accept' => 'application/json',
|
||||
])->postJson("/api/admin/notification-definitions/{$definition->id}/reset");
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
/**
|
||||
* 권한 없는 사용자 — 403
|
||||
*/
|
||||
public function test_index_requires_settings_read_permission(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$role = Role::create(['name' => ['ko' => '일반'], 'identifier' => 'user_basic']);
|
||||
$user->roles()->attach($role->id);
|
||||
$token = $user->createToken('test')->plainTextToken;
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer ' . $token,
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/notification-definitions');
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
/**
|
||||
* 인증된 요청 헬퍼.
|
||||
*
|
||||
* @return static
|
||||
*/
|
||||
private function authRequest(): static
|
||||
{
|
||||
return $this->withHeaders([
|
||||
'Authorization' => 'Bearer ' . $this->token,
|
||||
'Accept' => 'application/json',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자 생성 헬퍼.
|
||||
*
|
||||
* @return User
|
||||
*/
|
||||
private function createAdminWithPermissions(): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$role = Role::create([
|
||||
'name' => ['ko' => '최고관리자'],
|
||||
'identifier' => 'super_admin',
|
||||
'is_admin' => true,
|
||||
]);
|
||||
|
||||
foreach (['core.settings.read', 'core.settings.update'] as $identifier) {
|
||||
$perm = Permission::firstOrCreate(
|
||||
['identifier' => $identifier],
|
||||
['name' => ['ko' => $identifier], 'type' => 'admin', 'order' => 1]
|
||||
);
|
||||
$role->permissions()->attach($perm->id);
|
||||
}
|
||||
|
||||
$user->roles()->attach($role->id);
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Models\NotificationLog;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 관리자 알림 발송 이력 API 테스트
|
||||
*/
|
||||
class NotificationLogControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $admin;
|
||||
|
||||
private string $token;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->admin = $this->createAdminWithPermissions();
|
||||
$this->token = $this->admin->createToken('test-token')->plainTextToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록 조회 성공 — abilities 포함
|
||||
*/
|
||||
public function test_index_returns_notification_logs_with_abilities(): void
|
||||
{
|
||||
NotificationLog::create([
|
||||
'channel' => 'mail',
|
||||
'notification_type' => 'welcome',
|
||||
'recipient_identifier' => 'test@example.com',
|
||||
'status' => 'sent',
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/notification-logs');
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('success', true)
|
||||
->assertJsonStructure([
|
||||
'data' => [
|
||||
'data',
|
||||
'pagination',
|
||||
'abilities' => ['can_delete'],
|
||||
],
|
||||
])
|
||||
->assertJsonPath('data.abilities.can_delete', true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 채널 필터 적용
|
||||
*/
|
||||
public function test_index_filters_by_channel(): void
|
||||
{
|
||||
NotificationLog::create(['channel' => 'mail', 'notification_type' => 'test', 'recipient_identifier' => 'a@test.com', 'status' => 'sent']);
|
||||
NotificationLog::create(['channel' => 'database', 'notification_type' => 'test', 'recipient_identifier' => '1', 'status' => 'sent']);
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/notification-logs?channel=mail');
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('data.pagination.total', 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 단건 삭제
|
||||
*/
|
||||
public function test_destroy_deletes_log(): void
|
||||
{
|
||||
$log = NotificationLog::create([
|
||||
'channel' => 'mail',
|
||||
'notification_type' => 'test',
|
||||
'recipient_identifier' => 'test@example.com',
|
||||
'status' => 'sent',
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->deleteJson("/api/admin/notification-logs/{$log->id}");
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('success', true);
|
||||
|
||||
$this->assertDatabaseMissing('notification_logs', ['id' => $log->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 다건 삭제
|
||||
*/
|
||||
public function test_bulk_destroy(): void
|
||||
{
|
||||
$log1 = NotificationLog::create(['channel' => 'mail', 'notification_type' => 'test', 'recipient_identifier' => 'a@test.com', 'status' => 'sent']);
|
||||
$log2 = NotificationLog::create(['channel' => 'mail', 'notification_type' => 'test', 'recipient_identifier' => 'b@test.com', 'status' => 'sent']);
|
||||
|
||||
$response = $this->authRequest()->postJson('/api/admin/notification-logs/bulk-delete', [
|
||||
'ids' => [$log1->id, $log2->id],
|
||||
]);
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('data.deleted_count', 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* 인증된 요청 헬퍼.
|
||||
*
|
||||
* @return static
|
||||
*/
|
||||
private function authRequest(): static
|
||||
{
|
||||
return $this->withHeaders([
|
||||
'Authorization' => 'Bearer ' . $this->token,
|
||||
'Accept' => 'application/json',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자 생성 헬퍼.
|
||||
*
|
||||
* @return User
|
||||
*/
|
||||
private function createAdminWithPermissions(): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$role = Role::create([
|
||||
'name' => ['ko' => '최고관리자'],
|
||||
'identifier' => 'super_admin',
|
||||
'is_admin' => true,
|
||||
]);
|
||||
|
||||
foreach (['core.notification-logs.read', 'core.notification-logs.delete'] as $identifier) {
|
||||
$perm = Permission::firstOrCreate(
|
||||
['identifier' => $identifier],
|
||||
['name' => ['ko' => $identifier], 'type' => 'admin', 'order' => 1]
|
||||
);
|
||||
$role->permissions()->attach($perm->id);
|
||||
}
|
||||
|
||||
$user->roles()->attach($role->id);
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Models\NotificationDefinition;
|
||||
use App\Models\NotificationTemplate;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 관리자 알림 템플릿 API 테스트
|
||||
*/
|
||||
class NotificationTemplateControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $admin;
|
||||
|
||||
private string $token;
|
||||
|
||||
private NotificationDefinition $definition;
|
||||
|
||||
private NotificationTemplate $template;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->admin = $this->createAdminWithPermissions();
|
||||
$this->token = $this->admin->createToken('test-token')->plainTextToken;
|
||||
|
||||
$this->definition = NotificationDefinition::create([
|
||||
'type' => 'welcome',
|
||||
'hook_prefix' => 'core.auth',
|
||||
'extension_type' => 'core',
|
||||
'extension_identifier' => 'core',
|
||||
'name' => ['ko' => '환영', 'en' => 'Welcome'],
|
||||
'channels' => ['mail'],
|
||||
'hooks' => ['core.auth.after_register'],
|
||||
]);
|
||||
|
||||
$this->template = NotificationTemplate::create([
|
||||
'definition_id' => $this->definition->id,
|
||||
'channel' => 'mail',
|
||||
'subject' => ['ko' => '환영합니다', 'en' => 'Welcome'],
|
||||
'body' => ['ko' => '<p>안녕하세요</p>', 'en' => '<p>Hello</p>'],
|
||||
'is_active' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 수정 성공
|
||||
*/
|
||||
public function test_update_template(): void
|
||||
{
|
||||
$response = $this->authRequest()->putJson("/api/admin/notification-templates/{$this->template->id}", [
|
||||
'subject' => ['ko' => '수정된 제목', 'en' => 'Updated Subject'],
|
||||
'body' => ['ko' => '<p>수정됨</p>', 'en' => '<p>Updated</p>'],
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('success', true);
|
||||
|
||||
$this->assertEquals('수정된 제목', $this->template->fresh()->subject['ko']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 편집 시 Template.is_default + Definition.is_default 모두 false로 전환
|
||||
* (리셋 버튼 노출 근거)
|
||||
*/
|
||||
public function test_update_template_marks_template_and_definition_as_customized(): void
|
||||
{
|
||||
// 초기 상태: 템플릿·정의 모두 기본 상태
|
||||
$this->template->update(['is_default' => true]);
|
||||
$this->template->definition->update(['is_default' => true]);
|
||||
|
||||
$response = $this->authRequest()->putJson("/api/admin/notification-templates/{$this->template->id}", [
|
||||
'subject' => ['ko' => '커스텀 제목', 'en' => 'Custom'],
|
||||
'body' => ['ko' => '본문', 'en' => 'Body'],
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
$this->assertFalse($this->template->fresh()->is_default, '템플릿이 커스터마이징 상태로 전환되어야 함');
|
||||
$this->assertFalse($this->template->definition->fresh()->is_default, '정의도 커스터마이징 상태로 전환되어야 함');
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성/비활성 토글
|
||||
*/
|
||||
public function test_toggle_active(): void
|
||||
{
|
||||
$response = $this->authRequest()->patchJson("/api/admin/notification-templates/{$this->template->id}/toggle-active");
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertFalse($this->template->fresh()->is_active);
|
||||
}
|
||||
|
||||
/**
|
||||
* 기본값 복원
|
||||
*/
|
||||
public function test_reset_template(): void
|
||||
{
|
||||
$this->template->update([
|
||||
'subject' => ['ko' => '사용자 수정본'],
|
||||
'is_default' => false,
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->postJson("/api/admin/notification-templates/{$this->template->id}/reset");
|
||||
|
||||
$response->assertStatus(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* 미리보기 성공 — definition_id로 변수 조회 후 치환
|
||||
*/
|
||||
public function test_preview_template(): void
|
||||
{
|
||||
$this->definition->update([
|
||||
'variables' => [
|
||||
['key' => 'name', 'description' => '수신자 이름'],
|
||||
['key' => 'app_name', 'description' => '사이트명'],
|
||||
],
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->postJson('/api/admin/notification-templates/preview', [
|
||||
'definition_id' => $this->definition->id,
|
||||
'subject' => ['ko' => '[{app_name}] 환영합니다', 'en' => '[{app_name}] Welcome'],
|
||||
'body' => ['ko' => '<p>{name}님 환영합니다</p>', 'en' => '<p>Welcome {name}</p>'],
|
||||
'locale' => 'ko',
|
||||
]);
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('success', true);
|
||||
|
||||
$data = $response->json('data');
|
||||
$this->assertStringContainsString('[사이트명]', $data['subject']);
|
||||
$this->assertStringContainsString('[수신자 이름]', $data['body']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 미리보기 — definition_id 누락 시 422 검증 실패
|
||||
*/
|
||||
public function test_preview_requires_definition_id(): void
|
||||
{
|
||||
$response = $this->authRequest()->postJson('/api/admin/notification-templates/preview', [
|
||||
'subject' => ['ko' => '제목'],
|
||||
'body' => ['ko' => '<p>본문</p>'],
|
||||
]);
|
||||
|
||||
$response->assertStatus(422);
|
||||
}
|
||||
|
||||
/**
|
||||
* 권한 없는 사용자 — 403
|
||||
*/
|
||||
public function test_update_requires_settings_update_permission(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$role = Role::create(['name' => ['ko' => '읽기전용'], 'identifier' => 'readonly']);
|
||||
$readPerm = Permission::firstOrCreate(
|
||||
['identifier' => 'core.settings.read'],
|
||||
['name' => ['ko' => '설정 조회'], 'type' => 'admin', 'order' => 1]
|
||||
);
|
||||
$role->permissions()->attach($readPerm->id);
|
||||
$user->roles()->attach($role->id);
|
||||
$token = $user->createToken('test')->plainTextToken;
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer ' . $token,
|
||||
'Accept' => 'application/json',
|
||||
])->putJson("/api/admin/notification-templates/{$this->template->id}", [
|
||||
'subject' => ['ko' => '변경 시도'],
|
||||
'body' => ['ko' => '<p>변경</p>'],
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
/**
|
||||
* 인증된 요청 헬퍼.
|
||||
*
|
||||
* @return static
|
||||
*/
|
||||
private function authRequest(): static
|
||||
{
|
||||
return $this->withHeaders([
|
||||
'Authorization' => 'Bearer ' . $this->token,
|
||||
'Accept' => 'application/json',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자 생성 헬퍼.
|
||||
*
|
||||
* @return User
|
||||
*/
|
||||
private function createAdminWithPermissions(): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$role = Role::create([
|
||||
'name' => ['ko' => '최고관리자'],
|
||||
'identifier' => 'super_admin',
|
||||
'is_admin' => true,
|
||||
]);
|
||||
|
||||
foreach (['core.settings.read', 'core.settings.update'] as $identifier) {
|
||||
$perm = Permission::firstOrCreate(
|
||||
['identifier' => $identifier],
|
||||
['name' => ['ko' => $identifier], 'type' => 'admin', 'order' => 1]
|
||||
);
|
||||
$role->permissions()->attach($perm->id);
|
||||
}
|
||||
|
||||
$user->roles()->attach($role->id);
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Http\Requests\Plugin\InstallPluginRequest;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 플러그인 설치 API 의 vendor_mode 파라미터 검증.
|
||||
*
|
||||
* `POST /api/admin/plugins/install` 엔드포인트가 `vendor_mode` 를 올바르게 받아
|
||||
* FormRequest 검증을 통과하고, Service 레이어로 전달하는지 검증한다.
|
||||
*/
|
||||
class PluginInstallWithVendorModeTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_install_request_accepts_valid_vendor_modes(): void
|
||||
{
|
||||
foreach (['auto', 'composer', 'bundled'] as $mode) {
|
||||
$request = new InstallPluginRequest;
|
||||
$request->replace([
|
||||
'plugin_name' => 'test-valid-plugin',
|
||||
'vendor_mode' => $mode,
|
||||
]);
|
||||
$request->setContainer($this->app);
|
||||
|
||||
$validator = \Validator::make($request->all(), $request->rules());
|
||||
|
||||
$this->assertTrue(
|
||||
$validator->passes() || ! in_array('vendor_mode', array_keys($validator->failed()), true),
|
||||
"vendor_mode={$mode} 는 유효해야 합니다"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_install_request_rejects_invalid_vendor_mode(): void
|
||||
{
|
||||
$request = new InstallPluginRequest;
|
||||
$request->replace([
|
||||
'plugin_name' => 'test-plugin',
|
||||
'vendor_mode' => 'invalid-mode',
|
||||
]);
|
||||
$request->setContainer($this->app);
|
||||
|
||||
$validator = \Validator::make($request->all(), $request->rules());
|
||||
|
||||
$this->assertTrue($validator->fails());
|
||||
$this->assertArrayHasKey('vendor_mode', $validator->errors()->toArray());
|
||||
}
|
||||
|
||||
public function test_install_request_allows_nullable_vendor_mode(): void
|
||||
{
|
||||
$request = new InstallPluginRequest;
|
||||
$request->replace(['plugin_name' => 'test-plugin']);
|
||||
$request->setContainer($this->app);
|
||||
|
||||
$validator = \Validator::make($request->all(), $request->rules());
|
||||
|
||||
$failed = $validator->failed();
|
||||
$this->assertArrayNotHasKey('vendor_mode', $failed);
|
||||
}
|
||||
|
||||
public function test_plugin_service_install_signature_accepts_vendor_mode(): void
|
||||
{
|
||||
$reflection = new \ReflectionClass(\App\Services\PluginService::class);
|
||||
$method = $reflection->getMethod('installPlugin');
|
||||
$params = $method->getParameters();
|
||||
|
||||
$vendorParam = collect($params)->first(fn ($p) => $p->getName() === 'vendorMode');
|
||||
$this->assertNotNull($vendorParam, 'PluginService::installPlugin 에 vendorMode 파라미터가 있어야 합니다');
|
||||
$this->assertSame(
|
||||
\App\Extension\Vendor\VendorMode::class,
|
||||
$vendorParam->getType()?->getName()
|
||||
);
|
||||
}
|
||||
|
||||
public function test_plugin_service_update_signature_accepts_vendor_mode(): void
|
||||
{
|
||||
$reflection = new \ReflectionClass(\App\Services\PluginService::class);
|
||||
$method = $reflection->getMethod('updatePlugin');
|
||||
$params = $method->getParameters();
|
||||
|
||||
$vendorParam = collect($params)->first(fn ($p) => $p->getName() === 'vendorMode');
|
||||
$this->assertNotNull($vendorParam, 'PluginService::updatePlugin 에 vendorMode 파라미터가 있어야 합니다');
|
||||
}
|
||||
|
||||
public function test_plugin_controller_install_method_reads_vendor_mode_from_request(): void
|
||||
{
|
||||
// PluginController::install() 메서드가 $request->validated()['vendor_mode'] 를 참조하는지 확인
|
||||
$file = file_get_contents(base_path('app/Http/Controllers/Api/Admin/PluginController.php'));
|
||||
$this->assertStringContainsString("VendorMode::fromStringOrAuto", $file);
|
||||
$this->assertStringContainsString("vendor_mode", $file);
|
||||
}
|
||||
}
|
||||
@@ -229,7 +229,7 @@ class PluginUpdateTest extends TestCase
|
||||
{
|
||||
$mockService = Mockery::mock(PluginService::class);
|
||||
$mockService->shouldReceive('updatePlugin')
|
||||
->with('test-plugin')
|
||||
->with('test-plugin', Mockery::any(), 'overwrite')
|
||||
->once()
|
||||
->andReturn([
|
||||
'success' => true,
|
||||
@@ -288,7 +288,7 @@ class PluginUpdateTest extends TestCase
|
||||
{
|
||||
$mockService = Mockery::mock(PluginService::class);
|
||||
$mockService->shouldReceive('updatePlugin')
|
||||
->with('test-plugin')
|
||||
->with('test-plugin', Mockery::any(), 'overwrite')
|
||||
->once()
|
||||
->andReturn([
|
||||
'success' => true,
|
||||
@@ -332,7 +332,7 @@ class PluginUpdateTest extends TestCase
|
||||
{
|
||||
$mockService = Mockery::mock(PluginService::class);
|
||||
$mockService->shouldReceive('updatePlugin')
|
||||
->with('nonexistent-plugin')
|
||||
->with('nonexistent-plugin', Mockery::any(), 'overwrite')
|
||||
->once()
|
||||
->andThrow(
|
||||
ValidationException::withMessages([
|
||||
@@ -353,7 +353,7 @@ class PluginUpdateTest extends TestCase
|
||||
{
|
||||
$mockService = Mockery::mock(PluginService::class);
|
||||
$mockService->shouldReceive('updatePlugin')
|
||||
->with('test-plugin')
|
||||
->with('test-plugin', Mockery::any(), 'overwrite')
|
||||
->once()
|
||||
->andThrow(new \RuntimeException('Unexpected error'));
|
||||
$this->app->instance(PluginService::class, $mockService);
|
||||
@@ -404,4 +404,78 @@ class PluginUpdateTest extends TestCase
|
||||
'Route api.admin.plugins.update should exist'
|
||||
);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// layout_strategy 파라미터 전달 검증
|
||||
// ========================================================================
|
||||
|
||||
public function test_perform_update_sends_layout_strategy_keep_to_service(): void
|
||||
{
|
||||
$mockService = Mockery::mock(PluginService::class);
|
||||
$mockService->shouldReceive('updatePlugin')
|
||||
->with('test-plugin', Mockery::any(), 'keep')
|
||||
->once()
|
||||
->andReturn([
|
||||
'success' => true,
|
||||
'from_version' => '1.0.0',
|
||||
'to_version' => '2.0.0',
|
||||
'plugin_info' => null,
|
||||
]);
|
||||
$this->app->instance(PluginService::class, $mockService);
|
||||
|
||||
$response = $this->authRequest()->postJson('/api/admin/plugins/test-plugin/update', [
|
||||
'layout_strategy' => 'keep',
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
}
|
||||
|
||||
public function test_perform_update_rejects_invalid_layout_strategy(): void
|
||||
{
|
||||
$response = $this->authRequest()->postJson('/api/admin/plugins/test-plugin/update', [
|
||||
'layout_strategy' => 'garbage',
|
||||
]);
|
||||
|
||||
$response->assertStatus(422);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// checkModifiedLayouts 엔드포인트 테스트
|
||||
// ========================================================================
|
||||
|
||||
public function test_check_modified_layouts_returns_result_from_service(): void
|
||||
{
|
||||
$mockService = Mockery::mock(PluginService::class);
|
||||
$mockService->shouldReceive('checkModifiedLayouts')
|
||||
->with('test-plugin')
|
||||
->once()
|
||||
->andReturn([
|
||||
'has_modified_layouts' => false,
|
||||
'modified_count' => 0,
|
||||
'modified_layouts' => [],
|
||||
]);
|
||||
$this->app->instance(PluginService::class, $mockService);
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/plugins/test-plugin/check-modified-layouts');
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('success', true)
|
||||
->assertJsonPath('data.has_modified_layouts', false)
|
||||
->assertJsonPath('data.modified_count', 0);
|
||||
}
|
||||
|
||||
public function test_check_modified_layouts_returns_401_without_authentication(): void
|
||||
{
|
||||
$response = $this->getJson('/api/admin/plugins/test-plugin/check-modified-layouts');
|
||||
|
||||
$response->assertStatus(401);
|
||||
}
|
||||
|
||||
public function test_check_modified_layouts_route_name_exists(): void
|
||||
{
|
||||
$this->assertTrue(
|
||||
\Illuminate\Support\Facades\Route::has('api.admin.plugins.check-modified-layouts'),
|
||||
'Route api.admin.plugins.check-modified-layouts should exist'
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* Settings API에서 available_drivers 필드 포함 검증
|
||||
*
|
||||
* DriverRegistryService를 통해 코어 + 플러그인 드라이버 목록이
|
||||
* settings API 응답에 포함되는지 검증합니다.
|
||||
*/
|
||||
class SettingsControllerDriverOptionsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $admin;
|
||||
|
||||
private string $token;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->admin = $this->createAdminUser();
|
||||
$this->token = $this->admin->createToken('test-token')->plainTextToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자 사용자 생성
|
||||
*/
|
||||
private function createAdminUser(): User
|
||||
{
|
||||
$user = User::factory()->create([
|
||||
'password' => Hash::make('password123'),
|
||||
]);
|
||||
|
||||
$permissionIds = [];
|
||||
foreach (['core.settings.read', 'core.settings.update'] as $permIdentifier) {
|
||||
$permission = Permission::firstOrCreate(
|
||||
['identifier' => $permIdentifier],
|
||||
[
|
||||
'name' => json_encode(['ko' => $permIdentifier, 'en' => $permIdentifier]),
|
||||
'description' => json_encode(['ko' => $permIdentifier, 'en' => $permIdentifier]),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'type' => 'admin',
|
||||
]
|
||||
);
|
||||
$permissionIds[] = $permission->id;
|
||||
}
|
||||
|
||||
$roleIdentifier = 'admin_test_' . uniqid();
|
||||
$adminRole = Role::create([
|
||||
'identifier' => $roleIdentifier,
|
||||
'name' => json_encode(['ko' => '테스트 관리자', 'en' => 'Test Admin']),
|
||||
'description' => json_encode(['ko' => '테스트', 'en' => 'Test']),
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$adminBaseRole = Role::firstOrCreate(
|
||||
['identifier' => 'admin'],
|
||||
[
|
||||
'name' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
|
||||
'description' => json_encode(['ko' => '시스템 관리자', 'en' => 'System Administrator']),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
|
||||
$adminRole->permissions()->sync($permissionIds);
|
||||
|
||||
$user->roles()->attach($adminBaseRole->id, [
|
||||
'assigned_at' => now(),
|
||||
'assigned_by' => null,
|
||||
]);
|
||||
$user->roles()->attach($adminRole->id, [
|
||||
'assigned_at' => now(),
|
||||
'assigned_by' => null,
|
||||
]);
|
||||
|
||||
return $user->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* 인증된 요청 헬퍼 메서드
|
||||
*/
|
||||
private function authRequest(): static
|
||||
{
|
||||
return $this->withHeaders([
|
||||
'Authorization' => 'Bearer ' . $this->token,
|
||||
'Accept' => 'application/json',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* settings index 응답에 available_drivers가 포함되는지 검증합니다.
|
||||
*/
|
||||
#[Test]
|
||||
public function index_response_includes_available_drivers(): void
|
||||
{
|
||||
$response = $this->authRequest()->getJson('/api/admin/settings');
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonStructure([
|
||||
'data' => [
|
||||
'available_drivers' => [
|
||||
'storage',
|
||||
'cache',
|
||||
'session',
|
||||
'queue',
|
||||
'log',
|
||||
'websocket',
|
||||
'mail',
|
||||
],
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* available_drivers의 각 드라이버에 id와 label 필드가 있는지 검증합니다.
|
||||
*/
|
||||
#[Test]
|
||||
public function available_drivers_have_correct_structure(): void
|
||||
{
|
||||
$response = $this->authRequest()->getJson('/api/admin/settings');
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
$data = $response->json('data.available_drivers');
|
||||
|
||||
// 7개 카테고리 존재
|
||||
$this->assertCount(7, $data);
|
||||
|
||||
// 각 카테고리에 최소 1개 이상의 드라이버 존재
|
||||
foreach ($data as $category => $drivers) {
|
||||
$this->assertNotEmpty($drivers, "{$category} 카테고리에 드라이버가 없습니다.");
|
||||
|
||||
// 첫 번째 드라이버 구조 검증
|
||||
$this->assertArrayHasKey('id', $drivers[0]);
|
||||
$this->assertArrayHasKey('label', $drivers[0]);
|
||||
$this->assertArrayHasKey('ko', $drivers[0]['label']);
|
||||
$this->assertArrayHasKey('en', $drivers[0]['label']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* storage 카테고리에 코어 드라이버가 포함되는지 검증합니다.
|
||||
*/
|
||||
#[Test]
|
||||
public function storage_drivers_include_core_options(): void
|
||||
{
|
||||
$response = $this->authRequest()->getJson('/api/admin/settings');
|
||||
|
||||
$storageDrivers = $response->json('data.available_drivers.storage');
|
||||
$ids = array_column($storageDrivers, 'id');
|
||||
|
||||
$this->assertContains('local', $ids);
|
||||
$this->assertContains('s3', $ids);
|
||||
}
|
||||
|
||||
/**
|
||||
* mail 카테고리에 코어 드라이버가 포함되는지 검증합니다.
|
||||
*/
|
||||
#[Test]
|
||||
public function mail_drivers_include_core_options(): void
|
||||
{
|
||||
$response = $this->authRequest()->getJson('/api/admin/settings');
|
||||
|
||||
$mailDrivers = $response->json('data.available_drivers.mail');
|
||||
$ids = array_column($mailDrivers, 'id');
|
||||
|
||||
$this->assertContains('smtp', $ids);
|
||||
$this->assertContains('mailgun', $ids);
|
||||
$this->assertContains('ses', $ids);
|
||||
}
|
||||
}
|
||||
@@ -1055,4 +1055,87 @@ class SettingsControllerTest extends TestCase
|
||||
$response->assertStatus(200)
|
||||
->assertJson(['success' => true]);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// 드라이버 탭 - 웹소켓 필수 필드 검증 테스트
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* 웹소켓 활성화 시 앱 ID, 앱 키, 앱 시크릿 필수 검증
|
||||
*/
|
||||
public function test_store_validates_websocket_required_fields_when_enabled(): void
|
||||
{
|
||||
$response = $this->authRequest()->postJson('/api/admin/settings', [
|
||||
'_tab' => 'drivers',
|
||||
'drivers' => [
|
||||
'websocket_enabled' => true,
|
||||
'websocket_app_id' => '',
|
||||
'websocket_app_key' => '',
|
||||
'websocket_app_secret' => '',
|
||||
'websocket_host' => 'localhost',
|
||||
'websocket_port' => 8080,
|
||||
'websocket_scheme' => 'https',
|
||||
],
|
||||
]);
|
||||
|
||||
$response->assertStatus(422)
|
||||
->assertJsonValidationErrors([
|
||||
'drivers.websocket_app_id',
|
||||
'drivers.websocket_app_key',
|
||||
'drivers.websocket_app_secret',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 웹소켓 비활성화 시 앱 ID, 앱 키, 앱 시크릿 비필수
|
||||
*/
|
||||
public function test_store_allows_empty_websocket_fields_when_disabled(): void
|
||||
{
|
||||
$response = $this->authRequest()->postJson('/api/admin/settings', [
|
||||
'_tab' => 'drivers',
|
||||
'drivers' => [
|
||||
'storage_driver' => 'local',
|
||||
'cache_driver' => 'file',
|
||||
'session_driver' => 'file',
|
||||
'queue_driver' => 'database',
|
||||
'log_driver' => 'daily',
|
||||
'log_level' => 'error',
|
||||
'websocket_enabled' => false,
|
||||
'websocket_app_id' => '',
|
||||
'websocket_app_key' => '',
|
||||
'websocket_app_secret' => '',
|
||||
],
|
||||
]);
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJson(['success' => true]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 웹소켓 활성화 + 모든 필수 필드 입력 시 저장 성공
|
||||
*/
|
||||
public function test_store_saves_websocket_settings_with_all_required_fields(): void
|
||||
{
|
||||
$response = $this->authRequest()->postJson('/api/admin/settings', [
|
||||
'_tab' => 'drivers',
|
||||
'drivers' => [
|
||||
'storage_driver' => 'local',
|
||||
'cache_driver' => 'file',
|
||||
'session_driver' => 'file',
|
||||
'queue_driver' => 'database',
|
||||
'log_driver' => 'daily',
|
||||
'log_level' => 'error',
|
||||
'websocket_enabled' => true,
|
||||
'websocket_app_id' => 'test-app-id',
|
||||
'websocket_app_key' => 'test-app-key',
|
||||
'websocket_app_secret' => 'test-app-secret',
|
||||
'websocket_host' => 'localhost',
|
||||
'websocket_port' => 8080,
|
||||
'websocket_scheme' => 'https',
|
||||
],
|
||||
]);
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJson(['success' => true]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Auth;
|
||||
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use App\Notifications\GenericNotification;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 사용자 알림 API 컨트롤러 테스트
|
||||
*/
|
||||
class NotificationControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $user;
|
||||
|
||||
private string $token;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->user = $this->createUserWithPermissions([], [
|
||||
'core.notifications.read',
|
||||
'core.notifications.update',
|
||||
'core.notifications.delete',
|
||||
]);
|
||||
$this->token = $this->user->createToken('test-token')->plainTextToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* 권한이 부여된 사용자 생성 헬퍼.
|
||||
*
|
||||
* @param array $attributes 사용자 속성
|
||||
* @param array $permissions 권한 식별자 배열
|
||||
* @return User
|
||||
*/
|
||||
private function createUserWithPermissions(array $attributes = [], array $permissions = []): User
|
||||
{
|
||||
$user = User::factory()->create($attributes);
|
||||
|
||||
if (! empty($permissions)) {
|
||||
$permissionIds = [];
|
||||
foreach ($permissions as $permIdentifier) {
|
||||
$permission = Permission::firstOrCreate(
|
||||
['identifier' => $permIdentifier],
|
||||
[
|
||||
'name' => json_encode(['ko' => $permIdentifier, 'en' => $permIdentifier]),
|
||||
'description' => json_encode(['ko' => $permIdentifier, 'en' => $permIdentifier]),
|
||||
'extension_type' => 'core',
|
||||
'extension_identifier' => 'core',
|
||||
'type' => 'user',
|
||||
'order' => 0,
|
||||
]
|
||||
);
|
||||
$permissionIds[] = $permission->id;
|
||||
}
|
||||
|
||||
$role = Role::firstOrCreate(
|
||||
['identifier' => 'test-user-role'],
|
||||
[
|
||||
'name' => json_encode(['ko' => '테스트 유저', 'en' => 'Test User']),
|
||||
'description' => json_encode(['ko' => '테스트용 역할', 'en' => 'Test role']),
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
$role->permissions()->syncWithoutDetaching($permissionIds);
|
||||
$user->roles()->syncWithoutDetaching([$role->id]);
|
||||
}
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* 인증된 요청 헬퍼.
|
||||
*
|
||||
* @return static
|
||||
*/
|
||||
private function authRequest(): static
|
||||
{
|
||||
return $this->withHeaders([
|
||||
'Authorization' => 'Bearer ' . $this->token,
|
||||
'Accept' => 'application/json',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 알림 목록 조회
|
||||
*/
|
||||
public function test_index_returns_notifications(): void
|
||||
{
|
||||
$this->createNotification($this->user);
|
||||
$this->createNotification($this->user);
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/user/notifications');
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('success', true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 미읽음 수 조회
|
||||
*/
|
||||
public function test_unread_count(): void
|
||||
{
|
||||
$this->createNotification($this->user);
|
||||
$this->createNotification($this->user, readAt: now());
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/user/notifications/unread-count');
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('data.unread_count', 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 알림 읽음 처리
|
||||
*/
|
||||
public function test_mark_as_read(): void
|
||||
{
|
||||
$notification = $this->createNotification($this->user);
|
||||
|
||||
$response = $this->authRequest()->patchJson("/api/user/notifications/{$notification->id}/read");
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('success', true);
|
||||
|
||||
$this->assertNotNull($notification->fresh()->read_at);
|
||||
}
|
||||
|
||||
/**
|
||||
* 전체 읽음 처리
|
||||
*/
|
||||
public function test_mark_all_as_read(): void
|
||||
{
|
||||
$this->createNotification($this->user);
|
||||
$this->createNotification($this->user);
|
||||
|
||||
$response = $this->authRequest()->postJson('/api/user/notifications/read-all');
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('data.marked_count', 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* 알림 삭제
|
||||
*/
|
||||
public function test_destroy_notification(): void
|
||||
{
|
||||
$notification = $this->createNotification($this->user);
|
||||
|
||||
$response = $this->authRequest()->deleteJson("/api/user/notifications/{$notification->id}");
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('success', true);
|
||||
|
||||
$this->assertDatabaseMissing('notifications', ['id' => $notification->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 비인증 사용자 접근 거부
|
||||
*/
|
||||
public function test_unauthenticated_returns_401(): void
|
||||
{
|
||||
$response = $this->getJson('/api/user/notifications');
|
||||
|
||||
$response->assertStatus(401);
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트용 알림 생성 헬퍼.
|
||||
*
|
||||
* @param User $user
|
||||
* @param \DateTimeInterface|null $readAt
|
||||
* @return \Illuminate\Notifications\DatabaseNotification
|
||||
*/
|
||||
private function createNotification(User $user, ?\DateTimeInterface $readAt = null)
|
||||
{
|
||||
return $user->notifications()->create([
|
||||
'id' => Str::uuid(),
|
||||
'type' => GenericNotification::class,
|
||||
'data' => ['type' => 'test', 'subject' => 'Test Notification'],
|
||||
'read_at' => $readAt,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,7 @@ use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use App\Models\UserConsent;
|
||||
use App\Notifications\Auth\ResetPasswordNotification;
|
||||
use App\Notifications\Auth\WelcomeNotification;
|
||||
use App\Notifications\GenericNotification;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
@@ -128,7 +127,7 @@ class UserAuthControllerTest extends TestCase
|
||||
'data' => [
|
||||
'token',
|
||||
'user' => [
|
||||
'id',
|
||||
'uuid',
|
||||
'name',
|
||||
'email',
|
||||
],
|
||||
@@ -612,7 +611,7 @@ class UserAuthControllerTest extends TestCase
|
||||
$this->assertNotNull($user);
|
||||
|
||||
// 환영 알림 발송 확인
|
||||
Notification::assertSentTo($user, WelcomeNotification::class);
|
||||
Notification::assertSentTo($user, GenericNotification::class);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -877,7 +876,7 @@ class UserAuthControllerTest extends TestCase
|
||||
]);
|
||||
|
||||
// 알림 발송 확인
|
||||
Notification::assertSentTo($user, ResetPasswordNotification::class);
|
||||
Notification::assertSentTo($user, GenericNotification::class);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -939,7 +938,7 @@ class UserAuthControllerTest extends TestCase
|
||||
$this->assertNotEquals($firstCreatedAt->timestamp, $secondToken->created_at->timestamp);
|
||||
|
||||
// 알림이 2번 발송됨 확인
|
||||
Notification::assertSentToTimes($user, ResetPasswordNotification::class, 2);
|
||||
Notification::assertSentToTimes($user, GenericNotification::class, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -961,7 +960,7 @@ class UserAuthControllerTest extends TestCase
|
||||
$response->assertStatus(200)
|
||||
->assertJson(['success' => true]);
|
||||
|
||||
Notification::assertSentTo($user, ResetPasswordNotification::class);
|
||||
Notification::assertSentTo($user, GenericNotification::class);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1000,7 +999,7 @@ class UserAuthControllerTest extends TestCase
|
||||
$response->assertStatus(200)
|
||||
->assertJson(['success' => true]);
|
||||
|
||||
Notification::assertSentTo($user, ResetPasswordNotification::class);
|
||||
Notification::assertSentTo($user, GenericNotification::class);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Console;
|
||||
|
||||
use App\Extension\Vendor\VendorBundler;
|
||||
use App\Extension\Vendor\VendorMode;
|
||||
use App\Services\CoreUpdateService;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* core:update --vendor-mode 3 모드 Feature 테스트.
|
||||
*
|
||||
* 실제 core:update 커맨드를 풀 체인으로 검증하는 것은 마이그레이션/GitHub 연동 등
|
||||
* 사이드 이펙트가 크므로, CoreUpdateService::runVendorInstallInPending() 경로를
|
||||
* 중심으로 VendorResolver 분기 + 해시 검증 + zip 추출 동작을 격리 검증한다.
|
||||
*/
|
||||
class CoreUpdateWithBundleTest extends TestCase
|
||||
{
|
||||
private CoreUpdateService $service;
|
||||
|
||||
private string $pendingDir;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->service = app(CoreUpdateService::class);
|
||||
$this->pendingDir = storage_path('app/test-core-vendor-bundle-'.uniqid());
|
||||
File::ensureDirectoryExists($this->pendingDir);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
if (File::isDirectory($this->pendingDir)) {
|
||||
File::deleteDirectory($this->pendingDir);
|
||||
}
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트용 _pending 디렉토리에 vendor-bundle.zip 을 생성합니다.
|
||||
*/
|
||||
private function createPendingBundle(): void
|
||||
{
|
||||
File::put($this->pendingDir.'/composer.json', json_encode([
|
||||
'name' => 'test/core',
|
||||
'require' => ['php' => '^8.2'],
|
||||
]));
|
||||
|
||||
$zipPath = $this->pendingDir.'/vendor-bundle.zip';
|
||||
$zip = new \ZipArchive;
|
||||
$zip->open($zipPath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
|
||||
$zip->addFromString('vendor/autoload.php', '<?php // test autoload');
|
||||
$zip->addFromString('vendor/laravel/framework/src/file.php', '<?php // framework');
|
||||
$zip->close();
|
||||
|
||||
File::put($this->pendingDir.'/vendor-bundle.json', json_encode([
|
||||
'schema_version' => VendorBundler::SCHEMA_VERSION,
|
||||
'zip_sha256' => hash_file('sha256', $zipPath),
|
||||
'package_count' => 1,
|
||||
]));
|
||||
}
|
||||
|
||||
public function test_vendor_mode_bundled_extracts_bundle_zip(): void
|
||||
{
|
||||
$this->createPendingBundle();
|
||||
|
||||
$result = $this->service->runVendorInstallInPending($this->pendingDir, VendorMode::Bundled);
|
||||
|
||||
$this->assertSame(VendorMode::Bundled, $result->mode);
|
||||
$this->assertSame('bundled', $result->strategy);
|
||||
$this->assertFileExists($this->pendingDir.'/vendor/autoload.php');
|
||||
$this->assertFileExists($this->pendingDir.'/vendor/laravel/framework/src/file.php');
|
||||
}
|
||||
|
||||
public function test_vendor_mode_bundled_fails_when_bundle_missing(): void
|
||||
{
|
||||
// composer.json 은 있지만 vendor-bundle.zip 없음
|
||||
File::put($this->pendingDir.'/composer.json', json_encode(['name' => 'test/core']));
|
||||
|
||||
$this->expectException(\App\Extension\Vendor\Exceptions\VendorInstallException::class);
|
||||
$this->service->runVendorInstallInPending($this->pendingDir, VendorMode::Bundled);
|
||||
}
|
||||
|
||||
public function test_vendor_mode_bundled_fails_on_tampered_zip(): void
|
||||
{
|
||||
$this->createPendingBundle();
|
||||
|
||||
// zip 해시를 조작하여 무결성 검증 실패 유도
|
||||
$manifestPath = $this->pendingDir.'/vendor-bundle.json';
|
||||
$manifest = json_decode(File::get($manifestPath), true);
|
||||
$manifest['zip_sha256'] = hash('sha256', 'tampered');
|
||||
File::put($manifestPath, json_encode($manifest));
|
||||
|
||||
$this->expectException(\App\Extension\Vendor\Exceptions\VendorInstallException::class);
|
||||
$this->service->runVendorInstallInPending($this->pendingDir, VendorMode::Bundled);
|
||||
}
|
||||
|
||||
public function test_vendor_mode_composer_requires_composer_executor_fallback(): void
|
||||
{
|
||||
// composer 모드 요청이지만 실제 composer 실행은 스킵될 수 있는 환경
|
||||
// runVendorInstallInPending 은 내부적으로 CoreUpdateService::runComposerInstallInPending() 을
|
||||
// composerExecutor 로 전달하므로, composer 바이너리 존재 여부에 따라 동작이 달라짐.
|
||||
File::put($this->pendingDir.'/composer.json', json_encode(['name' => 'test/core']));
|
||||
|
||||
// composer 모드에서 번들 zip 없어도 composer 실행을 시도하지 — zip 무결성 검증 불필요
|
||||
// 실제 실행은 환경에 따라 실패할 수 있으므로 예외 타입만 확인
|
||||
try {
|
||||
$this->service->runVendorInstallInPending($this->pendingDir, VendorMode::Composer);
|
||||
$this->assertTrue(true); // composer 실행 성공 (거의 없음)
|
||||
} catch (\Throwable $e) {
|
||||
$this->assertNotEmpty($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function test_core_update_command_accepts_vendor_mode_option(): void
|
||||
{
|
||||
// 실제 core:update 는 풀 체인 실행이 복잡하므로 --help 출력에서 옵션 존재만 검증
|
||||
$this->artisan('core:update', ['--help' => true])
|
||||
->expectsOutputToContain('--vendor-mode')
|
||||
->assertExitCode(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Console\Vendor;
|
||||
|
||||
use App\Extension\Vendor\VendorBundler;
|
||||
use App\Extension\Vendor\VendorIntegrityChecker;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 신규 명령어 체계 (옵션 B) + 분리 구조 (소스=활성, 출력=_bundled) 회귀 테스트.
|
||||
*
|
||||
* 각 테스트는 고유 식별자 (uniqid) 로 격리된 fake 확장을 활성 + _bundled 양쪽에 생성하여
|
||||
* 실제 확장(sirsoft-*)을 오염시키지 않는다. setUp 에서 생성, tearDown 에서 완전 제거.
|
||||
*
|
||||
* - 활성 디렉토리 (`modules/{id}/`, `plugins/{id}/`): composer.json + composer.lock + vendor/ (소스)
|
||||
* - _bundled 디렉토리 (`modules/_bundled/{id}/`, `plugins/_bundled/{id}/`): composer.json + 빌드 후 vendor-bundle.zip (출력)
|
||||
*/
|
||||
class BuildVendorBundleCommandTest extends TestCase
|
||||
{
|
||||
// ===== 모듈 fake =====
|
||||
private string $fakeModuleIdentifier;
|
||||
|
||||
private string $fakeModuleActivePath;
|
||||
|
||||
private string $fakeModuleBundledPath;
|
||||
|
||||
// ===== 플러그인 fake =====
|
||||
private string $fakePluginIdentifier;
|
||||
|
||||
private string $fakePluginActivePath;
|
||||
|
||||
private string $fakePluginBundledPath;
|
||||
|
||||
/**
|
||||
* 실제 _bundled 번들 파일 스냅샷 — setUp 에서 저장, tearDown 에서 복원.
|
||||
*
|
||||
* `vendor-bundle:build-all` 은 `modules/_bundled/*` 와 `plugins/_bundled/*` 를
|
||||
* 모두 순회하여 빌드한다. 테스트의 fake runner 가 실제 확장(sirsoft-ecommerce 등)
|
||||
* 의 vendor-bundle.zip 까지 가짜 498-byte zip 으로 덮어쓰는 사고를 방지하기 위해
|
||||
* 실제 파일을 snapshot 하고 tearDown 에서 복원한다.
|
||||
*
|
||||
* @var array<string, string> path => content (binary-safe)
|
||||
*/
|
||||
private array $realBundleSnapshots = [];
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->snapshotRealBundles();
|
||||
|
||||
// 고유 식별자 — 실제 sirsoft-* 확장과 공간 격리
|
||||
$suffix = uniqid();
|
||||
$this->fakeModuleIdentifier = 'test-vendor-build-mod-'.$suffix;
|
||||
$this->fakeModuleActivePath = base_path('modules/'.$this->fakeModuleIdentifier);
|
||||
$this->fakeModuleBundledPath = base_path('modules/_bundled/'.$this->fakeModuleIdentifier);
|
||||
|
||||
$this->fakePluginIdentifier = 'test-vendor-build-plg-'.$suffix;
|
||||
$this->fakePluginActivePath = base_path('plugins/'.$this->fakePluginIdentifier);
|
||||
$this->fakePluginBundledPath = base_path('plugins/_bundled/'.$this->fakePluginIdentifier);
|
||||
|
||||
$this->createFakeExtension($this->fakeModuleActivePath, $this->fakeModuleBundledPath, 'module');
|
||||
$this->createFakeExtension($this->fakePluginActivePath, $this->fakePluginBundledPath, 'plugin');
|
||||
|
||||
// 실제 composer 실행 대신 가짜 vendor/ 구조를 스테이징에 생성 — fake 확장의 가상 패키지
|
||||
// (test/lib)는 packagist 에 존재하지 않으므로 실 composer install 로는 빌드 불가.
|
||||
$this->app->bind(VendorBundler::class, function ($app) {
|
||||
$bundler = new VendorBundler($app->make(VendorIntegrityChecker::class));
|
||||
$bundler->setComposerInstallRunner(function (string $stagingDir): void {
|
||||
File::ensureDirectoryExists($stagingDir.'/vendor/test/lib');
|
||||
File::put($stagingDir.'/vendor/test/lib/file.php', '<?php // test');
|
||||
File::put($stagingDir.'/vendor/autoload.php', '<?php // autoload');
|
||||
});
|
||||
|
||||
return $bundler;
|
||||
});
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
foreach ([
|
||||
$this->fakeModuleActivePath,
|
||||
$this->fakeModuleBundledPath,
|
||||
$this->fakePluginActivePath,
|
||||
$this->fakePluginBundledPath,
|
||||
] as $path) {
|
||||
if (File::isDirectory($path)) {
|
||||
File::deleteDirectory($path);
|
||||
}
|
||||
}
|
||||
|
||||
$this->restoreRealBundles();
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 실제 _bundled 번들 (코어 + 모든 모듈/플러그인) 스냅샷.
|
||||
*/
|
||||
private function snapshotRealBundles(): void
|
||||
{
|
||||
$paths = $this->collectRealBundlePaths();
|
||||
|
||||
foreach ($paths as $path) {
|
||||
if (file_exists($path)) {
|
||||
$this->realBundleSnapshots[$path] = (string) file_get_contents($path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 스냅샷된 번들 파일을 원상 복구.
|
||||
*/
|
||||
private function restoreRealBundles(): void
|
||||
{
|
||||
foreach ($this->realBundleSnapshots as $path => $content) {
|
||||
File::ensureDirectoryExists(dirname($path));
|
||||
file_put_contents($path, $content);
|
||||
}
|
||||
|
||||
// 스냅샷에 없던 파일 (테스트 중 새로 생성된 가짜 파일) 정리
|
||||
foreach ($this->collectRealBundlePaths() as $path) {
|
||||
if (file_exists($path) && ! array_key_exists($path, $this->realBundleSnapshots)) {
|
||||
@unlink($path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 보호 대상 실제 번들 파일 경로 목록.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function collectRealBundlePaths(): array
|
||||
{
|
||||
$paths = [
|
||||
base_path('vendor-bundle.zip'),
|
||||
base_path('vendor-bundle.json'),
|
||||
];
|
||||
|
||||
foreach (['modules', 'plugins'] as $kind) {
|
||||
$bundledDir = base_path($kind.'/_bundled');
|
||||
if (! is_dir($bundledDir)) {
|
||||
continue;
|
||||
}
|
||||
foreach (glob($bundledDir.'/*', GLOB_ONLYDIR) ?: [] as $extDir) {
|
||||
// fake 확장은 snapshot 대상 아님 — setUp 보다 먼저 호출되므로 이 시점에는 존재하지 않음
|
||||
$paths[] = $extDir.'/vendor-bundle.zip';
|
||||
$paths[] = $extDir.'/vendor-bundle.json';
|
||||
}
|
||||
}
|
||||
|
||||
return $paths;
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 디렉토리에 fake vendor 프로젝트 생성 + _bundled 에 composer.json 미러.
|
||||
*/
|
||||
private function createFakeExtension(string $activePath, string $bundledPath, string $kind): void
|
||||
{
|
||||
// 활성 디렉토리: composer.json + composer.lock + vendor/
|
||||
File::ensureDirectoryExists($activePath);
|
||||
$composerJson = json_encode([
|
||||
'name' => 'test/fake-'.$kind,
|
||||
// VendorBundler 는 php/ext-* 만 있는 확장을 skip 하므로 외부 의존성 선언 필수
|
||||
'require' => ['php' => '^8.2', 'test/lib' => '^1.0'],
|
||||
]);
|
||||
File::put($activePath.'/composer.json', $composerJson);
|
||||
File::put($activePath.'/composer.lock', json_encode([
|
||||
'packages' => [
|
||||
['name' => 'test/lib', 'version' => '1.0.0', 'type' => 'library'],
|
||||
],
|
||||
]));
|
||||
File::ensureDirectoryExists($activePath.'/vendor/test/lib');
|
||||
File::put($activePath.'/vendor/autoload.php', '<?php // autoload');
|
||||
File::put($activePath.'/vendor/test/lib/file.php', '<?php // test');
|
||||
|
||||
// _bundled 디렉토리: composer.json 미러만 (vendor/ 없음 — 번들링 출력 경로)
|
||||
File::ensureDirectoryExists($bundledPath);
|
||||
File::put($bundledPath.'/composer.json', $composerJson);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 모듈 명령어 (module:vendor-bundle / module:vendor-verify)
|
||||
// =========================================================================
|
||||
|
||||
public function test_module_vendor_bundle_builds_specific_identifier(): void
|
||||
{
|
||||
$this->artisan('module:vendor-bundle', [
|
||||
'identifier' => $this->fakeModuleIdentifier,
|
||||
])->assertExitCode(0);
|
||||
|
||||
// 출력은 _bundled 에만 — 활성 디렉토리는 오염되지 않아야 함
|
||||
$this->assertFileExists($this->fakeModuleBundledPath.'/vendor-bundle.zip');
|
||||
$this->assertFileExists($this->fakeModuleBundledPath.'/vendor-bundle.json');
|
||||
$this->assertFileDoesNotExist($this->fakeModuleActivePath.'/vendor-bundle.zip');
|
||||
}
|
||||
|
||||
public function test_module_vendor_bundle_requires_identifier_or_all_flag(): void
|
||||
{
|
||||
$this->artisan('module:vendor-bundle')
|
||||
->expectsOutputToContain('식별자 또는 --all 옵션을 지정')
|
||||
->assertExitCode(1);
|
||||
}
|
||||
|
||||
public function test_module_vendor_bundle_check_reports_stale_when_not_built(): void
|
||||
{
|
||||
$this->artisan('module:vendor-bundle', [
|
||||
'identifier' => $this->fakeModuleIdentifier,
|
||||
'--check' => true,
|
||||
])->assertExitCode(1);
|
||||
}
|
||||
|
||||
public function test_module_vendor_bundle_check_reports_up_to_date_after_build(): void
|
||||
{
|
||||
$this->artisan('module:vendor-bundle', ['identifier' => $this->fakeModuleIdentifier])
|
||||
->assertExitCode(0);
|
||||
|
||||
$this->artisan('module:vendor-bundle', [
|
||||
'identifier' => $this->fakeModuleIdentifier,
|
||||
'--check' => true,
|
||||
])->assertExitCode(0);
|
||||
}
|
||||
|
||||
public function test_module_vendor_bundle_skipped_when_up_to_date(): void
|
||||
{
|
||||
$this->artisan('module:vendor-bundle', ['identifier' => $this->fakeModuleIdentifier])
|
||||
->assertExitCode(0);
|
||||
|
||||
$this->artisan('module:vendor-bundle', ['identifier' => $this->fakeModuleIdentifier])
|
||||
->expectsOutputToContain('스킵')
|
||||
->assertExitCode(0);
|
||||
}
|
||||
|
||||
public function test_module_vendor_bundle_force_rebuilds(): void
|
||||
{
|
||||
$this->artisan('module:vendor-bundle', ['identifier' => $this->fakeModuleIdentifier])
|
||||
->assertExitCode(0);
|
||||
|
||||
$this->artisan('module:vendor-bundle', [
|
||||
'identifier' => $this->fakeModuleIdentifier,
|
||||
'--force' => true,
|
||||
])->assertExitCode(0);
|
||||
}
|
||||
|
||||
public function test_module_vendor_verify_passes_after_successful_build(): void
|
||||
{
|
||||
$this->artisan('module:vendor-bundle', ['identifier' => $this->fakeModuleIdentifier])
|
||||
->assertExitCode(0);
|
||||
|
||||
$this->artisan('module:vendor-verify', [
|
||||
'identifier' => $this->fakeModuleIdentifier,
|
||||
])->assertExitCode(0);
|
||||
}
|
||||
|
||||
public function test_module_vendor_verify_skips_when_bundle_missing(): void
|
||||
{
|
||||
// _bundled 경로는 있지만 번들 파일 없음 — 스킵 처리되어 종료코드 0
|
||||
$this->artisan('module:vendor-verify', [
|
||||
'identifier' => $this->fakeModuleIdentifier,
|
||||
])->assertExitCode(0);
|
||||
}
|
||||
|
||||
public function test_module_vendor_verify_fails_on_tampered_zip(): void
|
||||
{
|
||||
$this->artisan('module:vendor-bundle', ['identifier' => $this->fakeModuleIdentifier])
|
||||
->assertExitCode(0);
|
||||
|
||||
file_put_contents($this->fakeModuleBundledPath.'/vendor-bundle.zip', 'tampered content');
|
||||
|
||||
$this->artisan('module:vendor-verify', [
|
||||
'identifier' => $this->fakeModuleIdentifier,
|
||||
])->assertExitCode(1);
|
||||
}
|
||||
|
||||
public function test_module_vendor_verify_requires_identifier_or_all_flag(): void
|
||||
{
|
||||
$this->artisan('module:vendor-verify')
|
||||
->expectsOutputToContain('식별자 또는 --all 옵션을 지정')
|
||||
->assertExitCode(1);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 플러그인 명령어 (plugin:vendor-bundle / plugin:vendor-verify)
|
||||
// =========================================================================
|
||||
|
||||
public function test_plugin_vendor_bundle_builds_specific_identifier(): void
|
||||
{
|
||||
$this->artisan('plugin:vendor-bundle', [
|
||||
'identifier' => $this->fakePluginIdentifier,
|
||||
])->assertExitCode(0);
|
||||
|
||||
$this->assertFileExists($this->fakePluginBundledPath.'/vendor-bundle.zip');
|
||||
$this->assertFileExists($this->fakePluginBundledPath.'/vendor-bundle.json');
|
||||
$this->assertFileDoesNotExist($this->fakePluginActivePath.'/vendor-bundle.zip');
|
||||
}
|
||||
|
||||
public function test_plugin_vendor_bundle_requires_identifier_or_all_flag(): void
|
||||
{
|
||||
$this->artisan('plugin:vendor-bundle')
|
||||
->expectsOutputToContain('식별자 또는 --all 옵션을 지정')
|
||||
->assertExitCode(1);
|
||||
}
|
||||
|
||||
public function test_plugin_vendor_bundle_check_reports_stale_when_not_built(): void
|
||||
{
|
||||
$this->artisan('plugin:vendor-bundle', [
|
||||
'identifier' => $this->fakePluginIdentifier,
|
||||
'--check' => true,
|
||||
])->assertExitCode(1);
|
||||
}
|
||||
|
||||
public function test_plugin_vendor_bundle_force_rebuilds(): void
|
||||
{
|
||||
$this->artisan('plugin:vendor-bundle', ['identifier' => $this->fakePluginIdentifier])
|
||||
->assertExitCode(0);
|
||||
|
||||
$this->artisan('plugin:vendor-bundle', [
|
||||
'identifier' => $this->fakePluginIdentifier,
|
||||
'--force' => true,
|
||||
])->assertExitCode(0);
|
||||
}
|
||||
|
||||
public function test_plugin_vendor_verify_passes_after_successful_build(): void
|
||||
{
|
||||
$this->artisan('plugin:vendor-bundle', ['identifier' => $this->fakePluginIdentifier])
|
||||
->assertExitCode(0);
|
||||
|
||||
$this->artisan('plugin:vendor-verify', [
|
||||
'identifier' => $this->fakePluginIdentifier,
|
||||
])->assertExitCode(0);
|
||||
}
|
||||
|
||||
public function test_plugin_vendor_verify_fails_on_tampered_zip(): void
|
||||
{
|
||||
$this->artisan('plugin:vendor-bundle', ['identifier' => $this->fakePluginIdentifier])
|
||||
->assertExitCode(0);
|
||||
|
||||
file_put_contents($this->fakePluginBundledPath.'/vendor-bundle.zip', 'tampered content');
|
||||
|
||||
$this->artisan('plugin:vendor-verify', [
|
||||
'identifier' => $this->fakePluginIdentifier,
|
||||
])->assertExitCode(1);
|
||||
}
|
||||
|
||||
public function test_plugin_vendor_verify_requires_identifier_or_all_flag(): void
|
||||
{
|
||||
$this->artisan('plugin:vendor-verify')
|
||||
->expectsOutputToContain('식별자 또는 --all 옵션을 지정')
|
||||
->assertExitCode(1);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 일괄 알리아스 (vendor-bundle:build-all / verify-all) — 모듈+플러그인 포함
|
||||
// =========================================================================
|
||||
|
||||
public function test_bulk_alias_build_all_builds_both_module_and_plugin_fakes(): void
|
||||
{
|
||||
// force 로 모든 _bundled 확장 빌드 (fake 모듈 + fake 플러그인 포함)
|
||||
$this->artisan('vendor-bundle:build-all', ['--force' => true])
|
||||
->assertExitCode(0);
|
||||
|
||||
$this->assertFileExists($this->fakeModuleBundledPath.'/vendor-bundle.zip');
|
||||
$this->assertFileExists($this->fakePluginBundledPath.'/vendor-bundle.zip');
|
||||
}
|
||||
|
||||
public function test_bulk_alias_verify_all_runs(): void
|
||||
{
|
||||
$this->artisan('module:vendor-bundle', ['identifier' => $this->fakeModuleIdentifier])
|
||||
->assertExitCode(0);
|
||||
$this->artisan('plugin:vendor-bundle', ['identifier' => $this->fakePluginIdentifier])
|
||||
->assertExitCode(0);
|
||||
|
||||
// 일괄 검증 — fake 대상은 통과, 다른 사전 빌드 없는 경우 스킵 처리
|
||||
$exitCode = $this->artisan('vendor-bundle:verify-all')->run();
|
||||
|
||||
// 다른 확장의 stale 상태에 따라 0/1 둘 다 가능 — fake 는 통과해야 함
|
||||
$this->assertContains($exitCode, [0, 1]);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,6 @@ use App\Extension\ModuleManager;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Models\Module;
|
||||
use App\Models\Plugin;
|
||||
use App\Services\CacheService;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
@@ -15,16 +14,22 @@ use Tests\TestCase;
|
||||
/**
|
||||
* 모듈/플러그인 상태 캐시 통합 테스트
|
||||
*
|
||||
* 빈 배열 캐싱 금지 기능이 모듈/플러그인 활성 목록 조회에
|
||||
* 올바르게 적용되는지 검증합니다.
|
||||
* 새 CacheInterface 기반 캐시 키(`g7:core:ext.modules.active_identifiers` 등)와
|
||||
* Trait 의 캐시 무효화 동작을 검증합니다.
|
||||
*
|
||||
* 참고: 이전의 "빈 배열 캐시 금지" 정책은 새 시스템에서 폐기되었습니다.
|
||||
* 대신 모듈 설치/활성화 훅에서 invalidateModuleStatusCache() 로 확실히 무효화합니다.
|
||||
*/
|
||||
class ModuleCacheTest extends TestCase
|
||||
{
|
||||
private const MODULE_ACTIVE_KEY = 'g7:core:ext.modules.active_identifiers';
|
||||
|
||||
private const PLUGIN_ACTIVE_KEY = 'g7:core:ext.plugins.active_identifiers';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
// 캐시 초기화
|
||||
Cache::flush();
|
||||
ModuleManager::invalidateModuleStatusCache();
|
||||
PluginManager::invalidatePluginStatusCache();
|
||||
@@ -36,62 +41,23 @@ class ModuleCacheTest extends TestCase
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 모듈이 없을 때 빈 배열이 캐시되지 않아야 합니다.
|
||||
*/
|
||||
#[Test]
|
||||
public function it_does_not_cache_empty_active_modules(): void
|
||||
{
|
||||
// 기존 상태 백업
|
||||
$originalStatuses = Module::pluck('status', 'id')->toArray();
|
||||
|
||||
try {
|
||||
// 모든 모듈 비활성화
|
||||
Module::query()->update(['status' => ExtensionStatus::Inactive->value]);
|
||||
|
||||
// 캐시 무효화
|
||||
ModuleManager::invalidateModuleStatusCache();
|
||||
|
||||
// 첫 번째 조회
|
||||
$result1 = ModuleManager::getActiveModuleIdentifiers();
|
||||
$this->assertEquals([], $result1);
|
||||
|
||||
// 캐시에 저장되지 않았는지 확인
|
||||
$cacheKey = CacheService::key('modules', 'active_identifiers');
|
||||
$this->assertNull(Cache::get($cacheKey), '빈 배열이 캐시에 저장되면 안됩니다');
|
||||
|
||||
// 두 번째 조회도 동일하게 빈 배열 반환
|
||||
$result2 = ModuleManager::getActiveModuleIdentifiers();
|
||||
$this->assertEquals([], $result2);
|
||||
} finally {
|
||||
// 원래 상태 복원
|
||||
foreach ($originalStatuses as $id => $status) {
|
||||
Module::where('id', $id)->update(['status' => $status]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 모듈이 있을 때 정상적으로 캐시되어야 합니다.
|
||||
*/
|
||||
#[Test]
|
||||
public function it_caches_non_empty_active_modules(): void
|
||||
{
|
||||
// 최소 1개 활성 모듈 확인
|
||||
$activeModule = Module::where('status', ExtensionStatus::Active->value)->first();
|
||||
if (! $activeModule) {
|
||||
$this->markTestSkipped('활성 모듈이 없습니다.');
|
||||
}
|
||||
|
||||
// 캐시 무효화 후 조회
|
||||
ModuleManager::invalidateModuleStatusCache();
|
||||
$result = ModuleManager::getActiveModuleIdentifiers();
|
||||
|
||||
$this->assertNotEmpty($result, '활성 모듈 목록이 비어있으면 안됩니다');
|
||||
|
||||
// 캐시에 저장되었는지 확인
|
||||
$cacheKey = CacheService::key('modules', 'active_identifiers');
|
||||
$cached = Cache::get($cacheKey);
|
||||
$cached = Cache::get(self::MODULE_ACTIVE_KEY);
|
||||
$this->assertNotNull($cached, '활성 모듈 목록이 캐시되어야 합니다');
|
||||
$this->assertEquals($result, $cached);
|
||||
}
|
||||
@@ -102,54 +68,17 @@ class ModuleCacheTest extends TestCase
|
||||
#[Test]
|
||||
public function it_invalidates_cache_on_status_change(): void
|
||||
{
|
||||
// 초기 조회 (캐시 생성)
|
||||
$initialResult = ModuleManager::getActiveModuleIdentifiers();
|
||||
|
||||
if (empty($initialResult)) {
|
||||
$this->markTestSkipped('활성 모듈이 없습니다.');
|
||||
}
|
||||
|
||||
$cacheKey = CacheService::key('modules', 'active_identifiers');
|
||||
$this->assertNotNull(Cache::get(self::MODULE_ACTIVE_KEY), '초기 캐시가 생성되어야 합니다');
|
||||
|
||||
// 캐시 확인
|
||||
$this->assertNotNull(Cache::get($cacheKey), '초기 캐시가 생성되어야 합니다');
|
||||
|
||||
// 캐시 무효화
|
||||
ModuleManager::invalidateModuleStatusCache();
|
||||
|
||||
// 캐시 삭제 확인
|
||||
$this->assertNull(Cache::get($cacheKey), '캐시가 무효화되어야 합니다');
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 플러그인이 없을 때 빈 배열이 캐시되지 않아야 합니다.
|
||||
*/
|
||||
#[Test]
|
||||
public function it_does_not_cache_empty_active_plugins(): void
|
||||
{
|
||||
// 기존 상태 백업
|
||||
$originalStatuses = Plugin::pluck('status', 'id')->toArray();
|
||||
|
||||
try {
|
||||
// 모든 플러그인 비활성화
|
||||
Plugin::query()->update(['status' => ExtensionStatus::Inactive->value]);
|
||||
|
||||
// 캐시 무효화
|
||||
PluginManager::invalidatePluginStatusCache();
|
||||
|
||||
// 조회
|
||||
$result = PluginManager::getActivePluginIdentifiers();
|
||||
$this->assertEquals([], $result);
|
||||
|
||||
// 캐시에 저장되지 않았는지 확인
|
||||
$cacheKey = CacheService::key('plugins', 'active_identifiers');
|
||||
$this->assertNull(Cache::get($cacheKey), '빈 배열이 캐시에 저장되면 안됩니다');
|
||||
} finally {
|
||||
// 원래 상태 복원
|
||||
foreach ($originalStatuses as $id => $status) {
|
||||
Plugin::where('id', $id)->update(['status' => $status]);
|
||||
}
|
||||
}
|
||||
$this->assertNull(Cache::get(self::MODULE_ACTIVE_KEY), '캐시가 무효화되어야 합니다');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -158,21 +87,17 @@ class ModuleCacheTest extends TestCase
|
||||
#[Test]
|
||||
public function it_caches_non_empty_active_plugins(): void
|
||||
{
|
||||
// 최소 1개 활성 플러그인 확인
|
||||
$activePlugin = Plugin::where('status', ExtensionStatus::Active->value)->first();
|
||||
if (! $activePlugin) {
|
||||
$this->markTestSkipped('활성 플러그인이 없습니다.');
|
||||
}
|
||||
|
||||
// 캐시 무효화 후 조회
|
||||
PluginManager::invalidatePluginStatusCache();
|
||||
$result = PluginManager::getActivePluginIdentifiers();
|
||||
|
||||
$this->assertNotEmpty($result, '활성 플러그인 목록이 비어있으면 안됩니다');
|
||||
|
||||
// 캐시에 저장되었는지 확인
|
||||
$cacheKey = CacheService::key('plugins', 'active_identifiers');
|
||||
$cached = Cache::get($cacheKey);
|
||||
$cached = Cache::get(self::PLUGIN_ACTIVE_KEY);
|
||||
$this->assertNotNull($cached, '활성 플러그인 목록이 캐시되어야 합니다');
|
||||
$this->assertEquals($result, $cached);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Extension;
|
||||
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Extension\PluginManager;
|
||||
use ReflectionMethod;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* Test-4: 확장 업데이트 시 클래스 캐싱 회피 메커니즘(`evalFreshModule` / `evalFreshPlugin`,
|
||||
* `reloadModule` / `reloadPlugin`)이 존재하고 올바른 시그니처를 유지함을 보장하는 회귀 테스트.
|
||||
*
|
||||
* 이 메커니즘은 모듈/플러그인 업데이트 시 진입점 클래스를 eval + 이름 교체 트릭으로 **메모리에 재로드**
|
||||
* 하여 getPermissions/getMenus 등이 최신 정의를 반환하게 한다. 본 테스트는 메서드가 제거되거나
|
||||
* 시그니처가 변경되는 회귀를 조기에 감지한다.
|
||||
*
|
||||
* 실제 eval 동작 자체는 모듈 파일을 디스크에 두고 호출해야 하므로 여기서는 "존재/시그니처" 계약만
|
||||
* 검증한다. 회귀 시 업데이트 경로 A (확장) 가 조용히 파손될 수 있으므로 중요하다.
|
||||
*/
|
||||
class ModuleReloadTest extends TestCase
|
||||
{
|
||||
public function test_module_manager_has_reload_and_evalfresh_methods(): void
|
||||
{
|
||||
$this->assertTrue(
|
||||
method_exists(ModuleManager::class, 'reloadModule'),
|
||||
'ModuleManager::reloadModule 메서드가 존재해야 한다'
|
||||
);
|
||||
$this->assertTrue(
|
||||
method_exists(ModuleManager::class, 'evalFreshModule'),
|
||||
'ModuleManager::evalFreshModule 메서드가 존재해야 한다'
|
||||
);
|
||||
|
||||
$reload = new ReflectionMethod(ModuleManager::class, 'reloadModule');
|
||||
$this->assertSame(1, $reload->getNumberOfRequiredParameters(), 'reloadModule 은 moduleName 1개 필수 파라미터');
|
||||
$params = $reload->getParameters();
|
||||
$this->assertSame('moduleName', $params[0]->getName());
|
||||
|
||||
$eval = new ReflectionMethod(ModuleManager::class, 'evalFreshModule');
|
||||
$this->assertSame(
|
||||
3,
|
||||
$eval->getNumberOfRequiredParameters(),
|
||||
'evalFreshModule 은 moduleFile, moduleClass, moduleDir 3개 필수 파라미터'
|
||||
);
|
||||
}
|
||||
|
||||
public function test_plugin_manager_has_reload_and_evalfresh_methods(): void
|
||||
{
|
||||
$this->assertTrue(
|
||||
method_exists(PluginManager::class, 'reloadPlugin'),
|
||||
'PluginManager::reloadPlugin 메서드가 존재해야 한다'
|
||||
);
|
||||
$this->assertTrue(
|
||||
method_exists(PluginManager::class, 'evalFreshPlugin'),
|
||||
'PluginManager::evalFreshPlugin 메서드가 존재해야 한다'
|
||||
);
|
||||
|
||||
$reload = new ReflectionMethod(PluginManager::class, 'reloadPlugin');
|
||||
$this->assertSame(1, $reload->getNumberOfRequiredParameters(), 'reloadPlugin 은 pluginName 1개 필수 파라미터');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Extension;
|
||||
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Extension\Vendor\VendorMode;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use ReflectionClass;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* Module Manager 의 vendor_mode 통합 회귀 테스트.
|
||||
*
|
||||
* 검증 대상:
|
||||
* - installModule() 의 VendorMode 파라미터가 Manager에 전달되는지
|
||||
* - updateModule() 의 VendorMode 파라미터 전달
|
||||
* - getPreviousVendorMode() 가 DB에서 vendor_mode 컬럼을 읽는지
|
||||
* - vendor_mode 마이그레이션이 modules/plugins 테이블에 적용되었는지
|
||||
*/
|
||||
class ModuleVendorModeIntegrationTest extends TestCase
|
||||
{
|
||||
public function test_modules_table_has_vendor_mode_column(): void
|
||||
{
|
||||
$hasColumn = DB::getSchemaBuilder()->hasColumn('modules', 'vendor_mode');
|
||||
$this->assertTrue($hasColumn, 'modules 테이블에 vendor_mode 컬럼이 있어야 합니다');
|
||||
}
|
||||
|
||||
public function test_plugins_table_has_vendor_mode_column(): void
|
||||
{
|
||||
$hasColumn = DB::getSchemaBuilder()->hasColumn('plugins', 'vendor_mode');
|
||||
$this->assertTrue($hasColumn, 'plugins 테이블에 vendor_mode 컬럼이 있어야 합니다');
|
||||
}
|
||||
|
||||
public function test_install_module_method_signature_accepts_vendor_mode(): void
|
||||
{
|
||||
$reflection = new ReflectionClass(ModuleManager::class);
|
||||
$method = $reflection->getMethod('installModule');
|
||||
$params = $method->getParameters();
|
||||
|
||||
$vendorParam = collect($params)->first(fn ($p) => $p->getName() === 'vendorMode');
|
||||
|
||||
$this->assertNotNull($vendorParam, 'installModule() 에 vendorMode 파라미터가 있어야 합니다');
|
||||
$this->assertSame(VendorMode::class, $vendorParam->getType()?->getName());
|
||||
}
|
||||
|
||||
public function test_update_module_method_signature_accepts_vendor_mode(): void
|
||||
{
|
||||
$reflection = new ReflectionClass(ModuleManager::class);
|
||||
$method = $reflection->getMethod('updateModule');
|
||||
$params = $method->getParameters();
|
||||
|
||||
$vendorParam = collect($params)->first(fn ($p) => $p->getName() === 'vendorMode');
|
||||
|
||||
$this->assertNotNull($vendorParam, 'updateModule() 에 vendorMode 파라미터가 있어야 합니다');
|
||||
$this->assertSame(VendorMode::class, $vendorParam->getType()?->getName());
|
||||
}
|
||||
|
||||
public function test_get_previous_vendor_mode_reads_from_db(): void
|
||||
{
|
||||
$manager = app(ModuleManager::class);
|
||||
$reflection = new ReflectionClass($manager);
|
||||
$method = $reflection->getMethod('getPreviousVendorMode');
|
||||
$method->setAccessible(true);
|
||||
|
||||
// 존재하지 않는 모듈 → null
|
||||
$result = $method->invoke($manager, 'nonexistent-test-module-'.uniqid());
|
||||
$this->assertNull($result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Installer;
|
||||
|
||||
use App\Extension\Vendor\VendorBundleInstaller;
|
||||
use App\Extension\Vendor\VendorBundler;
|
||||
use App\Extension\Vendor\VendorIntegrityChecker;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 웹 인스톨러 PHP shim 과 Laravel 클래스의 동등성 검증.
|
||||
*
|
||||
* public/install/includes/vendor-bundle-installer.php 의 함수들이
|
||||
* App\Extension\Vendor\VendorBundleInstaller / VendorIntegrityChecker 와
|
||||
* 동일한 입력에 대해 동일한 결과를 반환하는지 검증한다.
|
||||
*/
|
||||
class VendorBundleInstallerShimTest extends TestCase
|
||||
{
|
||||
private string $testDir;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->testDir = storage_path('app/test-shim-'.uniqid());
|
||||
File::ensureDirectoryExists($this->testDir);
|
||||
|
||||
require_once base_path('public/install/includes/vendor-bundle-installer.php');
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
if (File::isDirectory($this->testDir)) {
|
||||
File::deleteDirectory($this->testDir);
|
||||
}
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function createValidBundle(): void
|
||||
{
|
||||
$zipPath = $this->testDir.'/vendor-bundle.zip';
|
||||
$zip = new \ZipArchive;
|
||||
$zip->open($zipPath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
|
||||
$zip->addFromString('vendor/autoload.php', '<?php // shim test');
|
||||
$zip->addFromString('vendor/test/lib/file.php', '<?php // test lib');
|
||||
$zip->close();
|
||||
|
||||
File::put($this->testDir.'/vendor-bundle.json', json_encode([
|
||||
'schema_version' => VendorBundler::SCHEMA_VERSION,
|
||||
'zip_sha256' => hash_file('sha256', $zipPath),
|
||||
'package_count' => 1,
|
||||
'packages' => [['name' => 'test/lib', 'version' => '1.0.0', 'type' => 'library']],
|
||||
]));
|
||||
}
|
||||
|
||||
public function test_shim_verify_matches_laravel_class_on_valid_bundle(): void
|
||||
{
|
||||
$this->createValidBundle();
|
||||
|
||||
$checker = new VendorIntegrityChecker;
|
||||
$laravelResult = $checker->verify($this->testDir);
|
||||
|
||||
$shimResult = verifyVendorBundle($this->testDir);
|
||||
|
||||
$this->assertSame($laravelResult->valid, $shimResult['valid']);
|
||||
$this->assertSame($laravelResult->errors, $shimResult['errors']);
|
||||
}
|
||||
|
||||
public function test_shim_verify_matches_on_missing_zip(): void
|
||||
{
|
||||
$checker = new VendorIntegrityChecker;
|
||||
$laravelResult = $checker->verify($this->testDir);
|
||||
|
||||
$shimResult = verifyVendorBundle($this->testDir);
|
||||
|
||||
$this->assertFalse($laravelResult->valid);
|
||||
$this->assertFalse($shimResult['valid']);
|
||||
$this->assertContains('bundle_zip_missing', $shimResult['errors']);
|
||||
}
|
||||
|
||||
public function test_shim_verify_matches_on_hash_mismatch(): void
|
||||
{
|
||||
$this->createValidBundle();
|
||||
|
||||
// manifest 조작
|
||||
$manifest = json_decode(file_get_contents($this->testDir.'/vendor-bundle.json'), true);
|
||||
$manifest['zip_sha256'] = hash('sha256', 'tampered');
|
||||
File::put($this->testDir.'/vendor-bundle.json', json_encode($manifest));
|
||||
|
||||
$checker = new VendorIntegrityChecker;
|
||||
$laravelResult = $checker->verify($this->testDir);
|
||||
|
||||
$shimResult = verifyVendorBundle($this->testDir);
|
||||
|
||||
$this->assertFalse($laravelResult->valid);
|
||||
$this->assertFalse($shimResult['valid']);
|
||||
$this->assertContains('zip_hash_mismatch', $shimResult['errors']);
|
||||
}
|
||||
|
||||
public function test_shim_extract_produces_same_files_as_laravel_class(): void
|
||||
{
|
||||
// shim 경로
|
||||
$shimDir = $this->testDir.'/shim';
|
||||
File::ensureDirectoryExists($shimDir);
|
||||
$this->createBundleAt($shimDir);
|
||||
|
||||
// Laravel 경로
|
||||
$laravelDir = $this->testDir.'/laravel';
|
||||
File::ensureDirectoryExists($laravelDir);
|
||||
$this->createBundleAt($laravelDir);
|
||||
|
||||
// 양쪽 추출
|
||||
$shimResult = extractVendorBundle($shimDir, $shimDir);
|
||||
$this->assertTrue($shimResult['success'], 'shim 추출 실패: '.($shimResult['error'] ?? ''));
|
||||
|
||||
$installer = new VendorBundleInstaller(new VendorIntegrityChecker);
|
||||
$installer->install($laravelDir, $laravelDir);
|
||||
|
||||
// 추출된 파일이 동일한지 비교
|
||||
$this->assertFileExists($shimDir.'/vendor/autoload.php');
|
||||
$this->assertFileExists($laravelDir.'/vendor/autoload.php');
|
||||
$this->assertSame(
|
||||
file_get_contents($shimDir.'/vendor/autoload.php'),
|
||||
file_get_contents($laravelDir.'/vendor/autoload.php'),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_shim_rejects_unsafe_paths(): void
|
||||
{
|
||||
$zipPath = $this->testDir.'/vendor-bundle.zip';
|
||||
$zip = new \ZipArchive;
|
||||
$zip->open($zipPath, \ZipArchive::CREATE);
|
||||
$zip->addFromString('../evil.php', '<?php // evil');
|
||||
$zip->close();
|
||||
|
||||
File::put($this->testDir.'/vendor-bundle.json', json_encode([
|
||||
'schema_version' => VendorBundler::SCHEMA_VERSION,
|
||||
'zip_sha256' => hash_file('sha256', $zipPath),
|
||||
'package_count' => 0,
|
||||
]));
|
||||
|
||||
$result = extractVendorBundle($this->testDir, $this->testDir);
|
||||
$this->assertFalse($result['success']);
|
||||
$this->assertStringContainsString('unsafe_path', (string) ($result['error'] ?? ''));
|
||||
}
|
||||
|
||||
private function createBundleAt(string $dir): void
|
||||
{
|
||||
$zipPath = $dir.'/vendor-bundle.zip';
|
||||
$zip = new \ZipArchive;
|
||||
$zip->open($zipPath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
|
||||
$zip->addFromString('vendor/autoload.php', '<?php // identical content');
|
||||
$zip->close();
|
||||
|
||||
File::put($dir.'/vendor-bundle.json', json_encode([
|
||||
'schema_version' => VendorBundler::SCHEMA_VERSION,
|
||||
'zip_sha256' => hash_file('sha256', $zipPath),
|
||||
'package_count' => 0,
|
||||
]));
|
||||
}
|
||||
}
|
||||
@@ -2,14 +2,13 @@
|
||||
|
||||
namespace Tests\Feature\Mail;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Mail\DbTemplateMail;
|
||||
use App\Models\MailSendLog;
|
||||
use App\Models\MailTemplate;
|
||||
use App\Models\NotificationDefinition;
|
||||
use App\Models\NotificationTemplate;
|
||||
use App\Models\User;
|
||||
use App\Notifications\Auth\PasswordChangedNotification;
|
||||
use App\Notifications\Auth\ResetPasswordNotification;
|
||||
use App\Notifications\Auth\WelcomeNotification;
|
||||
use App\Notifications\GenericNotification;
|
||||
use App\Services\NotificationDefinitionService;
|
||||
use App\Services\NotificationTemplateService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
@@ -18,8 +17,8 @@ use Tests\TestCase;
|
||||
/**
|
||||
* 인증 알림 → DbTemplateMail 통합 테스트
|
||||
*
|
||||
* Notification.toMail()이 DB 템플릿을 해석하여 DbTemplateMail을 올바르게 생성하는지,
|
||||
* 비활성 템플릿일 때 logSkipped가 기록되는지 검증합니다.
|
||||
* GenericNotification.toMail()이 notification_templates에서 템플릿을 조회하여
|
||||
* DbTemplateMail을 올바르게 생성하는지, 비활성/미존재 시 스킵되는지 검증합니다.
|
||||
*/
|
||||
class AuthNotificationDbTemplateTest extends TestCase
|
||||
{
|
||||
@@ -35,36 +34,53 @@ class AuthNotificationDbTemplateTest extends TestCase
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// WelcomeNotification + DbTemplateMail
|
||||
// Welcome 알림 + DbTemplateMail
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* WelcomeNotification이 활성 템플릿으로 DbTemplateMail 생성
|
||||
* welcome 알림이 활성 템플릿으로 DbTemplateMail 생성
|
||||
*/
|
||||
public function test_welcome_notification_creates_db_template_mail(): void
|
||||
{
|
||||
MailTemplate::factory()->withType('welcome')->withVariables()->create();
|
||||
$this->createDefinitionWithMailChannel('welcome', 'core.auth', 'core', 'core', [
|
||||
'subject' => ['ko' => '[{app_name}] 환영합니다', 'en' => '[{app_name}] Welcome'],
|
||||
'body' => ['ko' => '<p>{name}님 환영합니다</p>', 'en' => '<p>Welcome {name}</p>'],
|
||||
]);
|
||||
|
||||
$user = User::factory()->create(['name' => '홍길동', 'email' => 'hong@example.com']);
|
||||
$notification = new WelcomeNotification();
|
||||
|
||||
$notification = new GenericNotification('welcome', 'core.auth', [
|
||||
'name' => $user->name,
|
||||
'app_name' => config('app.name'),
|
||||
'action_url' => config('app.url') . '/login',
|
||||
'site_url' => config('app.url'),
|
||||
]);
|
||||
|
||||
$mailable = $notification->toMail($user);
|
||||
|
||||
$this->assertInstanceOf(DbTemplateMail::class, $mailable);
|
||||
$this->assertEquals('welcome', $mailable->getTemplateType());
|
||||
$this->assertEquals(ExtensionOwnerType::Core, $mailable->getExtensionType());
|
||||
$this->assertEquals('core', $mailable->getExtensionIdentifier());
|
||||
$this->assertFalse($mailable->isSkipped());
|
||||
}
|
||||
|
||||
/**
|
||||
* WelcomeNotification의 DbTemplateMail에 수신자가 설정됨
|
||||
* welcome 알림의 DbTemplateMail에 수신자가 설정됨
|
||||
*/
|
||||
public function test_welcome_notification_sets_recipient(): void
|
||||
{
|
||||
MailTemplate::factory()->withType('welcome')->withVariables()->create();
|
||||
$this->createDefinitionWithMailChannel('welcome', 'core.auth', 'core', 'core', [
|
||||
'subject' => ['ko' => '환영', 'en' => 'Welcome'],
|
||||
'body' => ['ko' => '<p>환영</p>', 'en' => '<p>Welcome</p>'],
|
||||
]);
|
||||
|
||||
$user = User::factory()->create(['name' => '홍길동', 'email' => 'hong@example.com']);
|
||||
$notification = new WelcomeNotification();
|
||||
|
||||
$notification = new GenericNotification('welcome', 'core.auth', [
|
||||
'name' => '홍길동',
|
||||
'app_name' => 'G7 Test',
|
||||
'action_url' => 'https://g7.test/login',
|
||||
'site_url' => 'https://g7.test',
|
||||
]);
|
||||
|
||||
$mailable = $notification->toMail($user);
|
||||
|
||||
@@ -74,66 +90,48 @@ class AuthNotificationDbTemplateTest extends TestCase
|
||||
}
|
||||
|
||||
/**
|
||||
* WelcomeNotification이 비활성 템플릿에서 스킵 인스턴스 반환 + send() 시 logSkipped 기록
|
||||
*/
|
||||
public function test_welcome_notification_returns_skipped_and_logs_when_inactive(): void
|
||||
{
|
||||
MailTemplate::factory()->withType('welcome')->inactive()->create();
|
||||
|
||||
$user = User::factory()->create(['email' => 'test@example.com']);
|
||||
$notification = new WelcomeNotification();
|
||||
|
||||
$mailable = $notification->toMail($user);
|
||||
|
||||
$this->assertInstanceOf(DbTemplateMail::class, $mailable);
|
||||
$this->assertTrue($mailable->isSkipped());
|
||||
|
||||
$mailable->send(app('mailer'));
|
||||
|
||||
$log = MailSendLog::where('recipient_email', 'test@example.com')
|
||||
->where('template_type', 'welcome')
|
||||
->first();
|
||||
|
||||
$this->assertNotNull($log);
|
||||
$this->assertEquals('skipped', $log->status);
|
||||
$this->assertEquals('notification', $log->source);
|
||||
}
|
||||
|
||||
/**
|
||||
* WelcomeNotification이 템플릿 미존재 시 스킵 인스턴스 반환 + send() 시 logSkipped 기록
|
||||
* welcome 알림이 템플릿 미존재 시 스킵 인스턴스 반환
|
||||
*/
|
||||
public function test_welcome_notification_returns_skipped_when_no_template(): void
|
||||
{
|
||||
$user = User::factory()->create(['email' => 'notemplate@example.com']);
|
||||
$notification = new WelcomeNotification();
|
||||
|
||||
$notification = new GenericNotification('welcome', 'core.auth', [
|
||||
'name' => $user->name ?? '',
|
||||
'app_name' => 'G7 Test',
|
||||
'action_url' => 'https://g7.test/login',
|
||||
'site_url' => 'https://g7.test',
|
||||
]);
|
||||
|
||||
$mailable = $notification->toMail($user);
|
||||
|
||||
$this->assertInstanceOf(DbTemplateMail::class, $mailable);
|
||||
$this->assertTrue($mailable->isSkipped());
|
||||
|
||||
$mailable->send(app('mailer'));
|
||||
|
||||
$this->assertDatabaseHas('mail_send_logs', [
|
||||
'recipient_email' => 'notemplate@example.com',
|
||||
'template_type' => 'welcome',
|
||||
'status' => 'skipped',
|
||||
]);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// ResetPasswordNotification + DbTemplateMail
|
||||
// Reset Password 알림 + DbTemplateMail
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* ResetPasswordNotification이 활성 템플릿으로 DbTemplateMail 생성
|
||||
* reset_password 알림이 활성 템플릿으로 DbTemplateMail 생성
|
||||
*/
|
||||
public function test_reset_password_notification_creates_db_template_mail(): void
|
||||
{
|
||||
MailTemplate::factory()->withType('reset_password')->create();
|
||||
$this->createDefinitionWithMailChannel('reset_password', 'core.auth', 'core', 'core', [
|
||||
'subject' => ['ko' => '비밀번호 재설정', 'en' => 'Password Reset'],
|
||||
'body' => ['ko' => '<p>{name}님, 비밀번호 재설정</p>', 'en' => '<p>Reset password, {name}</p>'],
|
||||
]);
|
||||
|
||||
$user = User::factory()->create();
|
||||
$notification = new ResetPasswordNotification('test-token-123');
|
||||
|
||||
$notification = new GenericNotification('reset_password', 'core.auth', [
|
||||
'name' => $user->name ?? '',
|
||||
'app_name' => 'G7 Test',
|
||||
'action_url' => 'https://g7.test/reset-password?token=abc',
|
||||
'expire_minutes' => '60',
|
||||
'site_url' => 'https://g7.test',
|
||||
]);
|
||||
|
||||
$mailable = $notification->toMail($user);
|
||||
|
||||
@@ -141,59 +139,28 @@ class AuthNotificationDbTemplateTest extends TestCase
|
||||
$this->assertEquals('reset_password', $mailable->getTemplateType());
|
||||
}
|
||||
|
||||
/**
|
||||
* ResetPasswordNotification의 DbTemplateMail에 수신자가 설정됨
|
||||
*/
|
||||
public function test_reset_password_notification_sets_recipient(): void
|
||||
{
|
||||
MailTemplate::factory()->withType('reset_password')->create();
|
||||
|
||||
$user = User::factory()->create(['email' => 'reset@example.com', 'name' => 'Reset User']);
|
||||
$notification = new ResetPasswordNotification('test-token');
|
||||
|
||||
$mailable = $notification->toMail($user);
|
||||
|
||||
$to = collect($mailable->to)->first();
|
||||
$this->assertEquals('reset@example.com', $to['address']);
|
||||
}
|
||||
|
||||
/**
|
||||
* ResetPasswordNotification이 비활성 시 스킵 인스턴스 반환 + send() 시 logSkipped 기록
|
||||
*/
|
||||
public function test_reset_password_notification_logs_skipped_when_inactive(): void
|
||||
{
|
||||
MailTemplate::factory()->withType('reset_password')->inactive()->create();
|
||||
|
||||
$user = User::factory()->create(['email' => 'reset@example.com']);
|
||||
$notification = new ResetPasswordNotification('token');
|
||||
|
||||
$mailable = $notification->toMail($user);
|
||||
|
||||
$this->assertInstanceOf(DbTemplateMail::class, $mailable);
|
||||
$this->assertTrue($mailable->isSkipped());
|
||||
|
||||
$mailable->send(app('mailer'));
|
||||
|
||||
$this->assertDatabaseHas('mail_send_logs', [
|
||||
'recipient_email' => 'reset@example.com',
|
||||
'template_type' => 'reset_password',
|
||||
'status' => 'skipped',
|
||||
]);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// PasswordChangedNotification + DbTemplateMail
|
||||
// Password Changed 알림 + DbTemplateMail
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* PasswordChangedNotification이 활성 템플릿으로 DbTemplateMail 생성
|
||||
* password_changed 알림이 활성 템플릿으로 DbTemplateMail 생성
|
||||
*/
|
||||
public function test_password_changed_notification_creates_db_template_mail(): void
|
||||
{
|
||||
MailTemplate::factory()->withType('password_changed')->create();
|
||||
$this->createDefinitionWithMailChannel('password_changed', 'core.auth', 'core', 'core', [
|
||||
'subject' => ['ko' => '비밀번호 변경', 'en' => 'Password Changed'],
|
||||
'body' => ['ko' => '<p>{name}님, 비밀번호 변경됨</p>', 'en' => '<p>Password changed, {name}</p>'],
|
||||
]);
|
||||
|
||||
$user = User::factory()->create();
|
||||
$notification = new PasswordChangedNotification();
|
||||
|
||||
$notification = new GenericNotification('password_changed', 'core.auth', [
|
||||
'name' => $user->name ?? '',
|
||||
'app_name' => 'G7 Test',
|
||||
'action_url' => 'https://g7.test/login',
|
||||
'site_url' => 'https://g7.test',
|
||||
]);
|
||||
|
||||
$mailable = $notification->toMail($user);
|
||||
|
||||
@@ -202,75 +169,78 @@ class AuthNotificationDbTemplateTest extends TestCase
|
||||
}
|
||||
|
||||
/**
|
||||
* PasswordChangedNotification이 비활성 시 스킵 인스턴스 반환 + send() 시 logSkipped 기록
|
||||
* password_changed 알림이 비활성 템플릿에서 스킵 반환
|
||||
*/
|
||||
public function test_password_changed_notification_logs_skipped_when_inactive(): void
|
||||
public function test_password_changed_notification_returns_skipped_when_inactive(): void
|
||||
{
|
||||
MailTemplate::factory()->withType('password_changed')->inactive()->create();
|
||||
$this->createDefinitionWithMailChannel('password_changed', 'core.auth', 'core', 'core', [
|
||||
'subject' => ['ko' => '비밀번호 변경', 'en' => 'Password Changed'],
|
||||
'body' => ['ko' => '<p>변경됨</p>', 'en' => '<p>Changed</p>'],
|
||||
], templateActive: false);
|
||||
|
||||
$user = User::factory()->create(['email' => 'changed@example.com']);
|
||||
$notification = new PasswordChangedNotification();
|
||||
|
||||
$notification = new GenericNotification('password_changed', 'core.auth', [
|
||||
'name' => $user->name ?? '',
|
||||
'app_name' => 'G7 Test',
|
||||
'action_url' => 'https://g7.test/login',
|
||||
'site_url' => 'https://g7.test',
|
||||
]);
|
||||
|
||||
$mailable = $notification->toMail($user);
|
||||
|
||||
$this->assertInstanceOf(DbTemplateMail::class, $mailable);
|
||||
$this->assertTrue($mailable->isSkipped());
|
||||
}
|
||||
|
||||
$mailable->send(app('mailer'));
|
||||
// ========================================================================
|
||||
// 헬퍼 메서드
|
||||
// ========================================================================
|
||||
|
||||
$this->assertDatabaseHas('mail_send_logs', [
|
||||
'recipient_email' => 'changed@example.com',
|
||||
'template_type' => 'password_changed',
|
||||
'status' => 'skipped',
|
||||
/**
|
||||
* NotificationDefinition + NotificationTemplate(mail 채널) 생성 헬퍼.
|
||||
*
|
||||
* @param string $type
|
||||
* @param string $hookPrefix
|
||||
* @param string $extensionType
|
||||
* @param string $extensionIdentifier
|
||||
* @param array $templateData ['subject' => [...], 'body' => [...]]
|
||||
* @param bool $templateActive
|
||||
* @return NotificationDefinition
|
||||
*/
|
||||
private function createDefinitionWithMailChannel(
|
||||
string $type,
|
||||
string $hookPrefix,
|
||||
string $extensionType,
|
||||
string $extensionIdentifier,
|
||||
array $templateData,
|
||||
bool $templateActive = true,
|
||||
): NotificationDefinition {
|
||||
$definition = NotificationDefinition::create([
|
||||
'type' => $type,
|
||||
'hook_prefix' => $hookPrefix,
|
||||
'extension_type' => $extensionType,
|
||||
'extension_identifier' => $extensionIdentifier,
|
||||
'name' => ['ko' => $type, 'en' => $type],
|
||||
'variables' => [],
|
||||
'channels' => ['mail'],
|
||||
'hooks' => [],
|
||||
'is_active' => true,
|
||||
'is_default' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// DbTemplateMail 속성 검증
|
||||
// ========================================================================
|
||||
NotificationTemplate::create([
|
||||
'definition_id' => $definition->id,
|
||||
'channel' => 'mail',
|
||||
'subject' => $templateData['subject'],
|
||||
'body' => $templateData['body'],
|
||||
'is_active' => $templateActive,
|
||||
'is_default' => true,
|
||||
]);
|
||||
|
||||
/**
|
||||
* DbTemplateMail의 커스텀 헤더가 올바르게 설정됨
|
||||
*/
|
||||
public function test_db_template_mail_has_custom_headers(): void
|
||||
{
|
||||
$mail = new DbTemplateMail(
|
||||
renderedSubject: 'Test Subject',
|
||||
renderedBody: '<p>Test</p>',
|
||||
recipientEmail: 'test@example.com',
|
||||
templateType: 'welcome',
|
||||
extensionType: ExtensionOwnerType::Core,
|
||||
extensionIdentifier: 'core',
|
||||
source: 'notification',
|
||||
);
|
||||
app(NotificationDefinitionService::class)->invalidateCache($type);
|
||||
app(NotificationTemplateService::class)->invalidateCache($type, 'mail');
|
||||
|
||||
$headers = $mail->headers();
|
||||
$textHeaders = $headers->text;
|
||||
|
||||
$this->assertEquals('welcome', $textHeaders['X-G7-Template-Type']);
|
||||
$this->assertEquals('core', $textHeaders['X-G7-Extension-Type']);
|
||||
$this->assertEquals('core', $textHeaders['X-G7-Extension-Id']);
|
||||
$this->assertEquals('notification', $textHeaders['X-G7-Source']);
|
||||
}
|
||||
|
||||
/**
|
||||
* DbTemplateMail의 getter 메서드 검증
|
||||
*/
|
||||
public function test_db_template_mail_getters(): void
|
||||
{
|
||||
$mail = new DbTemplateMail(
|
||||
renderedSubject: 'Subject',
|
||||
renderedBody: '<p>Body</p>',
|
||||
recipientEmail: 'test@example.com',
|
||||
templateType: 'reset_password',
|
||||
extensionType: ExtensionOwnerType::Module,
|
||||
extensionIdentifier: 'sirsoft-board',
|
||||
source: 'test_mail',
|
||||
);
|
||||
|
||||
$this->assertEquals('reset_password', $mail->getTemplateType());
|
||||
$this->assertEquals(ExtensionOwnerType::Module, $mail->getExtensionType());
|
||||
$this->assertEquals('sirsoft-board', $mail->getExtensionIdentifier());
|
||||
$this->assertEquals('test_mail', $mail->getSource());
|
||||
return $definition;
|
||||
}
|
||||
}
|
||||
@@ -95,29 +95,33 @@ class ModuleRolePermissionTest extends TestCase
|
||||
*
|
||||
* 계층형 구조로 권한이 생성됨:
|
||||
* - 1레벨: 모듈 노드 (sirsoft-board)
|
||||
* - 2레벨: 카테고리 노드 (sirsoft-board.boards, sirsoft-board.reports)
|
||||
* - 3레벨: 개별 권한 (sirsoft-board.boards.read, create, update, delete, sirsoft-board.reports.view, manage)
|
||||
* - 2레벨: 카테고리 노드 (sirsoft-board.boards, sirsoft-board.settings, sirsoft-board.reports)
|
||||
* - 3레벨: 개별 권한 (boards: read/create/update/delete, settings: read/update, reports: view/manage)
|
||||
*/
|
||||
public function test_module_installation_creates_permissions(): void
|
||||
{
|
||||
$this->moduleManager->installModule('sirsoft-board');
|
||||
|
||||
// 권한이 생성되었는지 확인 (계층형 구조: 모듈 1 + 카테고리 2 + 개별 권한 6 = 9개)
|
||||
// 권한이 생성되었는지 확인 (계층형 구조: 모듈 1 + 카테고리 3 + 개별 권한 8 = 12개)
|
||||
$permissions = Permission::where('extension_type', ExtensionOwnerType::Module)
|
||||
->where('extension_identifier', 'sirsoft-board')->get();
|
||||
$this->assertCount(9, $permissions);
|
||||
$this->assertCount(12, $permissions);
|
||||
|
||||
$identifiers = $permissions->pluck('identifier')->toArray();
|
||||
// 1레벨: 모듈 노드
|
||||
$this->assertContains('sirsoft-board', $identifiers);
|
||||
// 2레벨: 카테고리 노드
|
||||
$this->assertContains('sirsoft-board.boards', $identifiers);
|
||||
$this->assertContains('sirsoft-board.settings', $identifiers);
|
||||
$this->assertContains('sirsoft-board.reports', $identifiers);
|
||||
// 3레벨: 개별 권한 - boards
|
||||
$this->assertContains('sirsoft-board.boards.read', $identifiers);
|
||||
$this->assertContains('sirsoft-board.boards.create', $identifiers);
|
||||
$this->assertContains('sirsoft-board.boards.update', $identifiers);
|
||||
$this->assertContains('sirsoft-board.boards.delete', $identifiers);
|
||||
// 3레벨: 개별 권한 - settings
|
||||
$this->assertContains('sirsoft-board.settings.read', $identifiers);
|
||||
$this->assertContains('sirsoft-board.settings.update', $identifiers);
|
||||
// 3레벨: 개별 권한 - reports
|
||||
$this->assertContains('sirsoft-board.reports.view', $identifiers);
|
||||
$this->assertContains('sirsoft-board.reports.manage', $identifiers);
|
||||
@@ -130,10 +134,10 @@ class ModuleRolePermissionTest extends TestCase
|
||||
{
|
||||
$this->moduleManager->installModule('sirsoft-board');
|
||||
|
||||
// admin role에 모든 개별 권한(6개)이 할당되었는지 확인
|
||||
// admin role에 모든 개별 권한(8개)이 할당되었는지 확인 (boards 4 + settings 2 + reports 2)
|
||||
$adminRole = Role::where('identifier', 'admin')->first();
|
||||
$adminPermissions = $adminRole->permissions()->where('extension_identifier', 'sirsoft-board')->get();
|
||||
$this->assertCount(6, $adminPermissions);
|
||||
$this->assertCount(8, $adminPermissions);
|
||||
|
||||
// manager role에 할당된 권한 확인 (boards: read, create, update + reports: view = 4개)
|
||||
$managerRole = Role::where('identifier', 'manager')->first();
|
||||
@@ -280,16 +284,16 @@ class ModuleRolePermissionTest extends TestCase
|
||||
$this->moduleManager->installModule('sirsoft-board');
|
||||
|
||||
// 계층형 구조에서 개별 권한(3레벨)만 role에 할당됨
|
||||
// 모듈의 getPermissions()에서 정의된 개별 권한 6개만 할당되어야 함
|
||||
// 모듈의 getPermissions()에서 정의된 개별 권한 8개만 할당되어야 함
|
||||
$adminRole = Role::where('identifier', 'admin')->first();
|
||||
|
||||
// admin role에 할당된 모듈 권한 개수 확인 (개별 권한 6개)
|
||||
// admin role에 할당된 모듈 권한 개수 확인 (개별 권한 8개)
|
||||
$assignedPermissions = $adminRole->permissions()->where('extension_identifier', 'sirsoft-board')->count();
|
||||
$this->assertEquals(6, $assignedPermissions);
|
||||
$this->assertEquals(8, $assignedPermissions);
|
||||
|
||||
// 전체 모듈 권한 개수 확인 (모듈 1 + 카테고리 2 + 개별 6 = 9개)
|
||||
// 전체 모듈 권한 개수 확인 (모듈 1 + 카테고리 3 + 개별 8 = 12개)
|
||||
$totalModulePermissions = Permission::where('extension_identifier', 'sirsoft-board')->count();
|
||||
$this->assertEquals(9, $totalModulePermissions);
|
||||
$this->assertEquals(12, $totalModulePermissions);
|
||||
|
||||
// 개별 권한만 role에 할당되었는지 확인
|
||||
$assignedIdentifiers = $adminRole->permissions()
|
||||
@@ -301,12 +305,15 @@ class ModuleRolePermissionTest extends TestCase
|
||||
$this->assertContains('sirsoft-board.boards.create', $assignedIdentifiers);
|
||||
$this->assertContains('sirsoft-board.boards.update', $assignedIdentifiers);
|
||||
$this->assertContains('sirsoft-board.boards.delete', $assignedIdentifiers);
|
||||
$this->assertContains('sirsoft-board.settings.read', $assignedIdentifiers);
|
||||
$this->assertContains('sirsoft-board.settings.update', $assignedIdentifiers);
|
||||
$this->assertContains('sirsoft-board.reports.view', $assignedIdentifiers);
|
||||
$this->assertContains('sirsoft-board.reports.manage', $assignedIdentifiers);
|
||||
|
||||
// 모듈 노드와 카테고리 노드는 할당되지 않음
|
||||
$this->assertNotContains('sirsoft-board', $assignedIdentifiers);
|
||||
$this->assertNotContains('sirsoft-board.boards', $assignedIdentifiers);
|
||||
$this->assertNotContains('sirsoft-board.settings', $assignedIdentifiers);
|
||||
$this->assertNotContains('sirsoft-board.reports', $assignedIdentifiers);
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ class SitemapTest extends TestCase
|
||||
|
||||
// 캐시에 XML 미리 저장하여 Generator 호출 방지
|
||||
$sampleXml = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>';
|
||||
Cache::put('seo:sitemap', $sampleXml, 86400);
|
||||
Cache::put('g7:core:seo.sitemap', $sampleXml, 86400);
|
||||
|
||||
$response = $this->get('/sitemap.xml');
|
||||
|
||||
@@ -67,7 +67,7 @@ class SitemapTest extends TestCase
|
||||
.'<url><loc>https://example.com/cached</loc></url>'
|
||||
.'</urlset>';
|
||||
|
||||
Cache::put('seo:sitemap', $cachedXml, 86400);
|
||||
Cache::put('g7:core:seo.sitemap', $cachedXml, 86400);
|
||||
|
||||
$response = $this->get('/sitemap.xml');
|
||||
|
||||
@@ -86,7 +86,7 @@ class SitemapTest extends TestCase
|
||||
Config::set('g7_settings.core.seo.sitemap_cache_ttl', 3600);
|
||||
|
||||
// 캐시 비우기
|
||||
Cache::forget('seo:sitemap');
|
||||
Cache::forget('g7:core:seo.sitemap');
|
||||
|
||||
$generatedXml = '<?xml version="1.0" encoding="UTF-8"?>'
|
||||
.'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
|
||||
@@ -109,7 +109,7 @@ class SitemapTest extends TestCase
|
||||
$this->assertSame($generatedXml, $response->getContent());
|
||||
|
||||
// 캐시에 저장되었는지 확인
|
||||
$this->assertSame($generatedXml, Cache::get('seo:sitemap'));
|
||||
$this->assertSame($generatedXml, Cache::get('g7:core:seo.sitemap'));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -135,7 +135,7 @@ class SitemapTest extends TestCase
|
||||
Config::set('g7_settings.core.seo.sitemap_enabled', true);
|
||||
|
||||
$sampleXml = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>';
|
||||
Cache::put('seo:sitemap', $sampleXml, 86400);
|
||||
Cache::put('g7:core:seo.sitemap', $sampleXml, 86400);
|
||||
|
||||
$response = $this->get('/sitemap.xml');
|
||||
|
||||
@@ -156,7 +156,7 @@ class SitemapTest extends TestCase
|
||||
.' </url>'."\n"
|
||||
.'</urlset>';
|
||||
|
||||
Cache::put('seo:sitemap', $validXml, 86400);
|
||||
Cache::put('g7:core:seo.sitemap', $validXml, 86400);
|
||||
|
||||
$response = $this->get('/sitemap.xml');
|
||||
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Services;
|
||||
|
||||
use App\Services\CoreUpdateService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* CoreUpdateService::collectBundledExtensionUpdates() 테스트.
|
||||
*
|
||||
* 핵심 불변:
|
||||
* - _bundled/{id}/{manifest}.json 의 version 이 DB 현재 version 보다 크면 감지
|
||||
* - GitHub 상태와 무관 (Manager::checkXxxUpdate() 의 GitHub 엄격 우선 정책 우회)
|
||||
* - _bundled manifest 부재 또는 버전 동일/이하면 미감지
|
||||
*/
|
||||
class CollectBundledExtensionUpdatesTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private string $modulesDir;
|
||||
|
||||
private string $pluginsDir;
|
||||
|
||||
private string $templatesDir;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->modulesDir = base_path('modules/_bundled');
|
||||
$this->pluginsDir = base_path('plugins/_bundled');
|
||||
$this->templatesDir = base_path('templates/_bundled');
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
// 테스트용 임시 번들 디렉토리 정리
|
||||
foreach (['test-bundled-mod', 'test-same-mod', 'test-older-mod'] as $id) {
|
||||
$path = $this->modulesDir.'/'.$id;
|
||||
if (File::isDirectory($path)) {
|
||||
File::deleteDirectory($path);
|
||||
}
|
||||
}
|
||||
foreach (['test-bundled-plug'] as $id) {
|
||||
$path = $this->pluginsDir.'/'.$id;
|
||||
if (File::isDirectory($path)) {
|
||||
File::deleteDirectory($path);
|
||||
}
|
||||
}
|
||||
foreach (['test-bundled-tpl'] as $id) {
|
||||
$path = $this->templatesDir.'/'.$id;
|
||||
if (File::isDirectory($path)) {
|
||||
File::deleteDirectory($path);
|
||||
}
|
||||
}
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function writeManifest(string $dir, string $id, string $manifestName, string $version): void
|
||||
{
|
||||
$path = $dir.'/'.$id;
|
||||
File::ensureDirectoryExists($path);
|
||||
File::put($path.'/'.$manifestName, json_encode(['identifier' => $id, 'version' => $version]));
|
||||
}
|
||||
|
||||
public function test_detects_bundled_module_with_newer_version(): void
|
||||
{
|
||||
DB::table('modules')->insert([
|
||||
'identifier' => 'test-bundled-mod',
|
||||
'vendor' => 'test',
|
||||
'name' => json_encode(['ko' => 'T']),
|
||||
'description' => json_encode(['ko' => 'T']),
|
||||
'version' => '1.0.0',
|
||||
'status' => 'active',
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
$this->writeManifest($this->modulesDir, 'test-bundled-mod', 'module.json', '1.1.0');
|
||||
|
||||
$result = app(CoreUpdateService::class)->collectBundledExtensionUpdates();
|
||||
|
||||
$modules = collect($result['modules'])->pluck('identifier')->all();
|
||||
$this->assertContains('test-bundled-mod', $modules);
|
||||
|
||||
$entry = collect($result['modules'])->firstWhere('identifier', 'test-bundled-mod');
|
||||
$this->assertEquals('1.0.0', $entry['current_version']);
|
||||
$this->assertEquals('1.1.0', $entry['latest_version']);
|
||||
$this->assertEquals('bundled', $entry['update_source']);
|
||||
}
|
||||
|
||||
public function test_skips_when_bundled_version_equals_current(): void
|
||||
{
|
||||
DB::table('modules')->insert([
|
||||
'identifier' => 'test-same-mod',
|
||||
'vendor' => 'test',
|
||||
'name' => json_encode(['ko' => 'T']),
|
||||
'description' => json_encode(['ko' => 'T']),
|
||||
'version' => '1.2.3',
|
||||
'status' => 'active',
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
$this->writeManifest($this->modulesDir, 'test-same-mod', 'module.json', '1.2.3');
|
||||
|
||||
$result = app(CoreUpdateService::class)->collectBundledExtensionUpdates();
|
||||
|
||||
$modules = collect($result['modules'])->pluck('identifier')->all();
|
||||
$this->assertNotContains('test-same-mod', $modules);
|
||||
}
|
||||
|
||||
public function test_skips_when_bundled_version_is_older(): void
|
||||
{
|
||||
DB::table('modules')->insert([
|
||||
'identifier' => 'test-older-mod',
|
||||
'vendor' => 'test',
|
||||
'name' => json_encode(['ko' => 'T']),
|
||||
'description' => json_encode(['ko' => 'T']),
|
||||
'version' => '2.0.0',
|
||||
'status' => 'active',
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
$this->writeManifest($this->modulesDir, 'test-older-mod', 'module.json', '1.9.0');
|
||||
|
||||
$result = app(CoreUpdateService::class)->collectBundledExtensionUpdates();
|
||||
|
||||
$modules = collect($result['modules'])->pluck('identifier')->all();
|
||||
$this->assertNotContains('test-older-mod', $modules);
|
||||
}
|
||||
|
||||
public function test_detects_bundled_plugin_and_template_with_newer_version(): void
|
||||
{
|
||||
DB::table('plugins')->insert([
|
||||
'identifier' => 'test-bundled-plug',
|
||||
'vendor' => 'test',
|
||||
'name' => json_encode(['ko' => 'T']),
|
||||
'description' => json_encode(['ko' => 'T']),
|
||||
'version' => '1.0.0',
|
||||
'status' => 'active',
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
$this->writeManifest($this->pluginsDir, 'test-bundled-plug', 'plugin.json', '1.1.0');
|
||||
|
||||
DB::table('templates')->insert([
|
||||
'identifier' => 'test-bundled-tpl',
|
||||
'vendor' => 'test',
|
||||
'type' => 'admin',
|
||||
'name' => json_encode(['ko' => 'T']),
|
||||
'description' => json_encode(['ko' => 'T']),
|
||||
'version' => '1.0.0',
|
||||
'status' => 'active',
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
$this->writeManifest($this->templatesDir, 'test-bundled-tpl', 'template.json', '1.2.0');
|
||||
|
||||
$result = app(CoreUpdateService::class)->collectBundledExtensionUpdates();
|
||||
|
||||
$pluginIds = collect($result['plugins'])->pluck('identifier')->all();
|
||||
$templateIds = collect($result['templates'])->pluck('identifier')->all();
|
||||
|
||||
$this->assertContains('test-bundled-plug', $pluginIds);
|
||||
$this->assertContains('test-bundled-tpl', $templateIds);
|
||||
}
|
||||
}
|
||||
@@ -192,15 +192,15 @@ class PublicLayoutControllerTest extends TestCase
|
||||
]);
|
||||
|
||||
// 캐시 초기화
|
||||
Cache::forget("layout.{$template->identifier}.{$layout->name}");
|
||||
Cache::forget("template.{$template->id}.layout.{$layout->name}");
|
||||
Cache::forget("g7:core:layout.{$template->identifier}.{$layout->name}.v0");
|
||||
Cache::forget("g7:core:template.{$template->id}.layout.{$layout->name}");
|
||||
|
||||
// Act: 첫 번째 요청 (캐시 생성)
|
||||
$response1 = $this->getJson("/api/layouts/{$template->identifier}/{$layout->name}.json");
|
||||
$response1->assertStatus(200);
|
||||
|
||||
// 캐시가 생성되었는지 확인
|
||||
$this->assertTrue(Cache::has("layout.{$template->identifier}.{$layout->name}"));
|
||||
$this->assertTrue(Cache::has("g7:core:layout.{$template->identifier}.{$layout->name}.v0"));
|
||||
|
||||
// Act: 두 번째 요청 (캐시에서 조회)
|
||||
$response2 = $this->getJson("/api/layouts/{$template->identifier}/{$layout->name}.json");
|
||||
|
||||
@@ -124,7 +124,7 @@ class TemplateCacheManagementTest extends TestCase
|
||||
);
|
||||
|
||||
// 캐시 버전을 과거 값으로 설정하여 비활성화 후 증가를 검증
|
||||
Cache::put('extension_cache_version', 1000);
|
||||
Cache::put('g7:core:ext.cache_version', 1000);
|
||||
|
||||
// Act
|
||||
$this->templateManager->deactivateTemplate('sirsoft-admin_basic');
|
||||
@@ -189,7 +189,7 @@ class TemplateCacheManagementTest extends TestCase
|
||||
);
|
||||
|
||||
// 캐시 버전을 과거 값으로 설정하여 제거 후 증가를 검증
|
||||
Cache::put('extension_cache_version', 1000);
|
||||
Cache::put('g7:core:ext.cache_version', 1000);
|
||||
|
||||
// Act (spy가 활성 디렉토리 삭제/이동 차단)
|
||||
$this->templateManager->uninstallTemplate('sirsoft-admin_basic');
|
||||
@@ -251,7 +251,7 @@ class TemplateCacheManagementTest extends TestCase
|
||||
|
||||
// 수동으로 내부 레이아웃 캐시 생성 (버전 없는 LayoutService 캐시 키)
|
||||
foreach ($layouts as $layout) {
|
||||
$cacheKey = "template.{$template->id}.layout.{$layout->name}";
|
||||
$cacheKey = "g7:core:template.{$template->id}.layout.{$layout->name}";
|
||||
Cache::put($cacheKey, ['test' => 'data'], 3600);
|
||||
}
|
||||
|
||||
@@ -260,7 +260,7 @@ class TemplateCacheManagementTest extends TestCase
|
||||
|
||||
// Assert - 내부 레이아웃 캐시가 삭제되었는지 확인
|
||||
foreach ($layouts as $layout) {
|
||||
$cacheKey = "template.{$template->id}.layout.{$layout->name}";
|
||||
$cacheKey = "g7:core:template.{$template->id}.layout.{$layout->name}";
|
||||
$this->assertFalse(
|
||||
Cache::has($cacheKey),
|
||||
"비활성화 후 {$layout->name} 내부 레이아웃 캐시가 삭제되어야 합니다."
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Upgrade;
|
||||
|
||||
use App\Services\CoreUpdateService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* Test-2: `CoreUpdateService::reloadCoreConfigAndResync()` 가
|
||||
*
|
||||
* 1. config/core.php 를 디스크에서 다시 require 하고
|
||||
* 2. config repository 의 'core' 네임스페이스를 갱신하며
|
||||
* 3. syncCoreRolesAndPermissions / syncCoreMenus 를 재호출하여 DB 에 반영
|
||||
*
|
||||
* 하는지 실증한다. 경로 B (spawn) 실패 시 in-process fallback 으로 사용되는 핵심 로직.
|
||||
*
|
||||
* 파일 IO 경로는 config_path('core.php') 를 일시적으로 백업/복원하는 방식으로 검증한다.
|
||||
* tearDown 에서 원본을 반드시 복원하므로 테스트 실패 시에도 데이터 손상은 없다.
|
||||
*/
|
||||
class CoreConfigReloadTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private string $coreConfigPath;
|
||||
|
||||
private string $backupPath;
|
||||
|
||||
private bool $backupCreated = false;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->coreConfigPath = config_path('core.php');
|
||||
$this->backupPath = $this->coreConfigPath.'.test-backup-'.uniqid();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
// 테스트 실패 시에도 원본 복원 보장
|
||||
if ($this->backupCreated && File::exists($this->backupPath)) {
|
||||
File::copy($this->backupPath, $this->coreConfigPath);
|
||||
File::delete($this->backupPath);
|
||||
// 메모리 config 도 원본으로 재주입
|
||||
config(['core' => require $this->coreConfigPath]);
|
||||
}
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_reloadCoreConfigAndResync_runs_without_error_on_current_config(): void
|
||||
{
|
||||
$service = app(CoreUpdateService::class);
|
||||
|
||||
// 현재 config/core.php 기반으로 재동기화 수행 — 예외 없이 완료해야 한다
|
||||
$service->reloadCoreConfigAndResync();
|
||||
|
||||
// 코어 최상위 권한(module) 이 DB 에 존재해야 한다
|
||||
$coreIdentifier = config('core.permissions.module.identifier', 'core');
|
||||
$this->assertDatabaseHas('permissions', ['identifier' => $coreIdentifier]);
|
||||
}
|
||||
|
||||
public function test_reloadCoreConfigAndResync_picks_up_disk_changes(): void
|
||||
{
|
||||
if (! File::exists($this->coreConfigPath)) {
|
||||
$this->markTestSkipped('config/core.php 미존재');
|
||||
}
|
||||
|
||||
// 1. 원본 백업
|
||||
File::copy($this->coreConfigPath, $this->backupPath);
|
||||
$this->backupCreated = true;
|
||||
|
||||
// 2. 디스크의 config/core.php 에 새 권한 1건 추가 (category/permission 둘 다 신규)
|
||||
$original = require $this->coreConfigPath;
|
||||
$modified = $original;
|
||||
$modified['permissions']['categories'][] = [
|
||||
'identifier' => 'core.test_reload_disk',
|
||||
'name' => ['ko' => '테스트 재로드', 'en' => 'Test Reload'],
|
||||
'description' => ['ko' => 'Test reload disk sync', 'en' => 'Test reload disk sync'],
|
||||
'order' => 9999,
|
||||
'permissions' => [
|
||||
[
|
||||
'identifier' => 'core.test_reload_disk.read',
|
||||
'type' => 'admin',
|
||||
'name' => ['ko' => '테스트 재로드 조회', 'en' => 'View Test Reload'],
|
||||
'description' => ['ko' => 'Can view', 'en' => 'Can view'],
|
||||
'order' => 1,
|
||||
],
|
||||
],
|
||||
];
|
||||
File::put($this->coreConfigPath, '<?php return '.var_export($modified, true).';');
|
||||
|
||||
// 3. 메모리 config 는 아직 구 값 (Laravel 부팅 시점 기준)
|
||||
$memoryNames = collect(config('core.permissions.categories', []))
|
||||
->pluck('identifier')
|
||||
->all();
|
||||
$this->assertNotContains(
|
||||
'core.test_reload_disk',
|
||||
$memoryNames,
|
||||
'메모리 config 에는 아직 신규 권한이 없어야 한다 (디스크만 변경됨)'
|
||||
);
|
||||
|
||||
// 4. reloadCoreConfigAndResync 호출 → 디스크 재읽기 + sync
|
||||
$service = app(CoreUpdateService::class);
|
||||
$service->reloadCoreConfigAndResync();
|
||||
|
||||
// 5. DB 에 신규 권한이 반영되어야 한다
|
||||
$this->assertDatabaseHas('permissions', [
|
||||
'identifier' => 'core.test_reload_disk.read',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_reloadCoreConfigAndResync_skips_gracefully_if_file_missing(): void
|
||||
{
|
||||
if (! File::exists($this->coreConfigPath)) {
|
||||
$this->markTestSkipped('config/core.php 미존재');
|
||||
}
|
||||
|
||||
// 원본 백업 후 일시 삭제
|
||||
File::copy($this->coreConfigPath, $this->backupPath);
|
||||
$this->backupCreated = true;
|
||||
File::delete($this->coreConfigPath);
|
||||
|
||||
try {
|
||||
$service = app(CoreUpdateService::class);
|
||||
$service->reloadCoreConfigAndResync();
|
||||
$this->assertTrue(true, 'config 파일 미존재 시 예외 없이 정상 반환해야 한다');
|
||||
} finally {
|
||||
// 즉시 복원 (tearDown 이전에도)
|
||||
File::copy($this->backupPath, $this->coreConfigPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Upgrade;
|
||||
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* Test-1: 경로 B — `core:execute-upgrade-steps` 가 별도 PHP 프로세스로 실행될 때
|
||||
* 최신 파일 기준으로 클래스를 로드함을 실증한다.
|
||||
*
|
||||
* 시나리오:
|
||||
* 1. 임시 Service 클래스(`app/Services/TestUpgradeSpawnMarkerService.php`) 작성 —
|
||||
* 프로세스 메모리 캐시와 무관한 마커 파일을 생성하는 정적 메서드 보유
|
||||
* 2. 임시 upgrade 파일(`upgrades/Upgrade_0_0_1_test_spawn.php`) 작성 — run() 이
|
||||
* 신규 Service 의 정적 메서드 호출
|
||||
* 3. `proc_open` 으로 `php artisan core:execute-upgrade-steps --from=0.0.0 --to=0.0.1 --force`
|
||||
* 실행 → 새 PHP 프로세스가 방금 작성한 파일들을 autoload 로 읽어 실행
|
||||
* 4. 마커 파일 존재로 정상 호출 검증
|
||||
* 5. tearDown: 임시 파일 3종(Service, Upgrade, 마커) 삭제
|
||||
*
|
||||
* 본 테스트가 통과하면 경로 B 구조(별도 프로세스 spawn → 최신 클래스 로드)가
|
||||
* 실제로 작동함을 보장한다.
|
||||
*/
|
||||
class CoreUpgradeStepSpawnTest extends TestCase
|
||||
{
|
||||
private string $tmpServicePath;
|
||||
|
||||
private string $tmpUpgradePath;
|
||||
|
||||
private string $markerPath;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->tmpServicePath = base_path('app/Services/TestUpgradeSpawnMarkerService.php');
|
||||
$this->tmpUpgradePath = base_path('upgrades/Upgrade_0_0_1_test_spawn.php');
|
||||
$this->markerPath = storage_path('app/test-upgrade-spawn-marker-'.uniqid().'.txt');
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
foreach ([$this->tmpServicePath, $this->tmpUpgradePath, $this->markerPath] as $p) {
|
||||
if (File::exists($p)) {
|
||||
File::delete($p);
|
||||
}
|
||||
}
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_spawned_process_loads_fresh_classes(): void
|
||||
{
|
||||
if (! function_exists('proc_open')) {
|
||||
$this->markTestSkipped('proc_open 미지원 환경');
|
||||
}
|
||||
|
||||
$markerPath = addslashes($this->markerPath);
|
||||
|
||||
$serviceCode = <<<PHP
|
||||
<?php
|
||||
|
||||
namespace App\\Services;
|
||||
|
||||
class TestUpgradeSpawnMarkerService
|
||||
{
|
||||
public static function writeMarker(): void
|
||||
{
|
||||
file_put_contents('{$markerPath}', 'spawned:'.getmypid());
|
||||
}
|
||||
}
|
||||
PHP;
|
||||
|
||||
$upgradeCode = <<<'PHP'
|
||||
<?php
|
||||
|
||||
namespace App\Upgrades;
|
||||
|
||||
use App\Contracts\Extension\UpgradeStepInterface;
|
||||
use App\Extension\UpgradeContext;
|
||||
|
||||
class Upgrade_0_0_1_test_spawn implements UpgradeStepInterface
|
||||
{
|
||||
public function version(): string
|
||||
{
|
||||
return '0.0.1';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Test spawn marker';
|
||||
}
|
||||
|
||||
public function run(UpgradeContext $context): void
|
||||
{
|
||||
\App\Services\TestUpgradeSpawnMarkerService::writeMarker();
|
||||
}
|
||||
}
|
||||
PHP;
|
||||
|
||||
File::put($this->tmpServicePath, $serviceCode);
|
||||
File::put($this->tmpUpgradePath, $upgradeCode);
|
||||
|
||||
$this->assertFileDoesNotExist($this->markerPath, '사전: 마커 파일이 없어야 한다');
|
||||
|
||||
$phpBinary = PHP_BINARY;
|
||||
$artisan = base_path('artisan');
|
||||
$commandLine = implode(' ', array_map('escapeshellarg', [
|
||||
$phpBinary,
|
||||
$artisan,
|
||||
'core:execute-upgrade-steps',
|
||||
'--from=0.0.0',
|
||||
'--to=0.0.1',
|
||||
'--force',
|
||||
'--env=testing',
|
||||
])).' 2>&1';
|
||||
|
||||
$descriptors = [
|
||||
0 => ['pipe', 'r'],
|
||||
1 => ['pipe', 'w'],
|
||||
2 => ['pipe', 'w'],
|
||||
];
|
||||
|
||||
$process = proc_open($commandLine, $descriptors, $pipes, base_path());
|
||||
$this->assertIsResource($process, 'proc_open 으로 별도 프로세스 실행 성공해야 한다');
|
||||
|
||||
fclose($pipes[0]);
|
||||
$stdout = stream_get_contents($pipes[1]);
|
||||
fclose($pipes[1]);
|
||||
fclose($pipes[2]);
|
||||
$exitCode = proc_close($process);
|
||||
|
||||
$this->assertSame(
|
||||
0,
|
||||
$exitCode,
|
||||
"spawn 프로세스가 exit 0 으로 종료되어야 한다. output:\n{$stdout}"
|
||||
);
|
||||
|
||||
$this->assertFileExists(
|
||||
$this->markerPath,
|
||||
'별도 프로세스가 최신 Service 를 autoload 로 로드하여 마커를 작성해야 한다'
|
||||
);
|
||||
|
||||
$marker = File::get($this->markerPath);
|
||||
$this->assertStringStartsWith('spawned:', $marker, '마커 내용이 예상 형식이어야 한다');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Upgrade;
|
||||
|
||||
use App\Extension\UpgradeContext;
|
||||
use App\Upgrades\Upgrade_7_0_0_beta_2;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use ReflectionMethod;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* Test-3: 경로 C — `Upgrade_7_0_0_beta_2::resyncCorePermissionsAndMenus()` 가
|
||||
*
|
||||
* 1. config/core.php 를 디스크에서 다시 require 하고
|
||||
* 2. config repository 의 'core' 네임스페이스를 갱신하며
|
||||
* 3. `CoreUpdateService::syncCoreRolesAndPermissions` / `syncCoreMenus` 를 재호출
|
||||
*
|
||||
* 하는지 실증한다. beta.1 → beta.2 특수 경로(Path C)의 단발성 로컬 로직 검증.
|
||||
*
|
||||
* 본 메서드는 beta.1 메모리에서 실행되는 전제로 작성되었으므로 **기존 클래스(CoreUpdateService)
|
||||
* 의 기존 메서드만** 호출한다. 새로 도입된 `reloadCoreConfigAndResync` 호출 금지 (beta.1 메모리에는
|
||||
* 존재하지 않음 — Fatal 유발). 본 테스트는 이 계약을 검증하기보다 "동일한 효과를 로컬 로직으로
|
||||
* 달성하는지" 를 확인한다.
|
||||
*/
|
||||
class Upgrade700Beta2ResyncTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private string $coreConfigPath;
|
||||
|
||||
private string $backupPath;
|
||||
|
||||
private bool $backupCreated = false;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->coreConfigPath = config_path('core.php');
|
||||
$this->backupPath = $this->coreConfigPath.'.test-backup-'.uniqid();
|
||||
|
||||
// upgrade 파일은 composer PSR-4 autoload 대상이 아니며 runUpgradeSteps()가
|
||||
// 실행 시점에 require_once 로 수동 로드한다. 테스트에서도 동일하게 수동 로드.
|
||||
require_once base_path('upgrades/Upgrade_7_0_0_beta_2.php');
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
if ($this->backupCreated && File::exists($this->backupPath)) {
|
||||
File::copy($this->backupPath, $this->coreConfigPath);
|
||||
File::delete($this->backupPath);
|
||||
config(['core' => require $this->coreConfigPath]);
|
||||
}
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* private resyncCorePermissionsAndMenus 를 Reflection 으로 호출합니다.
|
||||
*/
|
||||
private function invokeResync(Upgrade_7_0_0_beta_2 $upgrade, UpgradeContext $context): void
|
||||
{
|
||||
$ref = new ReflectionMethod($upgrade, 'resyncCorePermissionsAndMenus');
|
||||
$ref->setAccessible(true);
|
||||
$ref->invoke($upgrade, $context);
|
||||
}
|
||||
|
||||
public function test_resyncCorePermissionsAndMenus_reads_disk_and_upserts_new_permissions(): void
|
||||
{
|
||||
if (! File::exists($this->coreConfigPath)) {
|
||||
$this->markTestSkipped('config/core.php 미존재');
|
||||
}
|
||||
|
||||
File::copy($this->coreConfigPath, $this->backupPath);
|
||||
$this->backupCreated = true;
|
||||
|
||||
// 디스크에 신규 카테고리 + 권한 추가 (beta.2 신규 권한 시뮬레이션)
|
||||
$original = require $this->coreConfigPath;
|
||||
$modified = $original;
|
||||
$modified['permissions']['categories'][] = [
|
||||
'identifier' => 'core.test_beta2_path_c',
|
||||
'name' => ['ko' => '경로 C 테스트', 'en' => 'Path C Test'],
|
||||
'description' => ['ko' => 'Path C test category', 'en' => 'Path C test category'],
|
||||
'order' => 9998,
|
||||
'permissions' => [
|
||||
[
|
||||
'identifier' => 'core.test_beta2_path_c.read',
|
||||
'type' => 'admin',
|
||||
'name' => ['ko' => '경로 C 조회', 'en' => 'View Path C'],
|
||||
'description' => ['ko' => 'Can view', 'en' => 'Can view'],
|
||||
'order' => 1,
|
||||
],
|
||||
],
|
||||
];
|
||||
File::put($this->coreConfigPath, '<?php return '.var_export($modified, true).';');
|
||||
|
||||
// 메모리 config 에는 아직 신규 권한 없음
|
||||
$memoryNames = collect(config('core.permissions.categories', []))
|
||||
->pluck('identifier')
|
||||
->all();
|
||||
$this->assertNotContains('core.test_beta2_path_c', $memoryNames);
|
||||
|
||||
// Reflection 으로 private resyncCorePermissionsAndMenus 호출
|
||||
$upgrade = new Upgrade_7_0_0_beta_2;
|
||||
$context = new UpgradeContext('7.0.0-beta.1', '7.0.0-beta.2', '7.0.0-beta.2');
|
||||
$this->invokeResync($upgrade, $context);
|
||||
|
||||
// 디스크 재로드가 성공하여 신규 권한이 DB 에 upsert 되어야 한다
|
||||
$this->assertDatabaseHas('permissions', [
|
||||
'identifier' => 'core.test_beta2_path_c.read',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_resyncCorePermissionsAndMenus_skips_gracefully_if_config_missing(): void
|
||||
{
|
||||
if (! File::exists($this->coreConfigPath)) {
|
||||
$this->markTestSkipped('config/core.php 미존재');
|
||||
}
|
||||
|
||||
File::copy($this->coreConfigPath, $this->backupPath);
|
||||
$this->backupCreated = true;
|
||||
File::delete($this->coreConfigPath);
|
||||
|
||||
try {
|
||||
$upgrade = new Upgrade_7_0_0_beta_2;
|
||||
$context = new UpgradeContext('7.0.0-beta.1', '7.0.0-beta.2', '7.0.0-beta.2');
|
||||
$this->invokeResync($upgrade, $context);
|
||||
$this->assertTrue(true, 'config 파일 미존재 시 예외 없이 로그 경고 후 정상 반환');
|
||||
} finally {
|
||||
File::copy($this->backupPath, $this->coreConfigPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\UserOverrides;
|
||||
|
||||
use App\Models\NotificationDefinition;
|
||||
use Database\Seeders\NotificationDefinitionSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* NotificationDefinition user_overrides 회귀 테스트.
|
||||
*
|
||||
* NotificationDefinitionSeeder 가 syncOrCreateFromUpgrade 패턴을 사용하여
|
||||
* 사용자가 수정한 trackable 필드(name, is_active)를 보존하는지 검증합니다.
|
||||
*
|
||||
* 시나리오:
|
||||
* 1. 시더 첫 실행 → NotificationDefinition 생성
|
||||
* 2. 사용자가 name 을 수정 → user_overrides 자동 기록
|
||||
* 3. 시더 재실행 → name 보존 (시더 정의값 무시), 다른 필드는 갱신
|
||||
*/
|
||||
class NotificationDefinitionUserOverridesTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_seeder_creates_definitions_with_null_user_overrides(): void
|
||||
{
|
||||
(new NotificationDefinitionSeeder)->run();
|
||||
|
||||
$welcome = NotificationDefinition::where('type', 'welcome')->first();
|
||||
$this->assertNotNull($welcome);
|
||||
$this->assertNull($welcome->user_overrides);
|
||||
}
|
||||
|
||||
public function test_user_modification_records_name_in_user_overrides(): void
|
||||
{
|
||||
(new NotificationDefinitionSeeder)->run();
|
||||
$definition = NotificationDefinition::where('type', 'welcome')->first();
|
||||
|
||||
$definition->name = ['ko' => '커스텀 회원가입 환영', 'en' => 'Custom Welcome'];
|
||||
$definition->save();
|
||||
|
||||
$this->assertEquals(['name'], $definition->fresh()->user_overrides);
|
||||
}
|
||||
|
||||
public function test_seeder_re_run_preserves_user_modified_name(): void
|
||||
{
|
||||
(new NotificationDefinitionSeeder)->run();
|
||||
$definition = NotificationDefinition::where('type', 'welcome')->first();
|
||||
$definition->name = ['ko' => '커스텀 회원가입 환영', 'en' => 'Custom Welcome'];
|
||||
$definition->save();
|
||||
|
||||
// 시더 재실행 — syncOrCreateFromUpgrade 가 trackable 필드는 보존해야 함
|
||||
(new NotificationDefinitionSeeder)->run();
|
||||
|
||||
$fresh = $definition->fresh();
|
||||
$this->assertEquals(['ko' => '커스텀 회원가입 환영', 'en' => 'Custom Welcome'], $fresh->name);
|
||||
$this->assertEquals(['name'], $fresh->user_overrides);
|
||||
}
|
||||
|
||||
public function test_seeder_re_run_updates_non_trackable_fields(): void
|
||||
{
|
||||
(new NotificationDefinitionSeeder)->run();
|
||||
$definition = NotificationDefinition::where('type', 'welcome')->first();
|
||||
|
||||
// hooks 는 trackable 외 필드 — 시더 재실행 시 항상 갱신되어야 함
|
||||
$definition->hooks = ['legacy.hook'];
|
||||
// hooks 수정은 user_overrides 에 기록되지 않아야 함
|
||||
$definition->save();
|
||||
$this->assertNull($definition->fresh()->user_overrides);
|
||||
|
||||
(new NotificationDefinitionSeeder)->run();
|
||||
|
||||
// 시더 정의값으로 갱신
|
||||
$this->assertEquals(['core.auth.after_register'], $definition->fresh()->hooks);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user