v7.0.0-beta.1 release

This commit is contained in:
HeuJung committed 2026-04-01 10:30:52 +09:00
commit 6595fd0eb5
3967 files changed
+1875383

No files matched your search

@@ -0,0 +1,409 @@
<?php
namespace Tests\Unit\Services;
use App\ActivityLog\ActivityLogManager;
use App\Enums\ActivityLogType;
use App\Extension\HookManager;
use App\Listeners\ActivityLogListener;
use App\Models\ActivityLog;
use App\Models\User;
use App\Services\ActivityLogService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
use Tests\TestCase;
/**
* ActivityLogService 테스트
*
* ActivityLogService의 훅 발행 및 조회 기능을 검증합니다.
*/
class ActivityLogServiceTest extends TestCase
{
use RefreshDatabase;
private ActivityLogService $activityLogService;
private string $testPrefix;
protected function setUp(): void
{
parent::setUp();
// 테스트 격리를 위한 고유 프리픽스
$this->testPrefix = 'test_' . uniqid() . '_';
// HookManager 및 Laravel Event 초기화 (중복 등록 방지)
HookManager::resetAll();
Event::forget('hook.core.activity.log');
Event::forget('hook.core.activity.admin');
Event::forget('hook.core.activity.user');
Event::forget('hook.core.activity.system');
// 설정 초기화
config(['activity_log.enabled' => true]);
config(['activity_log.driver' => 'database']);
// ActivityLogManager 인스턴스 초기화
$this->app->forgetInstance(ActivityLogManager::class);
// 리스너 등록 - static 배열에만 등록 (addAction은 Event::listen도 호출하여 중복 실행됨)
$listener = app(ActivityLogListener::class);
$this->registerHookWithoutEvent('core.activity.log', [$listener, 'processLog']);
$this->registerHookWithoutEvent('core.activity.admin', [$listener, 'handleAdmin']);
$this->registerHookWithoutEvent('core.activity.user', [$listener, 'handleUser']);
$this->registerHookWithoutEvent('core.activity.system', [$listener, 'handleSystem']);
$this->activityLogService = app(ActivityLogService::class);
}
/**
* HookManager의 static 배열에만 훅을 등록합니다.
* addAction은 Event::listen도 호출하여 중복 실행되므로, static 배열에만 등록합니다.
*/
private function registerHookWithoutEvent(string $hookName, callable $callback, int $priority = 10): void
{
$reflection = new \ReflectionClass(HookManager::class);
$property = $reflection->getProperty('hooks');
$hooks = $property->getValue();
if (! isset($hooks[$hookName])) {
$hooks[$hookName] = [];
}
if (! isset($hooks[$hookName][$priority])) {
$hooks[$hookName][$priority] = [];
}
$hooks[$hookName][$priority][] = $callback;
$property->setValue(null, $hooks);
}
// ========================================================================
// log() - 기본 로그 기록 테스트 (훅 기반)
// ========================================================================
/**
* 기본 로그 기록이 훅을 통해 데이터베이스에 저장되는지 확인
*/
public function test_log_creates_activity_log_via_hook(): void
{
$action = $this->testPrefix . 'action';
$this->activityLogService->log(
ActivityLogType::Admin,
$action,
'Test action description'
);
$this->assertDatabaseHas('activity_logs', [
'log_type' => ActivityLogType::Admin->value,
'action' => $action,
'description' => 'Test action description',
]);
}
/**
* 로그에 대상 모델이 연결되는지 확인
*/
public function test_log_with_loggable_model(): void
{
$user = User::factory()->create();
$action = $this->testPrefix . 'user.update';
$this->activityLogService->log(
ActivityLogType::Admin,
$action,
'User updated',
$user
);
$log = ActivityLog::where('action', $action)->first();
$this->assertNotNull($log);
$this->assertEquals($user->getMorphClass(), $log->loggable_type);
$this->assertEquals($user->id, $log->loggable_id);
}
/**
* 로그에 추가 속성이 저장되는지 확인
*/
public function test_log_with_properties(): void
{
$properties = ['old_name' => 'John', 'new_name' => 'Jane'];
$action = $this->testPrefix . 'user.update.props';
$this->activityLogService->log(
ActivityLogType::Admin,
$action,
'User name updated',
null,
$properties
);
$log = ActivityLog::where('action', $action)->first();
$this->assertNotNull($log);
$this->assertEquals($properties, $log->properties);
}
/**
* 인증된 사용자가 로그에 기록되는지 확인
*/
public function test_log_records_authenticated_user(): void
{
$user = User::factory()->create();
$this->actingAs($user);
$action = $this->testPrefix . 'auth.action';
$this->activityLogService->log(
ActivityLogType::Admin,
$action,
'Test action'
);
$log = ActivityLog::where('action', $action)->first();
$this->assertNotNull($log);
$this->assertEquals($user->id, $log->user_id);
}
// ========================================================================
// logAdmin() / logUser() / logSystem() - 헬퍼 메서드 테스트
// ========================================================================
/**
* logAdmin이 관리자 유형으로 로그를 생성하는지 확인
*/
public function test_log_admin_creates_admin_type_log(): void
{
$action = $this->testPrefix . 'admin.action';
$this->activityLogService->logAdmin($action, 'Admin action');
$log = ActivityLog::where('action', $action)->first();
$this->assertNotNull($log);
$this->assertEquals(ActivityLogType::Admin, $log->log_type);
}
/**
* logUser가 사용자 유형으로 로그를 생성하는지 확인
*/
public function test_log_user_creates_user_type_log(): void
{
$action = $this->testPrefix . 'user.action';
$this->activityLogService->logUser($action, 'User action');
$log = ActivityLog::where('action', $action)->first();
$this->assertNotNull($log);
$this->assertEquals(ActivityLogType::User, $log->log_type);
}
/**
* logSystem이 시스템 유형으로 로그를 생성하는지 확인
*/
public function test_log_system_creates_system_type_log(): void
{
$action = $this->testPrefix . 'system.action';
$this->activityLogService->logSystem($action, 'System action');
$log = ActivityLog::where('action', $action)->first();
$this->assertNotNull($log);
$this->assertEquals(ActivityLogType::System, $log->log_type);
}
// ========================================================================
// getLogsForModel() - 모델별 로그 조회 테스트
// ========================================================================
/**
* 특정 모델의 로그만 조회되는지 확인
*/
public function test_get_logs_for_model_returns_only_model_logs(): void
{
$user1 = User::factory()->create();
$user2 = User::factory()->create();
$actionPrefix = $this->testPrefix . 'model_';
// user1에 대한 로그 2개 생성
$this->activityLogService->logAdmin($actionPrefix . 'view1', 'Viewed user 1', $user1);
$this->activityLogService->logAdmin($actionPrefix . 'update1', 'Updated user 1', $user1);
// user2에 대한 로그 1개 생성
$this->activityLogService->logAdmin($actionPrefix . 'view2', 'Viewed user 2', $user2);
$user1Logs = $this->activityLogService->getLogsForModel($user1);
// 이 테스트에서 생성한 로그만 필터링
$filteredLogs = collect($user1Logs->items())->filter(fn ($log) => str_starts_with($log->action, $actionPrefix));
$this->assertCount(2, $filteredLogs);
foreach ($filteredLogs as $log) {
$this->assertEquals($user1->id, $log->loggable_id);
}
}
// ========================================================================
// getList() - 전체 로그 조회 테스트
// ========================================================================
/**
* 로그 목록 조회가 페이지네이션을 반환하는지 확인
*/
public function test_get_list_returns_paginated_logs(): void
{
$actionPrefix = $this->testPrefix . 'paginate_';
// 로그 5개 생성
for ($i = 0; $i < 5; $i++) {
$this->activityLogService->logAdmin($actionPrefix . $i, "Action {$i}");
}
// 전체 로그 중 이 테스트에서 생성한 것만 확인
$allLogs = ActivityLog::where('action', 'like', $actionPrefix . '%')->get();
$this->assertCount(5, $allLogs);
}
/**
* 로그 유형 필터가 동작하는지 확인
*/
public function test_get_list_filters_by_log_type(): void
{
$actionPrefix = $this->testPrefix . 'type_';
$this->activityLogService->logAdmin($actionPrefix . 'admin', 'Admin action');
$this->activityLogService->logUser($actionPrefix . 'user', 'User action');
$this->activityLogService->logSystem($actionPrefix . 'system', 'System action');
$adminLogs = $this->activityLogService->getList(['log_type' => ActivityLogType::Admin]);
// 이 테스트에서 생성한 admin 로그만 필터링
$filteredLogs = collect($adminLogs->items())->filter(fn ($log) => str_starts_with($log->action, $actionPrefix));
$this->assertCount(1, $filteredLogs);
$this->assertEquals(ActivityLogType::Admin, $filteredLogs->first()->log_type);
}
/**
* 액션 필터가 동작하는지 확인
*/
public function test_get_list_filters_by_action(): void
{
$action = $this->testPrefix . 'filter.update';
$this->activityLogService->logAdmin($this->testPrefix . 'filter.create', 'User created');
$this->activityLogService->logAdmin($action, 'User updated');
$this->activityLogService->logAdmin($this->testPrefix . 'filter.delete', 'User deleted');
$logs = $this->activityLogService->getList(['action' => $action]);
$this->assertCount(1, $logs);
$this->assertEquals($action, $logs->first()->action);
}
/**
* 사용자 필터가 동작하는지 확인
*/
public function test_get_list_filters_by_user_id(): void
{
$user1 = User::factory()->create();
$user2 = User::factory()->create();
$action1 = $this->testPrefix . 'user1_action';
$action2 = $this->testPrefix . 'user2_action';
$this->actingAs($user1);
$this->activityLogService->logAdmin($action1, 'Action by user 1');
$this->actingAs($user2);
$this->activityLogService->logAdmin($action2, 'Action by user 2');
$user1Logs = $this->activityLogService->getList(['user_id' => $user1->id, 'action' => $action1]);
$this->assertCount(1, $user1Logs);
$this->assertEquals($user1->id, $user1Logs->first()->user_id);
}
// ========================================================================
// Model Accessors - 모델 속성 테스트
// ========================================================================
/**
* log_type_label 접근자가 동작하는지 확인
*/
public function test_log_type_label_accessor(): void
{
$action = $this->testPrefix . 'label.action';
$this->activityLogService->logAdmin($action, 'Test');
$log = ActivityLog::where('action', $action)->first();
$this->assertNotNull($log);
$this->assertNotEmpty($log->log_type_label);
}
/**
* actor_name 접근자가 사용자 이름을 반환하는지 확인
*/
public function test_actor_name_accessor_with_user(): void
{
$user = User::factory()->create(['name' => 'Test User']);
$this->actingAs($user);
$action = $this->testPrefix . 'actor.action';
$this->activityLogService->logAdmin($action, 'Test');
$log = ActivityLog::where('action', $action)->first();
$this->assertNotNull($log);
$this->assertEquals('Test User', $log->actor_name);
}
/**
* actor_name 접근자가 사용자 없을 때 시스템을 반환하는지 확인
*/
public function test_actor_name_accessor_without_user(): void
{
$action = $this->testPrefix . 'system.actor';
$this->activityLogService->logSystem($action, 'Test');
$log = ActivityLog::where('action', $action)->first();
$this->assertNotNull($log);
$this->assertNotEmpty($log->actor_name);
}
// ========================================================================
// 훅 통합 테스트
// ========================================================================
/**
* 훅이 비활성화되면 로그가 저장되지 않는지 확인
*/
public function test_log_not_saved_when_disabled(): void
{
config(['activity_log.enabled' => false]);
$action = $this->testPrefix . 'disabled.action';
$this->activityLogService->logAdmin($action, 'Test');
$this->assertDatabaseMissing('activity_logs', [
'action' => $action,
]);
}
/**
* null 드라이버 사용 시 로그가 저장되지 않는지 확인
*/
public function test_log_not_saved_with_null_driver(): void
{
// null 드라이버 설정
config(['activity_log.driver' => 'null']);
// HookManager 및 Event, 매니저 초기화
HookManager::resetAll();
Event::forget('hook.core.activity.admin');
$this->app->forgetInstance(ActivityLogManager::class);
// null 드라이버로 리스너 다시 등록 (static 배열에만)
$listener = app(ActivityLogListener::class);
$this->registerHookWithoutEvent('core.activity.admin', [$listener, 'handleAdmin']);
$action = $this->testPrefix . 'null_driver.action';
$this->activityLogService->logAdmin($action, 'Test');
$this->assertDatabaseMissing('activity_logs', [
'action' => $action,
]);
}
}
+243
View File
@@ -0,0 +1,243 @@
<?php
namespace Tests\Unit\Services;
use App\Services\CacheService;
use Illuminate\Support\Facades\Cache;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* CacheService 단위 테스트
*
* 빈 배열 캐싱 금지 기능을 검증합니다.
*/
class CacheServiceTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
Cache::flush();
}
protected function tearDown(): void
{
Cache::flush();
parent::tearDown();
}
/**
* 빈 배열은 캐시하지 않아야 합니다.
*/
#[Test]
public function it_does_not_cache_empty_arrays(): void
{
$callCount = 0;
$callback = function () use (&$callCount) {
$callCount++;
return [];
};
// 첫 번째 호출
$result1 = CacheService::remember('test', 'empty_array', $callback);
$this->assertEquals([], $result1);
$this->assertEquals(1, $callCount);
// 두 번째 호출 - 캐시되지 않았으므로 콜백 재실행
$result2 = CacheService::remember('test', 'empty_array', $callback);
$this->assertEquals([], $result2);
$this->assertEquals(2, $callCount);
// 캐시에 값이 없음을 확인
$this->assertNull(Cache::get(CacheService::key('test', 'empty_array')));
}
/**
* 비어있지 않은 배열은 정상적으로 캐시되어야 합니다.
*/
#[Test]
public function it_caches_non_empty_arrays(): void
{
$callCount = 0;
$callback = function () use (&$callCount) {
$callCount++;
return ['item1', 'item2'];
};
// 첫 번째 호출
$result1 = CacheService::remember('test', 'non_empty_array', $callback);
$this->assertEquals(['item1', 'item2'], $result1);
$this->assertEquals(1, $callCount);
// 두 번째 호출 - 캐시 히트
$result2 = CacheService::remember('test', 'non_empty_array', $callback);
$this->assertEquals(['item1', 'item2'], $result2);
$this->assertEquals(1, $callCount); // 콜백 재실행 안함
}
/**
* 문자열 등 배열이 아닌 값은 정상적으로 캐시되어야 합니다.
*/
#[Test]
public function it_caches_non_array_values(): void
{
$callCount = 0;
$callback = function () use (&$callCount) {
$callCount++;
return 'string_value';
};
$result1 = CacheService::remember('test', 'string', $callback);
$this->assertEquals('string_value', $result1);
$this->assertEquals(1, $callCount);
$result2 = CacheService::remember('test', 'string', $callback);
$this->assertEquals('string_value', $result2);
$this->assertEquals(1, $callCount);
}
/**
* 정수 값은 정상적으로 캐시되어야 합니다.
*/
#[Test]
public function it_caches_integer_values(): void
{
$callCount = 0;
$callback = function () use (&$callCount) {
$callCount++;
return 42;
};
$result1 = CacheService::remember('test', 'integer', $callback);
$this->assertEquals(42, $result1);
$this->assertEquals(1, $callCount);
$result2 = CacheService::remember('test', 'integer', $callback);
$this->assertEquals(42, $result2);
$this->assertEquals(1, $callCount);
}
/**
* 연관 배열도 정상적으로 캐시되어야 합니다.
*/
#[Test]
public function it_caches_associative_arrays(): void
{
$callCount = 0;
$callback = function () use (&$callCount) {
$callCount++;
return ['key' => 'value', 'count' => 10];
};
$result1 = CacheService::remember('test', 'assoc_array', $callback);
$this->assertEquals(['key' => 'value', 'count' => 10], $result1);
$this->assertEquals(1, $callCount);
$result2 = CacheService::remember('test', 'assoc_array', $callback);
$this->assertEquals(['key' => 'value', 'count' => 10], $result2);
$this->assertEquals(1, $callCount);
}
/**
* DB 테이블이 없으면 빈 배열을 반환하고 캐시하지 않아야 합니다.
*/
#[Test]
public function it_returns_empty_array_without_caching_when_table_not_exists(): void
{
$callCount = 0;
$callback = function () use (&$callCount) {
$callCount++;
return ['data'];
};
// 존재하지 않는 테이블 지정
$result = CacheService::remember(
'test',
'no_table',
$callback,
null,
'non_existent_table_xyz_123'
);
$this->assertEquals([], $result);
$this->assertEquals(0, $callCount); // 콜백 실행 안함
$this->assertNull(Cache::get(CacheService::key('test', 'no_table')));
}
/**
* 캐시 키가 올바르게 생성되어야 합니다.
*/
#[Test]
public function it_generates_correct_cache_key(): void
{
$key = CacheService::key('modules', 'active_identifiers');
$this->assertEquals('g7:modules:active_identifiers', $key);
}
/**
* forget 메서드가 캐시를 삭제해야 합니다.
*/
#[Test]
public function it_forgets_cached_values(): void
{
// 값 캐시
CacheService::remember('test', 'to_forget', fn () => ['data']);
// 캐시 확인
$this->assertNotNull(Cache::get(CacheService::key('test', 'to_forget')));
// 캐시 삭제
CacheService::forget('test', 'to_forget');
// 삭제 확인
$this->assertNull(Cache::get(CacheService::key('test', 'to_forget')));
}
/**
* forgetMany 메서드가 여러 캐시를 삭제해야 합니다.
*/
#[Test]
public function it_forgets_many_cached_values(): void
{
// 여러 값 캐시
CacheService::remember('test', 'key1', fn () => ['data1']);
CacheService::remember('test', 'key2', fn () => ['data2']);
// 캐시 확인
$this->assertNotNull(Cache::get(CacheService::key('test', 'key1')));
$this->assertNotNull(Cache::get(CacheService::key('test', 'key2')));
// 여러 캐시 삭제
CacheService::forgetMany('test', ['key1', 'key2']);
// 삭제 확인
$this->assertNull(Cache::get(CacheService::key('test', 'key1')));
$this->assertNull(Cache::get(CacheService::key('test', 'key2')));
}
/**
* refresh 메서드가 캐시를 갱신해야 합니다.
*/
#[Test]
public function it_refreshes_cached_values(): void
{
$value = 1;
// 초기 캐시
CacheService::remember('test', 'refresh', fn () => $value);
$this->assertEquals(1, Cache::get(CacheService::key('test', 'refresh')));
// 값 변경 후 refresh
$value = 2;
$result = CacheService::refresh('test', 'refresh', fn () => $value);
$this->assertEquals(2, $result);
$this->assertEquals(2, Cache::get(CacheService::key('test', 'refresh')));
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,331 @@
<?php
namespace Tests\Unit\Services;
use App\Contracts\Extension\ModuleManagerInterface;
use App\Contracts\Extension\PluginManagerInterface;
use App\Contracts\Repositories\UserRepositoryInterface;
use App\Services\DashboardService;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Mockery;
use Tests\TestCase;
/**
* DashboardService 단위 테스트
*/
class DashboardServiceTest extends TestCase
{
private DashboardService $service;
private $userRepository;
private $moduleManager;
private $pluginManager;
protected function setUp(): void
{
parent::setUp();
$this->userRepository = Mockery::mock(UserRepositoryInterface::class);
$this->moduleManager = Mockery::mock(ModuleManagerInterface::class);
$this->pluginManager = Mockery::mock(PluginManagerInterface::class);
$this->service = new DashboardService(
$this->userRepository,
$this->moduleManager,
$this->pluginManager
);
}
/**
* 기본 사용자 통계 mock을 설정합니다.
*/
private function mockUserStatistics(int $totalUsers = 100, int $usersThisMonth = 10): void
{
$this->userRepository->shouldReceive('getStatistics')->andReturn([
'total_users' => $totalUsers,
'users_this_month' => $usersThisMonth,
'users_this_week' => 5,
'users_today' => 1,
'active_users_this_week' => 50,
]);
}
/**
* 기본 모듈 mock을 설정합니다.
*/
private function mockModules(array $all = [], array $active = []): void
{
$this->moduleManager->shouldReceive('getAllModules')->andReturn($all);
$this->moduleManager->shouldReceive('getActiveModules')->andReturn($active);
}
/**
* 기본 플러그인 mock을 설정합니다.
*/
private function mockPlugins(array $all = [], array $active = []): void
{
$this->pluginManager->shouldReceive('getAllPlugins')->andReturn($all);
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn($active);
}
// ========================================================================
// getStats 테스트
// ========================================================================
public function test_get_stats_returns_correct_structure(): void
{
$this->mockUserStatistics(100, 90);
$this->mockModules(
[(object) ['identifier' => 'module1'], (object) ['identifier' => 'module2']],
[(object) ['identifier' => 'module1']]
);
$this->mockPlugins(
[(object) ['identifier' => 'plugin1'], (object) ['identifier' => 'plugin2'], (object) ['identifier' => 'plugin3']],
[(object) ['identifier' => 'plugin1'], (object) ['identifier' => 'plugin2']]
);
$stats = $this->service->getStats();
$this->assertArrayHasKey('total_users', $stats);
$this->assertArrayHasKey('installed_modules', $stats);
$this->assertArrayHasKey('active_plugins', $stats);
$this->assertArrayHasKey('system_status', $stats);
}
public function test_get_stats_calculates_change_percent_correctly_when_increased(): void
{
// 전체 100명, 이번달 20명 가입 → 전월 80명 대비 25% 증가
$this->mockUserStatistics(100, 20);
$this->mockModules();
$this->mockPlugins();
$stats = $this->service->getStats();
$this->assertEquals(25, $stats['total_users']['change_percent']);
$this->assertEquals('up', $stats['total_users']['trend']);
}
public function test_get_stats_shows_up_trend_when_new_users_exist(): void
{
// 전체 80명, 이번달 10명 가입
$this->mockUserStatistics(80, 10);
$this->mockModules();
$this->mockPlugins();
$stats = $this->service->getStats();
$this->assertEquals('up', $stats['total_users']['trend']);
$this->assertEquals('+10', $stats['total_users']['change_display']);
}
public function test_get_stats_handles_zero_new_users(): void
{
// 이번달 신규 가입자 0명일 때
$this->mockUserStatistics(100, 0);
$this->mockModules();
$this->mockPlugins();
$stats = $this->service->getStats();
// 신규 가입자 0명이면 0%
$this->assertEquals(0, $stats['total_users']['change_percent']);
$this->assertEquals('up', $stats['total_users']['trend']);
}
public function test_get_stats_returns_module_counts(): void
{
$this->mockUserStatistics(50, 50);
$this->mockModules(
[(object) ['identifier' => 'module1'], (object) ['identifier' => 'module2'], (object) ['identifier' => 'module3']],
[(object) ['identifier' => 'module1'], (object) ['identifier' => 'module2']]
);
$this->mockPlugins();
$stats = $this->service->getStats();
$this->assertEquals(3, $stats['installed_modules']['total']);
$this->assertEquals(2, $stats['installed_modules']['active']);
}
public function test_get_stats_returns_plugin_counts(): void
{
$this->mockUserStatistics(50, 50);
$this->mockModules();
$this->mockPlugins(
[(object) ['identifier' => 'plugin1'], (object) ['identifier' => 'plugin2'], (object) ['identifier' => 'plugin3'], (object) ['identifier' => 'plugin4']],
[(object) ['identifier' => 'plugin1'], (object) ['identifier' => 'plugin2'], (object) ['identifier' => 'plugin3']]
);
$stats = $this->service->getStats();
$this->assertEquals(4, $stats['active_plugins']['total']);
$this->assertEquals(3, $stats['active_plugins']['active']);
}
// ========================================================================
// getSystemResources 테스트
// ========================================================================
/**
* 시스템 리소스 조회를 위한 부분 모킹된 서비스를 생성합니다.
*
* 실제 시스템 명령(PowerShell, wmic 등) 호출을 피하고
* 테스트 성능을 향상시키기 위해 모킹된 값을 반환합니다.
*
* @return DashboardService 모킹된 서비스 인스턴스
*/
private function createMockedResourceService(): DashboardService
{
$service = Mockery::mock(DashboardService::class, [
$this->userRepository,
$this->moduleManager,
$this->pluginManager,
])->makePartial()->shouldAllowMockingProtectedMethods();
// CPU 조회 모킹 (실제 시스템 명령 호출 방지)
$service->shouldReceive('getCpuUsage')->andReturn([
'percentage' => 45,
'color' => 'green',
]);
// 메모리 조회 모킹 (실제 시스템 명령 호출 방지)
$service->shouldReceive('getMemoryUsage')->andReturn([
'percentage' => 60,
'used' => '8.5 GB',
'total' => '16 GB',
'color' => 'blue',
]);
// 디스크 조회 모킹 (disk_total_space, disk_free_space는 빠르지만 일관성을 위해 모킹)
$service->shouldReceive('getDiskUsage')->andReturn([
'percentage' => 75,
'used' => '300 GB',
'total' => '500 GB',
'color' => 'yellow',
]);
return $service;
}
public function test_get_system_resources_returns_correct_structure(): void
{
$service = $this->createMockedResourceService();
$resources = $service->getSystemResources();
$this->assertArrayHasKey('cpu', $resources);
$this->assertArrayHasKey('memory', $resources);
$this->assertArrayHasKey('disk', $resources);
}
public function test_get_system_resources_returns_valid_cpu_data(): void
{
$service = $this->createMockedResourceService();
$resources = $service->getSystemResources();
$this->assertArrayHasKey('percentage', $resources['cpu']);
$this->assertArrayHasKey('color', $resources['cpu']);
$this->assertGreaterThanOrEqual(0, $resources['cpu']['percentage']);
$this->assertLessThanOrEqual(100, $resources['cpu']['percentage']);
}
public function test_get_system_resources_returns_valid_memory_data(): void
{
$service = $this->createMockedResourceService();
$resources = $service->getSystemResources();
$this->assertArrayHasKey('percentage', $resources['memory']);
$this->assertArrayHasKey('used', $resources['memory']);
$this->assertArrayHasKey('total', $resources['memory']);
$this->assertArrayHasKey('color', $resources['memory']);
}
public function test_get_system_resources_returns_valid_disk_data(): void
{
$service = $this->createMockedResourceService();
$resources = $service->getSystemResources();
$this->assertArrayHasKey('percentage', $resources['disk']);
$this->assertArrayHasKey('used', $resources['disk']);
$this->assertArrayHasKey('total', $resources['disk']);
$this->assertArrayHasKey('color', $resources['disk']);
}
// ========================================================================
// getRecentActivities 테스트
// ========================================================================
public function test_get_recent_activities_returns_array(): void
{
$this->userRepository->shouldReceive('getRecentUsers')
->with(10)
->andReturn(new EloquentCollection([]));
$activities = $this->service->getRecentActivities();
$this->assertIsArray($activities);
}
public function test_get_recent_activities_formats_user_registration(): void
{
$mockUser = Mockery::mock();
$mockUser->name = 'Test User';
$mockUser->email = 'test@example.com';
$mockUser->created_at = now()->subMinutes(5);
$this->userRepository->shouldReceive('getRecentUsers')
->with(10)
->andReturn(new EloquentCollection([$mockUser]));
$activities = $this->service->getRecentActivities();
$this->assertCount(1, $activities);
$this->assertArrayHasKey('title', $activities[0]);
$this->assertArrayHasKey('description', $activities[0]);
$this->assertArrayHasKey('time', $activities[0]);
$this->assertArrayHasKey('type', $activities[0]);
}
// ========================================================================
// getSystemAlerts 테스트
// ========================================================================
public function test_get_system_alerts_returns_array(): void
{
$alerts = $this->service->getSystemAlerts();
$this->assertIsArray($alerts);
}
public function test_get_system_alerts_items_have_required_fields(): void
{
$alerts = $this->service->getSystemAlerts();
foreach ($alerts as $alert) {
$this->assertArrayHasKey('id', $alert);
$this->assertArrayHasKey('title', $alert);
$this->assertArrayHasKey('message', $alert);
$this->assertArrayHasKey('time', $alert);
$this->assertArrayHasKey('type', $alert);
$this->assertArrayHasKey('icon', $alert);
$this->assertArrayHasKey('read', $alert);
}
}
public function test_get_system_alerts_returns_valid_types(): void
{
$alerts = $this->service->getSystemAlerts();
$validTypes = ['info', 'warning', 'success', 'error'];
foreach ($alerts as $alert) {
$this->assertContains($alert['type'], $validTypes);
}
}
protected function tearDown(): void
{
Mockery::close();
parent::tearDown();
}
}
+263
View File
@@ -0,0 +1,263 @@
<?php
namespace Tests\Unit\Services;
use App\Services\GeoIpService;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;
class GeoIpServiceTest extends TestCase
{
private GeoIpService $geoIpService;
protected function setUp(): void
{
parent::setUp();
$this->geoIpService = app(GeoIpService::class);
}
/**
* GeoIP가 비활성화된 경우 null을 반환하는지 테스트합니다.
*/
public function test_returns_null_when_disabled(): void
{
config(['geoip.enabled' => false]);
$result = $this->geoIpService->getTimezoneByIp('8.8.8.8', ['America/New_York', 'UTC']);
$this->assertNull($result);
}
/**
* mmdb 파일이 없는 경우 null을 반환하는지 테스트합니다.
*/
public function test_returns_null_when_database_file_missing(): void
{
config(['geoip.enabled' => true]);
config(['geoip.database_path' => storage_path('app/geoip/nonexistent.mmdb')]);
$result = $this->geoIpService->getTimezoneByIp('8.8.8.8', ['America/New_York', 'UTC']);
$this->assertNull($result);
}
/**
* isAvailable()이 GeoIP 비활성화 시 false를 반환하는지 테스트합니다.
*/
public function test_is_available_returns_false_when_disabled(): void
{
config(['geoip.enabled' => false]);
$this->assertFalse($this->geoIpService->isAvailable());
}
/**
* isAvailable()이 파일이 없을 때 false를 반환하는지 테스트합니다.
*/
public function test_is_available_returns_false_when_file_missing(): void
{
config(['geoip.enabled' => true]);
config(['geoip.database_path' => storage_path('app/geoip/nonexistent.mmdb')]);
$this->assertFalse($this->geoIpService->isAvailable());
}
/**
* 실제 GeoIP 조회가 작동하는지 테스트합니다.
* (GeoLite2-City.mmdb 파일이 있어야 함)
*/
public function test_lookup_timezone_with_real_database(): void
{
$dbPath = storage_path('app/geoip/GeoLite2-City.mmdb');
if (! file_exists($dbPath)) {
$this->markTestSkipped('GeoLite2-City.mmdb 파일이 없습니다.');
}
config(['geoip.enabled' => true]);
config(['geoip.database_path' => $dbPath]);
config(['geoip.cache.enabled' => false]);
// 새로운 서비스 인스턴스 생성 (설정 변경 반영)
$service = new GeoIpService;
// Google DNS (미국) - America/Chicago 또는 다른 미국 타임존
$supportedTimezones = [
'America/New_York',
'America/Chicago',
'America/Los_Angeles',
'America/Denver',
'UTC',
];
$result = $service->getTimezoneByIp('8.8.8.8', $supportedTimezones);
// 미국 IP이므로 America/* 타임존이 반환되어야 함
$this->assertNotNull($result);
$this->assertStringStartsWith('America/', $result);
}
/**
* 지원하지 않는 타임존은 null을 반환하는지 테스트합니다.
*/
public function test_returns_null_when_timezone_not_in_supported_list(): void
{
$dbPath = storage_path('app/geoip/GeoLite2-City.mmdb');
if (! file_exists($dbPath)) {
$this->markTestSkipped('GeoLite2-City.mmdb 파일이 없습니다.');
}
config(['geoip.enabled' => true]);
config(['geoip.database_path' => $dbPath]);
config(['geoip.cache.enabled' => false]);
$service = new GeoIpService;
// 미국 IP인데 한국 타임존만 지원하는 경우
$result = $service->getTimezoneByIp('8.8.8.8', ['Asia/Seoul', 'Asia/Tokyo']);
$this->assertNull($result);
}
/**
* 캐싱이 작동하는지 테스트합니다.
*/
public function test_caching_works_correctly(): void
{
$dbPath = storage_path('app/geoip/GeoLite2-City.mmdb');
if (! file_exists($dbPath)) {
$this->markTestSkipped('GeoLite2-City.mmdb 파일이 없습니다.');
}
config(['geoip.enabled' => true]);
config(['geoip.database_path' => $dbPath]);
config(['geoip.cache.enabled' => true]);
config(['geoip.cache.prefix' => 'test.geoip.timezone.']);
config(['geoip.cache.ttl' => 3600]);
// 캐시 클리어
Cache::forget('test.geoip.timezone.8.8.8.8');
$service = new GeoIpService;
$supportedTimezones = [
'America/New_York',
'America/Chicago',
'America/Los_Angeles',
'America/Denver',
'UTC',
];
// 첫 번째 조회 (캐시 미스)
$result1 = $service->getTimezoneByIp('8.8.8.8', $supportedTimezones);
// 캐시에 저장되었는지 확인
$cached = Cache::get('test.geoip.timezone.8.8.8.8');
$this->assertNotNull($cached);
// 두 번째 조회 (캐시 히트)
$result2 = $service->getTimezoneByIp('8.8.8.8', $supportedTimezones);
$this->assertEquals($result1, $result2);
// 정리
Cache::forget('test.geoip.timezone.8.8.8.8');
}
/**
* 한국 IP로 타임존 조회 테스트
*/
public function test_korean_ip_returns_asia_seoul(): void
{
$dbPath = storage_path('app/geoip/GeoLite2-City.mmdb');
if (! file_exists($dbPath)) {
$this->markTestSkipped('GeoLite2-City.mmdb 파일이 없습니다.');
}
config(['geoip.enabled' => true]);
config(['geoip.database_path' => $dbPath]);
config(['geoip.cache.enabled' => false]);
$service = new GeoIpService;
// KT DNS (한국)
$supportedTimezones = ['Asia/Seoul', 'Asia/Tokyo', 'UTC'];
$result = $service->getTimezoneByIp('168.126.63.1', $supportedTimezones);
$this->assertEquals('Asia/Seoul', $result);
}
/**
* 일본 IP로 타임존 조회 테스트
*/
public function test_japanese_ip_returns_asia_tokyo(): void
{
$dbPath = storage_path('app/geoip/GeoLite2-City.mmdb');
if (! file_exists($dbPath)) {
$this->markTestSkipped('GeoLite2-City.mmdb 파일이 없습니다.');
}
config(['geoip.enabled' => true]);
config(['geoip.database_path' => $dbPath]);
config(['geoip.cache.enabled' => false]);
$service = new GeoIpService;
// NTT (일본)
$supportedTimezones = ['Asia/Seoul', 'Asia/Tokyo', 'UTC'];
$result = $service->getTimezoneByIp('203.178.136.1', $supportedTimezones);
$this->assertEquals('Asia/Tokyo', $result);
}
/**
* 프라이빗 IP는 null을 반환하는지 테스트합니다.
*/
public function test_private_ip_returns_null(): void
{
$dbPath = storage_path('app/geoip/GeoLite2-City.mmdb');
if (! file_exists($dbPath)) {
$this->markTestSkipped('GeoLite2-City.mmdb 파일이 없습니다.');
}
config(['geoip.enabled' => true]);
config(['geoip.database_path' => $dbPath]);
config(['geoip.cache.enabled' => false]);
$service = new GeoIpService;
// 프라이빗 IP (192.168.x.x)
$result = $service->getTimezoneByIp('192.168.1.1', ['Asia/Seoul', 'UTC']);
$this->assertNull($result);
}
/**
* localhost IP는 null을 반환하는지 테스트합니다.
*/
public function test_localhost_ip_returns_null(): void
{
$dbPath = storage_path('app/geoip/GeoLite2-City.mmdb');
if (! file_exists($dbPath)) {
$this->markTestSkipped('GeoLite2-City.mmdb 파일이 없습니다.');
}
config(['geoip.enabled' => true]);
config(['geoip.database_path' => $dbPath]);
config(['geoip.cache.enabled' => false]);
$service = new GeoIpService;
$result = $service->getTimezoneByIp('127.0.0.1', ['Asia/Seoul', 'UTC']);
$this->assertNull($result);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,712 @@
<?php
namespace Tests\Unit\Services;
use App\Enums\ExtensionStatus;
use App\Enums\LayoutExtensionType;
use App\Enums\LayoutSourceType;
use App\Models\LayoutExtension;
use App\Models\Module;
use App\Models\Template;
use App\Services\LayoutExtensionService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
use PHPUnit\Framework\Attributes\DataProvider;
/**
* LayoutExtensionService 버전 호환성 테스트
*
* 템플릿 오버라이드의 버전 제약 조건(version_constraint) 검사를 테스트합니다.
*/
class LayoutExtensionServiceVersionTest extends TestCase
{
use RefreshDatabase;
private LayoutExtensionService $service;
private Template $template;
protected function setUp(): void
{
parent::setUp();
// 매 테스트마다 새로운 서비스 인스턴스 생성 (캐시 초기화)
$this->app->forgetInstance(LayoutExtensionService::class);
$this->service = app(LayoutExtensionService::class);
// 테스트용 템플릿 생성
$this->template = Template::factory()->create([
'identifier' => 'test-admin',
'type' => 'admin',
'status' => ExtensionStatus::Active->value,
]);
}
/**
* version_constraint가 없으면 항상 적용되는지 테스트
*/
public function test_extension_without_version_constraint_always_applies(): void
{
// version_constraint가 없는 템플릿 오버라이드
LayoutExtension::create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::Overlay,
'target_name' => 'test_layout',
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'test-admin',
'override_target' => 'sirsoft-ecommerce',
'content' => [
'target_layout' => 'test_layout',
// version_constraint 없음
'injections' => [
[
'target_id' => 'target_component',
'position' => 'append',
'components' => [
['id' => 'injected_component'],
],
],
],
],
'is_active' => true,
]);
$layout = [
'layout_name' => 'test_layout',
'components' => [
['id' => 'target_component'],
],
'data_sources' => [],
];
$result = $this->service->applyExtensions($layout, $this->template->id);
// 버전 제약이 없으므로 적용됨
$componentIds = array_column($result['components'], 'id');
$this->assertContains('injected_component', $componentIds);
$this->assertEmpty($this->service->getIncompatibleOverrides());
}
/**
* 버전 제약 조건이 만족되면 적용되는지 테스트
*/
public function test_extension_with_satisfied_version_constraint_applies(): void
{
// 모듈 DB에 버전 저장
Module::create([
'identifier' => 'sirsoft-ecommerce',
'vendor' => 'sirsoft',
'name' => ['ko' => '이커머스', 'en' => 'Ecommerce'],
'version' => '1.5.0',
'status' => ExtensionStatus::Active->value,
]);
// ^1.0 제약 조건을 가진 오버라이드 (1.5.0은 만족)
LayoutExtension::create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::Overlay,
'target_name' => 'test_layout',
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'test-admin',
'override_target' => 'sirsoft-ecommerce',
'content' => [
'target_layout' => 'test_layout',
'version_constraint' => '^1.0',
'injections' => [
[
'target_id' => 'target_component',
'position' => 'append',
'components' => [
['id' => 'compatible_component'],
],
],
],
],
'is_active' => true,
]);
$layout = [
'layout_name' => 'test_layout',
'components' => [
['id' => 'target_component'],
],
'data_sources' => [],
];
$result = $this->service->applyExtensions($layout, $this->template->id);
// 버전 제약 만족 (^1.0 + 1.5.0)
$componentIds = array_column($result['components'], 'id');
$this->assertContains('compatible_component', $componentIds);
$this->assertEmpty($this->service->getIncompatibleOverrides());
}
/**
* 버전 제약 조건이 불만족되면 스킵되고 경고가 수집되는지 테스트
*/
public function test_extension_with_unsatisfied_version_constraint_skipped(): void
{
// 모듈 DB에 버전 저장 (2.0.0 - 메이저 버전 변경)
Module::create([
'identifier' => 'sirsoft-ecommerce',
'vendor' => 'sirsoft',
'name' => ['ko' => '이커머스', 'en' => 'Ecommerce'],
'version' => '2.0.0',
'status' => ExtensionStatus::Active->value,
]);
// ^1.0 제약 조건을 가진 오버라이드 (2.0.0은 불만족)
LayoutExtension::create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::Overlay,
'target_name' => 'test_layout',
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'test-admin',
'override_target' => 'sirsoft-ecommerce',
'content' => [
'target_layout' => 'test_layout',
'version_constraint' => '^1.0',
'injections' => [
[
'target_id' => 'target_component',
'position' => 'append',
'components' => [
['id' => 'incompatible_component'],
],
],
],
],
'is_active' => true,
]);
$layout = [
'layout_name' => 'test_layout',
'components' => [
['id' => 'target_component'],
],
'data_sources' => [],
];
$result = $this->service->applyExtensions($layout, $this->template->id);
// 버전 제약 불만족 (^1.0 + 2.0.0) → 스킵됨
$componentIds = array_column($result['components'], 'id');
$this->assertNotContains('incompatible_component', $componentIds);
// 비호환 오버라이드 목록에 추가됨
$incompatible = $this->service->getIncompatibleOverrides();
$this->assertCount(1, $incompatible);
$this->assertEquals('test-admin', $incompatible[0]['source']);
$this->assertEquals('sirsoft-ecommerce', $incompatible[0]['target']);
$this->assertEquals('^1.0', $incompatible[0]['constraint']);
$this->assertEquals('2.0.0', $incompatible[0]['current_version']);
}
/**
* 버전 정보가 없으면 적용되는지 테스트 (하위 호환성)
*/
public function test_extension_applies_when_module_version_not_found(): void
{
// 모듈이 활성화되어 있지만 버전 정보가 빈 문자열인 경우
// (예: 버전 정보를 입력하지 않은 레거시 데이터)
Module::create([
'identifier' => 'legacy-module',
'vendor' => 'sirsoft',
'name' => ['ko' => '레거시 모듈'],
'version' => '', // 버전 정보 빈 문자열
'status' => ExtensionStatus::Active->value,
]);
// version_constraint가 있지만 모듈 버전을 찾을 수 없음
LayoutExtension::create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::Overlay,
'target_name' => 'test_layout',
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'test-admin',
'override_target' => 'legacy-module',
'content' => [
'target_layout' => 'test_layout',
'version_constraint' => '^1.0',
'injections' => [
[
'target_id' => 'target_component',
'position' => 'append',
'components' => [
['id' => 'fallback_component'],
],
],
],
],
'is_active' => true,
]);
$layout = [
'layout_name' => 'test_layout',
'components' => [
['id' => 'target_component'],
],
'data_sources' => [],
];
$result = $this->service->applyExtensions($layout, $this->template->id);
// 버전 정보 없으면 하위 호환성으로 적용
$componentIds = array_column($result['components'], 'id');
$this->assertContains('fallback_component', $componentIds);
$this->assertEmpty($this->service->getIncompatibleOverrides());
}
/**
* 여러 오버라이드 중 호환되는 것만 적용되는지 테스트
*/
public function test_mixed_compatible_incompatible_extensions(): void
{
// 모듈 버전 설정
Module::create([
'identifier' => 'sirsoft-ecommerce',
'vendor' => 'sirsoft',
'name' => ['ko' => '이커머스', 'en' => 'Ecommerce'],
'version' => '2.0.0',
'status' => ExtensionStatus::Active->value,
]);
// 호환되는 오버라이드 (>=2.0)
LayoutExtension::create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::Overlay,
'target_name' => 'test_layout',
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'test-admin',
'override_target' => 'sirsoft-ecommerce',
'content' => [
'target_layout' => 'test_layout',
'version_constraint' => '>=2.0',
'injections' => [
[
'target_id' => 'target_component',
'position' => 'append',
'components' => [
['id' => 'v2_compatible'],
],
],
],
],
'priority' => 100,
'is_active' => true,
]);
// 비호환 오버라이드 (^1.0)
LayoutExtension::create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::Overlay,
'target_name' => 'test_layout',
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'other-template',
'override_target' => 'sirsoft-ecommerce',
'content' => [
'target_layout' => 'test_layout',
'version_constraint' => '^1.0',
'injections' => [
[
'target_id' => 'target_component',
'position' => 'append',
'components' => [
['id' => 'v1_only'],
],
],
],
],
'priority' => 200,
'is_active' => true,
]);
$layout = [
'layout_name' => 'test_layout',
'components' => [
['id' => 'target_component'],
],
'data_sources' => [],
];
$result = $this->service->applyExtensions($layout, $this->template->id);
$componentIds = array_column($result['components'], 'id');
// 호환되는 것만 적용
$this->assertContains('v2_compatible', $componentIds);
$this->assertNotContains('v1_only', $componentIds);
// 비호환 목록에 하나만
$incompatible = $this->service->getIncompatibleOverrides();
$this->assertCount(1, $incompatible);
$this->assertEquals('other-template', $incompatible[0]['source']);
}
/**
* 비호환 경고가 warnings 필드에 추가되는지 테스트
*/
public function test_incompatible_warning_added_to_warnings_field(): void
{
// 모듈 버전 설정
Module::create([
'identifier' => 'sirsoft-ecommerce',
'vendor' => 'sirsoft',
'name' => ['ko' => '이커머스', 'en' => 'Ecommerce'],
'version' => '2.0.0',
'status' => ExtensionStatus::Active->value,
]);
// 비호환 오버라이드
$extension = LayoutExtension::create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::Overlay,
'target_name' => 'test_layout',
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'test-admin',
'override_target' => 'sirsoft-ecommerce',
'content' => [
'target_layout' => 'test_layout',
'version_constraint' => '^1.0',
'injections' => [],
],
'is_active' => true,
]);
$layout = [
'layout_name' => 'test_layout',
'components' => [
['id' => 'original_component'],
],
'data_sources' => [],
];
$result = $this->service->applyExtensions($layout, $this->template->id);
// warnings 필드가 존재함
$this->assertArrayHasKey('warnings', $result);
$this->assertCount(1, $result['warnings']);
// warnings 필드의 형식 확인
$warning = $result['warnings'][0];
$this->assertEquals('compatibility_'.$extension->id, $warning['id']);
$this->assertEquals('compatibility', $warning['type']);
$this->assertEquals('warning', $warning['level']);
$this->assertArrayHasKey('message', $warning);
$this->assertEquals('test-admin', $warning['source']);
$this->assertEquals('sirsoft-ecommerce', $warning['target']);
$this->assertEquals('^1.0', $warning['constraint']);
$this->assertEquals('2.0.0', $warning['current_version']);
// 원래 컴포넌트는 그대로
$this->assertEquals('original_component', $result['components'][0]['id']);
}
/**
* 다양한 버전 제약 문법 테스트
* */
#[DataProvider('versionConstraintProvider')]
public function test_various_version_constraint_syntaxes(string $version, string $constraint, bool $expected): void
{
// 모듈 생성
Module::create([
'identifier' => 'sirsoft-test-module',
'vendor' => 'sirsoft',
'name' => ['ko' => '테스트'],
'version' => $version,
'status' => ExtensionStatus::Active->value,
]);
LayoutExtension::create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::Overlay,
'target_name' => 'test_layout',
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'test-template',
'override_target' => 'sirsoft-test-module',
'content' => [
'target_layout' => 'test_layout',
'version_constraint' => $constraint,
'injections' => [
[
'target_id' => 'target',
'position' => 'append',
'components' => [['id' => 'injected']],
],
],
],
'is_active' => true,
]);
$layout = [
'layout_name' => 'test_layout',
'components' => [['id' => 'target']],
'data_sources' => [],
];
$result = $this->service->applyExtensions($layout, $this->template->id);
$componentIds = array_column($result['components'], 'id');
$isApplied = in_array('injected', $componentIds, true);
$this->assertEquals(
$expected,
$isApplied,
"version={$version}, constraint={$constraint} should be ".($expected ? 'compatible' : 'incompatible')
);
}
/**
* 버전 제약 조건 테스트 데이터 제공
*
* @return array<array{string, string, bool}>
*/
public static function versionConstraintProvider(): array
{
return [
// ^ (caret) - 호환되는 변경 허용
'caret 1.0 with 1.5.0' => ['1.5.0', '^1.0', true],
'caret 1.0 with 2.0.0' => ['2.0.0', '^1.0', false],
// ~ (tilde) - 패치 레벨 변경 허용
// ~1.5.0은 >=1.5.0 <1.6.0, ~1.5는 >=1.5.0 <2.0.0
'tilde 1.5.0 with 1.5.5' => ['1.5.5', '~1.5.0', true],
'tilde 1.5.0 with 1.6.0' => ['1.6.0', '~1.5.0', false],
// 범위 연산자
'range >=1.0 <2.0 with 1.5.0' => ['1.5.0', '>=1.0 <2.0', true],
'range >=1.0 <2.0 with 2.0.0' => ['2.0.0', '>=1.0 <2.0', false],
// 하이픈 범위
'hyphen range with 1.9.9' => ['1.9.9', '1.0.0 - 1.9.9', true],
'hyphen range with 2.0.0' => ['2.0.0', '1.0.0 - 1.9.9', false],
// 정확한 버전 일치
'exact version match' => ['1.2.3', '1.2.3', true],
'exact version mismatch' => ['1.2.4', '1.2.3', false],
];
}
/**
* 모듈이 아닌 확장은 버전 검사를 건너뛰는지 테스트
*/
public function test_non_template_override_skips_version_check(): void
{
// 모듈에서 직접 등록된 확장 (템플릿 오버라이드가 아님)
LayoutExtension::create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::Overlay,
'target_name' => 'test_layout',
'source_type' => LayoutSourceType::Module, // 템플릿이 아닌 모듈
'source_identifier' => 'sirsoft-ecommerce',
'override_target' => null, // 오버라이드 대상 없음
'content' => [
'target_layout' => 'test_layout',
'version_constraint' => '^999.0', // 절대 만족 안 되는 버전
'injections' => [
[
'target_id' => 'target_component',
'position' => 'append',
'components' => [['id' => 'module_component']],
],
],
],
'is_active' => true,
]);
$layout = [
'layout_name' => 'test_layout',
'components' => [['id' => 'target_component']],
'data_sources' => [],
];
$result = $this->service->applyExtensions($layout, $this->template->id);
// 모듈 확장은 버전 검사 없이 적용됨
$componentIds = array_column($result['components'], 'id');
$this->assertContains('module_component', $componentIds);
$this->assertEmpty($this->service->getIncompatibleOverrides());
}
/**
* 버전 비호환 템플릿 오버라이드가 있을 때 원본 모듈 UI로 fallback하는지 테스트
*
* 시나리오:
* 1. 모듈이 원본 동적 UI를 등록
* 2. 템플릿이 해당 모듈의 UI를 오버라이드 (하지만 버전 비호환)
* 3. 결과: 템플릿 오버라이드 대신 원본 모듈 UI가 사용되어야 함
*/
public function test_incompatible_override_fallback_to_original_module_ui(): void
{
// 모듈 버전 설정 (2.0.0)
Module::create([
'identifier' => 'sirsoft-ecommerce',
'vendor' => 'sirsoft',
'name' => ['ko' => '이커머스', 'en' => 'Ecommerce'],
'version' => '2.0.0',
'status' => ExtensionStatus::Active->value,
]);
// 모듈이 등록한 원본 동적 UI
LayoutExtension::create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::Overlay,
'target_name' => 'test_layout',
'source_type' => LayoutSourceType::Module,
'source_identifier' => 'sirsoft-ecommerce',
'override_target' => null,
'content' => [
'target_layout' => 'test_layout',
'injections' => [
[
'target_id' => 'target_component',
'position' => 'append',
'components' => [
['id' => 'original_module_ui'],
],
],
],
],
'priority' => 100,
'is_active' => true,
]);
// 템플릿이 등록한 오버라이드 (버전 비호환: ^1.0은 2.0.0과 호환 안 됨)
LayoutExtension::create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::Overlay,
'target_name' => 'test_layout',
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'test-admin',
'override_target' => 'sirsoft-ecommerce',
'content' => [
'target_layout' => 'test_layout',
'version_constraint' => '^1.0', // 2.0.0과 비호환
'injections' => [
[
'target_id' => 'target_component',
'position' => 'append',
'components' => [
['id' => 'template_override_ui'],
],
],
],
],
'priority' => 200, // 오버라이드라서 더 높은 우선순위
'is_active' => true,
]);
$layout = [
'layout_name' => 'test_layout',
'components' => [
['id' => 'target_component'],
],
'data_sources' => [],
];
$result = $this->service->applyExtensions($layout, $this->template->id);
$componentIds = array_column($result['components'], 'id');
// 원본 모듈 UI가 사용되어야 함
$this->assertContains('original_module_ui', $componentIds);
// 템플릿 오버라이드 UI는 사용되면 안 됨
$this->assertNotContains('template_override_ui', $componentIds);
// 비호환 경고가 있어야 함
$incompatible = $this->service->getIncompatibleOverrides();
$this->assertCount(1, $incompatible);
$this->assertEquals('test-admin', $incompatible[0]['source']);
$this->assertEquals('sirsoft-ecommerce', $incompatible[0]['target']);
}
/**
* 호환되는 템플릿 오버라이드가 있을 때 원본 모듈 UI 대신 사용되는지 테스트
*
* 시나리오:
* 1. 모듈이 원본 동적 UI를 등록
* 2. 템플릿이 해당 모듈의 UI를 오버라이드 (버전 호환)
* 3. 결과: 원본 모듈 UI 대신 템플릿 오버라이드가 사용되어야 함
*/
public function test_compatible_override_replaces_original_module_ui(): void
{
// 모듈 버전 설정 (2.0.0)
Module::create([
'identifier' => 'sirsoft-ecommerce',
'vendor' => 'sirsoft',
'name' => ['ko' => '이커머스', 'en' => 'Ecommerce'],
'version' => '2.0.0',
'status' => ExtensionStatus::Active->value,
]);
// 모듈이 등록한 원본 동적 UI
LayoutExtension::create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::Overlay,
'target_name' => 'test_layout',
'source_type' => LayoutSourceType::Module,
'source_identifier' => 'sirsoft-ecommerce',
'override_target' => null,
'content' => [
'target_layout' => 'test_layout',
'injections' => [
[
'target_id' => 'target_component',
'position' => 'append',
'components' => [
['id' => 'original_module_ui'],
],
],
],
],
'priority' => 100,
'is_active' => true,
]);
// 템플릿이 등록한 오버라이드 (버전 호환: >=2.0은 2.0.0과 호환)
LayoutExtension::create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::Overlay,
'target_name' => 'test_layout',
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'test-admin',
'override_target' => 'sirsoft-ecommerce',
'content' => [
'target_layout' => 'test_layout',
'version_constraint' => '>=2.0', // 2.0.0과 호환
'injections' => [
[
'target_id' => 'target_component',
'position' => 'append',
'components' => [
['id' => 'template_override_ui'],
],
],
],
],
'priority' => 200,
'is_active' => true,
]);
$layout = [
'layout_name' => 'test_layout',
'components' => [
['id' => 'target_component'],
],
'data_sources' => [],
];
$result = $this->service->applyExtensions($layout, $this->template->id);
$componentIds = array_column($result['components'], 'id');
// 템플릿 오버라이드 UI가 사용되어야 함
$this->assertContains('template_override_ui', $componentIds);
// 원본 모듈 UI는 사용되면 안 됨 (오버라이드됨)
$this->assertNotContains('original_module_ui', $componentIds);
// 비호환 경고가 없어야 함
$this->assertEmpty($this->service->getIncompatibleOverrides());
}
}
@@ -0,0 +1,527 @@
<?php
namespace Tests\Unit\Services;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use App\Providers\AuthServiceProvider;
use App\Services\LayoutService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* LayoutService 컴포넌트별 권한 필터링 테스트
*
* 레이아웃 JSON의 컴포넌트에 permissions 속성을 정의하면
* 서빙 시 사용자 권한에 따라 해당 컴포넌트를 제거합니다.
*/
class LayoutPermissionFilterTest extends TestCase
{
use RefreshDatabase;
private LayoutService $layoutService;
private Role $adminRole;
private Role $userRole;
private User $adminUser;
private User $regularUser;
protected function setUp(): void
{
parent::setUp();
$this->layoutService = app(LayoutService::class);
AuthServiceProvider::clearGuestRoleCache();
// 역할 생성
$this->adminRole = Role::create([
'identifier' => 'admin',
'name' => ['ko' => '관리자', 'en' => 'Administrator'],
'description' => ['ko' => '시스템 관리자', 'en' => 'System Administrator'],
]);
$this->userRole = Role::create([
'identifier' => 'user',
'name' => ['ko' => '일반 사용자', 'en' => 'Regular User'],
'description' => ['ko' => '일반 사용자', 'en' => 'Regular User'],
]);
// 권한 생성 및 부여
$viewPermission = Permission::create([
'identifier' => 'core.dashboard.view',
'name' => ['ko' => '대시보드 조회', 'en' => 'View Dashboard'],
'description' => ['ko' => '대시보드 조회', 'en' => 'View Dashboard'],
'type' => 'admin',
]);
$editPermission = Permission::create([
'identifier' => 'core.dashboard.edit',
'name' => ['ko' => '대시보드 편집', 'en' => 'Edit Dashboard'],
'description' => ['ko' => '대시보드 편집', 'en' => 'Edit Dashboard'],
'type' => 'admin',
]);
// adminRole에 view, edit 권한 부여 (바이패스 없이 명시 할당)
$this->adminRole->permissions()->attach([
$viewPermission->id,
$editPermission->id,
]);
// userRole에 view 권한만 부여
$this->userRole->permissions()->attach($viewPermission->id);
// 사용자 생성 및 역할 할당
$this->adminUser = User::factory()->create(['name' => 'Admin']);
$this->adminUser->roles()->attach($this->adminRole->id);
$this->regularUser = User::factory()->create(['name' => 'Regular']);
$this->regularUser->roles()->attach($this->userRole->id);
AuthServiceProvider::clearGuestRoleCache();
}
protected function tearDown(): void
{
AuthServiceProvider::clearGuestRoleCache();
parent::tearDown();
}
/**
* permissions 없는 컴포넌트는 항상 포함됩니다.
*/
public function test_component_without_permissions_is_always_included(): void
{
$layout = [
'components' => [
['type' => 'basic', 'name' => 'Div', 'id' => 'container'],
['type' => 'basic', 'name' => 'H1', 'text' => '제목'],
],
];
$result = $this->layoutService->filterComponentsByPermissions($layout, $this->regularUser);
$this->assertCount(2, $result['components']);
}
/**
* 단일 permissions — 권한 있으면 포함됩니다.
*/
public function test_component_with_permission_is_included_when_user_has_permission(): void
{
$layout = [
'components' => [
[
'type' => 'basic',
'name' => 'Div',
'id' => 'dashboard_widget',
'permissions' => ['core.dashboard.view'],
],
],
];
$result = $this->layoutService->filterComponentsByPermissions($layout, $this->regularUser);
$this->assertCount(1, $result['components']);
$this->assertEquals('dashboard_widget', $result['components'][0]['id']);
}
/**
* 단일 permissions — 권한 없으면 제거됩니다.
*/
public function test_component_with_permission_is_removed_when_user_lacks_permission(): void
{
$layout = [
'components' => [
[
'type' => 'basic',
'name' => 'Div',
'id' => 'admin_widget',
'permissions' => ['core.dashboard.edit'],
],
],
];
$result = $this->layoutService->filterComponentsByPermissions($layout, $this->regularUser);
$this->assertCount(0, $result['components']);
}
/**
* 복수 permissions — AND 조건 (모두 충족해야 포함).
*/
public function test_multiple_permissions_require_all_and_condition(): void
{
$layout = [
'components' => [
[
'type' => 'basic',
'name' => 'Div',
'id' => 'restricted',
'permissions' => ['core.dashboard.view', 'core.dashboard.edit'],
],
],
];
// regularUser는 view만 있고 edit는 없으므로 제거
$result = $this->layoutService->filterComponentsByPermissions($layout, $this->regularUser);
$this->assertCount(0, $result['components']);
}
/**
* 중첩 children 재귀 필터링.
*/
public function test_nested_children_are_recursively_filtered(): void
{
$layout = [
'components' => [
[
'type' => 'basic',
'name' => 'Div',
'id' => 'container',
'children' => [
['type' => 'basic', 'name' => 'H1', 'text' => '공개'],
[
'type' => 'basic',
'name' => 'Button',
'id' => 'edit_btn',
'permissions' => ['core.dashboard.edit'],
'text' => '수정',
],
['type' => 'basic', 'name' => 'Span', 'text' => '정보'],
],
],
],
];
$result = $this->layoutService->filterComponentsByPermissions($layout, $this->regularUser);
$this->assertCount(1, $result['components']);
$this->assertCount(2, $result['components'][0]['children']);
$this->assertEquals('공개', $result['components'][0]['children'][0]['text']);
$this->assertEquals('정보', $result['components'][0]['children'][1]['text']);
}
/**
* 상위 제거 시 하위는 평가하지 않고 전체 제거됩니다.
*/
public function test_parent_removal_removes_all_children(): void
{
$layout = [
'components' => [
[
'type' => 'basic',
'name' => 'Div',
'id' => 'parent',
'permissions' => ['core.dashboard.edit'],
'children' => [
['type' => 'basic', 'name' => 'H1', 'text' => '자식'],
[
'type' => 'basic',
'name' => 'Button',
'permissions' => ['core.dashboard.view'],
],
],
],
],
];
$result = $this->layoutService->filterComponentsByPermissions($layout, $this->regularUser);
// 상위가 edit 권한 필요하므로 전체 제거
$this->assertCount(0, $result['components']);
}
/**
* 상위 통과 + 하위 독립 평가.
*/
public function test_parent_passes_child_evaluated_independently(): void
{
$layout = [
'components' => [
[
'type' => 'basic',
'name' => 'Div',
'id' => 'parent',
'permissions' => ['core.dashboard.view'],
'children' => [
['type' => 'basic', 'name' => 'Span', 'text' => '공개 자식'],
[
'type' => 'basic',
'name' => 'Button',
'id' => 'edit_btn',
'permissions' => ['core.dashboard.edit'],
],
],
],
],
];
$result = $this->layoutService->filterComponentsByPermissions($layout, $this->regularUser);
$this->assertCount(1, $result['components']);
$this->assertCount(1, $result['components'][0]['children']);
$this->assertEquals('공개 자식', $result['components'][0]['children'][0]['text']);
}
/**
* modals 자체에 permissions → 모달 항목 전체 제거.
*/
public function test_modal_with_permissions_is_removed_when_user_lacks_permission(): void
{
$layout = [
'components' => [],
'modals' => [
[
'id' => 'public_modal',
'components' => [
['type' => 'basic', 'name' => 'Div', 'text' => '공개 모달'],
],
],
[
'id' => 'admin_modal',
'permissions' => ['core.dashboard.edit'],
'components' => [
['type' => 'basic', 'name' => 'Div', 'text' => '관리자 모달'],
],
],
],
];
$result = $this->layoutService->filterComponentsByPermissions($layout, $this->regularUser);
$this->assertCount(1, $result['modals']);
$this->assertEquals('public_modal', $result['modals'][0]['id']);
}
/**
* modals 내부 컴포넌트 필터링.
*/
public function test_modal_internal_components_are_filtered(): void
{
$layout = [
'components' => [],
'modals' => [
[
'id' => 'mixed_modal',
'components' => [
['type' => 'basic', 'name' => 'Span', 'text' => '공개 내용'],
[
'type' => 'basic',
'name' => 'Button',
'id' => 'delete_btn',
'permissions' => ['core.dashboard.edit'],
],
],
],
],
];
$result = $this->layoutService->filterComponentsByPermissions($layout, $this->regularUser);
$this->assertCount(1, $result['modals']);
$this->assertCount(1, $result['modals'][0]['components']);
$this->assertEquals('공개 내용', $result['modals'][0]['components'][0]['text']);
}
/**
* defines 내 컴포넌트 필터링.
*/
public function test_defines_are_filtered(): void
{
$layout = [
'components' => [],
'defines' => [
[
'id' => 'public_define',
'children' => [
['type' => 'basic', 'name' => 'Div', 'text' => '공개'],
],
],
[
'id' => 'admin_define',
'permissions' => ['core.dashboard.edit'],
'children' => [
['type' => 'basic', 'name' => 'Div', 'text' => '관리자'],
],
],
],
];
$result = $this->layoutService->filterComponentsByPermissions($layout, $this->regularUser);
$this->assertCount(1, $result['defines']);
$this->assertEquals('public_define', $result['defines'][0]['id']);
}
/**
* 필터링 후 permissions 속성이 제거되어 클라이언트에 노출되지 않습니다.
*/
public function test_permissions_attribute_is_removed_after_filtering(): void
{
$layout = [
'components' => [
[
'type' => 'basic',
'name' => 'Div',
'id' => 'widget',
'permissions' => ['core.dashboard.view'],
'children' => [
[
'type' => 'basic',
'name' => 'Span',
'permissions' => ['core.dashboard.view'],
],
],
],
],
'modals' => [
[
'id' => 'modal1',
'permissions' => ['core.dashboard.view'],
'components' => [],
],
],
];
$result = $this->layoutService->filterComponentsByPermissions($layout, $this->regularUser);
// 컴포넌트 permissions 속성 제거 확인
$this->assertArrayNotHasKey('permissions', $result['components'][0]);
$this->assertArrayNotHasKey('permissions', $result['components'][0]['children'][0]);
// 모달 permissions 속성 제거 확인
$this->assertArrayNotHasKey('permissions', $result['modals'][0]);
}
/**
* guest 사용자 (null) 처리.
*/
public function test_guest_user_filtering(): void
{
$layout = [
'components' => [
['type' => 'basic', 'name' => 'Div', 'text' => '공개'],
[
'type' => 'basic',
'name' => 'Div',
'id' => 'member_only',
'permissions' => ['core.dashboard.view'],
],
],
];
// guest (null) — core.dashboard.view 권한 없음
$result = $this->layoutService->filterComponentsByPermissions($layout, null);
$this->assertCount(1, $result['components']);
$this->assertEquals('공개', $result['components'][0]['text']);
}
/**
* admin 역할 → 명시 할당된 권한의 컴포넌트만 통과.
*/
public function test_admin_user_passes_assigned_components(): void
{
$layout = [
'components' => [
[
'type' => 'basic',
'name' => 'Div',
'permissions' => ['core.dashboard.view'],
],
[
'type' => 'basic',
'name' => 'Div',
'permissions' => ['core.dashboard.edit'],
],
[
'type' => 'basic',
'name' => 'Div',
'permissions' => ['unassigned.permission'],
],
],
'modals' => [
[
'id' => 'admin_modal',
'permissions' => ['core.dashboard.edit'],
'components' => [],
],
],
];
$result = $this->layoutService->filterComponentsByPermissions($layout, $this->adminUser);
// admin에 명시 할당된 view, edit 권한의 컴포넌트만 통과 (unassigned는 필터링)
$this->assertCount(2, $result['components']);
$this->assertCount(1, $result['modals']);
}
/**
* 빈 layout (components, modals, defines 없음) 처리.
*/
public function test_empty_layout_returns_unchanged(): void
{
$layout = [
'meta' => ['title' => 'Test'],
'data_sources' => [],
];
$result = $this->layoutService->filterComponentsByPermissions($layout, $this->regularUser);
$this->assertEquals($layout, $result);
}
/**
* 빈 permissions 배열은 무시됩니다 (권한 요구 없음).
*/
public function test_empty_permissions_array_is_treated_as_no_requirement(): void
{
$layout = [
'components' => [
[
'type' => 'basic',
'name' => 'Div',
'id' => 'widget',
'permissions' => [],
],
],
];
$result = $this->layoutService->filterComponentsByPermissions($layout, $this->regularUser);
$this->assertCount(1, $result['components']);
}
/**
* 배열 인덱스가 재정렬됩니다 (중간 요소 제거 후).
*/
public function test_array_indices_are_reindexed_after_filtering(): void
{
$layout = [
'components' => [
['type' => 'basic', 'name' => 'Div', 'id' => 'first'],
[
'type' => 'basic',
'name' => 'Div',
'id' => 'removed',
'permissions' => ['core.dashboard.edit'],
],
['type' => 'basic', 'name' => 'Div', 'id' => 'last'],
],
];
$result = $this->layoutService->filterComponentsByPermissions($layout, $this->regularUser);
$this->assertCount(2, $result['components']);
// 연속적인 인덱스 확인 (0, 1)
$this->assertArrayHasKey(0, $result['components']);
$this->assertArrayHasKey(1, $result['components']);
$this->assertEquals('first', $result['components'][0]['id']);
$this->assertEquals('last', $result['components'][1]['id']);
}
}
@@ -0,0 +1,177 @@
<?php
namespace Tests\Unit\Services;
use App\Models\Template;
use App\Models\TemplateLayoutPreview;
use App\Services\LayoutPreviewService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* LayoutPreviewService 유닛 테스트
*/
class LayoutPreviewServiceTest extends TestCase
{
use RefreshDatabase;
private LayoutPreviewService $service;
private Template $template;
protected function setUp(): void
{
parent::setUp();
$this->service = app(LayoutPreviewService::class);
$this->template = Template::factory()->create();
}
/**
* 미리보기 생성 성공
*/
public function test_create_preview(): void
{
// Arrange
$content = [
'version' => '1.0.0',
'layout_name' => 'main',
'components' => [['id' => 'root']],
];
// Act
$preview = $this->service->createPreview(
$this->template->id,
'main',
$content,
1
);
// Assert
$this->assertInstanceOf(TemplateLayoutPreview::class, $preview);
$this->assertEquals($this->template->id, $preview->template_id);
$this->assertEquals('main', $preview->layout_name);
$this->assertEquals($content, $preview->content);
$this->assertEquals(1, $preview->admin_id);
$this->assertNotEmpty($preview->token);
$this->assertTrue($preview->expires_at->isFuture());
}
/**
* 동일 조합으로 미리보기 생성 시 이전 것 삭제
*/
public function test_create_preview_replaces_existing(): void
{
// Arrange
$preview1 = $this->service->createPreview(
$this->template->id,
'main',
['version' => '1.0.0', 'components' => [['id' => 'v1']]],
1
);
// Act
$preview2 = $this->service->createPreview(
$this->template->id,
'main',
['version' => '1.0.0', 'components' => [['id' => 'v2']]],
1
);
// Assert
$this->assertDatabaseMissing('template_layout_previews', ['token' => $preview1->token]);
$this->assertDatabaseHas('template_layout_previews', ['token' => $preview2->token]);
}
/**
* 다른 관리자의 미리보기는 삭제하지 않음
*/
public function test_create_preview_does_not_delete_other_admins_preview(): void
{
// Arrange
$preview1 = $this->service->createPreview(
$this->template->id,
'main',
['version' => '1.0.0', 'components' => []],
1 // admin 1
);
// Act
$preview2 = $this->service->createPreview(
$this->template->id,
'main',
['version' => '1.0.0', 'components' => []],
2 // admin 2
);
// Assert - 둘 다 존재
$this->assertDatabaseHas('template_layout_previews', ['token' => $preview1->token]);
$this->assertDatabaseHas('template_layout_previews', ['token' => $preview2->token]);
}
/**
* 만료된 미리보기 정리
*/
public function test_cleanup_expired(): void
{
// Arrange - 만료된 미리보기
TemplateLayoutPreview::create([
'token' => 'expired-token-1',
'template_id' => $this->template->id,
'layout_name' => 'main',
'content' => ['components' => []],
'admin_id' => 1,
'expires_at' => now()->subMinutes(1),
]);
// Arrange - 유효한 미리보기
TemplateLayoutPreview::create([
'token' => 'valid-token-1',
'template_id' => $this->template->id,
'layout_name' => 'main',
'content' => ['components' => []],
'admin_id' => 2,
'expires_at' => now()->addMinutes(30),
]);
// Act
$deleted = $this->service->cleanupExpired();
// Assert
$this->assertEquals(1, $deleted);
$this->assertDatabaseMissing('template_layout_previews', ['token' => 'expired-token-1']);
$this->assertDatabaseHas('template_layout_previews', ['token' => 'valid-token-1']);
}
/**
* 특정 관리자/레이아웃 조합 미리보기 삭제
*/
public function test_delete_by_layout_and_admin(): void
{
// Arrange
TemplateLayoutPreview::create([
'token' => 'target-token',
'template_id' => $this->template->id,
'layout_name' => 'main',
'content' => ['components' => []],
'admin_id' => 1,
'expires_at' => now()->addMinutes(30),
]);
TemplateLayoutPreview::create([
'token' => 'other-token',
'template_id' => $this->template->id,
'layout_name' => 'sidebar',
'content' => ['components' => []],
'admin_id' => 1,
'expires_at' => now()->addMinutes(30),
]);
// Act
$deleted = $this->service->deleteByLayoutAndAdmin($this->template->id, 'main', 1);
// Assert
$this->assertEquals(1, $deleted);
$this->assertDatabaseMissing('template_layout_previews', ['token' => 'target-token']);
$this->assertDatabaseHas('template_layout_previews', ['token' => 'other-token']);
}
}
@@ -0,0 +1,689 @@
<?php
namespace Tests\Unit\Services;
use App\Enums\ExtensionStatus;
use App\Enums\LayoutSourceType;
use App\Extension\ModuleManager;
use App\Models\Module;
use App\Models\Template;
use App\Models\TemplateLayout;
use App\Repositories\LayoutRepository;
use App\Services\LayoutResolverService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;
class LayoutResolverServiceTest extends TestCase
{
use RefreshDatabase;
private LayoutResolverService $resolverService;
private LayoutRepository $layoutRepository;
private Template $template;
protected function setUp(): void
{
parent::setUp();
$this->layoutRepository = app(LayoutRepository::class);
$this->resolverService = new LayoutResolverService(
$this->layoutRepository,
app(ModuleManager::class)
);
// 테스트용 템플릿 생성
$this->template = Template::create([
'identifier' => 'test-admin-template',
'vendor' => 'test',
'name' => ['ko' => '테스트 관리자 템플릿', 'en' => 'Test Admin Template'],
'version' => '1.0.0',
'type' => 'admin',
'status' => ExtensionStatus::Active->value,
'description' => ['ko' => '테스트용', 'en' => 'For testing'],
]);
}
/**
* 템플릿 오버라이드가 모듈 레이아웃보다 우선하는지 테스트
*/
public function test_resolve_prioritizes_template_override_over_module_layout(): void
{
$layoutName = 'sirsoft-sample_admin_index';
// 모듈 기본 레이아웃 생성
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => ['slots' => ['content' => [['component' => 'ModuleComponent']]]],
'source_type' => LayoutSourceType::Module,
'source_identifier' => 'sirsoft-sample',
]);
// 템플릿 오버라이드 레이아웃 생성
$override = TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => ['slots' => ['content' => [['component' => 'OverrideComponent']]]],
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'test-admin-template',
]);
// 해석 실행
$resolved = $this->resolverService->resolve($layoutName, $this->template->id);
// 오버라이드가 반환되어야 함
$this->assertNotNull($resolved);
$this->assertEquals($override->id, $resolved->id);
$this->assertEquals(LayoutSourceType::Template, $resolved->source_type);
$this->assertStringContainsString('OverrideComponent', json_encode($resolved->content));
}
/**
* 오버라이드가 없을 때 모듈 레이아웃이 반환되는지 테스트
*/
public function test_resolve_returns_module_layout_when_no_override(): void
{
$layoutName = 'sirsoft-sample_admin_edit';
// 모듈 기본 레이아웃만 생성
$moduleLayout = TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => ['slots' => ['content' => [['component' => 'ModuleEditComponent']]]],
'source_type' => LayoutSourceType::Module,
'source_identifier' => 'sirsoft-sample',
]);
// 해석 실행
$resolved = $this->resolverService->resolve($layoutName, $this->template->id);
// 모듈 레이아웃이 반환되어야 함
$this->assertNotNull($resolved);
$this->assertEquals($moduleLayout->id, $resolved->id);
$this->assertEquals(LayoutSourceType::Module, $resolved->source_type);
}
/**
* 레이아웃이 존재하지 않을 때 null 반환 테스트
*/
public function test_resolve_returns_null_when_layout_not_found(): void
{
$resolved = $this->resolverService->resolve('non-existent-layout', $this->template->id);
$this->assertNull($resolved);
}
/**
* 캐시 히트 테스트
*/
public function test_resolve_uses_cache_on_subsequent_calls(): void
{
$layoutName = 'cached-layout';
// 레이아웃 생성
$layout = TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => ['slots' => []],
'source_type' => LayoutSourceType::Module,
'source_identifier' => 'test-module',
]);
// 캐시 통계 초기화
$this->resolverService->resetCacheStats();
// 첫 번째 호출 (캐시 미스)
$resolved1 = $this->resolverService->resolve($layoutName, $this->template->id);
$stats1 = $this->resolverService->getCacheStats();
$this->assertEquals(0, $stats1['hits']);
$this->assertEquals(1, $stats1['misses']);
// 두 번째 호출 (캐시 히트)
$resolved2 = $this->resolverService->resolve($layoutName, $this->template->id);
$stats2 = $this->resolverService->getCacheStats();
$this->assertEquals(1, $stats2['hits']);
$this->assertEquals(1, $stats2['misses']);
// 동일한 결과 반환
$this->assertEquals($resolved1->id, $resolved2->id);
}
/**
* 캐시 무효화 후 새 데이터 로드 테스트
*/
public function test_clear_resolution_cache_invalidates_cache(): void
{
$layoutName = 'invalidate-test-layout';
// 레이아웃 생성
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => ['slots' => []],
'source_type' => LayoutSourceType::Module,
'source_identifier' => 'test-module',
]);
// 첫 번째 호출로 캐싱
$this->resolverService->resolve($layoutName, $this->template->id);
// 캐시 무효화
$this->resolverService->clearResolutionCache($layoutName, $this->template->id);
// 캐시가 삭제되었는지 확인
$cacheKey = "layout_resolver.{$this->template->id}.{$layoutName}";
$this->assertNull(Cache::get($cacheKey));
}
/**
* 템플릿별 전체 캐시 무효화 테스트
*/
public function test_clear_all_resolution_cache_by_template(): void
{
// 여러 레이아웃 생성
for ($i = 1; $i <= 3; $i++) {
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => "layout-{$i}",
'content' => ['slots' => []],
'source_type' => LayoutSourceType::Module,
'source_identifier' => 'test-module',
]);
// 캐싱
$this->resolverService->resolve("layout-{$i}", $this->template->id);
}
// 전체 캐시 무효화
$this->resolverService->clearAllResolutionCacheByTemplate($this->template->id);
// 모든 캐시가 삭제되었는지 확인
for ($i = 1; $i <= 3; $i++) {
$cacheKey = "layout_resolver.{$this->template->id}.layout-{$i}";
$this->assertNull(Cache::get($cacheKey));
}
}
/**
* 모듈별 캐시 무효화 테스트
*/
public function test_clear_resolution_cache_by_module(): void
{
$moduleIdentifier = 'sirsoft-ecommerce';
// 모듈 레이아웃 생성
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => "{$moduleIdentifier}_admin_products",
'content' => ['slots' => []],
'source_type' => LayoutSourceType::Module,
'source_identifier' => $moduleIdentifier,
]);
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => "{$moduleIdentifier}_admin_orders",
'content' => ['slots' => []],
'source_type' => LayoutSourceType::Module,
'source_identifier' => $moduleIdentifier,
]);
// 캐싱
$this->resolverService->resolve("{$moduleIdentifier}_admin_products", $this->template->id);
$this->resolverService->resolve("{$moduleIdentifier}_admin_orders", $this->template->id);
// 모듈 캐시 무효화
$this->resolverService->clearResolutionCacheByModule($moduleIdentifier);
// 캐시가 삭제되었는지 확인
$cacheKey1 = "layout_resolver.{$this->template->id}.{$moduleIdentifier}_admin_products";
$cacheKey2 = "layout_resolver.{$this->template->id}.{$moduleIdentifier}_admin_orders";
$this->assertNull(Cache::get($cacheKey1));
$this->assertNull(Cache::get($cacheKey2));
}
/**
* 오버라이드 여부 확인 테스트
*/
public function test_is_overridden_returns_true_when_override_exists(): void
{
$layoutName = 'sirsoft-sample_admin_list';
// 모듈 레이아웃
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => ['slots' => []],
'source_type' => LayoutSourceType::Module,
'source_identifier' => 'sirsoft-sample',
]);
// 오버라이드 없음
$this->assertFalse($this->resolverService->isOverridden($layoutName, $this->template->id));
// 템플릿 오버라이드 추가
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => ['slots' => []],
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'test-admin-template',
]);
// 오버라이드 있음
$this->assertTrue($this->resolverService->isOverridden($layoutName, $this->template->id));
}
/**
* 오버라이드된 레이아웃 목록 조회 테스트
*/
public function test_get_overridden_layouts_returns_all_overrides(): void
{
// 모듈 레이아웃들
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => 'module_layout_1',
'content' => ['slots' => []],
'source_type' => LayoutSourceType::Module,
'source_identifier' => 'test-module',
]);
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => 'module_layout_2',
'content' => ['slots' => []],
'source_type' => LayoutSourceType::Module,
'source_identifier' => 'test-module',
]);
// 오버라이드 1개만 추가
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => 'module_layout_1',
'content' => ['slots' => []],
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'test-admin-template',
]);
$overriddenLayouts = $this->resolverService->getOverriddenLayouts($this->template->id);
$this->assertCount(1, $overriddenLayouts);
$this->assertEquals('module_layout_1', $overriddenLayouts->first()->name);
}
/**
* 특정 모듈의 오버라이드된 레이아웃 조회 테스트
*/
public function test_get_module_layout_overrides(): void
{
$moduleIdentifier = 'sirsoft-test';
// 모듈 레이아웃 생성
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => "{$moduleIdentifier}_layout_1",
'content' => ['slots' => []],
'source_type' => LayoutSourceType::Module,
'source_identifier' => $moduleIdentifier,
]);
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => "{$moduleIdentifier}_layout_2",
'content' => ['slots' => []],
'source_type' => LayoutSourceType::Module,
'source_identifier' => $moduleIdentifier,
]);
// 오버라이드 추가
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => "{$moduleIdentifier}_layout_1",
'content' => ['slots' => []],
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'test-admin-template',
]);
$moduleOverrides = $this->resolverService->getModuleLayoutOverrides($moduleIdentifier, $this->template->id);
$this->assertCount(1, $moduleOverrides);
$this->assertEquals("{$moduleIdentifier}_layout_1", $moduleOverrides->first()->name);
}
/**
* 캐시 통계 계산 테스트
*/
public function test_cache_stats_calculation(): void
{
$layoutName = 'stats-test-layout';
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => ['slots' => []],
'source_type' => LayoutSourceType::Module,
'source_identifier' => 'test-module',
]);
// 초기화
$this->resolverService->resetCacheStats();
// 5번 호출 (1 미스 + 4 히트)
for ($i = 0; $i < 5; $i++) {
$this->resolverService->resolve($layoutName, $this->template->id);
}
$stats = $this->resolverService->getCacheStats();
$this->assertEquals(4, $stats['hits']);
$this->assertEquals(1, $stats['misses']);
$this->assertEquals(5, $stats['total']);
$this->assertEquals(80.0, $stats['hit_rate']);
}
/**
* 캐시에 null 결과도 저장되는지 테스트
*/
public function test_resolve_caches_null_result(): void
{
$layoutName = 'non-existent-layout';
// 통계 초기화
$this->resolverService->resetCacheStats();
// 첫 번째 호출 (캐시 미스)
$result1 = $this->resolverService->resolve($layoutName, $this->template->id);
$this->assertNull($result1);
// 두 번째 호출 (캐시 히트 - null이 캐시됨)
$result2 = $this->resolverService->resolve($layoutName, $this->template->id);
$this->assertNull($result2);
$stats = $this->resolverService->getCacheStats();
$this->assertEquals(1, $stats['hits']);
$this->assertEquals(1, $stats['misses']);
}
/**
* version_constraint가 없는 오버라이드는 항상 적용됨
*/
public function test_override_without_version_constraint_is_always_applied(): void
{
$layoutName = 'sirsoft-sample.admin_index';
// 모듈 기본 레이아웃
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => ['slots' => ['content' => [['component' => 'ModuleComponent']]]],
'source_type' => LayoutSourceType::Module,
'source_identifier' => 'sirsoft-sample',
]);
// version_constraint 없는 오버라이드
$override = TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => ['slots' => ['content' => [['component' => 'OverrideComponent']]]],
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'test-admin-template',
]);
$resolved = $this->resolverService->resolve($layoutName, $this->template->id);
$this->assertNotNull($resolved);
$this->assertEquals($override->id, $resolved->id);
}
/**
* version_constraint 호환 시 오버라이드 적용됨
*/
public function test_override_with_compatible_version_constraint_is_applied(): void
{
$layoutName = 'sirsoft-ver-test.admin_index';
$moduleIdentifier = 'sirsoft-ver-test';
// 모듈 레코드 생성 (버전 1.2.0)
Module::create([
'identifier' => $moduleIdentifier,
'vendor' => 'sirsoft',
'name' => ['ko' => '버전 테스트', 'en' => 'Version Test'],
'version' => '1.2.0',
'status' => ExtensionStatus::Active->value,
'description' => ['ko' => '테스트용', 'en' => 'For testing'],
]);
// 모듈 기본 레이아웃
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => ['slots' => ['content' => [['component' => 'ModuleComponent']]]],
'source_type' => LayoutSourceType::Module,
'source_identifier' => $moduleIdentifier,
]);
// 호환 버전 제약 오버라이드 (>=1.0.0)
$override = TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => [
'version_constraint' => '>=1.0.0',
'slots' => ['content' => [['component' => 'OverrideComponent']]],
],
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'test-admin-template',
]);
$resolved = $this->resolverService->resolve($layoutName, $this->template->id);
$this->assertNotNull($resolved);
$this->assertEquals($override->id, $resolved->id);
$this->assertEquals(LayoutSourceType::Template, $resolved->source_type);
}
/**
* version_constraint 비호환 시 모듈 기본 레이아웃으로 폴백
*/
public function test_override_with_incompatible_version_falls_back_to_module(): void
{
$layoutName = 'sirsoft-fallback.admin_index';
$moduleIdentifier = 'sirsoft-fallback';
// 모듈 레코드 생성 (버전 0.9.0)
Module::create([
'identifier' => $moduleIdentifier,
'vendor' => 'sirsoft',
'name' => ['ko' => '폴백 테스트', 'en' => 'Fallback Test'],
'version' => '0.9.0',
'status' => ExtensionStatus::Active->value,
'description' => ['ko' => '테스트용', 'en' => 'For testing'],
]);
// 모듈 기본 레이아웃
$moduleLayout = TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => ['slots' => ['content' => [['component' => 'ModuleComponent']]]],
'source_type' => LayoutSourceType::Module,
'source_identifier' => $moduleIdentifier,
]);
// 비호환 버전 제약 오버라이드 (>=1.0.0 이지만 모듈은 0.9.0)
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => [
'version_constraint' => '>=1.0.0',
'slots' => ['content' => [['component' => 'OverrideComponent']]],
],
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'test-admin-template',
]);
$resolved = $this->resolverService->resolve($layoutName, $this->template->id);
// 모듈 기본 레이아웃으로 폴백
$this->assertNotNull($resolved);
$this->assertEquals($moduleLayout->id, $resolved->id);
$this->assertEquals(LayoutSourceType::Module, $resolved->source_type);
}
/**
* 모듈 버전 정보 없을 때 오버라이드 적용됨 (하위 호환)
*/
public function test_override_applied_when_module_version_unknown(): void
{
$layoutName = 'sirsoft-unknown.admin_index';
// 모듈 레코드 없음 (미설치)
// 모듈 기본 레이아웃
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => ['slots' => []],
'source_type' => LayoutSourceType::Module,
'source_identifier' => 'sirsoft-unknown',
]);
// version_constraint가 있지만 모듈 버전 정보 없음
$override = TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => [
'version_constraint' => '>=1.0.0',
'slots' => [],
],
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'test-admin-template',
]);
$resolved = $this->resolverService->resolve($layoutName, $this->template->id);
// 버전 정보 없으면 호환으로 처리
$this->assertNotNull($resolved);
$this->assertEquals($override->id, $resolved->id);
}
/**
* 잘못된 version_constraint 포맷 시 오버라이드 적용됨 (안전 폴백)
*/
public function test_override_applied_when_version_constraint_invalid(): void
{
$layoutName = 'sirsoft-invalid.admin_index';
$moduleIdentifier = 'sirsoft-invalid';
Module::create([
'identifier' => $moduleIdentifier,
'vendor' => 'sirsoft',
'name' => ['ko' => '잘못된 제약', 'en' => 'Invalid Constraint'],
'version' => '1.0.0',
'status' => ExtensionStatus::Active->value,
'description' => ['ko' => '테스트용', 'en' => 'For testing'],
]);
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => ['slots' => []],
'source_type' => LayoutSourceType::Module,
'source_identifier' => $moduleIdentifier,
]);
// 잘못된 제약 조건
$override = TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => [
'version_constraint' => '>>>invalid<<<',
'slots' => [],
],
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'test-admin-template',
]);
$resolved = $this->resolverService->resolve($layoutName, $this->template->id);
// 파싱 실패 시 호환으로 처리 (안전 폴백)
$this->assertNotNull($resolved);
$this->assertEquals($override->id, $resolved->id);
}
/**
* DOT 포맷 layout_name으로 오버라이드 end-to-end 매칭 테스트
*/
public function test_dot_format_layout_name_override_matching(): void
{
$layoutName = 'sirsoft-sample.admin_index';
// 모듈 기본 레이아웃 (DOT 포맷)
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => ['slots' => ['content' => [['component' => 'ModuleComponent']]]],
'source_type' => LayoutSourceType::Module,
'source_identifier' => 'sirsoft-sample',
]);
// 오버라이드 (DOT 포맷 매칭)
$override = TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => ['slots' => ['content' => [['component' => 'OverrideComponent']]]],
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'test-admin-template',
]);
$resolved = $this->resolverService->resolve($layoutName, $this->template->id);
$this->assertNotNull($resolved);
$this->assertEquals($override->id, $resolved->id);
}
/**
* 다중 템플릿 간 캐시 분리 테스트
*/
public function test_cache_separation_between_templates(): void
{
$layoutName = 'shared-layout';
// 두 번째 템플릿 생성
$template2 = Template::create([
'identifier' => 'second-template',
'vendor' => 'test',
'name' => ['ko' => '두 번째 템플릿', 'en' => 'Second Template'],
'version' => '1.0.0',
'type' => 'admin',
'status' => ExtensionStatus::Active->value,
'description' => ['ko' => '테스트용', 'en' => 'For testing'],
]);
// 각 템플릿에 동일한 이름의 레이아웃 생성
$layout1 = TemplateLayout::create([
'template_id' => $this->template->id,
'name' => $layoutName,
'content' => ['version' => '1'],
'source_type' => LayoutSourceType::Module,
'source_identifier' => 'test-module',
]);
$layout2 = TemplateLayout::create([
'template_id' => $template2->id,
'name' => $layoutName,
'content' => ['version' => '2'],
'source_type' => LayoutSourceType::Module,
'source_identifier' => 'test-module',
]);
// 각 템플릿에서 해석
$resolved1 = $this->resolverService->resolve($layoutName, $this->template->id);
$resolved2 = $this->resolverService->resolve($layoutName, $template2->id);
// 서로 다른 레이아웃이 반환되어야 함
$this->assertNotEquals($resolved1->id, $resolved2->id);
$this->assertEquals('1', $resolved1->content['version']);
$this->assertEquals('2', $resolved2->content['version']);
}
}
@@ -0,0 +1,311 @@
<?php
namespace Tests\Unit\Services;
use App\Models\Template;
use App\Models\TemplateLayout;
use App\Services\LayoutService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;
class LayoutServiceCachingTest extends TestCase
{
use RefreshDatabase;
private LayoutService $layoutService;
private Template $template;
protected function setUp(): void
{
parent::setUp();
$this->layoutService = app(LayoutService::class);
$this->template = Template::factory()->create();
}
/**
* 병합된 레이아웃이 캐싱되는지 테스트
*/
public function test_merged_layout_is_cached(): void
{
// Arrange
$parentLayout = TemplateLayout::factory()->create([
'template_id' => $this->template->id,
'name' => '_base',
'extends' => null,
'content' => [
'meta' => ['title' => 'Base'],
'components' => [
['type' => 'Slot', 'slot' => 'content'],
],
],
]);
$childLayout = TemplateLayout::factory()->create([
'template_id' => $this->template->id,
'name' => 'dashboard',
'extends' => '_base',
'content' => [
'extends' => '_base',
'meta' => ['title' => 'Dashboard'],
'slots' => [
'content' => [
['type' => 'Text', 'content' => 'Dashboard Content'],
],
],
],
]);
// Act: 첫 번째 호출 (캐시 미스)
$result1 = $this->layoutService->loadAndMergeLayout(
$this->template->id,
'dashboard'
);
// Assert: 캐시에 저장되었는지 확인
$cacheKey = "template.{$this->template->id}.layout.dashboard";
$this->assertTrue(Cache::has($cacheKey));
// Act: 두 번째 호출 (캐시 히트)
$result2 = $this->layoutService->loadAndMergeLayout(
$this->template->id,
'dashboard'
);
// Assert: 두 결과가 동일
$this->assertEquals($result1, $result2);
// Assert: 캐시 통계 확인
// 첫 호출: _base 미스, dashboard 미스 (총 2회 미스)
// 두 번째 호출: dashboard 히트 (총 1회 히트)
$stats = $this->layoutService->getCacheStats();
$this->assertEquals(1, $stats['hits']);
$this->assertEquals(2, $stats['misses']); // _base + dashboard
$this->assertEquals(3, $stats['total']);
$this->assertEquals(33.33, $stats['hit_rate']);
}
/**
* 레이아웃 캐시가 올바르게 무효화되는지 테스트
*/
public function test_layout_cache_is_cleared(): void
{
// Arrange
$layout = TemplateLayout::factory()->create([
'template_id' => $this->template->id,
'name' => '_base',
'extends' => null,
'content' => [
'meta' => ['title' => 'Base'],
'components' => [],
],
]);
// 캐시 생성
$this->layoutService->loadAndMergeLayout($this->template->id, '_base');
$cacheKey = "template.{$this->template->id}.layout._base";
$this->assertTrue(Cache::has($cacheKey));
// Act: 캐시 무효화
$this->layoutService->clearLayoutCache($this->template->id, '_base');
// Assert: 캐시가 삭제됨
$this->assertFalse(Cache::has($cacheKey));
}
/**
* 부모 레이아웃 수정 시 자식 레이아웃 캐시도 재귀적으로 무효화되는지 테스트
*/
public function test_dependent_layouts_cache_is_cleared_recursively(): void
{
// Arrange: 3단계 레이아웃 상속 구조
// _base → dashboard → dashboard_custom
$baseLayout = TemplateLayout::factory()->create([
'template_id' => $this->template->id,
'name' => '_base',
'extends' => null,
'content' => [
'meta' => ['title' => 'Base'],
'components' => [
['type' => 'Slot', 'slot' => 'content'],
],
],
]);
$dashboardLayout = TemplateLayout::factory()->create([
'template_id' => $this->template->id,
'name' => 'dashboard',
'extends' => '_base',
'content' => [
'extends' => '_base',
'meta' => ['title' => 'Dashboard'],
'components' => [
['type' => 'Slot', 'slot' => 'sub_content'],
],
'slots' => [
'content' => [
['type' => 'Text', 'content' => 'Dashboard'],
],
],
],
]);
$customLayout = TemplateLayout::factory()->create([
'template_id' => $this->template->id,
'name' => 'dashboard_custom',
'extends' => 'dashboard',
'content' => [
'extends' => 'dashboard',
'meta' => ['title' => 'Custom Dashboard'],
'slots' => [
'sub_content' => [
['type' => 'Text', 'content' => 'Custom'],
],
],
],
]);
// 모든 레이아웃 캐시 생성
$this->layoutService->loadAndMergeLayout($this->template->id, '_base');
$this->layoutService->loadAndMergeLayout($this->template->id, 'dashboard');
$this->layoutService->loadAndMergeLayout($this->template->id, 'dashboard_custom');
$baseCacheKey = "template.{$this->template->id}.layout._base";
$dashboardCacheKey = "template.{$this->template->id}.layout.dashboard";
$customCacheKey = "template.{$this->template->id}.layout.dashboard_custom";
$this->assertTrue(Cache::has($baseCacheKey));
$this->assertTrue(Cache::has($dashboardCacheKey));
$this->assertTrue(Cache::has($customCacheKey));
// Act: 부모 레이아웃 캐시 무효화
$this->layoutService->clearDependentLayoutsCache($this->template->id, '_base');
// Assert: 부모와 모든 자식의 캐시가 삭제됨
$this->assertFalse(Cache::has($baseCacheKey));
$this->assertFalse(Cache::has($dashboardCacheKey));
$this->assertFalse(Cache::has($customCacheKey));
}
/**
* 캐시 히트율 통계가 올바르게 계산되는지 테스트
*/
public function test_cache_hit_rate_is_calculated_correctly(): void
{
// Arrange
$layout = TemplateLayout::factory()->create([
'template_id' => $this->template->id,
'name' => '_base',
'extends' => null,
'content' => [
'meta' => ['title' => 'Base'],
'components' => [],
],
]);
$this->layoutService->resetCacheStats();
// Act: 1회 캐시 미스 + 3회 캐시 히트
$this->layoutService->loadAndMergeLayout($this->template->id, '_base'); // miss
$this->layoutService->loadAndMergeLayout($this->template->id, '_base'); // hit
$this->layoutService->loadAndMergeLayout($this->template->id, '_base'); // hit
$this->layoutService->loadAndMergeLayout($this->template->id, '_base'); // hit
// Assert
$stats = $this->layoutService->getCacheStats();
$this->assertEquals(3, $stats['hits']);
$this->assertEquals(1, $stats['misses']);
$this->assertEquals(4, $stats['total']);
$this->assertEquals(75.0, $stats['hit_rate']);
}
/**
* 캐시 만료 후 재생성되는지 테스트
*/
public function test_cache_expires_and_regenerates(): void
{
// Arrange
$layout = TemplateLayout::factory()->create([
'template_id' => $this->template->id,
'name' => '_base',
'extends' => null,
'content' => [
'meta' => ['title' => 'Base'],
'components' => [],
],
]);
// Act: 첫 호출로 캐시 생성
$result1 = $this->layoutService->loadAndMergeLayout($this->template->id, '_base');
$cacheKey = "template.{$this->template->id}.layout._base";
$this->assertTrue(Cache::has($cacheKey));
// 캐시 수동 삭제 (만료 시뮬레이션)
Cache::forget($cacheKey);
$this->assertFalse(Cache::has($cacheKey));
// Act: 캐시 만료 후 재호출
$result2 = $this->layoutService->loadAndMergeLayout($this->template->id, '_base');
// Assert: 캐시 재생성됨
$this->assertTrue(Cache::has($cacheKey));
$this->assertEquals($result1, $result2);
}
/**
* 중첩된 부모 레이아웃도 캐싱되는지 테스트
*/
public function test_nested_parent_layouts_are_cached(): void
{
// Arrange
$baseLayout = TemplateLayout::factory()->create([
'template_id' => $this->template->id,
'name' => '_base',
'extends' => null,
'content' => [
'meta' => ['title' => 'Base'],
'components' => [
['type' => 'Slot', 'slot' => 'content'],
],
],
]);
$dashboardLayout = TemplateLayout::factory()->create([
'template_id' => $this->template->id,
'name' => 'dashboard',
'extends' => '_base',
'content' => [
'extends' => '_base',
'meta' => ['title' => 'Dashboard'],
'slots' => [
'content' => [
['type' => 'Text', 'content' => 'Dashboard'],
],
],
],
]);
$this->layoutService->resetCacheStats();
// Act: 자식 레이아웃 로드 (부모도 자동 로드됨)
$this->layoutService->loadAndMergeLayout($this->template->id, 'dashboard');
// Assert: 부모와 자식 모두 캐싱됨
$baseCacheKey = "template.{$this->template->id}.layout._base";
$dashboardCacheKey = "template.{$this->template->id}.layout.dashboard";
$this->assertTrue(Cache::has($baseCacheKey));
$this->assertTrue(Cache::has($dashboardCacheKey));
// 다시 호출 시 부모와 자식 모두 캐시에서 조회됨
$this->layoutService->loadAndMergeLayout($this->template->id, 'dashboard');
$stats = $this->layoutService->getCacheStats();
$this->assertEquals(1, $stats['hits']); // dashboard 캐시 히트
$this->assertEquals(2, $stats['misses']); // _base, dashboard 최초 미스
}
}
@@ -0,0 +1,200 @@
<?php
namespace Tests\Unit\Services;
use App\Exceptions\CircularReferenceException;
use App\Models\Template;
use App\Models\TemplateLayout;
use App\Services\LayoutService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class LayoutServiceCircularReferenceTest extends TestCase
{
use RefreshDatabase;
private LayoutService $layoutService;
private Template $template;
protected function setUp(): void
{
parent::setUp();
$this->layoutService = app(LayoutService::class);
// 템플릿 생성 - 고유 identifier 사용하여 트랜잭션 락 충돌 방지
$this->template = Template::create([
'identifier' => 'test-template-'.uniqid(),
'vendor' => 'test',
'name' => 'Test Template',
'version' => '1.0.0',
'type' => 'admin',
'status' => 'active',
]);
}
/**
* A→B→A 형태의 직접 순환 참조 테스트
*/
public function test_detects_direct_circular_reference(): void
{
// Arrange: A→B→A 순환 참조 생성
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => 'layout-a',
'content' => [
'extends' => 'layout-b',
'meta' => ['title' => 'Layout A'],
],
]);
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => 'layout-b',
'content' => [
'extends' => 'layout-a',
'meta' => ['title' => 'Layout B'],
],
]);
// Act & Assert
$this->expectException(CircularReferenceException::class);
$this->expectExceptionMessage('layout-a → layout-b');
$this->layoutService->loadAndMergeLayout($this->template->id, 'layout-a');
}
/**
* A→B→C→A 형태의 간접 순환 참조 테스트
*/
public function test_detects_indirect_circular_reference(): void
{
// Arrange: A→B→C→A 순환 참조 생성
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => 'layout-a',
'content' => [
'extends' => 'layout-b',
'meta' => ['title' => 'Layout A'],
],
]);
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => 'layout-b',
'content' => [
'extends' => 'layout-c',
'meta' => ['title' => 'Layout B'],
],
]);
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => 'layout-c',
'content' => [
'extends' => 'layout-a',
'meta' => ['title' => 'Layout C'],
],
]);
// Act & Assert
$this->expectException(CircularReferenceException::class);
$this->expectExceptionMessage('layout-a → layout-b → layout-c');
$this->layoutService->loadAndMergeLayout($this->template->id, 'layout-a');
}
/**
* 10단계 이상 깊이 테스트
*/
public function test_prevents_max_depth_exceeded(): void
{
// Arrange: 11단계 상속 구조 생성 (최대 10단계 초과)
for ($i = 0; $i <= 10; $i++) {
$layoutData = ['meta' => ['title' => "Layout {$i}"]];
if ($i < 10) {
$layoutData['extends'] = 'layout-' . ($i + 1);
}
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => 'layout-' . $i,
'content' => $layoutData,
]);
}
// Act & Assert
$this->expectException(\Exception::class);
// 다국어 메시지 지원: 한국어 또는 영어
$this->expectExceptionMessageMatches('/(최대 허용 깊이|maximum allowed depth)/');
$this->layoutService->loadAndMergeLayout($this->template->id, 'layout-0');
}
/**
* 정상적인 상속 구조 테스트 (순환 참조 없음)
*
* 현재 구현: 슬롯 래퍼의 children에 슬롯 내용이 삽입됨
*/
public function test_loads_valid_inheritance_structure(): void
{
// Arrange: 정상적인 상속 구조 생성
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => 'base',
'content' => [
'meta' => ['title' => 'Base Layout'],
'components' => [
['type' => 'Header', 'slot' => 'header'],
],
],
]);
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => 'child',
'content' => [
'extends' => 'base',
'meta' => ['title' => 'Child Layout'],
'slots' => [
'header' => [['type' => 'CustomHeader']],
],
],
]);
// Act
$result = $this->layoutService->loadAndMergeLayout($this->template->id, 'child');
// Assert
$this->assertEquals('Child Layout', $result['meta']['title']);
// 슬롯 래퍼(Header)의 children에 CustomHeader가 삽입됨
$this->assertEquals('Header', $result['components'][0]['type']);
$this->assertEquals('CustomHeader', $result['components'][0]['children'][0]['type']);
}
/**
* extends가 없는 단일 레이아웃 테스트
*/
public function test_loads_single_layout_without_extends(): void
{
// Arrange
TemplateLayout::create([
'template_id' => $this->template->id,
'name' => 'standalone',
'content' => [
'meta' => ['title' => 'Standalone Layout'],
'components' => [
['type' => 'Header'],
],
],
]);
// Act
$result = $this->layoutService->loadAndMergeLayout($this->template->id, 'standalone');
// Assert
$this->assertEquals('Standalone Layout', $result['meta']['title']);
$this->assertCount(1, $result['components']);
}
}
@@ -0,0 +1,571 @@
<?php
namespace Tests\Unit\Services;
use App\Services\LayoutService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class LayoutServiceSeoMergeTest extends TestCase
{
use RefreshDatabase;
private LayoutService $layoutService;
/**
* 테스트 초기화 - LayoutService 인스턴스를 준비합니다.
*/
protected function setUp(): void
{
parent::setUp();
$this->layoutService = app(LayoutService::class);
}
/**
* 부모만 meta.seo가 있을 때 부모의 seo가 사용됩니다.
*/
public function test_parent_only_seo_is_used(): void
{
$parentSeo = [
'enabled' => true,
'priority' => 'high',
'og' => ['type' => 'website'],
];
$parent = $this->buildLayout(seo: $parentSeo);
$child = $this->buildLayout();
$result = $this->layoutService->mergeLayouts($parent, $child);
$this->assertTrue($result['meta']['seo']['enabled']);
$this->assertSame('high', $result['meta']['seo']['priority']);
$this->assertSame('website', $result['meta']['seo']['og']['type']);
}
/**
* 자식만 meta.seo가 있을 때 자식의 seo가 사용됩니다.
*/
public function test_child_only_seo_is_used(): void
{
$childSeo = [
'enabled' => true,
'priority' => 'low',
'og' => ['title' => '자식 페이지'],
];
$parent = $this->buildLayout();
$child = $this->buildLayout(seo: $childSeo);
$result = $this->layoutService->mergeLayouts($parent, $child);
$this->assertTrue($result['meta']['seo']['enabled']);
$this->assertSame('low', $result['meta']['seo']['priority']);
$this->assertSame('자식 페이지', $result['meta']['seo']['og']['title']);
}
/**
* 부모와 자식 모두 meta.seo가 있을 때 자식의 priority가 우선됩니다.
*/
public function test_child_overrides_priority_parent_rest_preserved(): void
{
$parentSeo = [
'enabled' => true,
'priority' => 'high',
'title_template' => '{{title}} - 사이트명',
'description' => '기본 설명',
];
$childSeo = [
'priority' => 'low',
];
$parent = $this->buildLayout(seo: $parentSeo);
$child = $this->buildLayout(seo: $childSeo);
$result = $this->layoutService->mergeLayouts($parent, $child);
// 자식이 오버라이드한 값
$this->assertSame('low', $result['meta']['seo']['priority']);
// 부모에서 보존된 값
$this->assertTrue($result['meta']['seo']['enabled']);
$this->assertSame('{{title}} - 사이트명', $result['meta']['seo']['title_template']);
$this->assertSame('기본 설명', $result['meta']['seo']['description']);
}
/**
* 자식이 og를 추가하면 부모의 기본값과 함께 병합됩니다.
*/
public function test_child_adds_og_merged_with_parent_defaults(): void
{
$parentSeo = [
'enabled' => true,
'priority' => 'medium',
];
$childSeo = [
'og' => [
'title' => '상품 상세',
'type' => 'product',
],
];
$parent = $this->buildLayout(seo: $parentSeo);
$child = $this->buildLayout(seo: $childSeo);
$result = $this->layoutService->mergeLayouts($parent, $child);
// 부모 기본값 보존
$this->assertTrue($result['meta']['seo']['enabled']);
$this->assertSame('medium', $result['meta']['seo']['priority']);
// 자식이 추가한 og
$this->assertSame('상품 상세', $result['meta']['seo']['og']['title']);
$this->assertSame('product', $result['meta']['seo']['og']['type']);
}
/**
* 자식이 enabled=false로 설정하면 최종 결과에서 enabled=false가 됩니다.
*/
public function test_child_sets_enabled_false(): void
{
$parentSeo = [
'enabled' => true,
'priority' => 'high',
];
$childSeo = [
'enabled' => false,
];
$parent = $this->buildLayout(seo: $parentSeo);
$child = $this->buildLayout(seo: $childSeo);
$result = $this->layoutService->mergeLayouts($parent, $child);
$this->assertFalse($result['meta']['seo']['enabled']);
// 부모 나머지 보존
$this->assertSame('high', $result['meta']['seo']['priority']);
}
/**
* 부모 seo.og.type + 자식 seo.og.title → og가 deep merge됩니다.
*/
public function test_og_deep_merge_parent_type_child_title(): void
{
$parentSeo = [
'enabled' => true,
'og' => [
'type' => 'website',
'site_name' => 'G7 Store',
],
];
$childSeo = [
'og' => [
'title' => '카테고리 페이지',
],
];
$parent = $this->buildLayout(seo: $parentSeo);
$child = $this->buildLayout(seo: $childSeo);
$result = $this->layoutService->mergeLayouts($parent, $child);
// 부모 og 보존
$this->assertSame('website', $result['meta']['seo']['og']['type']);
$this->assertSame('G7 Store', $result['meta']['seo']['og']['site_name']);
// 자식 og 추가
$this->assertSame('카테고리 페이지', $result['meta']['seo']['og']['title']);
}
/**
* seo 이외의 meta 키(title, description)는 기존 얕은 병합이 유지됩니다.
*/
public function test_non_seo_meta_keys_use_shallow_merge(): void
{
$parent = [
'meta' => [
'title' => 'Parent Title',
'description' => 'Parent Description',
'seo' => ['enabled' => true, 'priority' => 'high'],
],
'data_sources' => [],
'components' => [],
];
$child = [
'meta' => [
'title' => 'Child Title',
'seo' => ['priority' => 'low'],
],
'data_sources' => [],
'components' => [],
];
$result = $this->layoutService->mergeLayouts($parent, $child);
// 얕은 병합: 자식 title 우선
$this->assertSame('Child Title', $result['meta']['title']);
// 얕은 병합: 자식에 없는 description 보존
$this->assertSame('Parent Description', $result['meta']['description']);
// seo는 deep merge
$this->assertSame('low', $result['meta']['seo']['priority']);
$this->assertTrue($result['meta']['seo']['enabled']);
}
/**
* 3단계 상속(mergeLayouts 2회 호출)에서 모든 레벨의 seo가 누적됩니다.
*/
public function test_three_level_inheritance_accumulates_seo(): void
{
// Level 1: _base (최상위 부모)
$base = [
'meta' => [
'seo' => [
'enabled' => true,
'title_template' => '{{title}} - G7',
'og' => [
'type' => 'website',
'site_name' => 'G7',
],
],
],
'data_sources' => [],
'components' => [
['component' => 'Div', 'slot' => 'content'],
],
];
// Level 2: shop 기본 (중간 레벨)
$shopBase = [
'meta' => [
'seo' => [
'priority' => 'medium',
'og' => [
'type' => 'product.group',
],
'structured_data' => [
'type' => 'ItemList',
],
],
],
'data_sources' => [],
'slots' => [
'content' => [
'component' => 'Div',
'slot' => 'shop_content',
],
],
];
// Level 3: 상품 상세 (최하위)
$shopShow = [
'meta' => [
'seo' => [
'priority' => 'high',
'og' => [
'title' => '{{product.name}}',
'image' => '{{product.image}}',
],
'data_sources' => ['product'],
],
],
'data_sources' => [],
'slots' => [
'shop_content' => [
'component' => 'Div',
'props' => ['text' => '상품 상세'],
],
],
];
// 3단계 병합: _base + shop_base → 중간 결과 + shop_show
$merged1 = $this->layoutService->mergeLayouts($base, $shopBase);
$result = $this->layoutService->mergeLayouts($merged1, $shopShow);
$seo = $result['meta']['seo'];
// _base에서 상속
$this->assertTrue($seo['enabled']);
$this->assertSame('{{title}} - G7', $seo['title_template']);
// shop_base에서 상속 (deep merge)
$this->assertSame('ItemList', $seo['structured_data']['type']);
// shop_show에서 오버라이드
$this->assertSame('high', $seo['priority']);
// data_sources는 합집합 병합 (Level 3의 'product'만 존재 — Level 1,2는 미정의)
$this->assertSame(['product'], $seo['data_sources']);
// og deep merge: _base의 site_name + shop_base의 type 오버라이드 + shop_show의 title, image
$this->assertSame('G7', $seo['og']['site_name']);
$this->assertSame('product.group', $seo['og']['type']);
$this->assertSame('{{product.name}}', $seo['og']['title']);
$this->assertSame('{{product.image}}', $seo['og']['image']);
}
// ─── data_sources 합집합 병합 테스트 ──────────────────────────────
/**
* 부모와 자식의 data_sources가 합집합으로 병합됩니다.
*/
public function test_data_sources_union_merge_parent_and_child(): void
{
$parent = $this->buildLayout(seo: [
'enabled' => true,
'data_sources' => ['stats', 'menu'],
]);
$child = $this->buildLayout(seo: [
'data_sources' => ['product'],
]);
$result = $this->layoutService->mergeLayouts($parent, $child);
$this->assertSame(['stats', 'menu', 'product'], $result['meta']['seo']['data_sources']);
}
/**
* 부모와 자식의 data_sources 중복이 제거됩니다.
*/
public function test_data_sources_union_dedup(): void
{
$parent = $this->buildLayout(seo: [
'enabled' => true,
'data_sources' => ['products', 'categories'],
]);
$child = $this->buildLayout(seo: [
'data_sources' => ['products', 'reviews'],
]);
$result = $this->layoutService->mergeLayouts($parent, $child);
$this->assertSame(['products', 'categories', 'reviews'], $result['meta']['seo']['data_sources']);
}
/**
* 자식만 data_sources를 정의하면 그대로 사용됩니다.
*/
public function test_data_sources_child_only(): void
{
$parent = $this->buildLayout(seo: [
'enabled' => true,
]);
$child = $this->buildLayout(seo: [
'data_sources' => ['product'],
]);
$result = $this->layoutService->mergeLayouts($parent, $child);
$this->assertSame(['product'], $result['meta']['seo']['data_sources']);
}
/**
* 부모만 data_sources를 정의하면 자식이 상속합니다.
*/
public function test_data_sources_parent_only(): void
{
$parent = $this->buildLayout(seo: [
'enabled' => true,
'data_sources' => ['stats'],
]);
$child = $this->buildLayout(seo: [
'priority' => 0.8,
]);
$result = $this->layoutService->mergeLayouts($parent, $child);
$this->assertSame(['stats'], $result['meta']['seo']['data_sources']);
}
/**
* 양쪽 모두 data_sources 미정의 시 키가 없습니다.
*/
public function test_data_sources_both_empty(): void
{
$parent = $this->buildLayout(seo: [
'enabled' => true,
]);
$child = $this->buildLayout(seo: [
'priority' => 0.5,
]);
$result = $this->layoutService->mergeLayouts($parent, $child);
$this->assertArrayNotHasKey('data_sources', $result['meta']['seo']);
}
// ─── vars deep merge 테스트 ──────────────────────────────────────
/**
* 부모와 자식의 vars가 deep merge되어 양쪽 모두 보존됩니다.
*/
public function test_vars_deep_merge_parent_child(): void
{
$parent = $this->buildLayout(seo: [
'enabled' => true,
'vars' => ['site_name' => '$core_settings:general.site_name'],
]);
$child = $this->buildLayout(seo: [
'vars' => ['product_name' => '{{product.data.name}}'],
]);
$result = $this->layoutService->mergeLayouts($parent, $child);
$vars = $result['meta']['seo']['vars'];
$this->assertSame('$core_settings:general.site_name', $vars['site_name']);
$this->assertSame('{{product.data.name}}', $vars['product_name']);
}
/**
* 자식의 vars가 부모의 동일 키를 오버라이드합니다.
*/
public function test_vars_child_overrides_parent_key(): void
{
$parent = $this->buildLayout(seo: [
'enabled' => true,
'vars' => ['name' => 'Parent Name'],
]);
$child = $this->buildLayout(seo: [
'vars' => ['name' => 'Child Name'],
]);
$result = $this->layoutService->mergeLayouts($parent, $child);
$this->assertSame('Child Name', $result['meta']['seo']['vars']['name']);
}
// ─── base enabled 상속 테스트 ────────────────────────────────────
/**
* 부모 enabled=false + 자식 enabled=true → 자식 우선으로 활성화됩니다.
*/
public function test_base_seo_disabled_child_enables(): void
{
$parent = $this->buildLayout(seo: [
'enabled' => false,
'og' => ['type' => 'website'],
]);
$child = $this->buildLayout(seo: [
'enabled' => true,
]);
$result = $this->layoutService->mergeLayouts($parent, $child);
$this->assertTrue($result['meta']['seo']['enabled']);
$this->assertSame('website', $result['meta']['seo']['og']['type']);
}
/**
* 부모의 og.type을 자식이 오버라이드합니다.
*/
public function test_base_og_type_inherited_child_overrides(): void
{
$parent = $this->buildLayout(seo: [
'enabled' => true,
'og' => ['type' => 'website'],
]);
$child = $this->buildLayout(seo: [
'og' => ['type' => 'product'],
]);
$result = $this->layoutService->mergeLayouts($parent, $child);
$this->assertSame('product', $result['meta']['seo']['og']['type']);
}
/**
* 부모의 og.type이 보존되면서 자식이 og.title을 추가합니다.
*/
public function test_base_og_type_inherited_child_adds_title(): void
{
$parent = $this->buildLayout(seo: [
'enabled' => true,
'og' => ['type' => 'website'],
]);
$child = $this->buildLayout(seo: [
'og' => ['title' => '상품 페이지'],
]);
$result = $this->layoutService->mergeLayouts($parent, $child);
$this->assertSame('website', $result['meta']['seo']['og']['type']);
$this->assertSame('상품 페이지', $result['meta']['seo']['og']['title']);
}
// ─── 3단계 상속 data_sources 누적 테스트 ─────────────────────────
/**
* 3단계 상속에서 각 레벨의 data_sources가 합집합으로 누적됩니다.
*/
public function test_three_level_data_sources_accumulate(): void
{
$base = [
'meta' => [
'seo' => [
'enabled' => true,
'data_sources' => ['stats'],
],
],
'data_sources' => [],
'components' => [
['component' => 'Div', 'slot' => 'content'],
],
];
$mid = [
'meta' => [
'seo' => [
'data_sources' => ['categories'],
],
],
'data_sources' => [],
'slots' => [
'content' => [
'component' => 'Div',
'slot' => 'inner',
],
],
];
$leaf = [
'meta' => [
'seo' => [
'data_sources' => ['product', 'stats'],
],
],
'data_sources' => [],
'slots' => [
'inner' => [
'component' => 'Div',
'props' => ['text' => 'leaf'],
],
],
];
$merged1 = $this->layoutService->mergeLayouts($base, $mid);
$result = $this->layoutService->mergeLayouts($merged1, $leaf);
// stats(base) + categories(mid) + product(leaf) — stats 중복 제거
$this->assertSame(['stats', 'categories', 'product'], $result['meta']['seo']['data_sources']);
$this->assertTrue($result['meta']['seo']['enabled']);
}
/**
* 테스트용 레이아웃 배열을 빌드합니다.
*
* @param array|null $seo SEO 설정 배열 (null이면 seo 키 없음)
* @return array 레이아웃 배열
*/
private function buildLayout(?array $seo = null): array
{
$meta = [];
if ($seo !== null) {
$meta['seo'] = $seo;
}
return [
'meta' => $meta,
'data_sources' => [],
'components' => [],
];
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,367 @@
<?php
namespace Tests\Unit\Services;
use App\Enums\ExtensionOwnerType;
use App\Enums\MailSendStatus;
use App\Models\MailSendLog;
use App\Services\MailSendLogService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* MailSendLogService 테스트
*
* 메일 발송 이력 서비스의 로깅, 조회, 통계 메서드를 검증합니다.
*/
class MailSendLogServiceTest extends TestCase
{
use RefreshDatabase;
private MailSendLogService $service;
protected function setUp(): void
{
parent::setUp();
$this->service = app(MailSendLogService::class);
}
// ========================================================================
// logSent
// ========================================================================
/**
* 발송 성공 이력을 기록합니다
*/
public function test_log_sent_creates_sent_record(): void
{
$log = $this->service->logSent(
recipientEmail: 'user@example.com',
recipientName: 'John Doe',
subject: 'Welcome',
templateType: 'welcome',
extensionType: ExtensionOwnerType::Core,
extensionIdentifier: 'core',
source: 'notification',
);
$this->assertInstanceOf(MailSendLog::class, $log);
$this->assertTrue($log->exists);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'user@example.com',
'recipient_name' => 'John Doe',
'subject' => 'Welcome',
'template_type' => 'welcome',
'extension_type' => ExtensionOwnerType::Core->value,
'extension_identifier' => 'core',
'source' => 'notification',
'status' => MailSendStatus::Sent->value,
]);
}
/**
* logSent는 기본값으로 extensionType=Core, extensionIdentifier='core', source=null을 사용
*/
public function test_log_sent_uses_default_values(): void
{
$log = $this->service->logSent(
recipientEmail: 'test@example.com',
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'test@example.com',
'recipient_name' => null,
'subject' => null,
'template_type' => null,
'extension_type' => ExtensionOwnerType::Core->value,
'extension_identifier' => 'core',
'source' => null,
'status' => MailSendStatus::Sent->value,
]);
}
/**
* logSent는 sent_at을 자동 설정
*/
public function test_log_sent_sets_sent_at(): void
{
$log = $this->service->logSent(recipientEmail: 'test@example.com');
$this->assertNotNull($log->sent_at);
}
/**
* logSent는 body를 기록합니다
*/
public function test_log_sent_records_body(): void
{
$body = '<p>Welcome to G7!</p>';
$log = $this->service->logSent(
recipientEmail: 'user@example.com',
subject: 'Welcome',
body: $body,
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'user@example.com',
'body' => $body,
]);
}
/**
* logSent는 body가 null일 수 있음
*/
public function test_log_sent_allows_null_body(): void
{
$log = $this->service->logSent(
recipientEmail: 'test@example.com',
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'test@example.com',
'body' => null,
]);
}
/**
* logSent는 발송자 정보를 기록합니다
*/
public function test_log_sent_records_sender(): void
{
$log = $this->service->logSent(
recipientEmail: 'user@example.com',
subject: 'Welcome',
senderEmail: 'admin@example.com',
senderName: 'G7 Admin',
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'user@example.com',
'sender_email' => 'admin@example.com',
'sender_name' => 'G7 Admin',
]);
}
/**
* logSent는 발송자 정보가 null일 수 있음
*/
public function test_log_sent_allows_null_sender(): void
{
$log = $this->service->logSent(
recipientEmail: 'test@example.com',
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'test@example.com',
'sender_email' => null,
'sender_name' => null,
]);
}
// ========================================================================
// logFailed
// ========================================================================
/**
* 발송 실패 이력을 기록합니다
*/
public function test_log_failed_creates_failed_record(): void
{
$log = $this->service->logFailed(
recipientEmail: 'user@example.com',
subject: 'Order Confirmation',
templateType: 'order_confirmed',
extensionType: ExtensionOwnerType::Module,
extensionIdentifier: 'sirsoft-ecommerce',
source: 'notification',
errorMessage: 'Connection timeout',
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'user@example.com',
'subject' => 'Order Confirmation',
'template_type' => 'order_confirmed',
'extension_type' => ExtensionOwnerType::Module->value,
'extension_identifier' => 'sirsoft-ecommerce',
'source' => 'notification',
'status' => MailSendStatus::Failed->value,
'error_message' => 'Connection timeout',
]);
}
/**
* logFailed는 body를 기록합니다
*/
public function test_log_failed_records_body(): void
{
$body = '<p>Order Confirmation</p>';
$log = $this->service->logFailed(
recipientEmail: 'user@example.com',
subject: 'Order',
errorMessage: 'SMTP error',
body: $body,
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'user@example.com',
'body' => $body,
'status' => MailSendStatus::Failed->value,
]);
}
/**
* logFailed는 발송자 정보를 기록합니다
*/
public function test_log_failed_records_sender(): void
{
$log = $this->service->logFailed(
recipientEmail: 'user@example.com',
errorMessage: 'SMTP error',
senderEmail: 'noreply@example.com',
senderName: 'G7 System',
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'user@example.com',
'sender_email' => 'noreply@example.com',
'sender_name' => 'G7 System',
'status' => MailSendStatus::Failed->value,
]);
}
/**
* logFailed는 error_message가 null일 수 있음
*/
public function test_log_failed_allows_null_error_message(): void
{
$log = $this->service->logFailed(
recipientEmail: 'test@example.com',
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'test@example.com',
'status' => MailSendStatus::Failed->value,
'error_message' => null,
]);
}
// ========================================================================
// logSkipped
// ========================================================================
/**
* 발송 건너뛰기 이력을 기록합니다
*/
public function test_log_skipped_creates_skipped_record(): void
{
$log = $this->service->logSkipped(
recipientEmail: 'user@example.com',
recipientName: 'User',
templateType: 'welcome',
extensionType: ExtensionOwnerType::Core,
extensionIdentifier: 'core',
source: 'notification',
errorMessage: '비활성 템플릿',
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'user@example.com',
'recipient_name' => 'User',
'subject' => null,
'template_type' => 'welcome',
'extension_type' => ExtensionOwnerType::Core->value,
'extension_identifier' => 'core',
'source' => 'notification',
'status' => MailSendStatus::Skipped->value,
'error_message' => '비활성 템플릿',
]);
}
/**
* logSkipped는 발송자 정보를 기록합니다
*/
public function test_log_skipped_records_sender(): void
{
$log = $this->service->logSkipped(
recipientEmail: 'user@example.com',
senderEmail: 'admin@example.com',
senderName: 'G7 Admin',
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'user@example.com',
'sender_email' => 'admin@example.com',
'sender_name' => 'G7 Admin',
'status' => MailSendStatus::Skipped->value,
]);
}
/**
* logSkipped는 subject를 항상 null로 설정
*/
public function test_log_skipped_always_sets_null_subject(): void
{
$log = $this->service->logSkipped(
recipientEmail: 'test@example.com',
);
$this->assertNull($log->subject);
}
// ========================================================================
// getLogs
// ========================================================================
/**
* 발송 이력 목록 조회
*/
public function test_get_logs_returns_paginated_result(): void
{
MailSendLog::factory()->count(5)->create();
$result = $this->service->getLogs();
$this->assertCount(5, $result->items());
$this->assertEquals(5, $result->total());
}
/**
* 발송 이력 목록 필터 조회
*/
public function test_get_logs_applies_filters(): void
{
MailSendLog::factory()->forExtension(ExtensionOwnerType::Core, 'core')->count(3)->create();
MailSendLog::factory()->forExtension(ExtensionOwnerType::Module, 'sirsoft-ecommerce')->count(2)->create();
$result = $this->service->getLogs(['extension_type' => 'core']);
$this->assertCount(3, $result->items());
}
// ========================================================================
// getStatistics
// ========================================================================
/**
* 발송 통계 조회
*/
public function test_get_statistics_returns_correct_data(): void
{
MailSendLog::factory()->count(3)->create([
'status' => MailSendStatus::Sent->value,
'sent_at' => now(),
]);
MailSendLog::factory()->failed()->count(1)->create([
'sent_at' => now(),
]);
$stats = $this->service->getStatistics();
$this->assertEquals(4, $stats['total']);
$this->assertEquals(3, $stats['sent']);
$this->assertEquals(1, $stats['failed']);
$this->assertEquals(4, $stats['today']);
}
}
@@ -0,0 +1,260 @@
<?php
namespace Tests\Unit\Services;
use App\Models\MailTemplate;
use App\Models\User;
use App\Services\MailTemplateService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;
/**
* MailTemplateService 테스트
*
* 서비스의 CRUD, resolveTemplate 캐시, toggleActive, resetToDefault를 검증합니다.
*/
class MailTemplateServiceTest extends TestCase
{
use RefreshDatabase;
private MailTemplateService $service;
protected function setUp(): void
{
parent::setUp();
Cache::flush();
$this->service = app(MailTemplateService::class);
}
// ========================================================================
// getTemplatesForSettings
// ========================================================================
/**
* 전체 템플릿 목록을 반환
*/
public function test_get_templates_for_settings_returns_all(): void
{
MailTemplate::factory()->withType('welcome')->create();
MailTemplate::factory()->withType('reset_password')->create();
MailTemplate::factory()->withType('password_changed')->inactive()->create();
$result = $this->service->getTemplatesForSettings();
$this->assertCount(3, $result);
}
// ========================================================================
// updateTemplate
// ========================================================================
/**
* 템플릿 수정이 올바르게 동작
*/
public function test_update_template_saves_data(): void
{
$user = User::factory()->create();
$template = MailTemplate::factory()->withType('welcome')->create();
$updated = $this->service->updateTemplate($template, [
'subject' => ['ko' => '수정된 제목', 'en' => 'Updated Subject'],
'body' => ['ko' => '<p>수정됨</p>', 'en' => '<p>Updated</p>'],
'is_active' => true,
], $user->id);
$this->assertEquals(['ko' => '수정된 제목', 'en' => 'Updated Subject'], $updated->subject);
$this->assertFalse($updated->is_default);
$this->assertEquals($user->id, $updated->updated_by);
}
/**
* 수정 시 캐시가 무효화됨
*/
public function test_update_template_invalidates_cache(): void
{
$template = MailTemplate::factory()->withType('welcome')->create();
Cache::put('mail_template:core:welcome', $template, 3600);
$this->service->updateTemplate($template, [
'subject' => ['ko' => '새 제목'],
'body' => ['ko' => '<p>새 본문</p>'],
]);
$this->assertFalse(Cache::has('mail_template:core:welcome'));
}
// ========================================================================
// toggleActive
// ========================================================================
/**
* 활성 상태를 토글
*/
public function test_toggle_active_flips_state(): void
{
$template = MailTemplate::factory()->create(['is_active' => true]);
$toggled = $this->service->toggleActive($template);
$this->assertFalse($toggled->is_active);
}
/**
* 비활성→활성 토글
*/
public function test_toggle_active_activates_inactive(): void
{
$template = MailTemplate::factory()->inactive()->create();
$toggled = $this->service->toggleActive($template);
$this->assertTrue($toggled->is_active);
}
/**
* 토글 시 캐시가 무효화됨
*/
public function test_toggle_active_invalidates_cache(): void
{
$template = MailTemplate::factory()->withType('reset_password')->create();
Cache::put('mail_template:core:reset_password', $template, 3600);
$this->service->toggleActive($template);
$this->assertFalse(Cache::has('mail_template:core:reset_password'));
}
// ========================================================================
// resolveTemplate (캐시)
// ========================================================================
/**
* resolveTemplate이 활성 템플릿을 반환
*/
public function test_resolve_template_returns_active(): void
{
MailTemplate::factory()->withType('welcome')->create(['is_active' => true]);
$result = $this->service->resolveTemplate('welcome');
$this->assertNotNull($result);
$this->assertEquals('welcome', $result->type);
}
/**
* resolveTemplate이 비활성 템플릿에 null 반환
*/
public function test_resolve_template_returns_null_for_inactive(): void
{
MailTemplate::factory()->withType('welcome')->inactive()->create();
$result = $this->service->resolveTemplate('welcome');
$this->assertNull($result);
}
/**
* resolveTemplate이 결과를 캐싱
*/
public function test_resolve_template_caches_result(): void
{
MailTemplate::factory()->withType('welcome')->create(['is_active' => true]);
$this->service->resolveTemplate('welcome');
$this->assertTrue(Cache::has('mail_template:core:welcome'));
}
// ========================================================================
// getPreview
// ========================================================================
/**
* 미리보기가 변수를 placeholder로 치환
*/
public function test_get_preview_replaces_variables(): void
{
$data = [
'subject' => 'Hello {name}',
'body' => '<p>Welcome to {app_name}</p>',
'variables' => [
['key' => 'name'],
['key' => 'app_name'],
],
];
$result = $this->service->getPreview($data);
$this->assertEquals('Hello {name}', $result['subject']);
$this->assertEquals('<p>Welcome to {app_name}</p>', $result['body']);
}
// ========================================================================
// resetToDefault
// ========================================================================
// ========================================================================
// getTemplates (페이지네이션)
// ========================================================================
/**
* 페이지네이션된 목록을 반환
*/
public function test_get_templates_returns_paginated(): void
{
MailTemplate::factory()->count(5)->create();
$result = $this->service->getTemplates([], 2);
$this->assertEquals(5, $result->total());
$this->assertCount(2, $result->items());
$this->assertEquals(3, $result->lastPage());
}
/**
* 검색 필터가 동작
*/
public function test_get_templates_filters_by_search(): void
{
MailTemplate::factory()->withType('welcome')->create([
'subject' => ['ko' => '환영 메일', 'en' => 'Welcome'],
]);
MailTemplate::factory()->withType('reset_password')->create([
'subject' => ['ko' => '비밀번호 재설정', 'en' => 'Reset Password'],
]);
$result = $this->service->getTemplates(['search' => '환영', 'search_type' => 'subject']);
$this->assertEquals(1, $result->total());
}
// ========================================================================
// resetToDefault
// ========================================================================
/**
* 기본값으로 복원
*/
public function test_reset_to_default_restores_data(): void
{
$template = MailTemplate::factory()->withType('welcome')->create([
'subject' => ['ko' => '사용자 수정'],
'body' => ['ko' => '<p>수정됨</p>'],
'is_default' => false,
]);
$defaultData = [
'subject' => ['ko' => '원래 제목', 'en' => 'Original Subject'],
'body' => ['ko' => '<p>원래 본문</p>', 'en' => '<p>Original Body</p>'],
'variables' => [['key' => 'name', 'description' => '이름']],
];
$result = $this->service->resetToDefault($template, $defaultData);
$this->assertEquals(['ko' => '원래 제목', 'en' => 'Original Subject'], $result->subject);
$this->assertTrue($result->is_default);
$this->assertTrue($result->is_active);
}
}
+130
View File
@@ -0,0 +1,130 @@
<?php
namespace Tests\Unit\Services;
use App\Extension\HookManager;
use App\Models\Menu;
use App\Models\Role;
use App\Services\MenuService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Validation\ValidationException;
use Tests\TestCase;
/**
* MenuService 삭제 테스트
*
* 메뉴 삭제 시 관계 레코드 명시적 삭제 및 훅 실행을 검증합니다.
*/
class MenuServiceTest extends TestCase
{
use RefreshDatabase;
private MenuService $menuService;
protected function setUp(): void
{
parent::setUp();
$this->menuService = app(MenuService::class);
HookManager::resetAll();
}
protected function tearDown(): void
{
HookManager::resetAll();
parent::tearDown();
}
// ========================================================================
// deleteMenu() - 관계 레코드 명시적 삭제 검증
// ========================================================================
/**
* 메뉴 삭제 시 역할 연결이 해제되는지 확인
*/
public function test_delete_menu_detaches_roles(): void
{
$menu = Menu::create([
'slug' => 'test-menu-detach',
'name' => ['ko' => '테스트 메뉴', 'en' => 'Test Menu'],
'url' => '/test',
'sort_order' => 1,
]);
$role = Role::create([
'identifier' => 'test-role-for-menu',
'name' => ['ko' => '테스트 역할', 'en' => 'Test Role'],
]);
$menu->roles()->attach($role->id);
$this->assertDatabaseHas('role_menus', ['menu_id' => $menu->id, 'role_id' => $role->id]);
$this->menuService->deleteMenu($menu);
$this->assertDatabaseMissing('role_menus', ['menu_id' => $menu->id]);
}
// ========================================================================
// deleteMenu() - 자식 메뉴 검증
// ========================================================================
/**
* 자식 메뉴가 있는 경우 삭제 시 예외 발생
*/
public function test_delete_menu_with_children_throws_exception(): void
{
$parentMenu = Menu::create([
'slug' => 'parent-menu',
'name' => ['ko' => '부모 메뉴', 'en' => 'Parent Menu'],
'url' => '/parent',
'sort_order' => 1,
]);
Menu::create([
'slug' => 'child-menu',
'name' => ['ko' => '자식 메뉴', 'en' => 'Child Menu'],
'url' => '/child',
'parent_id' => $parentMenu->id,
'sort_order' => 1,
]);
$this->expectException(ValidationException::class);
$this->menuService->deleteMenu($parentMenu);
}
// ========================================================================
// deleteMenu() - 훅 실행 검증
// ========================================================================
/**
* 메뉴 삭제 시 before_delete/after_delete 훅이 호출되는지 확인
*/
public function test_delete_menu_fires_hooks(): void
{
$menu = Menu::create([
'slug' => 'test-menu-hooks',
'name' => ['ko' => '훅 테스트', 'en' => 'Hook Test'],
'url' => '/hook-test',
'sort_order' => 1,
]);
$beforeCalled = false;
$afterCalled = false;
HookManager::addAction('core.menu.before_delete', function ($m) use (&$beforeCalled, $menu) {
$beforeCalled = true;
$this->assertEquals($menu->id, $m->id);
});
HookManager::addAction('core.menu.after_delete', function ($menuId) use (&$afterCalled, $menu) {
$afterCalled = true;
$this->assertEquals($menu->id, $menuId);
});
$this->menuService->deleteMenu($menu);
$this->assertTrue($beforeCalled);
$this->assertTrue($afterCalled);
}
}
@@ -0,0 +1,267 @@
<?php
namespace Tests\Unit\Services;
use App\Enums\ExtensionStatus;
use App\Models\Module;
use App\Services\ModuleService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* ModuleService::getAssetFilePath() 단위 테스트
*
* 모듈 에셋 파일 경로 조회 및 MIME 타입 결정을 테스트합니다.
*/
class ModuleServiceAssetTest extends TestCase
{
use RefreshDatabase;
private ModuleService $moduleService;
private string $testModulePath;
protected function setUp(): void
{
parent::setUp();
$this->moduleService = app(ModuleService::class);
$this->testModulePath = base_path('modules/test-module');
// 테스트용 디렉토리 생성
if (! file_exists($this->testModulePath.'/dist/js')) {
mkdir($this->testModulePath.'/dist/js', 0755, true);
}
}
protected function tearDown(): void
{
// 테스트용 파일 및 디렉토리 정리
if (file_exists($this->testModulePath)) {
$this->deleteDirectory($this->testModulePath);
}
parent::tearDown();
}
/**
* 디렉토리 재귀 삭제 헬퍼
*/
private function deleteDirectory(string $dir): bool
{
if (! file_exists($dir)) {
return true;
}
if (! is_dir($dir)) {
return unlink($dir);
}
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') {
continue;
}
if (! $this->deleteDirectory($dir.DIRECTORY_SEPARATOR.$item)) {
return false;
}
}
return rmdir($dir);
}
/**
* 존재하는 파일 경로 반환 성공 테스트
*/
public function test_returns_success_for_existing_file(): void
{
// Arrange
Module::factory()->create([
'identifier' => 'test-module',
'status' => ExtensionStatus::Active->value,
]);
$filePath = $this->testModulePath.'/dist/js/module.iife.js';
file_put_contents($filePath, 'console.log("test");');
// Act
$result = $this->moduleService->getAssetFilePath('test-module', 'dist/js/module.iife.js');
// Assert
$this->assertTrue($result['success']);
$this->assertEquals($filePath, $result['filePath']);
$this->assertEquals('application/javascript', $result['mimeType']);
}
/**
* JS 파일 MIME 타입 테스트
*/
public function test_returns_correct_mime_type_for_js(): void
{
// Arrange
Module::factory()->create([
'identifier' => 'test-module',
'status' => ExtensionStatus::Active->value,
]);
$filePath = $this->testModulePath.'/dist/js/app.js';
file_put_contents($filePath, 'console.log("test");');
// Act
$result = $this->moduleService->getAssetFilePath('test-module', 'dist/js/app.js');
// Assert
$this->assertTrue($result['success']);
$this->assertEquals('application/javascript', $result['mimeType']);
}
/**
* CSS 파일 MIME 타입 테스트
*/
public function test_returns_correct_mime_type_for_css(): void
{
// Arrange
Module::factory()->create([
'identifier' => 'test-module',
'status' => ExtensionStatus::Active->value,
]);
$cssPath = $this->testModulePath.'/dist/css';
if (! file_exists($cssPath)) {
mkdir($cssPath, 0755, true);
}
$filePath = $cssPath.'/module.css';
file_put_contents($filePath, '.module { color: blue; }');
// Act
$result = $this->moduleService->getAssetFilePath('test-module', 'dist/css/module.css');
// Assert
$this->assertTrue($result['success']);
$this->assertTrue(str_starts_with($result['mimeType'], 'text/css'));
}
/**
* JSON 파일 MIME 타입 테스트
*/
public function test_returns_correct_mime_type_for_json(): void
{
// Arrange
Module::factory()->create([
'identifier' => 'test-module',
'status' => ExtensionStatus::Active->value,
]);
$filePath = $this->testModulePath.'/dist/js/module.iife.js.map';
file_put_contents($filePath, '{"version":3,"sources":[]}');
// Act
$result = $this->moduleService->getAssetFilePath('test-module', 'dist/js/module.iife.js.map');
// Assert
$this->assertTrue($result['success']);
$this->assertEquals('application/json', $result['mimeType']);
}
/**
* 이미지 MIME 타입 테스트 (PNG)
*/
public function test_returns_correct_mime_type_for_images(): void
{
// Arrange
Module::factory()->create([
'identifier' => 'test-module',
'status' => ExtensionStatus::Active->value,
]);
$imagesPath = $this->testModulePath.'/dist/images';
if (! file_exists($imagesPath)) {
mkdir($imagesPath, 0755, true);
}
$filePath = $imagesPath.'/logo.png';
// 최소 PNG 헤더
file_put_contents($filePath, base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='));
// Act
$result = $this->moduleService->getAssetFilePath('test-module', 'dist/images/logo.png');
// Assert
$this->assertTrue($result['success']);
$this->assertEquals('image/png', $result['mimeType']);
}
/**
* 폰트 MIME 타입 테스트 (WOFF2)
*/
public function test_returns_correct_mime_type_for_fonts(): void
{
// Arrange
Module::factory()->create([
'identifier' => 'test-module',
'status' => ExtensionStatus::Active->value,
]);
$fontsPath = $this->testModulePath.'/dist/fonts';
if (! file_exists($fontsPath)) {
mkdir($fontsPath, 0755, true);
}
$filePath = $fontsPath.'/roboto.woff2';
file_put_contents($filePath, 'wOF2'); // WOFF2 magic bytes
// Act
$result = $this->moduleService->getAssetFilePath('test-module', 'dist/fonts/roboto.woff2');
// Assert
$this->assertTrue($result['success']);
$this->assertEquals('font/woff2', $result['mimeType']);
}
/**
* 존재하지 않는 모듈 오류 테스트
*/
public function test_returns_error_for_nonexistent_module(): void
{
// Act
$result = $this->moduleService->getAssetFilePath('nonexistent-module', 'dist/js/module.iife.js');
// Assert
$this->assertFalse($result['success']);
$this->assertEquals('module_not_found', $result['error']);
}
/**
* 비활성 모듈 오류 테스트
*/
public function test_returns_error_for_inactive_module(): void
{
// Arrange
Module::factory()->create([
'identifier' => 'inactive-module',
'status' => ExtensionStatus::Inactive->value,
]);
// Act
$result = $this->moduleService->getAssetFilePath('inactive-module', 'dist/js/module.iife.js');
// Assert
$this->assertFalse($result['success']);
$this->assertEquals('module_not_found', $result['error']);
}
/**
* 존재하지 않는 파일 오류 테스트
*/
public function test_returns_error_for_nonexistent_file(): void
{
// Arrange
Module::factory()->create([
'identifier' => 'test-module',
'status' => ExtensionStatus::Active->value,
]);
// Act
$result = $this->moduleService->getAssetFilePath('test-module', 'dist/js/nonexistent.js');
// Assert
$this->assertFalse($result['success']);
$this->assertEquals('file_not_found', $result['error']);
}
}
@@ -0,0 +1,801 @@
<?php
namespace Tests\Unit\Services;
use App\Contracts\Extension\ModuleInterface;
use App\Extension\ModuleManager;
use App\Extension\TemplateManager;
use App\Services\LayoutService;
use App\Services\ModuleSettingsService;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\File;
use Mockery;
use Tests\Helpers\MocksExtensions;
use Tests\TestCase;
/**
* ModuleSettingsService 단위 테스트
*
* 모듈 설정 조회, 저장, frontend_schema 기반 필터링 기능을 테스트합니다.
* 설정은 파일 기반으로 storage/app/modules/{identifier}/settings/setting.json에 저장됩니다.
*/
class ModuleSettingsServiceTest extends TestCase
{
use MocksExtensions;
private ModuleSettingsService $service;
private ModuleManager $moduleManager;
private TemplateManager $templateManager;
private LayoutService $layoutService;
private string $testSettingsDir;
protected function setUp(): void
{
parent::setUp();
$this->moduleManager = app(ModuleManager::class);
$this->templateManager = app(TemplateManager::class);
$this->layoutService = app(LayoutService::class);
$this->service = new ModuleSettingsService(
$this->moduleManager,
$this->templateManager,
$this->layoutService
);
// 테스트용 설정 디렉토리 경로
$this->testSettingsDir = storage_path('app/modules');
}
// ========================================================================
// get() 메서드 테스트
// ========================================================================
/**
* 존재하지 않는 모듈 조회 시 기본값 반환
*/
public function test_get_returns_default_when_module_not_found(): void
{
$result = $this->service->get('nonexistent-module');
$this->assertNull($result);
}
/**
* 존재하지 않는 모듈에 기본값 지정 시 해당 기본값 반환
*/
public function test_get_returns_custom_default_when_module_not_found(): void
{
$defaultValue = ['key' => 'default'];
$result = $this->service->get('nonexistent-module', null, $defaultValue);
$this->assertEquals($defaultValue, $result);
}
/**
* 모듈 전체 설정 조회 성공
*/
public function test_get_returns_all_settings_when_key_is_null(): void
{
// Mock module with config values
$mockModuleManager = Mockery::mock(ModuleManager::class);
$mockModule = $this->createMockModule([
'identifier' => 'test-settings-module',
'configValues' => [
'api_key' => 'default-api-key',
'enabled' => true,
'timeout' => 30,
],
'settingsSchema' => [],
]);
$mockModuleManager->shouldReceive('getModule')
->with('test-settings-module')
->andReturn($mockModule);
$service = new ModuleSettingsService(
$mockModuleManager,
$this->templateManager,
$this->layoutService
);
$result = $service->get('test-settings-module');
$this->assertIsArray($result);
$this->assertArrayHasKey('api_key', $result);
$this->assertArrayHasKey('enabled', $result);
$this->assertArrayHasKey('timeout', $result);
}
/**
* 특정 키의 설정값 조회 성공
*/
public function test_get_returns_specific_key_value(): void
{
$mockModuleManager = Mockery::mock(ModuleManager::class);
$mockModule = $this->createMockModule([
'identifier' => 'test-key-module',
'configValues' => [
'api_key' => 'my-secret-key',
'timeout' => 60,
],
'settingsSchema' => [],
]);
$mockModuleManager->shouldReceive('getModule')
->with('test-key-module')
->andReturn($mockModule);
$service = new ModuleSettingsService(
$mockModuleManager,
$this->templateManager,
$this->layoutService
);
$result = $service->get('test-key-module', 'timeout');
$this->assertEquals(60, $result);
}
/**
* 존재하지 않는 키 조회 시 기본값 반환
*/
public function test_get_returns_default_for_missing_key(): void
{
$mockModuleManager = Mockery::mock(ModuleManager::class);
$mockModule = $this->createMockModule([
'identifier' => 'test-missing-key-module',
'configValues' => ['existing_key' => 'value'],
'settingsSchema' => [],
]);
$mockModuleManager->shouldReceive('getModule')
->with('test-missing-key-module')
->andReturn($mockModule);
$service = new ModuleSettingsService(
$mockModuleManager,
$this->templateManager,
$this->layoutService
);
$result = $service->get('test-missing-key-module', 'nonexistent_key', 'default_value');
$this->assertEquals('default_value', $result);
}
/**
* 중첩된 키 값 조회 (dot notation)
*/
public function test_get_returns_nested_key_value(): void
{
$mockModuleManager = Mockery::mock(ModuleManager::class);
$mockModule = $this->createMockModule([
'identifier' => 'test-nested-module',
'configValues' => [
'database' => [
'host' => 'localhost',
'port' => 3306,
],
],
'settingsSchema' => [],
]);
$mockModuleManager->shouldReceive('getModule')
->with('test-nested-module')
->andReturn($mockModule);
$service = new ModuleSettingsService(
$mockModuleManager,
$this->templateManager,
$this->layoutService
);
$host = $service->get('test-nested-module', 'database.host');
$port = $service->get('test-nested-module', 'database.port');
$this->assertEquals('localhost', $host);
$this->assertEquals(3306, $port);
}
// ========================================================================
// save() 메서드 테스트
// ========================================================================
/**
* 존재하지 않는 모듈 저장 시 false 반환
*/
public function test_save_returns_false_when_module_not_found(): void
{
$result = $this->service->save('nonexistent-module', ['key' => 'value']);
$this->assertFalse($result);
}
/**
* 모듈 설정 저장 성공
*/
public function test_save_stores_settings_successfully(): void
{
$identifier = 'test-save-module-'.uniqid();
$mockModuleManager = Mockery::mock(ModuleManager::class);
$mockModule = $this->createMockModule([
'identifier' => $identifier,
'configValues' => [],
'settingsSchema' => [],
'storage' => [
'exists' => false,
'put' => true,
],
]);
$mockModuleManager->shouldReceive('getModule')
->with($identifier)
->andReturn($mockModule);
$service = new ModuleSettingsService(
$mockModuleManager,
$this->templateManager,
$this->layoutService
);
$result = $service->save($identifier, [
'api_key' => 'new-api-key',
'enabled' => true,
]);
$this->assertTrue($result);
}
/**
* 기존 설정과 병합되는지 확인
*/
public function test_save_merges_with_existing_settings(): void
{
$identifier = 'test-merge-module-'.uniqid();
// 기존 설정 파일 내용
$existingContent = json_encode([
'existing_key' => 'existing_value',
'to_update' => 'old_value',
]);
$mockModuleManager = Mockery::mock(ModuleManager::class);
$mockModule = $this->createMockModule([
'identifier' => $identifier,
'configValues' => [],
'settingsSchema' => [],
'storage' => [
'exists' => true,
'get' => $existingContent,
'put' => true,
],
]);
$mockModuleManager->shouldReceive('getModule')
->with($identifier)
->andReturn($mockModule);
$service = new ModuleSettingsService(
$mockModuleManager,
$this->templateManager,
$this->layoutService
);
$result = $service->save($identifier, [
'to_update' => 'new_value',
'new_key' => 'new_value',
]);
$this->assertTrue($result);
}
// ========================================================================
// 암호화/복호화 테스트
// ========================================================================
/**
* 민감한 필드가 암호화되어 저장되는지 확인
*/
public function test_save_encrypts_sensitive_fields(): void
{
$identifier = 'test-encrypt-module-'.uniqid();
// Mock module with sensitive field schema
$mockModuleManager = Mockery::mock(ModuleManager::class);
$mockModule = $this->createMockModule([
'identifier' => $identifier,
'configValues' => [],
'settingsSchema' => [
'api_key' => [
'type' => 'string',
'sensitive' => true,
],
'public_key' => [
'type' => 'string',
'sensitive' => false,
],
],
'storage' => [
'exists' => false,
'put' => true,
],
]);
$mockModuleManager->shouldReceive('getModule')
->with($identifier)
->andReturn($mockModule);
$service = new ModuleSettingsService(
$mockModuleManager,
$this->templateManager,
$this->layoutService
);
$result = $service->save($identifier, [
'api_key' => 'secret-api-key',
'public_key' => 'public-value',
]);
$this->assertTrue($result);
// 암호화 로직은 내부적으로 동작하며, put이 호출되었으므로 성공으로 간주
}
/**
* 민감한 필드가 복호화되어 조회되는지 확인
*/
public function test_get_decrypts_sensitive_fields(): void
{
$identifier = 'test-decrypt-module-'.uniqid();
// 암호화된 값으로 설정 파일 내용 생성
$encryptedValue = Crypt::encryptString('decrypted-secret');
$fileContent = json_encode([
'secret_key' => $encryptedValue,
'normal_key' => 'normal-value',
]);
// Mock module with sensitive field schema and Storage
$mockModuleManager = Mockery::mock(ModuleManager::class);
$mockModule = $this->createMockModule([
'identifier' => $identifier,
'configValues' => [],
'settingsSchema' => [
'secret_key' => [
'type' => 'string',
'sensitive' => true,
],
'normal_key' => [
'type' => 'string',
'sensitive' => false,
],
],
'storage' => [
'exists' => true,
'get' => $fileContent,
],
]);
$mockModuleManager->shouldReceive('getModule')
->with($identifier)
->andReturn($mockModule);
$service = new ModuleSettingsService(
$mockModuleManager,
$this->templateManager,
$this->layoutService
);
$result = $service->get($identifier);
// 민감한 필드는 복호화되어 반환됨
$this->assertEquals('decrypted-secret', $result['secret_key']);
// 비민감 필드는 그대로 반환됨
$this->assertEquals('normal-value', $result['normal_key']);
}
// ========================================================================
// getAllActiveSettings() 및 frontend_schema 필터링 테스트
// ========================================================================
/**
* frontend_schema가 없으면 빈 배열 반환
*/
public function test_get_all_active_settings_returns_empty_when_no_frontend_schema(): void
{
$identifier = 'test-no-schema-module-'.uniqid();
// defaults.json 없이 모듈 생성
$mockModuleManager = Mockery::mock(ModuleManager::class);
$mockModule = $this->createMockModule([
'identifier' => $identifier,
'hasSettings' => true,
'configValues' => ['key' => 'value'],
'settingsSchema' => [],
'settingsDefaultsPath' => null,
'storage' => [
'exists' => false,
],
]);
// getSettingsDefaultsPath()를 명시적으로 추가 (디버깅용)
$mockModule->shouldReceive('getSettingsDefaultsPath')->andReturn(null)->zeroOrMoreTimes();
$mockModuleManager->shouldReceive('getActiveModules')
->andReturn([$mockModule]);
$mockModuleManager->shouldReceive('getModule')
->with($identifier)
->andReturn($mockModule)
->zeroOrMoreTimes();
$service = new ModuleSettingsService(
$mockModuleManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getAllActiveSettings();
// frontend_schema가 없으므로 결과에 포함되지 않음
$this->assertArrayNotHasKey($identifier, $result);
}
/**
* frontend_schema.expose: true인 카테고리만 포함
*/
public function test_get_all_active_settings_filters_by_category_expose(): void
{
$identifier = 'test-category-expose-module-'.uniqid();
$modulePath = storage_path("app/test-modules/{$identifier}");
$defaultsPath = $modulePath.'/config/settings/defaults.json';
// defaults.json 생성
File::makeDirectory(dirname($defaultsPath), 0755, true);
File::put($defaultsPath, json_encode([
'defaults' => [
'public_category' => [
'field1' => 'value1',
'field2' => 'value2',
],
'private_category' => [
'secret' => 'secret-value',
],
],
'frontend_schema' => [
'public_category' => [
'expose' => true,
],
'private_category' => [
'expose' => false,
],
],
]));
$mockModuleManager = Mockery::mock(ModuleManager::class);
$mockModule = $this->createMockModule([
'identifier' => $identifier,
'hasSettings' => true,
'configValues' => [
'public_category' => [
'field1' => 'value1',
'field2' => 'value2',
],
'private_category' => [
'secret' => 'secret-value',
],
],
'settingsSchema' => [],
'settingsDefaultsPath' => $defaultsPath,
'storage' => [
'exists' => false,
],
]);
$mockModuleManager->shouldReceive('getActiveModules')
->andReturn([$mockModule]);
$mockModuleManager->shouldReceive('getModule')
->with($identifier)
->andReturn($mockModule)
->zeroOrMoreTimes();
$service = new ModuleSettingsService(
$mockModuleManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getAllActiveSettings();
// expose: true인 카테고리만 포함
$this->assertArrayHasKey($identifier, $result);
$this->assertArrayHasKey('public_category', $result[$identifier]);
$this->assertArrayNotHasKey('private_category', $result[$identifier]);
// 정리
File::deleteDirectory($modulePath);
}
/**
* frontend_schema.fields.expose: true인 필드만 포함
*/
public function test_get_all_active_settings_filters_by_field_expose(): void
{
$identifier = 'test-field-expose-module-'.uniqid();
$modulePath = storage_path("app/test-modules/{$identifier}");
$defaultsPath = $modulePath.'/config/settings/defaults.json';
// defaults.json 생성
File::makeDirectory(dirname($defaultsPath), 0755, true);
File::put($defaultsPath, json_encode([
'defaults' => [
'settings' => [
'public_field' => 'public-value',
'private_field' => 'private-value',
'another_public' => 'another-value',
],
],
'frontend_schema' => [
'settings' => [
'expose' => true,
'fields' => [
'public_field' => ['expose' => true],
'private_field' => ['expose' => false],
'another_public' => ['expose' => true],
],
],
],
]));
$mockModuleManager = Mockery::mock(ModuleManager::class);
$mockModule = $this->createMockModule([
'identifier' => $identifier,
'hasSettings' => true,
'configValues' => [
'settings' => [
'public_field' => 'public-value',
'private_field' => 'private-value',
'another_public' => 'another-value',
],
],
'settingsSchema' => [],
'settingsDefaultsPath' => $defaultsPath,
'storage' => [
'exists' => false,
],
]);
$mockModuleManager->shouldReceive('getActiveModules')
->andReturn([$mockModule]);
$mockModuleManager->shouldReceive('getModule')
->with($identifier)
->andReturn($mockModule)
->zeroOrMoreTimes();
$service = new ModuleSettingsService(
$mockModuleManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getAllActiveSettings();
// expose: true인 필드만 포함
$this->assertArrayHasKey($identifier, $result);
$this->assertArrayHasKey('settings', $result[$identifier]);
$this->assertArrayHasKey('public_field', $result[$identifier]['settings']);
$this->assertArrayHasKey('another_public', $result[$identifier]['settings']);
$this->assertArrayNotHasKey('private_field', $result[$identifier]['settings']);
// 정리
File::deleteDirectory($modulePath);
}
/**
* fields 정의가 없으면 카테고리 전체 포함
*/
public function test_get_all_active_settings_includes_all_fields_when_no_fields_defined(): void
{
$identifier = 'test-no-fields-module-'.uniqid();
$modulePath = storage_path("app/test-modules/{$identifier}");
$defaultsPath = $modulePath.'/config/settings/defaults.json';
// defaults.json 생성 (fields 정의 없음)
File::makeDirectory(dirname($defaultsPath), 0755, true);
File::put($defaultsPath, json_encode([
'defaults' => [
'basic' => [
'field1' => 'value1',
'field2' => 'value2',
'field3' => 'value3',
],
],
'frontend_schema' => [
'basic' => [
'expose' => true,
// fields 정의 없음
],
],
]));
$mockModuleManager = Mockery::mock(ModuleManager::class);
$mockModule = $this->createMockModule([
'identifier' => $identifier,
'hasSettings' => true,
'configValues' => [
'basic' => [
'field1' => 'value1',
'field2' => 'value2',
'field3' => 'value3',
],
],
'settingsSchema' => [],
'settingsDefaultsPath' => $defaultsPath,
'storage' => [
'exists' => false,
],
]);
$mockModuleManager->shouldReceive('getActiveModules')
->andReturn([$mockModule]);
$mockModuleManager->shouldReceive('getModule')
->with($identifier)
->andReturn($mockModule)
->zeroOrMoreTimes();
$service = new ModuleSettingsService(
$mockModuleManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getAllActiveSettings();
// fields 정의가 없으면 카테고리 전체 포함
$this->assertArrayHasKey($identifier, $result);
$this->assertArrayHasKey('basic', $result[$identifier]);
$this->assertEquals('value1', $result[$identifier]['basic']['field1']);
$this->assertEquals('value2', $result[$identifier]['basic']['field2']);
$this->assertEquals('value3', $result[$identifier]['basic']['field3']);
// 정리
File::deleteDirectory($modulePath);
}
/**
* hasSettings가 false인 모듈은 제외
*/
public function test_get_all_active_settings_skips_modules_without_settings(): void
{
$mockModuleManager = Mockery::mock(ModuleManager::class);
$mockModule = $this->createMockModule([
'identifier' => 'no-settings-module',
'hasSettings' => false,
]);
$mockModuleManager->shouldReceive('getActiveModules')
->andReturn([$mockModule]);
$service = new ModuleSettingsService(
$mockModuleManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getAllActiveSettings();
$this->assertArrayNotHasKey('no-settings-module', $result);
}
// ========================================================================
// reset() 및 캐시 테스트
// ========================================================================
/**
* reset() 메서드가 설정 파일을 삭제하는지 확인
*/
public function test_reset_deletes_settings_file(): void
{
$identifier = 'test-reset-module-'.uniqid();
$mockModuleManager = Mockery::mock(ModuleManager::class);
$mockModule = $this->createMockModule([
'identifier' => $identifier,
'storage' => [
'exists' => true,
'delete' => true,
],
]);
$mockModuleManager->shouldReceive('getModule')
->with($identifier)
->andReturn($mockModule);
$service = new ModuleSettingsService(
$mockModuleManager,
$this->templateManager,
$this->layoutService
);
$result = $service->reset($identifier);
$this->assertTrue($result);
}
/**
* clearCache() 메서드가 캐시를 초기화하는지 확인
*/
public function test_clear_cache_clears_settings_cache(): void
{
$identifier = 'test-cache-module';
$mockModuleManager = Mockery::mock(ModuleManager::class);
$mockModule = $this->createMockModule([
'identifier' => $identifier,
'configValues' => ['initial' => 'value'],
'settingsSchema' => [],
]);
$mockModuleManager->shouldReceive('getModule')
->with($identifier)
->andReturn($mockModule);
$service = new ModuleSettingsService(
$mockModuleManager,
$this->templateManager,
$this->layoutService
);
// 첫 번째 조회 (캐시에 저장됨)
$service->get($identifier);
// 캐시 초기화
$service->clearCache($identifier);
// 캐시가 초기화되었으므로 다시 getModule이 호출되어야 함
// (이 테스트는 내부 동작을 확인하는 것이 어려우므로 예외 없이 실행되는지만 확인)
$this->assertTrue(true);
}
/**
* deleteSettingsDirectory() 메서드가 디렉토리를 삭제하는지 확인
*/
public function test_delete_settings_directory_removes_directory(): void
{
$identifier = 'test-delete-dir-module-'.uniqid();
$mockModuleManager = Mockery::mock(ModuleManager::class);
$mockModule = $this->createMockModule([
'identifier' => $identifier,
'storage' => [
'getDisk' => 'local',
'deleteDirectory' => true,
],
]);
$mockModuleManager->shouldReceive('getModule')
->with($identifier)
->andReturn($mockModule);
$service = new ModuleSettingsService(
$mockModuleManager,
$this->templateManager,
$this->layoutService
);
$result = $service->deleteSettingsDirectory($identifier);
$this->assertTrue($result);
}
protected function tearDown(): void
{
Mockery::close();
parent::tearDown();
}
}
@@ -0,0 +1,481 @@
<?php
namespace Tests\Unit\Services;
use App\Enums\ExtensionOwnerType;
use App\Enums\PermissionType;
use App\Models\Permission;
use App\Services\PermissionService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* PermissionService 테스트
*
* PermissionService의 타입별 그룹화 기능을 검증합니다.
*/
class PermissionServiceTest extends TestCase
{
use RefreshDatabase;
private PermissionService $permissionService;
protected function setUp(): void
{
parent::setUp();
$this->permissionService = app(PermissionService::class);
}
// ========================================================================
// getPermissionTree() 타입별 그룹화 테스트
// ========================================================================
/**
* getPermissionTree()가 올바른 구조를 반환하는지 확인
*/
public function test_get_permission_tree_returns_correct_structure(): void
{
$result = $this->permissionService->getPermissionTree();
// 필수 키 확인
$this->assertArrayHasKey('permissions', $result);
$this->assertArrayHasKey('types', $result);
$this->assertArrayHasKey('default_type', $result);
}
/**
* types 배열에 admin과 user가 포함되어 있는지 확인
*/
public function test_get_permission_tree_includes_all_permission_types(): void
{
$result = $this->permissionService->getPermissionTree();
$this->assertContains('admin', $result['types']);
$this->assertContains('user', $result['types']);
}
/**
* default_type이 admin인지 확인
*/
public function test_get_permission_tree_default_type_is_admin(): void
{
$result = $this->permissionService->getPermissionTree();
$this->assertEquals('admin', $result['default_type']);
}
/**
* permissions 배열이 타입별로 그룹화되어 있는지 확인
*/
public function test_get_permission_tree_groups_by_type(): void
{
$result = $this->permissionService->getPermissionTree();
// 각 타입별 그룹 존재 확인
$this->assertArrayHasKey('admin', $result['permissions']);
$this->assertArrayHasKey('user', $result['permissions']);
// 각 그룹에 label과 permissions 키 존재 확인
$this->assertArrayHasKey('label', $result['permissions']['admin']);
$this->assertArrayHasKey('permissions', $result['permissions']['admin']);
$this->assertArrayHasKey('label', $result['permissions']['user']);
$this->assertArrayHasKey('permissions', $result['permissions']['user']);
}
/**
* 각 타입 그룹에 icon 필드가 포함되어 있는지 확인
*/
public function test_get_permission_tree_includes_icon_for_each_type(): void
{
$result = $this->permissionService->getPermissionTree();
$this->assertArrayHasKey('icon', $result['permissions']['admin']);
$this->assertArrayHasKey('icon', $result['permissions']['user']);
$this->assertEquals('cog', $result['permissions']['admin']['icon']);
$this->assertEquals('user', $result['permissions']['user']['icon']);
}
/**
* admin 타입 권한이 admin 그룹에 포함되는지 확인
*/
public function test_admin_permissions_are_grouped_under_admin(): void
{
// admin 타입 루트 권한 생성
Permission::create([
'identifier' => 'test-module',
'name' => ['ko' => '테스트 모듈', 'en' => 'Test Module'],
'type' => PermissionType::Admin,
'parent_id' => null,
]);
$result = $this->permissionService->getPermissionTree();
// admin 그룹에 권한이 있는지 확인
$adminPermissions = $result['permissions']['admin']['permissions'];
$identifiers = array_column($adminPermissions, 'identifier');
$this->assertContains('test-module', $identifiers);
}
/**
* user 타입 권한이 user 그룹에 포함되는지 확인
*/
public function test_user_permissions_are_grouped_under_user(): void
{
// user 타입 루트 권한 생성
Permission::create([
'identifier' => 'user-module',
'name' => ['ko' => '사용자 모듈', 'en' => 'User Module'],
'type' => PermissionType::User,
'parent_id' => null,
]);
$result = $this->permissionService->getPermissionTree();
// user 그룹에 권한이 있는지 확인
$userPermissions = $result['permissions']['user']['permissions'];
$identifiers = array_column($userPermissions, 'identifier');
$this->assertContains('user-module', $identifiers);
}
/**
* 권한 노드에 필수 필드가 포함되어 있는지 확인
*/
public function test_permission_node_has_required_fields(): void
{
// 권한 생성
Permission::create([
'identifier' => 'test-node',
'name' => ['ko' => '테스트 노드', 'en' => 'Test Node'],
'description' => ['ko' => '테스트 설명', 'en' => 'Test Description'],
'type' => PermissionType::Admin,
'parent_id' => null,
]);
$result = $this->permissionService->getPermissionTree();
$adminPermissions = $result['permissions']['admin']['permissions'];
// test-node 찾기
$testNode = collect($adminPermissions)->firstWhere('identifier', 'test-node');
$this->assertNotNull($testNode);
$this->assertArrayHasKey('id', $testNode);
$this->assertArrayHasKey('identifier', $testNode);
$this->assertArrayHasKey('name', $testNode);
$this->assertArrayHasKey('name_raw', $testNode);
$this->assertArrayHasKey('description', $testNode);
$this->assertArrayHasKey('description_raw', $testNode);
$this->assertArrayHasKey('extension_type', $testNode);
$this->assertArrayHasKey('type', $testNode);
$this->assertArrayHasKey('is_assignable', $testNode);
$this->assertArrayHasKey('children', $testNode);
$this->assertArrayHasKey('leaf_count', $testNode);
}
/**
* 계층 구조가 올바르게 포함되는지 확인
*/
public function test_permission_tree_includes_children(): void
{
// 부모 권한 생성
$parent = Permission::create([
'identifier' => 'parent-module',
'name' => ['ko' => '부모 모듈', 'en' => 'Parent Module'],
'type' => PermissionType::Admin,
'parent_id' => null,
]);
// 자식 권한 생성
Permission::create([
'identifier' => 'parent-module.child',
'name' => ['ko' => '자식 권한', 'en' => 'Child Permission'],
'type' => PermissionType::Admin,
'parent_id' => $parent->id,
]);
$result = $this->permissionService->getPermissionTree();
$adminPermissions = $result['permissions']['admin']['permissions'];
// 부모 노드 찾기
$parentNode = collect($adminPermissions)->firstWhere('identifier', 'parent-module');
$this->assertNotNull($parentNode);
$this->assertNotEmpty($parentNode['children']);
$this->assertEquals('parent-module.child', $parentNode['children'][0]['identifier']);
}
/**
* 리프 노드 개수가 올바르게 계산되는지 확인
*/
public function test_leaf_count_is_calculated_correctly(): void
{
// 부모 권한 생성
$parent = Permission::create([
'identifier' => 'count-test',
'name' => ['ko' => '카운트 테스트', 'en' => 'Count Test'],
'type' => PermissionType::Admin,
'parent_id' => null,
]);
// 자식 권한 3개 생성 (리프 노드)
for ($i = 1; $i <= 3; $i++) {
Permission::create([
'identifier' => "count-test.child{$i}",
'name' => ['ko' => "자식 {$i}", 'en' => "Child {$i}"],
'type' => PermissionType::Admin,
'parent_id' => $parent->id,
]);
}
$result = $this->permissionService->getPermissionTree();
$adminPermissions = $result['permissions']['admin']['permissions'];
// 부모 노드 찾기
$parentNode = collect($adminPermissions)->firstWhere('identifier', 'count-test');
$this->assertEquals(3, $parentNode['leaf_count']);
}
/**
* 코어 권한이 항상 먼저 정렬되는지 확인
*/
public function test_core_permissions_are_sorted_first(): void
{
// 비코어 모듈 권한 먼저 생성
Permission::create([
'identifier' => 'zzz-module',
'name' => ['ko' => 'ZZZ 모듈', 'en' => 'ZZZ Module'],
'type' => PermissionType::Admin,
'parent_id' => null,
'order' => 1,
]);
// 코어 모듈 권한 생성
Permission::create([
'identifier' => 'core',
'name' => ['ko' => '코어', 'en' => 'Core'],
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => PermissionType::Admin,
'parent_id' => null,
'order' => 1,
]);
$result = $this->permissionService->getPermissionTree();
$adminPermissions = $result['permissions']['admin']['permissions'];
// 첫 번째 권한이 코어인지 확인
$this->assertEquals('core', $adminPermissions[0]['identifier']);
}
/**
* 빈 권한 목록에서도 올바른 구조를 반환하는지 확인
*/
public function test_get_permission_tree_with_no_permissions(): void
{
// 권한 없이 호출
$result = $this->permissionService->getPermissionTree();
$this->assertArrayHasKey('permissions', $result);
$this->assertArrayHasKey('types', $result);
$this->assertArrayHasKey('default_type', $result);
// 빈 permissions 배열 확인
$this->assertEmpty($result['permissions']['admin']['permissions']);
$this->assertEmpty($result['permissions']['user']['permissions']);
}
/**
* is_assignable이 자식이 없는 노드에서 true인지 확인
*/
public function test_is_assignable_is_true_for_leaf_nodes(): void
{
// 리프 노드 (자식 없음)
Permission::create([
'identifier' => 'leaf-permission',
'name' => ['ko' => '리프 권한', 'en' => 'Leaf Permission'],
'type' => PermissionType::Admin,
'parent_id' => null,
]);
$result = $this->permissionService->getPermissionTree();
$adminPermissions = $result['permissions']['admin']['permissions'];
$leafNode = collect($adminPermissions)->firstWhere('identifier', 'leaf-permission');
$this->assertTrue($leafNode['is_assignable']);
}
/**
* 부모가 admin 타입이고 자식이 user 타입일 때 user 그룹에 올바르게 표시되는지 확인
*/
public function test_mixed_type_tree_user_children_appear_under_user_group(): void
{
// admin 타입 루트 생성
$root = Permission::create([
'identifier' => 'test-module',
'name' => ['ko' => '테스트 모듈', 'en' => 'Test Module'],
'type' => PermissionType::Admin,
'parent_id' => null,
]);
// admin 타입 중간 노드 생성
$middle = Permission::create([
'identifier' => 'test-module.board',
'name' => ['ko' => '게시판', 'en' => 'Board'],
'type' => PermissionType::Admin,
'parent_id' => $root->id,
]);
// user 타입 리프 노드 생성
Permission::create([
'identifier' => 'test-module.board.read',
'name' => ['ko' => '읽기', 'en' => 'Read'],
'type' => PermissionType::User,
'parent_id' => $middle->id,
]);
Permission::create([
'identifier' => 'test-module.board.write',
'name' => ['ko' => '쓰기', 'en' => 'Write'],
'type' => PermissionType::User,
'parent_id' => $middle->id,
]);
$result = $this->permissionService->getPermissionTree();
// user 그룹에 부모 구조가 포함되어야 함
$userPermissions = $result['permissions']['user']['permissions'];
$this->assertNotEmpty($userPermissions, 'user 그룹에 권한이 있어야 합니다');
// 루트 노드가 user 그룹에 포함
$rootNode = collect($userPermissions)->firstWhere('identifier', 'test-module');
$this->assertNotNull($rootNode, 'user 그룹에 루트 노드가 있어야 합니다');
// 중간 노드 확인
$this->assertNotEmpty($rootNode['children']);
$middleNode = collect($rootNode['children'])->firstWhere('identifier', 'test-module.board');
$this->assertNotNull($middleNode);
// user 타입 리프 노드 확인
$leafIdentifiers = array_column($middleNode['children'], 'identifier');
$this->assertContains('test-module.board.read', $leafIdentifiers);
$this->assertContains('test-module.board.write', $leafIdentifiers);
// leaf_count가 user 타입 리프만 카운트
$this->assertEquals(2, $rootNode['leaf_count']);
}
/**
* 혼합 타입 트리에서 admin 그룹에 user 타입 리프가 포함되지 않는지 확인
*/
public function test_mixed_type_tree_admin_group_excludes_user_leaves(): void
{
// admin 타입 루트 생성
$root = Permission::create([
'identifier' => 'mixed-module',
'name' => ['ko' => '혼합 모듈', 'en' => 'Mixed Module'],
'type' => PermissionType::Admin,
'parent_id' => null,
]);
// admin 타입 리프 생성
Permission::create([
'identifier' => 'mixed-module.admin-leaf',
'name' => ['ko' => '관리자 리프', 'en' => 'Admin Leaf'],
'type' => PermissionType::Admin,
'parent_id' => $root->id,
]);
// user 타입 리프 생성
Permission::create([
'identifier' => 'mixed-module.user-leaf',
'name' => ['ko' => '사용자 리프', 'en' => 'User Leaf'],
'type' => PermissionType::User,
'parent_id' => $root->id,
]);
$result = $this->permissionService->getPermissionTree();
// admin 그룹: admin 리프만 포함
$adminPermissions = $result['permissions']['admin']['permissions'];
$adminRoot = collect($adminPermissions)->firstWhere('identifier', 'mixed-module');
$this->assertNotNull($adminRoot);
$adminLeafIds = array_column($adminRoot['children'], 'identifier');
$this->assertContains('mixed-module.admin-leaf', $adminLeafIds);
$this->assertNotContains('mixed-module.user-leaf', $adminLeafIds);
$this->assertEquals(1, $adminRoot['leaf_count']);
// user 그룹: user 리프만 포함
$userPermissions = $result['permissions']['user']['permissions'];
$userRoot = collect($userPermissions)->firstWhere('identifier', 'mixed-module');
$this->assertNotNull($userRoot);
$userLeafIds = array_column($userRoot['children'], 'identifier');
$this->assertContains('mixed-module.user-leaf', $userLeafIds);
$this->assertNotContains('mixed-module.admin-leaf', $userLeafIds);
$this->assertEquals(1, $userRoot['leaf_count']);
}
/**
* 특정 타입의 리프가 없는 브랜치는 해당 타입 그룹에서 제외되는지 확인
*/
public function test_branch_without_matching_type_is_excluded(): void
{
// admin 전용 브랜치
$adminRoot = Permission::create([
'identifier' => 'admin-only',
'name' => ['ko' => '관리자 전용', 'en' => 'Admin Only'],
'type' => PermissionType::Admin,
'parent_id' => null,
]);
Permission::create([
'identifier' => 'admin-only.manage',
'name' => ['ko' => '관리', 'en' => 'Manage'],
'type' => PermissionType::Admin,
'parent_id' => $adminRoot->id,
]);
$result = $this->permissionService->getPermissionTree();
// user 그룹에 이 브랜치가 없어야 함
$userPermissions = $result['permissions']['user']['permissions'];
$userRoot = collect($userPermissions)->firstWhere('identifier', 'admin-only');
$this->assertNull($userRoot, 'admin 전용 브랜치는 user 그룹에 없어야 합니다');
// admin 그룹에는 존재
$adminPermissions = $result['permissions']['admin']['permissions'];
$adminRootNode = collect($adminPermissions)->firstWhere('identifier', 'admin-only');
$this->assertNotNull($adminRootNode);
}
/**
* is_assignable이 자식이 있는 노드에서 false인지 확인
*/
public function test_is_assignable_is_false_for_parent_nodes(): void
{
// 부모 노드
$parent = Permission::create([
'identifier' => 'parent-permission',
'name' => ['ko' => '부모 권한', 'en' => 'Parent Permission'],
'type' => PermissionType::Admin,
'parent_id' => null,
]);
// 자식 노드
Permission::create([
'identifier' => 'parent-permission.child',
'name' => ['ko' => '자식 권한', 'en' => 'Child Permission'],
'type' => PermissionType::Admin,
'parent_id' => $parent->id,
]);
$result = $this->permissionService->getPermissionTree();
$adminPermissions = $result['permissions']['admin']['permissions'];
$parentNode = collect($adminPermissions)->firstWhere('identifier', 'parent-permission');
$this->assertFalse($parentNode['is_assignable']);
}
}
@@ -0,0 +1,192 @@
<?php
namespace Tests\Unit\Services;
use App\Enums\ExtensionStatus;
use App\Models\Plugin;
use App\Services\PluginService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* PluginService::getAssetFilePath() 단위 테스트
*
* 플러그인 에셋 파일 경로 조회 및 MIME 타입 결정을 테스트합니다.
*/
class PluginServiceAssetTest extends TestCase
{
use RefreshDatabase;
private PluginService $pluginService;
private string $testPluginPath;
protected function setUp(): void
{
parent::setUp();
$this->pluginService = app(PluginService::class);
$this->testPluginPath = base_path('plugins/test-plugin');
// 테스트용 디렉토리 생성
if (! file_exists($this->testPluginPath.'/dist/js')) {
mkdir($this->testPluginPath.'/dist/js', 0755, true);
}
}
protected function tearDown(): void
{
// 테스트용 파일 및 디렉토리 정리
if (file_exists($this->testPluginPath)) {
$this->deleteDirectory($this->testPluginPath);
}
parent::tearDown();
}
/**
* 디렉토리 재귀 삭제 헬퍼
*/
private function deleteDirectory(string $dir): bool
{
if (! file_exists($dir)) {
return true;
}
if (! is_dir($dir)) {
return unlink($dir);
}
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') {
continue;
}
if (! $this->deleteDirectory($dir.DIRECTORY_SEPARATOR.$item)) {
return false;
}
}
return rmdir($dir);
}
/**
* 존재하는 파일 경로 반환 성공 테스트
*/
public function test_returns_success_for_existing_file(): void
{
// Arrange
Plugin::factory()->create([
'identifier' => 'test-plugin',
'status' => ExtensionStatus::Active->value,
]);
$filePath = $this->testPluginPath.'/dist/js/plugin.iife.js';
file_put_contents($filePath, 'console.log("test plugin");');
// Act
$result = $this->pluginService->getAssetFilePath('test-plugin', 'dist/js/plugin.iife.js');
// Assert
$this->assertTrue($result['success']);
$this->assertEquals($filePath, $result['filePath']);
$this->assertEquals('application/javascript', $result['mimeType']);
}
/**
* JS 파일 MIME 타입 테스트
*/
public function test_returns_correct_mime_type_for_js(): void
{
// Arrange
Plugin::factory()->create([
'identifier' => 'test-plugin',
'status' => ExtensionStatus::Active->value,
]);
$filePath = $this->testPluginPath.'/dist/js/app.js';
file_put_contents($filePath, 'console.log("test");');
// Act
$result = $this->pluginService->getAssetFilePath('test-plugin', 'dist/js/app.js');
// Assert
$this->assertTrue($result['success']);
$this->assertEquals('application/javascript', $result['mimeType']);
}
/**
* CSS 파일 MIME 타입 테스트
*/
public function test_returns_correct_mime_type_for_css(): void
{
// Arrange
Plugin::factory()->create([
'identifier' => 'test-plugin',
'status' => ExtensionStatus::Active->value,
]);
$cssPath = $this->testPluginPath.'/dist/css';
if (! file_exists($cssPath)) {
mkdir($cssPath, 0755, true);
}
$filePath = $cssPath.'/plugin.css';
file_put_contents($filePath, '.plugin { color: green; }');
// Act
$result = $this->pluginService->getAssetFilePath('test-plugin', 'dist/css/plugin.css');
// Assert
$this->assertTrue($result['success']);
$this->assertTrue(str_starts_with($result['mimeType'], 'text/css'));
}
/**
* 존재하지 않는 플러그인 오류 테스트
*/
public function test_returns_error_for_nonexistent_plugin(): void
{
// Act
$result = $this->pluginService->getAssetFilePath('nonexistent-plugin', 'dist/js/plugin.iife.js');
// Assert
$this->assertFalse($result['success']);
$this->assertEquals('plugin_not_found', $result['error']);
}
/**
* 비활성 플러그인 오류 테스트
*/
public function test_returns_error_for_inactive_plugin(): void
{
// Arrange
Plugin::factory()->create([
'identifier' => 'inactive-plugin',
'status' => ExtensionStatus::Inactive->value,
]);
// Act
$result = $this->pluginService->getAssetFilePath('inactive-plugin', 'dist/js/plugin.iife.js');
// Assert
$this->assertFalse($result['success']);
$this->assertEquals('plugin_not_found', $result['error']);
}
/**
* 존재하지 않는 파일 오류 테스트
*/
public function test_returns_error_for_nonexistent_file(): void
{
// Arrange
Plugin::factory()->create([
'identifier' => 'test-plugin',
'status' => ExtensionStatus::Active->value,
]);
// Act
$result = $this->pluginService->getAssetFilePath('test-plugin', 'dist/js/nonexistent.js');
// Assert
$this->assertFalse($result['success']);
$this->assertEquals('file_not_found', $result['error']);
}
}
@@ -0,0 +1,983 @@
<?php
namespace Tests\Unit\Services;
use App\Extension\PluginManager;
use App\Extension\TemplateManager;
use App\Services\LayoutService;
use App\Services\PluginSettingsService;
use Illuminate\Support\Facades\Crypt;
use Mockery;
use Tests\Helpers\MocksExtensions;
use Tests\TestCase;
/**
* PluginSettingsService 단위 테스트
*
* 플러그인 설정 조회, 저장, 레이아웃 조회 기능을 테스트합니다.
* 설정은 파일 기반으로 storage/app/plugins/{identifier}/settings/setting.json에 저장됩니다.
*/
class PluginSettingsServiceTest extends TestCase
{
use MocksExtensions;
private PluginSettingsService $service;
private PluginManager $pluginManager;
private TemplateManager $templateManager;
private LayoutService $layoutService;
private string $testSettingsDir;
protected function setUp(): void
{
parent::setUp();
$this->pluginManager = app(PluginManager::class);
$this->templateManager = app(TemplateManager::class);
$this->layoutService = app(LayoutService::class);
$this->service = new PluginSettingsService(
$this->pluginManager,
$this->templateManager,
$this->layoutService
);
// 테스트용 설정 디렉토리 경로
$this->testSettingsDir = storage_path('app/plugins');
}
// ========================================================================
// get() 메서드 테스트
// ========================================================================
/**
* 존재하지 않는 플러그인 조회 시 기본값 반환
*/
public function test_get_returns_default_when_plugin_not_found(): void
{
$result = $this->service->get('nonexistent-plugin');
$this->assertNull($result);
}
/**
* 존재하지 않는 플러그인에 기본값 지정 시 해당 기본값 반환
*/
public function test_get_returns_custom_default_when_plugin_not_found(): void
{
$defaultValue = ['key' => 'default'];
$result = $this->service->get('nonexistent-plugin', null, $defaultValue);
$this->assertEquals($defaultValue, $result);
}
/**
* 플러그인 전체 설정 조회 성공
*/
public function test_get_returns_all_settings_when_key_is_null(): void
{
// Mock plugin with config values
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => 'test-settings-plugin',
'configValues' => [
'api_key' => 'default-api-key',
'enabled' => true,
'timeout' => 30,
],
'settingsSchema' => [],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with('test-settings-plugin')
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->get('test-settings-plugin');
$this->assertIsArray($result);
$this->assertArrayHasKey('api_key', $result);
$this->assertArrayHasKey('enabled', $result);
$this->assertArrayHasKey('timeout', $result);
}
/**
* 특정 키의 설정값 조회 성공
*/
public function test_get_returns_specific_key_value(): void
{
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => 'test-key-plugin',
'configValues' => [
'api_key' => 'my-secret-key',
'timeout' => 60,
],
'settingsSchema' => [],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with('test-key-plugin')
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->get('test-key-plugin', 'timeout');
$this->assertEquals(60, $result);
}
/**
* 존재하지 않는 키 조회 시 기본값 반환
*/
public function test_get_returns_default_for_missing_key(): void
{
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => 'test-missing-key-plugin',
'configValues' => ['existing_key' => 'value'],
'settingsSchema' => [],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with('test-missing-key-plugin')
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->get('test-missing-key-plugin', 'nonexistent_key', 'default_value');
$this->assertEquals('default_value', $result);
}
/**
* 중첩된 키 값 조회 (dot notation)
*/
public function test_get_returns_nested_key_value(): void
{
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => 'test-nested-plugin',
'configValues' => [
'database' => [
'host' => 'localhost',
'port' => 3306,
],
],
'settingsSchema' => [],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with('test-nested-plugin')
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$host = $service->get('test-nested-plugin', 'database.host');
$port = $service->get('test-nested-plugin', 'database.port');
$this->assertEquals('localhost', $host);
$this->assertEquals(3306, $port);
}
// ========================================================================
// save() 메서드 테스트
// ========================================================================
/**
* 존재하지 않는 플러그인 저장 시 false 반환
*/
public function test_save_returns_false_when_plugin_not_found(): void
{
$result = $this->service->save('nonexistent-plugin', ['key' => 'value']);
$this->assertFalse($result);
}
/**
* 플러그인 설정 저장 성공
*/
public function test_save_stores_settings_successfully(): void
{
$identifier = 'test-save-plugin-'.uniqid();
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'configValues' => [],
'settingsSchema' => [],
'storage' => [
'exists' => false,
'put' => true,
],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->save($identifier, [
'api_key' => 'new-api-key',
'enabled' => true,
]);
$this->assertTrue($result);
}
/**
* 기존 설정과 병합되는지 확인
*/
public function test_save_merges_with_existing_settings(): void
{
$identifier = 'test-merge-plugin-'.uniqid();
// 기존 설정 파일 내용
$existingContent = json_encode([
'existing_key' => 'existing_value',
'to_update' => 'old_value',
]);
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'configValues' => [],
'settingsSchema' => [],
'storage' => [
'exists' => true,
'get' => $existingContent,
'put' => true,
],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->save($identifier, [
'to_update' => 'new_value',
'new_key' => 'new_value',
]);
$this->assertTrue($result);
}
// ========================================================================
// getLayout() 메서드 테스트
// ========================================================================
/**
* 플러그인 인스턴스가 없으면 null 반환
*/
public function test_get_layout_returns_null_when_plugin_instance_not_found(): void
{
$result = $this->service->getLayout('nonexistent-plugin');
$this->assertNull($result);
}
/**
* 레이아웃 파일이 없으면 null 반환
*/
public function test_get_layout_returns_null_when_layout_file_not_exists(): void
{
// Mock PluginManager to return a plugin without layout file
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => 'test-no-layout',
'settingsLayout' => '/nonexistent/path/settings.json',
]);
$mockPluginManager->shouldReceive('getPlugin')
->with('test-no-layout')
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getLayout('test-no-layout');
$this->assertNull($result);
}
/**
* 실제 Daum 우편번호 플러그인 레이아웃 조회 테스트
*/
public function test_get_layout_returns_layout_for_daum_postcode_plugin(): void
{
// Daum 우편번호 플러그인이 설치되어 있는지 확인
$pluginPath = base_path('plugins/sirsoft-daum_postcode/resources/layouts/settings.json');
if (! file_exists($pluginPath)) {
$this->markTestSkipped('Daum postcode plugin layout file not found');
}
// Mock PluginManager
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => 'sirsoft-daum_postcode',
'settingsLayout' => $pluginPath,
]);
$mockPluginManager->shouldReceive('getPlugin')
->with('sirsoft-daum_postcode')
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getLayout('sirsoft-daum_postcode');
$this->assertIsArray($result);
$this->assertArrayHasKey('version', $result);
$this->assertArrayHasKey('meta', $result);
$this->assertArrayHasKey('schema', $result);
}
/**
* 레이아웃 파일 파싱 실패 시 null 반환
*/
public function test_get_layout_returns_null_on_invalid_json(): void
{
// 임시 잘못된 JSON 파일 생성
$tempPath = sys_get_temp_dir().'/invalid_layout_'.uniqid().'.json';
file_put_contents($tempPath, 'invalid json content {{{');
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => 'test-invalid-json',
'settingsLayout' => $tempPath,
]);
$mockPluginManager->shouldReceive('getPlugin')
->with('test-invalid-json')
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getLayout('test-invalid-json');
$this->assertNull($result);
// 임시 파일 삭제
@unlink($tempPath);
}
/**
* 레이아웃이 sanitize 되는지 확인 (components, data_sources 대상)
*/
public function test_get_layout_sanitizes_layout_content(): void
{
// 임시 레이아웃 파일 생성 (components에 XSS 포함)
$tempPath = sys_get_temp_dir().'/xss_layout_'.uniqid().'.json';
$layoutContent = json_encode([
'version' => '1.0.0',
'meta' => [
'title' => 'Test Plugin Settings',
],
'schema' => [
'field1' => [
'type' => 'string',
'label' => 'API Key',
],
],
'components' => [
[
'type' => 'basic',
'name' => 'Div',
'props' => [
'onClick' => 'javascript:alert("XSS")',
],
],
],
]);
file_put_contents($tempPath, $layoutContent);
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => 'test-xss-plugin',
'settingsLayout' => $tempPath,
]);
$mockPluginManager->shouldReceive('getPlugin')
->with('test-xss-plugin')
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getLayout('test-xss-plugin');
$this->assertIsArray($result);
// 레이아웃이 정상적으로 반환되는지 확인
$this->assertArrayHasKey('version', $result);
$this->assertArrayHasKey('meta', $result);
$this->assertArrayHasKey('schema', $result);
// components의 props에서 javascript: 프로토콜이 제거되었는지 확인
$this->assertArrayHasKey('components', $result);
$this->assertStringNotContainsString('javascript:', $result['components'][0]['props']['onClick'] ?? '');
// 임시 파일 삭제
@unlink($tempPath);
}
// ========================================================================
// 암호화/복호화 테스트
// ========================================================================
/**
* 민감한 필드가 암호화되어 저장되는지 확인
*/
public function test_save_encrypts_sensitive_fields(): void
{
$identifier = 'test-encrypt-plugin-'.uniqid();
// Mock plugin with sensitive field schema
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'configValues' => [],
'settingsSchema' => [
'api_key' => [
'type' => 'string',
'sensitive' => true,
],
'public_key' => [
'type' => 'string',
'sensitive' => false,
],
],
'storage' => [
'exists' => false,
'put' => true,
],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->save($identifier, [
'api_key' => 'secret-api-key',
'public_key' => 'public-value',
]);
$this->assertTrue($result);
// 암호화 로직은 내부적으로 동작하며, put이 호출되었으므로 성공으로 간주
}
/**
* 민감한 필드가 복호화되어 조회되는지 확인
*/
public function test_get_decrypts_sensitive_fields(): void
{
$identifier = 'test-decrypt-plugin-'.uniqid();
// 암호화된 값으로 설정 파일 내용 생성
$encryptedValue = Crypt::encryptString('decrypted-secret');
$fileContent = json_encode([
'secret_key' => $encryptedValue,
'normal_key' => 'normal-value',
]);
// Mock plugin with sensitive field schema and Storage
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'configValues' => [],
'settingsSchema' => [
'secret_key' => [
'type' => 'string',
'sensitive' => true,
],
'normal_key' => [
'type' => 'string',
'sensitive' => false,
],
],
'storage' => [
'exists' => true,
'get' => $fileContent,
],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->get($identifier);
// 민감한 필드는 복호화되어 반환됨
$this->assertEquals('decrypted-secret', $result['secret_key']);
// 비민감 필드는 그대로 반환됨
$this->assertEquals('normal-value', $result['normal_key']);
}
/**
* 복호화 실패 시 원래 값 유지 (레거시 데이터 호환)
*/
public function test_get_preserves_value_on_decrypt_failure(): void
{
$identifier = 'test-legacy-plugin-'.uniqid();
// 암호화되지 않은 레거시 값으로 설정 파일 내용 생성
$fileContent = json_encode([
'old_secret' => 'plain-text-secret', // 암호화되지 않은 레거시 값
]);
// Mock plugin with sensitive field schema
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'configValues' => [],
'settingsSchema' => [
'old_secret' => [
'type' => 'string',
'sensitive' => true,
],
],
'storage' => [
'exists' => true,
'get' => $fileContent,
],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->get($identifier);
// 복호화 실패 시 원래 값 유지
$this->assertEquals('plain-text-secret', $result['old_secret']);
}
/**
* 이미 암호화된 값은 다시 암호화하지 않음
*/
public function test_save_does_not_double_encrypt(): void
{
$identifier = 'test-double-encrypt-plugin-'.uniqid();
$originalValue = 'original-secret';
$encryptedOnce = Crypt::encryptString($originalValue);
// Mock plugin with sensitive field schema
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'configValues' => [],
'settingsSchema' => [
'api_key' => [
'type' => 'string',
'sensitive' => true,
],
],
'storage' => [
'exists' => false,
'put' => true,
],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
// 이미 암호화된 값을 저장
$result = $service->save($identifier, [
'api_key' => $encryptedOnce,
]);
$this->assertTrue($result);
// 암호화 로직은 내부적으로 동작하며, put이 호출되었으므로 성공으로 간주
}
/**
* reset() 메서드가 설정 파일을 삭제하는지 확인
*/
public function test_reset_deletes_settings_file(): void
{
$identifier = 'test-reset-plugin-'.uniqid();
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'storage' => [
'exists' => true,
'delete' => true,
],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->reset($identifier);
$this->assertTrue($result);
}
/**
* clearCache() 메서드가 캐시를 초기화하는지 확인
*/
public function test_clear_cache_clears_settings_cache(): void
{
$identifier = 'test-cache-plugin';
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'configValues' => ['initial' => 'value'],
'settingsSchema' => [],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
// 첫 번째 조회 (캐시에 저장됨)
$service->get($identifier);
// 캐시 초기화
$service->clearCache($identifier);
// 캐시가 초기화되었으므로 다시 getPlugin이 호출되어야 함
// (이 테스트는 내부 동작을 확인하는 것이 어려우므로 예외 없이 실행되는지만 확인)
$this->assertTrue(true);
}
// ========================================================================
// getAllActiveSettings() 메서드 테스트
// ========================================================================
/**
* frontend_schema가 있는 defaults.json이 있을 때 스키마 기반 필터링
*/
public function test_get_all_active_settings_uses_frontend_schema_when_defaults_exists(): void
{
$identifier = 'test-frontend-schema-plugin';
// defaults.json 임시 파일 생성
$tempDefaultsPath = sys_get_temp_dir().'/defaults_'.uniqid().'.json';
file_put_contents($tempDefaultsPath, json_encode([
'defaults' => [
'display_mode' => 'layer',
'popup_width' => 500,
'theme_color' => '#1D4ED8',
],
'frontend_schema' => [
'display_mode' => ['expose' => true],
'popup_width' => ['expose' => true],
'theme_color' => ['expose' => false],
],
]));
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'hasSettings' => true,
'configValues' => [
'display_mode' => 'layer',
'popup_width' => 500,
'theme_color' => '#1D4ED8',
],
'settingsSchema' => [],
'settingsDefaultsPath' => $tempDefaultsPath,
]);
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPluginManager->shouldReceive('getActivePlugins')
->andReturn([$mockPlugin]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getAllActiveSettings();
$this->assertArrayHasKey($identifier, $result);
$this->assertArrayHasKey('display_mode', $result[$identifier]);
$this->assertArrayHasKey('popup_width', $result[$identifier]);
$this->assertArrayNotHasKey('theme_color', $result[$identifier]);
@unlink($tempDefaultsPath);
}
/**
* defaults.json이 없을 때 기존 동작 유지 (sensitive만 제외)
*/
public function test_get_all_active_settings_falls_back_to_exclude_sensitive_when_no_defaults(): void
{
$identifier = 'test-no-defaults-plugin';
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'hasSettings' => true,
'configValues' => [
'display_mode' => 'popup',
'api_key' => 'secret-key',
],
'settingsSchema' => [
'display_mode' => ['type' => 'string'],
'api_key' => ['type' => 'string', 'sensitive' => true],
],
'settingsDefaultsPath' => null,
]);
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPluginManager->shouldReceive('getActivePlugins')
->andReturn([$mockPlugin]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getAllActiveSettings();
$this->assertArrayHasKey($identifier, $result);
$this->assertArrayHasKey('display_mode', $result[$identifier]);
$this->assertArrayNotHasKey('api_key', $result[$identifier]);
}
/**
* hasSettings()=false인 플러그인은 결과에 미포함
*/
public function test_get_all_active_settings_skips_plugins_without_settings(): void
{
$mockPlugin = $this->createMockPlugin([
'identifier' => 'no-settings-plugin',
'hasSettings' => false,
'configValues' => [],
'settingsSchema' => [],
]);
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPluginManager->shouldReceive('getActivePlugins')
->andReturn([$mockPlugin]);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getAllActiveSettings();
$this->assertEmpty($result);
}
/**
* frontend_schema로 카테고리 구조 필터링 (카테고리 expose:false → 전체 제외)
*/
public function test_get_all_active_settings_filters_by_category_expose(): void
{
$identifier = 'test-category-expose-plugin';
// 카테고리 구조 설정을 가진 defaults.json
$tempDefaultsPath = sys_get_temp_dir().'/defaults_cat_'.uniqid().'.json';
file_put_contents($tempDefaultsPath, json_encode([
'defaults' => [
'general' => ['site_name' => 'Test'],
'secrets' => ['api_key' => 'hidden'],
],
'frontend_schema' => [
'general' => ['expose' => true],
'secrets' => ['expose' => false],
],
]));
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'hasSettings' => true,
'configValues' => [
'general' => ['site_name' => 'Test'],
'secrets' => ['api_key' => 'hidden'],
],
'settingsSchema' => [],
'settingsDefaultsPath' => $tempDefaultsPath,
]);
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPluginManager->shouldReceive('getActivePlugins')
->andReturn([$mockPlugin]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getAllActiveSettings();
$this->assertArrayHasKey($identifier, $result);
$this->assertArrayHasKey('general', $result[$identifier]);
$this->assertArrayNotHasKey('secrets', $result[$identifier]);
@unlink($tempDefaultsPath);
}
/**
* frontend_schema로 필드 레벨 필터링 (필드 expose:false → 해당 필드만 제외)
*/
public function test_get_all_active_settings_filters_by_field_expose(): void
{
$identifier = 'test-field-expose-plugin';
$tempDefaultsPath = sys_get_temp_dir().'/defaults_field_'.uniqid().'.json';
file_put_contents($tempDefaultsPath, json_encode([
'defaults' => [
'payment' => [
'currency' => 'KRW',
'secret_key' => 'sk_xxx',
'public_key' => 'pk_xxx',
],
],
'frontend_schema' => [
'payment' => [
'expose' => true,
'fields' => [
'currency' => ['expose' => true],
'secret_key' => ['expose' => false],
'public_key' => ['expose' => true],
],
],
],
]));
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'hasSettings' => true,
'configValues' => [
'payment' => [
'currency' => 'KRW',
'secret_key' => 'sk_xxx',
'public_key' => 'pk_xxx',
],
],
'settingsSchema' => [],
'settingsDefaultsPath' => $tempDefaultsPath,
]);
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPluginManager->shouldReceive('getActivePlugins')
->andReturn([$mockPlugin]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getAllActiveSettings();
$this->assertArrayHasKey($identifier, $result);
$this->assertArrayHasKey('payment', $result[$identifier]);
$this->assertSame('KRW', $result[$identifier]['payment']['currency']);
$this->assertSame('pk_xxx', $result[$identifier]['payment']['public_key']);
$this->assertArrayNotHasKey('secret_key', $result[$identifier]['payment']);
@unlink($tempDefaultsPath);
}
protected function tearDown(): void
{
Mockery::close();
parent::tearDown();
}
}
+186
View File
@@ -0,0 +1,186 @@
<?php
namespace Tests\Unit\Services;
use App\Enums\ExtensionOwnerType;
use App\Exceptions\ExtensionOwnedRoleDeleteException;
use App\Exceptions\SystemRoleDeleteException;
use App\Extension\HookManager;
use App\Models\Menu;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use App\Services\RoleService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* RoleService 삭제 테스트
*
* 역할 삭제 시 관계 레코드 명시적 삭제, 예외 처리, 훅 실행을 검증합니다.
*/
class RoleServiceTest extends TestCase
{
use RefreshDatabase;
private RoleService $roleService;
protected function setUp(): void
{
parent::setUp();
$this->roleService = app(RoleService::class);
HookManager::resetAll();
}
protected function tearDown(): void
{
HookManager::resetAll();
parent::tearDown();
}
// ========================================================================
// deleteRole() - 예외 처리 검증
// ========================================================================
/**
* 코어 역할 삭제 시 SystemRoleDeleteException 발생 확인
*/
public function test_delete_core_role_throws_exception(): void
{
$coreRole = Role::create([
'identifier' => 'core-admin',
'name' => ['ko' => '코어 관리자', 'en' => 'Core Admin'],
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
]);
$this->expectException(SystemRoleDeleteException::class);
$this->roleService->deleteRole($coreRole);
}
/**
* 확장 소유 역할 삭제 시 ExtensionOwnedRoleDeleteException 발생 확인
*/
public function test_delete_extension_owned_role_throws_exception(): void
{
$extensionRole = Role::create([
'identifier' => 'extension-role',
'name' => ['ko' => '확장 역할', 'en' => 'Extension Role'],
'extension_type' => ExtensionOwnerType::Module,
'extension_identifier' => 'sirsoft-ecommerce',
]);
$this->expectException(ExtensionOwnedRoleDeleteException::class);
$this->roleService->deleteRole($extensionRole);
}
// ========================================================================
// deleteRole() - 관계 레코드 명시적 삭제 검증
// ========================================================================
/**
* 역할 삭제 시 권한 연결이 해제되는지 확인
*/
public function test_delete_role_detaches_permissions(): void
{
$role = Role::create([
'identifier' => 'test-perm-detach',
'name' => ['ko' => '권한 해제 테스트', 'en' => 'Permission Detach Test'],
]);
$permission = Permission::create([
'identifier' => 'test.permission.detach',
'name' => ['ko' => '테스트 권한', 'en' => 'Test Permission'],
'type' => \App\Enums\PermissionType::Admin,
]);
$role->permissions()->attach($permission->id);
$this->assertDatabaseHas('role_permissions', ['role_id' => $role->id, 'permission_id' => $permission->id]);
$this->roleService->deleteRole($role);
$this->assertDatabaseMissing('role_permissions', ['role_id' => $role->id]);
}
/**
* 역할 삭제 시 메뉴 연결이 해제되는지 확인
*/
public function test_delete_role_detaches_menus(): void
{
$role = Role::create([
'identifier' => 'test-menu-detach',
'name' => ['ko' => '메뉴 해제 테스트', 'en' => 'Menu Detach Test'],
]);
$menu = Menu::create([
'slug' => 'test-menu-for-role',
'name' => ['ko' => '테스트 메뉴', 'en' => 'Test Menu'],
'url' => '/test',
'sort_order' => 1,
]);
$role->menus()->attach($menu->id);
$this->assertDatabaseHas('role_menus', ['role_id' => $role->id, 'menu_id' => $menu->id]);
$this->roleService->deleteRole($role);
$this->assertDatabaseMissing('role_menus', ['role_id' => $role->id]);
}
/**
* 역할 삭제 시 사용자 연결이 해제되는지 확인
*/
public function test_delete_role_detaches_users(): void
{
$role = Role::create([
'identifier' => 'test-user-detach',
'name' => ['ko' => '사용자 해제 테스트', 'en' => 'User Detach Test'],
]);
$user = User::factory()->create();
$role->users()->attach($user->id);
$this->assertDatabaseHas('user_roles', ['role_id' => $role->id, 'user_id' => $user->id]);
$this->roleService->deleteRole($role);
$this->assertDatabaseMissing('user_roles', ['role_id' => $role->id]);
}
// ========================================================================
// deleteRole() - 훅 실행 검증
// ========================================================================
/**
* 역할 삭제 시 before_delete/after_delete 훅이 호출되는지 확인
*/
public function test_delete_role_fires_hooks(): void
{
$role = Role::create([
'identifier' => 'test-hook-role',
'name' => ['ko' => '훅 테스트 역할', 'en' => 'Hook Test Role'],
]);
$beforeCalled = false;
$afterCalled = false;
HookManager::addAction('core.role.before_delete', function ($r) use (&$beforeCalled, $role) {
$beforeCalled = true;
$this->assertEquals($role->id, $r->id);
});
HookManager::addAction('core.role.after_delete', function ($roleId) use (&$afterCalled, $role) {
$afterCalled = true;
$this->assertEquals($role->id, $roleId);
});
$this->roleService->deleteRole($role);
$this->assertTrue($beforeCalled);
$this->assertTrue($afterCalled);
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
namespace Tests\Unit\Services;
use App\Enums\ScheduleType;
use App\Extension\HookManager;
use App\Models\Schedule;
use App\Models\ScheduleHistory;
use App\Services\ScheduleService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* ScheduleService 삭제 테스트
*
* 스케줄 삭제 시 관계 레코드 명시적 삭제 및 훅 실행을 검증합니다.
*/
class ScheduleServiceTest extends TestCase
{
use RefreshDatabase;
private ScheduleService $scheduleService;
protected function setUp(): void
{
parent::setUp();
$this->scheduleService = app(ScheduleService::class);
HookManager::resetAll();
}
protected function tearDown(): void
{
HookManager::resetAll();
parent::tearDown();
}
// ========================================================================
// delete() - 관계 레코드 명시적 삭제 검증
// ========================================================================
/**
* 스케줄 삭제 시 실행 이력이 삭제되는지 확인
*/
public function test_delete_schedule_deletes_histories(): void
{
$schedule = Schedule::create([
'name' => '테스트 스케줄',
'type' => ScheduleType::Artisan,
'command' => 'inspire',
'expression' => '* * * * *',
'is_active' => true,
]);
ScheduleHistory::create([
'schedule_id' => $schedule->id,
'started_at' => now(),
'finished_at' => now(),
'result_status' => 'success',
]);
$this->assertDatabaseHas('schedule_histories', ['schedule_id' => $schedule->id]);
$this->scheduleService->delete($schedule);
$this->assertDatabaseMissing('schedule_histories', ['schedule_id' => $schedule->id]);
}
// ========================================================================
// delete() - 훅 실행 검증
// ========================================================================
/**
* 스케줄 삭제 시 before_delete/after_delete 훅이 호출되는지 확인
*/
public function test_delete_schedule_fires_hooks(): void
{
$schedule = Schedule::create([
'name' => '훅 테스트 스케줄',
'type' => ScheduleType::Artisan,
'command' => 'inspire',
'expression' => '* * * * *',
'is_active' => true,
]);
$beforeCalled = false;
$afterCalled = false;
HookManager::addAction('core.schedule.before_delete', function ($s) use (&$beforeCalled, $schedule) {
$beforeCalled = true;
$this->assertEquals($schedule->id, $s->id);
});
HookManager::addAction('core.schedule.after_delete', function ($scheduleId) use (&$afterCalled, $schedule) {
$afterCalled = true;
$this->assertEquals($schedule->id, $scheduleId);
});
$this->scheduleService->delete($schedule);
$this->assertTrue($beforeCalled);
$this->assertTrue($afterCalled);
}
}
@@ -0,0 +1,114 @@
<?php
namespace Tests\Unit\Services;
use App\Services\SettingsService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* SettingsService의 getAppConfigForFrontend() 메서드 테스트
*
* config/frontend.php 스키마를 기반으로 config() 값을 프론트엔드에 노출하는
* 기능을 검증합니다.
*/
class SettingsServiceAppConfigTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->seed();
}
/**
* getAppConfigForFrontend()가 supportedTimezones를 올바르게 반환하는지 테스트합니다.
*/
public function test_get_app_config_returns_supported_timezones(): void
{
$service = app(SettingsService::class);
$result = $service->getAppConfigForFrontend();
$this->assertArrayHasKey('supportedTimezones', $result);
$this->assertIsArray($result['supportedTimezones']);
$this->assertContains('Asia/Seoul', $result['supportedTimezones']);
$this->assertContains('UTC', $result['supportedTimezones']);
}
/**
* getAppConfigForFrontend()가 supportedLocales를 올바르게 반환하는지 테스트합니다.
*/
public function test_get_app_config_returns_supported_locales(): void
{
$service = app(SettingsService::class);
$result = $service->getAppConfigForFrontend();
$this->assertArrayHasKey('supportedLocales', $result);
$this->assertIsArray($result['supportedLocales']);
$this->assertContains('ko', $result['supportedLocales']);
$this->assertContains('en', $result['supportedLocales']);
}
/**
* config/frontend.php가 없는 경우 빈 배열을 반환하는지 테스트합니다.
*/
public function test_get_app_config_returns_empty_when_no_config(): void
{
// config를 비움
config(['frontend.app_config' => []]);
$service = app(SettingsService::class);
$result = $service->getAppConfigForFrontend();
$this->assertIsArray($result);
$this->assertEmpty($result);
}
/**
* config_key가 없는 필드 스키마는 무시되는지 테스트합니다.
*/
public function test_get_app_config_skips_fields_without_config_key(): void
{
config(['frontend.app_config' => [
'validKey' => [
'config_key' => 'app.supported_timezones',
'type' => 'array',
],
'invalidKey' => [
'type' => 'string',
// config_key 누락
],
]]);
$service = app(SettingsService::class);
$result = $service->getAppConfigForFrontend();
$this->assertArrayHasKey('validKey', $result);
$this->assertArrayNotHasKey('invalidKey', $result);
}
/**
* castValue가 올바른 타입으로 캐스팅하는지 테스트합니다.
*/
public function test_get_app_config_casts_values_by_type(): void
{
config(['frontend.app_config' => [
'arrayValue' => [
'config_key' => 'app.supported_timezones',
'type' => 'array',
],
]]);
$service = app(SettingsService::class);
$result = $service->getAppConfigForFrontend();
$this->assertIsArray($result['arrayValue']);
}
}
+208
View File
@@ -0,0 +1,208 @@
<?php
namespace Tests\Unit\Services;
use App\Extension\HookManager;
use App\Models\User;
use App\Services\UserService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* UserService 훅 테스트
*
* 사용자 생성/수정 시 훅이 올바르게 실행되는지 테스트합니다.
*/
class UserServiceHookTest extends TestCase
{
use RefreshDatabase;
private UserService $userService;
protected function setUp(): void
{
parent::setUp();
$this->userService = app(UserService::class);
HookManager::resetAll();
}
protected function tearDown(): void
{
HookManager::resetAll();
parent::tearDown();
}
/**
* 사용자 생성 시 before_create 훅이 호출되는지 테스트합니다.
*/
public function test_before_create_hook_is_called(): void
{
$hookCalled = false;
HookManager::addAction('core.user.before_create', function ($data) use (&$hookCalled) {
$hookCalled = true;
$this->assertArrayHasKey('name', $data);
$this->assertArrayHasKey('email', $data);
});
$this->userService->createUser([
'name' => 'Test User',
'email' => 'test@example.com',
'password' => 'password123',
]);
$this->assertTrue($hookCalled);
}
/**
* 사용자 생성 시 filter_create_data 훅이 데이터를 변형하는지 테스트합니다.
*/
public function test_filter_create_data_hook_modifies_data(): void
{
HookManager::addFilter('core.user.filter_create_data', function ($data) {
// 테스트용 필드 제거
unset($data['custom_field']);
return $data;
});
$user = $this->userService->createUser([
'name' => 'Test User',
'email' => 'test@example.com',
'password' => 'password123',
'custom_field' => 'should be removed',
]);
// custom_field가 제거되어 DB에 저장되지 않음
$this->assertNotNull($user->id);
}
/**
* 사용자 생성 시 after_create 훅이 호출되는지 테스트합니다.
*/
public function test_after_create_hook_is_called(): void
{
$hookCalled = false;
$receivedUser = null;
$receivedData = null;
HookManager::addAction('core.user.after_create', function ($user, $data) use (&$hookCalled, &$receivedUser, &$receivedData) {
$hookCalled = true;
$receivedUser = $user;
$receivedData = $data;
});
$user = $this->userService->createUser([
'name' => 'Test User',
'email' => 'test@example.com',
'password' => 'password123',
]);
$this->assertTrue($hookCalled);
$this->assertInstanceOf(User::class, $receivedUser);
$this->assertEquals('Test User', $receivedData['name']);
}
/**
* 사용자 수정 시 before_update 훅이 호출되는지 테스트합니다.
*/
public function test_before_update_hook_is_called(): void
{
$user = User::factory()->create();
$hookCalled = false;
HookManager::addAction('core.user.before_update', function ($u, $data) use (&$hookCalled, $user) {
$hookCalled = true;
$this->assertEquals($user->id, $u->id);
$this->assertArrayHasKey('name', $data);
});
$this->userService->updateUser($user, [
'name' => 'Updated Name',
]);
$this->assertTrue($hookCalled);
}
/**
* 사용자 수정 시 filter_update_data 훅이 데이터를 변형하는지 테스트합니다.
*/
public function test_filter_update_data_hook_modifies_data(): void
{
$user = User::factory()->create();
HookManager::addFilter('core.user.filter_update_data', function ($data, $u) {
// 테스트용 필드 제거
unset($data['custom_field']);
return $data;
});
$updatedUser = $this->userService->updateUser($user, [
'name' => 'Updated Name',
'custom_field' => 'should be removed',
]);
$this->assertEquals('Updated Name', $updatedUser->name);
}
/**
* 사용자 수정 시 after_update 훅이 호출되는지 테스트합니다.
*/
public function test_after_update_hook_is_called(): void
{
$user = User::factory()->create();
$hookCalled = false;
HookManager::addAction('core.user.after_update', function ($u, $data) use (&$hookCalled) {
$hookCalled = true;
});
$this->userService->updateUser($user, [
'name' => 'Updated Name',
]);
$this->assertTrue($hookCalled);
}
/**
* 사용자 삭제 시 before_delete 훅이 호출되는지 테스트합니다.
*/
public function test_before_delete_hook_is_called(): void
{
$user = User::factory()->create(['is_super' => false]);
$hookCalled = false;
HookManager::addAction('core.user.before_delete', function ($u) use (&$hookCalled, $user) {
$hookCalled = true;
$this->assertEquals($user->id, $u->id);
});
$this->userService->deleteUser($user);
$this->assertTrue($hookCalled);
}
/**
* 사용자 삭제 시 after_delete 훅이 호출되는지 테스트합니다.
*/
public function test_after_delete_hook_is_called(): void
{
$user = User::factory()->create(['is_super' => false]);
$hookCalled = false;
$receivedData = null;
HookManager::addAction('core.user.after_delete', function ($userData) use (&$hookCalled, &$receivedData) {
$hookCalled = true;
$receivedData = $userData;
});
$this->userService->deleteUser($user);
$this->assertTrue($hookCalled);
$this->assertArrayHasKey('id', $receivedData);
$this->assertArrayHasKey('name', $receivedData);
$this->assertArrayHasKey('email', $receivedData);
}
}
+696
View File
@@ -0,0 +1,696 @@
<?php
namespace Tests\Unit\Services;
use App\Enums\ExtensionOwnerType;
use App\Enums\PermissionType;
use App\Exceptions\CannotDeleteAdminException;
use App\Exceptions\CannotDeleteSuperAdminException;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use App\Models\UserConsent;
use App\Services\UserService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* UserService 테스트
*
* UserService의 사용자 삭제 및 슈퍼 관리자 관련 기능을 검증합니다.
*/
class UserServiceTest extends TestCase
{
use RefreshDatabase;
private UserService $userService;
protected function setUp(): void
{
parent::setUp();
$this->userService = app(UserService::class);
}
// ========================================================================
// deleteUser() - 슈퍼 관리자 삭제 방지 테스트
// ========================================================================
/**
* 슈퍼 관리자 삭제 시 CannotDeleteSuperAdminException 발생 확인
*/
public function test_delete_super_admin_throws_cannot_delete_super_admin_exception(): void
{
$superAdmin = User::factory()->create(['is_super' => true]);
$this->expectException(CannotDeleteSuperAdminException::class);
$this->userService->deleteUser($superAdmin);
}
/**
* 슈퍼 관리자 삭제 시 예외 메시지가 올바른지 확인
*/
public function test_cannot_delete_super_admin_exception_has_correct_message(): void
{
$superAdmin = User::factory()->create(['is_super' => true]);
try {
$this->userService->deleteUser($superAdmin);
$this->fail('Expected CannotDeleteSuperAdminException was not thrown');
} catch (CannotDeleteSuperAdminException $e) {
// 예외 메시지가 다국어 키로 번역되는지 확인
$this->assertNotEmpty($e->getMessage());
}
}
// ========================================================================
// deleteUser() - 관리자 삭제 방지 테스트
// ========================================================================
/**
* 관리자 권한을 가진 사용자 삭제 시 CannotDeleteAdminException 발생 확인
*/
public function test_delete_admin_user_throws_cannot_delete_admin_exception(): void
{
// admin 타입 권한 생성
$adminPermission = Permission::create([
'identifier' => 'core.admin.test',
'name' => ['ko' => '관리자 권한', 'en' => 'Admin Permission'],
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => PermissionType::Admin,
]);
// 역할 생성 및 권한 연결
$role = Role::create([
'identifier' => 'test-admin',
'name' => ['ko' => '테스트 관리자', 'en' => 'Test Admin'],
]);
$role->permissions()->attach($adminPermission->id);
// 관리자 사용자 생성 (is_super=false이지만 admin 권한 보유)
$adminUser = User::factory()->create(['is_super' => false]);
$adminUser->roles()->attach($role->id);
$this->expectException(CannotDeleteAdminException::class);
$this->userService->deleteUser($adminUser);
}
/**
* 관리자 삭제 시 예외 메시지가 올바른지 확인
*/
public function test_cannot_delete_admin_exception_has_correct_message(): void
{
$adminPermission = Permission::create([
'identifier' => 'core.admin.msg.test',
'name' => ['ko' => '관리자 권한', 'en' => 'Admin Permission'],
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => PermissionType::Admin,
]);
$role = Role::create([
'identifier' => 'test-admin-msg',
'name' => ['ko' => '테스트 관리자', 'en' => 'Test Admin'],
]);
$role->permissions()->attach($adminPermission->id);
$adminUser = User::factory()->create(['is_super' => false]);
$adminUser->roles()->attach($role->id);
try {
$this->userService->deleteUser($adminUser);
$this->fail('Expected CannotDeleteAdminException was not thrown');
} catch (CannotDeleteAdminException $e) {
$this->assertNotEmpty($e->getMessage());
}
}
// ========================================================================
// deleteUser() - 일반 사용자 삭제 테스트
// ========================================================================
/**
* 일반 사용자는 정상적으로 삭제 가능
*/
public function test_delete_regular_user_succeeds(): void
{
$regularUser = User::factory()->create(['is_super' => false]);
$result = $this->userService->deleteUser($regularUser);
$this->assertTrue($result);
$this->assertDatabaseMissing('users', ['id' => $regularUser->id]);
}
/**
* user 타입 권한만 가진 사용자는 삭제 가능
*/
public function test_delete_user_with_only_user_type_permissions_succeeds(): void
{
// user 타입 권한 생성
$userPermission = Permission::create([
'identifier' => 'frontend.user.test',
'name' => ['ko' => '사용자 권한', 'en' => 'User Permission'],
'type' => PermissionType::User,
]);
// 역할 생성 및 권한 연결
$role = Role::create([
'identifier' => 'test-user',
'name' => ['ko' => '테스트 사용자', 'en' => 'Test User'],
]);
$role->permissions()->attach($userPermission->id);
// 사용자 생성 및 역할 연결
$user = User::factory()->create(['is_super' => false]);
$user->roles()->attach($role->id);
$result = $this->userService->deleteUser($user);
$this->assertTrue($result);
$this->assertDatabaseMissing('users', ['id' => $user->id]);
}
/**
* 역할이 없는 사용자도 삭제 가능
*/
public function test_delete_user_without_roles_succeeds(): void
{
$userWithoutRoles = User::factory()->create(['is_super' => false]);
// 역할이 없는지 확인
$this->assertEquals(0, $userWithoutRoles->roles()->count());
$result = $this->userService->deleteUser($userWithoutRoles);
$this->assertTrue($result);
$this->assertDatabaseMissing('users', ['id' => $userWithoutRoles->id]);
}
// ========================================================================
// 삭제 우선순위 테스트 (슈퍼 관리자 > 관리자)
// ========================================================================
/**
* 슈퍼 관리자이면서 관리자 권한도 있는 경우, 슈퍼 관리자 예외가 우선
*/
public function test_super_admin_exception_takes_priority_over_admin_exception(): void
{
// admin 타입 권한 생성
$adminPermission = Permission::create([
'identifier' => 'core.priority.test',
'name' => ['ko' => '우선순위 테스트', 'en' => 'Priority Test'],
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => PermissionType::Admin,
]);
// 역할 생성 및 권한 연결
$role = Role::create([
'identifier' => 'super-admin-role',
'name' => ['ko' => '슈퍼관리자 역할', 'en' => 'Super Admin Role'],
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
]);
$role->permissions()->attach($adminPermission->id);
// 슈퍼 관리자이면서 관리자 역할도 가진 사용자
$superAdminWithRole = User::factory()->create(['is_super' => true]);
$superAdminWithRole->roles()->attach($role->id);
// 슈퍼 관리자 예외가 먼저 발생해야 함
$this->expectException(CannotDeleteSuperAdminException::class);
$this->userService->deleteUser($superAdminWithRole);
}
// ========================================================================
// deleteUser() - 관계 레코드 명시적 삭제 검증 (CASCADE 의존 금지)
// ========================================================================
/**
* 사용자 삭제 시 역할 연결이 해제되는지 확인
*/
public function test_delete_user_detaches_roles(): void
{
$role = Role::create([
'identifier' => 'test-detach-role',
'name' => ['ko' => '역할 해제 테스트', 'en' => 'Detach Test'],
]);
$user = User::factory()->create(['is_super' => false]);
$user->roles()->attach($role->id);
$this->assertDatabaseHas('user_roles', ['user_id' => $user->id, 'role_id' => $role->id]);
$this->userService->deleteUser($user);
$this->assertDatabaseMissing('user_roles', ['user_id' => $user->id]);
}
/**
* 사용자 삭제 시 약관 동의 이력이 삭제되는지 확인
*/
public function test_delete_user_deletes_consents(): void
{
$user = User::factory()->create(['is_super' => false]);
UserConsent::create([
'user_id' => $user->id,
'consent_type' => 'terms',
'agreed_at' => now(),
]);
$this->assertDatabaseHas('user_consents', ['user_id' => $user->id]);
$this->userService->deleteUser($user);
$this->assertDatabaseMissing('user_consents', ['user_id' => $user->id]);
}
/**
* 사용자 삭제 시 API 토큰이 삭제되는지 확인
*/
public function test_delete_user_deletes_tokens(): void
{
$user = User::factory()->create(['is_super' => false]);
$user->createToken('test-token');
$this->assertDatabaseHas('personal_access_tokens', [
'tokenable_id' => $user->id,
'tokenable_type' => User::class,
]);
$this->userService->deleteUser($user);
$this->assertDatabaseMissing('personal_access_tokens', [
'tokenable_id' => $user->id,
'tokenable_type' => User::class,
]);
}
// ========================================================================
// createUser() 테스트 (is_super 필드 처리)
// ========================================================================
/**
* 사용자 생성 시 is_super 필드가 정상적으로 저장되는지 확인
*/
public function test_create_user_with_is_super_true(): void
{
$userData = [
'name' => 'Super Admin Test',
'email' => 'superadmin@test.com',
'password' => 'password123',
'is_super' => true,
];
$user = $this->userService->createUser($userData);
$this->assertTrue($user->is_super);
$this->assertTrue($user->isSuperAdmin());
}
/**
* 사용자 생성 시 is_super가 기본값 false인지 확인
*/
#[Test]
public function test_create_user_is_super_defaults_to_false(): void
{
$userData = [
'name' => 'Regular User Test',
'email' => 'regularuser@test.com',
'password' => 'password123',
];
$user = $this->userService->createUser($userData);
$this->assertFalse($user->is_super);
$this->assertFalse($user->isSuperAdmin());
}
// ========================================================================
// updateUser() 테스트 (is_super 필드 처리)
// ========================================================================
/**
* 사용자 업데이트 시 is_super 필드 변경 가능
*/
public function test_update_user_can_change_is_super(): void
{
$user = User::factory()->create(['is_super' => false]);
$this->assertFalse($user->is_super);
$updatedUser = $this->userService->updateUser($user, ['is_super' => true]);
$this->assertTrue($updatedUser->is_super);
$this->assertTrue($updatedUser->isSuperAdmin());
}
/**
* 슈퍼 관리자를 일반 사용자로 강등 가능
*/
public function test_update_user_can_demote_super_admin(): void
{
$superAdmin = User::factory()->create(['is_super' => true]);
$this->assertTrue($superAdmin->isSuperAdmin());
$updatedUser = $this->userService->updateUser($superAdmin, ['is_super' => false]);
$this->assertFalse($updatedUser->is_super);
$this->assertFalse($updatedUser->isSuperAdmin());
}
// ========================================================================
// updateUser() — 역할 할당 권한 체크 테스트
// ========================================================================
/**
* core.permissions.update 권한이 있으면 자기 자신의 역할도 변경 가능
*/
public function test_update_user_can_change_own_roles_with_permission(): void
{
// core.permissions.update 권한을 가진 사용자
$permUpdatePermission = Permission::create([
'identifier' => 'core.permissions.update',
'name' => ['ko' => '권한 수정', 'en' => 'Update Permissions'],
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => PermissionType::Admin,
]);
$adminRole = Role::create([
'identifier' => 'test-perm-admin',
'name' => ['ko' => '권한 관리자', 'en' => 'Permission Admin'],
]);
$adminRole->permissions()->attach($permUpdatePermission->id);
$newRole = Role::create([
'identifier' => 'new-role',
'name' => ['ko' => '새 역할', 'en' => 'New Role'],
]);
$user = User::factory()->create();
$user->roles()->attach($adminRole->id);
// 자기 자신으로 인증
Auth::login($user);
// 자기 자신의 역할 변경 시도 (admin 역할이 아니므로 자기잠금 방지 해당 없음)
$updatedUser = $this->userService->updateUser($user, [
'name' => 'Updated Name',
'role_ids' => [$adminRole->id, $newRole->id],
]);
// 이름과 역할 모두 변경되어야 함
$this->assertEquals('Updated Name', $updatedUser->name);
$this->assertTrue($updatedUser->roles->contains('id', $adminRole->id));
$this->assertTrue($updatedUser->roles->contains('id', $newRole->id));
}
/**
* 마지막 admin 역할 사용자가 자기 admin 역할을 제거하려는 경우 차단
*/
public function test_update_user_prevents_last_admin_role_removal(): void
{
$permUpdatePermission = Permission::create([
'identifier' => 'core.permissions.update',
'name' => ['ko' => '권한 수정', 'en' => 'Update Permissions'],
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => PermissionType::Admin,
]);
$adminRole = Role::create([
'identifier' => 'admin',
'name' => ['ko' => '관리자', 'en' => 'Admin'],
]);
$adminRole->permissions()->attach($permUpdatePermission->id);
$otherRole = Role::create([
'identifier' => 'other-role',
'name' => ['ko' => '다른 역할', 'en' => 'Other Role'],
]);
// 유일한 admin 사용자
$user = User::factory()->create();
$user->roles()->attach($adminRole->id);
Auth::login($user);
// admin 역할을 제거하고 다른 역할만 남기려는 시도
$this->expectException(ValidationException::class);
$this->userService->updateUser($user, [
'role_ids' => [$otherRole->id],
]);
}
/**
* admin 역할을 가진 다른 사용자가 있으면 자기 admin 역할 제거 가능
*/
public function test_update_user_allows_admin_role_removal_when_other_admins_exist(): void
{
$permUpdatePermission = Permission::create([
'identifier' => 'core.permissions.update',
'name' => ['ko' => '권한 수정', 'en' => 'Update Permissions'],
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => PermissionType::Admin,
]);
$adminRole = Role::create([
'identifier' => 'admin',
'name' => ['ko' => '관리자', 'en' => 'Admin'],
]);
$adminRole->permissions()->attach($permUpdatePermission->id);
$otherRole = Role::create([
'identifier' => 'other-role-2',
'name' => ['ko' => '다른 역할', 'en' => 'Other Role'],
]);
// admin 역할을 가진 사용자 2명
$user = User::factory()->create();
$user->roles()->attach($adminRole->id);
$otherAdmin = User::factory()->create();
$otherAdmin->roles()->attach($adminRole->id);
Auth::login($user);
// 다른 admin이 있으므로 자기 admin 역할 제거 가능
$updatedUser = $this->userService->updateUser($user, [
'role_ids' => [$otherRole->id],
]);
$this->assertFalse($updatedUser->roles->contains('id', $adminRole->id));
$this->assertTrue($updatedUser->roles->contains('id', $otherRole->id));
}
/**
* 마지막 admin 역할 제거 시 ValidationException에 role_ids 에러가 포함되는지 확인
*/
public function test_last_admin_role_removal_has_role_ids_error_key(): void
{
$permUpdatePermission = Permission::create([
'identifier' => 'core.permissions.update',
'name' => ['ko' => '권한 수정', 'en' => 'Update Permissions'],
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => PermissionType::Admin,
]);
$adminRole = Role::create([
'identifier' => 'admin',
'name' => ['ko' => '관리자', 'en' => 'Admin'],
]);
$adminRole->permissions()->attach($permUpdatePermission->id);
$otherRole = Role::create([
'identifier' => 'user-role',
'name' => ['ko' => '사용자', 'en' => 'User'],
]);
$user = User::factory()->create();
$user->roles()->attach($adminRole->id);
Auth::login($user);
try {
$this->userService->updateUser($user, [
'role_ids' => [$otherRole->id],
]);
$this->fail('Expected ValidationException was not thrown');
} catch (ValidationException $e) {
$this->assertArrayHasKey('role_ids', $e->errors());
$this->assertNotEmpty($e->errors()['role_ids']);
}
}
/**
* core.permissions.update 권한 없으면 타인의 역할 변경 불가 (무시됨)
*/
public function test_update_user_ignores_role_ids_without_permission(): void
{
$originalRole = Role::create([
'identifier' => 'original-role',
'name' => ['ko' => '원래 역할', 'en' => 'Original Role'],
]);
$newRole = Role::create([
'identifier' => 'new-role-test',
'name' => ['ko' => '새 역할', 'en' => 'New Role'],
]);
$targetUser = User::factory()->create();
$targetUser->roles()->attach($originalRole->id);
// 권한 없는 사용자로 인증
$authUser = User::factory()->create();
Auth::login($authUser);
// 타인의 역할 변경 시도
$updatedUser = $this->userService->updateUser($targetUser, [
'name' => 'Changed Name',
'role_ids' => [$newRole->id],
]);
// 이름은 변경되지만 역할은 변경되지 않아야 함
$this->assertEquals('Changed Name', $updatedUser->name);
$this->assertTrue($updatedUser->roles->contains('id', $originalRole->id));
$this->assertFalse($updatedUser->roles->contains('id', $newRole->id));
}
/**
* core.permissions.update 권한이 있으면 타인의 역할 변경 가능
*/
public function test_update_user_allows_role_change_with_permission(): void
{
$permUpdatePermission = Permission::create([
'identifier' => 'core.permissions.update',
'name' => ['ko' => '권한 수정', 'en' => 'Update Permissions'],
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => PermissionType::Admin,
]);
$adminRole = Role::create([
'identifier' => 'perm-admin-role',
'name' => ['ko' => '권한 관리 역할', 'en' => 'Permission Admin Role'],
]);
$adminRole->permissions()->attach($permUpdatePermission->id);
$originalRole = Role::create([
'identifier' => 'original-role-2',
'name' => ['ko' => '원래 역할', 'en' => 'Original Role'],
]);
$newRole = Role::create([
'identifier' => 'target-role',
'name' => ['ko' => '대상 역할', 'en' => 'Target Role'],
]);
$targetUser = User::factory()->create();
$targetUser->roles()->attach($originalRole->id);
// 권한 있는 사용자로 인증
$authUser = User::factory()->create();
$authUser->roles()->attach($adminRole->id);
Auth::login($authUser);
// 타인의 역할 변경
$updatedUser = $this->userService->updateUser($targetUser, [
'role_ids' => [$newRole->id],
]);
// 역할이 새 역할로 변경되어야 함
$this->assertTrue($updatedUser->roles->contains('id', $newRole->id));
$this->assertFalse($updatedUser->roles->contains('id', $originalRole->id));
}
// ========================================================================
// createUser() — 역할 할당 권한 체크 테스트
// ========================================================================
/**
* core.permissions.update 권한 없으면 기본 역할(user) 자동 할당
*/
public function test_create_user_assigns_default_role_without_permission(): void
{
// 기본 user 역할 생성
$userRole = Role::create([
'identifier' => 'user',
'name' => ['ko' => '사용자', 'en' => 'User'],
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'is_active' => true,
]);
$customRole = Role::create([
'identifier' => 'custom-role',
'name' => ['ko' => '커스텀 역할', 'en' => 'Custom Role'],
]);
// 권한 없는 사용자로 인증
$authUser = User::factory()->create();
Auth::login($authUser);
$user = $this->userService->createUser([
'name' => 'Test User',
'email' => 'testcreate@test.com',
'password' => 'password123',
'role_ids' => [$customRole->id],
]);
// 커스텀 역할 대신 기본 역할이 할당되어야 함
$this->assertTrue($user->roles->contains('id', $userRole->id));
$this->assertFalse($user->roles->contains('id', $customRole->id));
}
/**
* core.permissions.update 권한이 있으면 지정한 역할 할당 가능
*/
public function test_create_user_assigns_specified_roles_with_permission(): void
{
$permUpdatePermission = Permission::create([
'identifier' => 'core.permissions.update',
'name' => ['ko' => '권한 수정', 'en' => 'Update Permissions'],
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => PermissionType::Admin,
]);
$adminRole = Role::create([
'identifier' => 'create-perm-admin',
'name' => ['ko' => '권한 관리자', 'en' => 'Permission Admin'],
]);
$adminRole->permissions()->attach($permUpdatePermission->id);
$customRole = Role::create([
'identifier' => 'assigned-role',
'name' => ['ko' => '할당 역할', 'en' => 'Assigned Role'],
]);
// 권한 있는 사용자로 인증
$authUser = User::factory()->create();
$authUser->roles()->attach($adminRole->id);
Auth::login($authUser);
$user = $this->userService->createUser([
'name' => 'New User',
'email' => 'newuser@test.com',
'password' => 'password123',
'role_ids' => [$customRole->id],
]);
// 지정한 역할이 할당되어야 함
$this->assertTrue($user->roles->contains('id', $customRole->id));
}
}