v7.0.0 release
This commit is contained in:
1 parent
0e7fa04b03
commit
c4ea9a6cd1
3582 files changed
+626189
-160151
No files matched your search
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Tests\Unit\Services;
|
||||
|
||||
use App\Extension\Helpers\FilePermissionHelper;
|
||||
use App\Services\CoreUpdateService;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\File;
|
||||
@@ -1097,7 +1098,7 @@ MD;
|
||||
File::put($tempDest.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'OrphanFile.php', '<?php // orphan');
|
||||
|
||||
// FilePermissionHelper::copyDirectory 직접 호출로 검증
|
||||
\App\Extension\Helpers\FilePermissionHelper::copyDirectory(
|
||||
FilePermissionHelper::copyDirectory(
|
||||
$tempSource.DIRECTORY_SEPARATOR.'app',
|
||||
$tempDest.DIRECTORY_SEPARATOR.'app',
|
||||
removeOrphans: true
|
||||
@@ -1186,7 +1187,7 @@ MD;
|
||||
* 만 있을 때, 활성 디렉토리(`templates/sirsoft-basic` 등) 가 자동 발견 폴백의
|
||||
* removeOrphans 로 삭제되지 않아야 한다.
|
||||
*
|
||||
* 회귀 시나리오 (#347): beta.4 의 `isCoveredByApplied` 가 단방향 검사만 수행하여
|
||||
* 회귀 시나리오: beta.4 의 `isCoveredByApplied` 가 단방향 검사만 수행하여
|
||||
* applied=['templates/_bundled'] 일 때 source 의 'templates' 자체를 신규 항목으로
|
||||
* 오인 → `copyDirectory(removeOrphans:true)` 가 base 의 활성 sirsoft-* 서브디렉토리를
|
||||
* orphan 으로 판정하여 삭제.
|
||||
@@ -1240,7 +1241,7 @@ MD;
|
||||
// 활성 디렉토리는 source 에 부재하지만 base 에 보존되어야 함 (회귀 차단)
|
||||
$this->assertFileExists(
|
||||
$fakeBase.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.'sirsoft-basic'.DIRECTORY_SEPARATOR.'manifest.json',
|
||||
'활성 templates/sirsoft-basic 이 자동 발견 폴백에 의해 삭제되어서는 안 된다 (#347 회귀)'
|
||||
'활성 templates/sirsoft-basic 이 자동 발견 폴백에 의해 삭제되어서는 안 된다'
|
||||
);
|
||||
} finally {
|
||||
app()->setBasePath($originalBasePath);
|
||||
@@ -1248,7 +1249,156 @@ MD;
|
||||
}
|
||||
|
||||
/**
|
||||
* modules/, plugins/ 에도 동일 패턴 보존 확인 (#347 회귀).
|
||||
* 회귀: 사용자가 `_bundled/` 바로 아래에 직접 생성한 커스텀 확장 디렉토리가
|
||||
* 코어 업데이트의 정상 targets 흐름(removeOrphans:true)에 의해 삭제되지 않아야 한다.
|
||||
*
|
||||
* 확장 3종 + 언어팩 4개 도메인 전부 검증한다.
|
||||
*
|
||||
* 회귀 시나리오: targets 의 `{domain}/_bundled` 를 source 기준으로 sync 할 때,
|
||||
* source(신버전 코어 배포본)에 없는 사용자 디렉토리(`_bundled/my-project`) 가
|
||||
* orphan 으로 판정되어 삭제되던 결함 (공개 gnuboard/g7 #43 제보).
|
||||
*/
|
||||
public function test_apply_update_preserves_user_added_bundled_subdir_all_domains(): void
|
||||
{
|
||||
$domains = [
|
||||
'modules' => 'sirsoft-ecommerce',
|
||||
'plugins' => 'sirsoft-payment',
|
||||
'templates' => 'sirsoft-basic',
|
||||
'lang-packs' => 'g7-core-ja',
|
||||
];
|
||||
|
||||
$sourcePath = storage_path('test_388_src_'.uniqid());
|
||||
$this->tempDirs[] = $sourcePath;
|
||||
File::ensureDirectoryExists($sourcePath);
|
||||
|
||||
$fakeBase = storage_path('test_388_base_'.uniqid());
|
||||
$this->tempDirs[] = $fakeBase;
|
||||
File::ensureDirectoryExists($fakeBase);
|
||||
|
||||
$targets = [];
|
||||
|
||||
foreach ($domains as $domain => $bundledId) {
|
||||
$targets[] = $domain.'/_bundled';
|
||||
|
||||
// source: {domain}/_bundled/{bundledId} 만 보유 (코어 번들 확장)
|
||||
$srcExt = $sourcePath.DIRECTORY_SEPARATOR.$domain.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.$bundledId;
|
||||
File::ensureDirectoryExists($srcExt);
|
||||
File::put($srcExt.DIRECTORY_SEPARATOR.'manifest.json', '{"identifier":"'.$bundledId.'","version":"1.0.0"}');
|
||||
|
||||
// base: 코어 번들 확장 + 사용자 추가 디렉토리(my-project) + 사용자 추가 파일(메모.txt)
|
||||
$baseBundled = $fakeBase.DIRECTORY_SEPARATOR.$domain.DIRECTORY_SEPARATOR.'_bundled';
|
||||
$baseExt = $baseBundled.DIRECTORY_SEPARATOR.$bundledId;
|
||||
File::ensureDirectoryExists($baseExt);
|
||||
File::put($baseExt.DIRECTORY_SEPARATOR.'manifest.json', '{"identifier":"'.$bundledId.'","version":"0.9.0"}');
|
||||
|
||||
// 사용자 추가 디렉토리 (source 에 없음)
|
||||
$userDir = $baseBundled.DIRECTORY_SEPARATOR.'my-project';
|
||||
File::ensureDirectoryExists($userDir);
|
||||
File::put($userDir.DIRECTORY_SEPARATOR.'custom.json', '{"mine":true}');
|
||||
|
||||
// 사용자 추가 단일 파일 (source 에 없음)
|
||||
File::put($baseBundled.DIRECTORY_SEPARATOR.'memo.txt', 'keep me');
|
||||
}
|
||||
|
||||
$originalBasePath = base_path();
|
||||
app()->setBasePath($fakeBase);
|
||||
|
||||
try {
|
||||
config([
|
||||
'app.update.targets' => $targets,
|
||||
'app.update.excludes' => [],
|
||||
'app.update.protected_paths' => ['.env', 'storage', 'vendor', 'node_modules', '.git'],
|
||||
]);
|
||||
|
||||
$this->service->applyUpdate($sourcePath);
|
||||
|
||||
foreach ($domains as $domain => $bundledId) {
|
||||
$baseBundled = $fakeBase.DIRECTORY_SEPARATOR.$domain.DIRECTORY_SEPARATOR.'_bundled';
|
||||
|
||||
// 사용자 추가 디렉토리 보존
|
||||
$this->assertFileExists(
|
||||
$baseBundled.DIRECTORY_SEPARATOR.'my-project'.DIRECTORY_SEPARATOR.'custom.json',
|
||||
$domain.'/_bundled/my-project 가 코어 업데이트에 의해 삭제되어서는 안 된다'
|
||||
);
|
||||
|
||||
// 사용자 추가 단일 파일 보존
|
||||
$this->assertFileExists(
|
||||
$baseBundled.DIRECTORY_SEPARATOR.'memo.txt',
|
||||
$domain.'/_bundled/memo.txt 가 코어 업데이트에 의해 삭제되어서는 안 된다'
|
||||
);
|
||||
|
||||
// 코어 번들 확장은 source 기준으로 정상 sync
|
||||
$this->assertStringContainsString(
|
||||
'"version":"1.0.0"',
|
||||
File::get($baseBundled.DIRECTORY_SEPARATOR.$bundledId.DIRECTORY_SEPARATOR.'manifest.json'),
|
||||
$domain.'/_bundled/'.$bundledId.' 는 source 기준으로 갱신되어야 한다'
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
app()->setBasePath($originalBasePath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 비회귀: `_bundled` 최상위 사용자 항목은 보존하되, source 에 존재하는 코어
|
||||
* 번들 확장 디렉토리 *내부* 의 stale 파일 정리는 그대로 유지되어야 한다.
|
||||
*/
|
||||
public function test_apply_update_still_cleans_stale_file_inside_bundled_extension(): void
|
||||
{
|
||||
$sourcePath = storage_path('test_388_stale_src_'.uniqid());
|
||||
$this->tempDirs[] = $sourcePath;
|
||||
File::ensureDirectoryExists($sourcePath);
|
||||
|
||||
// source: modules/_bundled/sirsoft-ecommerce/module.json 만 (old.json 없음)
|
||||
$srcExt = $sourcePath.DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.'sirsoft-ecommerce';
|
||||
File::ensureDirectoryExists($srcExt);
|
||||
File::put($srcExt.DIRECTORY_SEPARATOR.'module.json', '{"version":"1.0.0"}');
|
||||
|
||||
$fakeBase = storage_path('test_388_stale_base_'.uniqid());
|
||||
$this->tempDirs[] = $fakeBase;
|
||||
File::ensureDirectoryExists($fakeBase);
|
||||
|
||||
// base: 코어 번들 확장 내부에 source 에 없는 stale 파일(old.json) + 사용자 디렉토리
|
||||
$baseBundled = $fakeBase.DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR.'_bundled';
|
||||
$baseExt = $baseBundled.DIRECTORY_SEPARATOR.'sirsoft-ecommerce';
|
||||
File::ensureDirectoryExists($baseExt);
|
||||
File::put($baseExt.DIRECTORY_SEPARATOR.'module.json', '{"version":"0.9.0"}');
|
||||
File::put($baseExt.DIRECTORY_SEPARATOR.'old.json', 'stale');
|
||||
|
||||
$userDir = $baseBundled.DIRECTORY_SEPARATOR.'my-project';
|
||||
File::ensureDirectoryExists($userDir);
|
||||
File::put($userDir.DIRECTORY_SEPARATOR.'custom.json', '{"mine":true}');
|
||||
|
||||
$originalBasePath = base_path();
|
||||
app()->setBasePath($fakeBase);
|
||||
|
||||
try {
|
||||
config([
|
||||
'app.update.targets' => ['modules/_bundled'],
|
||||
'app.update.excludes' => [],
|
||||
'app.update.protected_paths' => ['.env', 'storage', 'vendor', 'node_modules', '.git'],
|
||||
]);
|
||||
|
||||
$this->service->applyUpdate($sourcePath);
|
||||
|
||||
// 코어 번들 확장 내부의 stale 파일은 정리되어야 함
|
||||
$this->assertFileDoesNotExist(
|
||||
$baseExt.DIRECTORY_SEPARATOR.'old.json',
|
||||
'코어 번들 확장 내부의 stale 파일은 정리되어야 한다'
|
||||
);
|
||||
|
||||
// 사용자 추가 디렉토리는 보존
|
||||
$this->assertFileExists(
|
||||
$userDir.DIRECTORY_SEPARATOR.'custom.json',
|
||||
'사용자 추가 _bundled/my-project 는 보존되어야 한다'
|
||||
);
|
||||
} finally {
|
||||
app()->setBasePath($originalBasePath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* modules/, plugins/ 에도 동일 패턴 보존 확인.
|
||||
*/
|
||||
public function test_apply_update_preserves_active_module_and_plugin_dirs_same_pattern(): void
|
||||
{
|
||||
@@ -1310,11 +1460,11 @@ MD;
|
||||
// 활성 모듈/플러그인 디렉토리 보존
|
||||
$this->assertFileExists(
|
||||
$fakeBase.DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR.'sirsoft-ecommerce'.DIRECTORY_SEPARATOR.'module.json',
|
||||
'활성 modules/sirsoft-ecommerce 이 보존되어야 한다 (#347 회귀)'
|
||||
'활성 modules/sirsoft-ecommerce 이 보존되어야 한다'
|
||||
);
|
||||
$this->assertFileExists(
|
||||
$fakeBase.DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'sirsoft-payment'.DIRECTORY_SEPARATOR.'plugin.json',
|
||||
'활성 plugins/sirsoft-payment 이 보존되어야 한다 (#347 회귀)'
|
||||
'활성 plugins/sirsoft-payment 이 보존되어야 한다'
|
||||
);
|
||||
|
||||
// _bundled sync 정상
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services;
|
||||
|
||||
use App\Services\LanguagePack\CustomTranslationUsageScanner;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* CustomTranslationUsageScanner 단위 테스트.
|
||||
*
|
||||
* 레이아웃 content 에서 `$t:custom.*` 키 수집 / custom 아닌 `$t:` 제외 / 중복 dedup /
|
||||
* 중첩 노드·props·표현식 스캔 / normalizeLayoutKey SSoT 정규화를 검증합니다.
|
||||
*/
|
||||
class CustomTranslationUsageScannerTest extends TestCase
|
||||
{
|
||||
private CustomTranslationUsageScanner $scanner;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->scanner = new CustomTranslationUsageScanner();
|
||||
}
|
||||
|
||||
public function test_collects_custom_key_from_node_text(): void
|
||||
{
|
||||
$content = [
|
||||
['type' => 'Span', 'text' => '$t:custom.home.1'],
|
||||
];
|
||||
|
||||
$this->assertSame(['custom.home.1'], $this->scanner->collectReferencedKeys($content));
|
||||
}
|
||||
|
||||
public function test_collects_from_nested_children_and_props(): void
|
||||
{
|
||||
$content = [
|
||||
[
|
||||
'type' => 'Div',
|
||||
'children' => [
|
||||
['type' => 'Span', 'text' => '$t:custom.home.1'],
|
||||
['type' => 'Button', 'props' => ['label' => '$t:custom.home.2']],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$keys = $this->scanner->collectReferencedKeys($content);
|
||||
sort($keys);
|
||||
|
||||
$this->assertSame(['custom.home.1', 'custom.home.2'], $keys);
|
||||
}
|
||||
|
||||
public function test_excludes_non_custom_t_keys(): void
|
||||
{
|
||||
$content = [
|
||||
['text' => '$t:common.save'],
|
||||
['text' => '$t:layout_editor.title'],
|
||||
['text' => '$t:custom.board_list.3'],
|
||||
];
|
||||
|
||||
$this->assertSame(['custom.board_list.3'], $this->scanner->collectReferencedKeys($content));
|
||||
}
|
||||
|
||||
public function test_dedups_repeated_keys(): void
|
||||
{
|
||||
$content = [
|
||||
['text' => '$t:custom.home.1'],
|
||||
['text' => '$t:custom.home.1'],
|
||||
['children' => [['text' => '$t:custom.home.1']]],
|
||||
];
|
||||
|
||||
$this->assertSame(['custom.home.1'], $this->scanner->collectReferencedKeys($content));
|
||||
}
|
||||
|
||||
public function test_collects_from_expression_substring(): void
|
||||
{
|
||||
// 코드 편집기 경유 표현식/문자열 안에 섞인 참조도 보수적으로 수집.
|
||||
$content = [
|
||||
['text' => '{{ flag ? "$t:custom.home.5" : "plain" }}'],
|
||||
];
|
||||
|
||||
$this->assertSame(['custom.home.5'], $this->scanner->collectReferencedKeys($content));
|
||||
}
|
||||
|
||||
public function test_returns_empty_for_no_custom_keys(): void
|
||||
{
|
||||
$content = [
|
||||
['type' => 'Div', 'children' => [['text' => 'hello'], ['text' => '$t:common.ok']]],
|
||||
];
|
||||
|
||||
$this->assertSame([], $this->scanner->collectReferencedKeys($content));
|
||||
}
|
||||
|
||||
public function test_handles_empty_and_scalar_content(): void
|
||||
{
|
||||
$this->assertSame([], $this->scanner->collectReferencedKeys([]));
|
||||
$this->assertSame([], $this->scanner->collectReferencedKeys(''));
|
||||
$this->assertSame([], $this->scanner->collectReferencedKeys('plain text without keys'));
|
||||
// 단일 문자열도 보수적으로 스캔된다 (코드 편집기 경유 참조 보존):
|
||||
$this->assertSame(['custom.home.1'], $this->scanner->collectReferencedKeys('$t:custom.home.1'));
|
||||
$this->assertSame(
|
||||
['custom.home.1'],
|
||||
$this->scanner->collectReferencedKeys('prefix $t:custom.home.1 suffix'),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_normalize_layout_key_matches_service_format(): void
|
||||
{
|
||||
$this->assertSame('board_list', CustomTranslationUsageScanner::normalizeLayoutKey('board/list'));
|
||||
$this->assertSame('home', CustomTranslationUsageScanner::normalizeLayoutKey('home'));
|
||||
$this->assertSame('a_b', CustomTranslationUsageScanner::normalizeLayoutKey('a b'));
|
||||
$this->assertSame('layout', CustomTranslationUsageScanner::normalizeLayoutKey(''));
|
||||
$this->assertSame('shopproduct', CustomTranslationUsageScanner::normalizeLayoutKey('shop@product'));
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,17 @@ namespace Tests\Unit\Services;
|
||||
|
||||
use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
use App\Contracts\Extension\TemplateManagerInterface;
|
||||
use App\Contracts\Repositories\ActivityLogRepositoryInterface;
|
||||
use App\Contracts\Repositories\LanguagePackRepositoryInterface;
|
||||
use App\Contracts\Repositories\NotificationLogRepositoryInterface;
|
||||
use App\Contracts\Repositories\UserRepositoryInterface;
|
||||
use App\Enums\ActivityLogType;
|
||||
use App\Enums\NotificationLogStatus;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Models\NotificationLog;
|
||||
use App\Services\DashboardService;
|
||||
use App\Services\LanguagePackService;
|
||||
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Mockery;
|
||||
@@ -29,6 +37,14 @@ class DashboardServiceTest extends TestCase
|
||||
|
||||
private $pluginManager;
|
||||
|
||||
private $notificationLogRepository;
|
||||
|
||||
private $templateManager;
|
||||
|
||||
private $languagePackRepository;
|
||||
|
||||
private $languagePackService;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
@@ -37,13 +53,24 @@ class DashboardServiceTest extends TestCase
|
||||
$this->activityLogRepository = Mockery::mock(ActivityLogRepositoryInterface::class);
|
||||
$this->moduleManager = Mockery::mock(ModuleManagerInterface::class);
|
||||
$this->pluginManager = Mockery::mock(PluginManagerInterface::class);
|
||||
$this->notificationLogRepository = Mockery::mock(NotificationLogRepositoryInterface::class);
|
||||
$this->templateManager = Mockery::mock(TemplateManagerInterface::class);
|
||||
$this->languagePackRepository = Mockery::mock(LanguagePackRepositoryInterface::class);
|
||||
$this->languagePackService = Mockery::mock(LanguagePackService::class);
|
||||
|
||||
$this->service = new DashboardService(
|
||||
$this->userRepository,
|
||||
$this->activityLogRepository,
|
||||
$this->moduleManager,
|
||||
$this->pluginManager
|
||||
$this->pluginManager,
|
||||
$this->notificationLogRepository,
|
||||
$this->templateManager,
|
||||
$this->languagePackRepository,
|
||||
$this->languagePackService
|
||||
);
|
||||
|
||||
// getStats() 가 항상 호출하는 템플릿/언어팩 의존성의 기본 mock (개별 테스트에서 재정의 가능).
|
||||
$this->mockTemplatesAndPacks();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -78,6 +105,32 @@ class DashboardServiceTest extends TestCase
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn($active);
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿/언어팩 mock을 설정합니다.
|
||||
*
|
||||
* @param array $allTemplates 전체 템플릿 목록
|
||||
* @param array<string, bool> $activeByType 타입별 활성 여부 (admin/user)
|
||||
* @param int $activePacks 활성 언어팩 수
|
||||
* @param int $uninstalledBundledPacks 미설치 번들 언어팩 수
|
||||
*/
|
||||
private function mockTemplatesAndPacks(
|
||||
array $allTemplates = [],
|
||||
array $activeByType = ['admin' => false, 'user' => false],
|
||||
int $activePacks = 0,
|
||||
int $uninstalledBundledPacks = 0,
|
||||
): void {
|
||||
// byDefault() — setUp 의 기본 mock 을 개별 테스트가 재호출로 덮어쓸 수 있게 한다.
|
||||
$this->templateManager->shouldReceive('getAllTemplates')->andReturn($allTemplates)->byDefault();
|
||||
foreach (['admin', 'user'] as $type) {
|
||||
$this->templateManager->shouldReceive('getActiveTemplate')->with($type)
|
||||
->andReturn(($activeByType[$type] ?? false) ? ['identifier' => "tpl-{$type}"] : null)->byDefault();
|
||||
}
|
||||
$this->languagePackRepository->shouldReceive('getActivePacks')
|
||||
->andReturn(new EloquentCollection(array_fill(0, $activePacks, (object) [])))->byDefault();
|
||||
$this->languagePackService->shouldReceive('getUninstalledBundledPacks')
|
||||
->andReturn(collect(array_fill(0, $uninstalledBundledPacks, (object) [])))->byDefault();
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// getStats 테스트
|
||||
// ========================================================================
|
||||
@@ -99,9 +152,42 @@ class DashboardServiceTest extends TestCase
|
||||
$this->assertArrayHasKey('total_users', $stats);
|
||||
$this->assertArrayHasKey('installed_modules', $stats);
|
||||
$this->assertArrayHasKey('active_plugins', $stats);
|
||||
$this->assertArrayHasKey('installed_templates', $stats);
|
||||
$this->assertArrayHasKey('language_packs', $stats);
|
||||
$this->assertArrayHasKey('system_status', $stats);
|
||||
}
|
||||
|
||||
public function test_get_stats_returns_template_counts(): void
|
||||
{
|
||||
$this->mockUserStatistics();
|
||||
$this->mockModules();
|
||||
$this->mockPlugins();
|
||||
// 전체 템플릿 2개, admin/user 둘 다 활성 → 2/2
|
||||
$this->mockTemplatesAndPacks(
|
||||
allTemplates: [['identifier' => 'a'], ['identifier' => 'b']],
|
||||
activeByType: ['admin' => true, 'user' => true],
|
||||
);
|
||||
|
||||
$stats = $this->service->getStats();
|
||||
|
||||
$this->assertSame(2, $stats['installed_templates']['total']);
|
||||
$this->assertSame(2, $stats['installed_templates']['active']);
|
||||
}
|
||||
|
||||
public function test_get_stats_returns_language_pack_counts(): void
|
||||
{
|
||||
$this->mockUserStatistics();
|
||||
$this->mockModules();
|
||||
$this->mockPlugins();
|
||||
// 활성 14, 미설치 번들 4 → 활성 14 / 전체 18
|
||||
$this->mockTemplatesAndPacks(activePacks: 14, uninstalledBundledPacks: 4);
|
||||
|
||||
$stats = $this->service->getStats();
|
||||
|
||||
$this->assertSame(14, $stats['language_packs']['active']);
|
||||
$this->assertSame(18, $stats['language_packs']['total']);
|
||||
}
|
||||
|
||||
public function test_get_stats_calculates_change_percent_correctly_when_increased(): void
|
||||
{
|
||||
// 전체 100명, 이번달 20명 가입 → 전월 80명 대비 25% 증가
|
||||
@@ -191,6 +277,10 @@ class DashboardServiceTest extends TestCase
|
||||
$this->activityLogRepository,
|
||||
$this->moduleManager,
|
||||
$this->pluginManager,
|
||||
$this->notificationLogRepository,
|
||||
$this->templateManager,
|
||||
$this->languagePackRepository,
|
||||
$this->languagePackService,
|
||||
])->makePartial()->shouldAllowMockingProtectedMethods();
|
||||
|
||||
// CPU 조회 모킹 (실제 시스템 명령 호출 방지)
|
||||
@@ -261,6 +351,111 @@ class DashboardServiceTest extends TestCase
|
||||
$this->assertArrayHasKey('color', $resources['disk']);
|
||||
}
|
||||
|
||||
/**
|
||||
* probe 1개가 예외를 던지고 나머지는 정상값을 반환하는 부분 모킹 서비스를 생성합니다 (공개#40).
|
||||
*
|
||||
* @param string $throwingProbe 예외를 던질 probe 메서드명 (getCpuUsage|getMemoryUsage|getDiskUsage)
|
||||
* @return DashboardService 부분 모킹 서비스
|
||||
*/
|
||||
private function createPartiallyFailingResourceService(string $throwingProbe): DashboardService
|
||||
{
|
||||
$service = Mockery::mock(DashboardService::class, [
|
||||
$this->userRepository,
|
||||
$this->activityLogRepository,
|
||||
$this->moduleManager,
|
||||
$this->pluginManager,
|
||||
$this->notificationLogRepository,
|
||||
$this->templateManager,
|
||||
$this->languagePackRepository,
|
||||
$this->languagePackService,
|
||||
])->makePartial()->shouldAllowMockingProtectedMethods();
|
||||
|
||||
$normal = [
|
||||
'getCpuUsage' => ['percentage' => 45, 'color' => 'green'],
|
||||
'getMemoryUsage' => ['percentage' => 60, 'used' => '8.5 GB', 'total' => '16 GB', 'color' => 'blue'],
|
||||
'getDiskUsage' => ['percentage' => 75, 'used' => '300 GB', 'total' => '500 GB', 'color' => 'yellow'],
|
||||
];
|
||||
|
||||
foreach ($normal as $probe => $value) {
|
||||
if ($probe === $throwingProbe) {
|
||||
$service->shouldReceive($probe)->andThrow(new \ErrorException('open_basedir restriction in effect'));
|
||||
} else {
|
||||
$service->shouldReceive($probe)->andReturn($value);
|
||||
}
|
||||
}
|
||||
|
||||
return $service;
|
||||
}
|
||||
|
||||
public function test_get_system_resources_isolates_failing_cpu_probe(): void
|
||||
{
|
||||
$service = $this->createPartiallyFailingResourceService('getCpuUsage');
|
||||
|
||||
$resources = $service->getSystemResources();
|
||||
|
||||
// cpu 는 폴백, 나머지는 정상값 — 예외 비전파.
|
||||
$this->assertSame(0, $resources['cpu']['percentage']);
|
||||
$this->assertSame('gray', $resources['cpu']['color']);
|
||||
$this->assertSame(60, $resources['memory']['percentage']);
|
||||
$this->assertSame(75, $resources['disk']['percentage']);
|
||||
}
|
||||
|
||||
public function test_get_system_resources_isolates_failing_memory_probe(): void
|
||||
{
|
||||
$service = $this->createPartiallyFailingResourceService('getMemoryUsage');
|
||||
|
||||
$resources = $service->getSystemResources();
|
||||
|
||||
$this->assertSame(0, $resources['memory']['percentage']);
|
||||
$this->assertSame('gray', $resources['memory']['color']);
|
||||
$this->assertSame(__('common.unknown'), $resources['memory']['used']);
|
||||
$this->assertSame(__('common.unknown'), $resources['memory']['total']);
|
||||
$this->assertSame(45, $resources['cpu']['percentage']);
|
||||
$this->assertSame(75, $resources['disk']['percentage']);
|
||||
}
|
||||
|
||||
public function test_get_system_resources_isolates_failing_disk_probe(): void
|
||||
{
|
||||
$service = $this->createPartiallyFailingResourceService('getDiskUsage');
|
||||
|
||||
$resources = $service->getSystemResources();
|
||||
|
||||
$this->assertSame(0, $resources['disk']['percentage']);
|
||||
$this->assertSame('gray', $resources['disk']['color']);
|
||||
$this->assertSame(__('common.unknown'), $resources['disk']['used']);
|
||||
$this->assertSame(45, $resources['cpu']['percentage']);
|
||||
$this->assertSame(60, $resources['memory']['percentage']);
|
||||
}
|
||||
|
||||
public function test_get_system_resources_all_probes_fail_returns_fallback_structure(): void
|
||||
{
|
||||
$service = Mockery::mock(DashboardService::class, [
|
||||
$this->userRepository,
|
||||
$this->activityLogRepository,
|
||||
$this->moduleManager,
|
||||
$this->pluginManager,
|
||||
$this->notificationLogRepository,
|
||||
$this->templateManager,
|
||||
$this->languagePackRepository,
|
||||
$this->languagePackService,
|
||||
])->makePartial()->shouldAllowMockingProtectedMethods();
|
||||
|
||||
foreach (['getCpuUsage', 'getMemoryUsage', 'getDiskUsage'] as $probe) {
|
||||
$service->shouldReceive($probe)->andThrow(new \ErrorException('open_basedir'));
|
||||
}
|
||||
|
||||
$resources = $service->getSystemResources();
|
||||
|
||||
// 키 구조 유지 + 폴백값 — 예외 비전파.
|
||||
$this->assertArrayHasKey('cpu', $resources);
|
||||
$this->assertArrayHasKey('memory', $resources);
|
||||
$this->assertArrayHasKey('disk', $resources);
|
||||
$this->assertSame('gray', $resources['cpu']['color']);
|
||||
$this->assertSame('gray', $resources['memory']['color']);
|
||||
$this->assertSame('gray', $resources['disk']['color']);
|
||||
$this->assertSame(0, $resources['cpu']['percentage']);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// getRecentActivities 테스트
|
||||
// ========================================================================
|
||||
@@ -278,8 +473,8 @@ class DashboardServiceTest extends TestCase
|
||||
|
||||
public function test_get_recent_activities_formats_user_registration(): void
|
||||
{
|
||||
$mockLog = Mockery::mock(\App\Models\ActivityLog::class)->makePartial();
|
||||
$mockLog->shouldReceive('getAttribute')->with('log_type')->andReturn(\App\Enums\ActivityLogType::User);
|
||||
$mockLog = Mockery::mock(ActivityLog::class)->makePartial();
|
||||
$mockLog->shouldReceive('getAttribute')->with('log_type')->andReturn(ActivityLogType::User);
|
||||
$mockLog->shouldReceive('getAttribute')->with('action')->andReturn('register');
|
||||
$mockLog->shouldReceive('getAttribute')->with('localized_description')->andReturn('테스트 유저가 가입했습니다');
|
||||
$mockLog->shouldReceive('getAttribute')->with('actor_name')->andReturn('Test User');
|
||||
@@ -343,6 +538,36 @@ class DashboardServiceTest extends TestCase
|
||||
$this->assertIsArray($alerts);
|
||||
}
|
||||
|
||||
public function test_get_recent_notification_logs_maps_display_fields(): void
|
||||
{
|
||||
$log = new NotificationLog([
|
||||
'channel' => 'mail',
|
||||
'notification_type' => 'order_confirmed',
|
||||
'recipient_name' => '홍길동',
|
||||
'recipient_identifier' => 'test@example.com',
|
||||
'subject' => '주문이 확인되었습니다',
|
||||
'status' => NotificationLogStatus::Sent,
|
||||
'sent_at' => now(),
|
||||
]);
|
||||
$log->id = 1;
|
||||
$log->setRelation('recipientUser', null);
|
||||
|
||||
$this->notificationLogRepository
|
||||
->shouldReceive('getRecent')
|
||||
->once()
|
||||
->with(5)
|
||||
->andReturn(new EloquentCollection([$log]));
|
||||
|
||||
$result = $this->service->getRecentNotificationLogs(5);
|
||||
|
||||
$this->assertCount(1, $result);
|
||||
$this->assertSame(1, $result[0]['id']);
|
||||
$this->assertSame('order_confirmed', $result[0]['type']);
|
||||
$this->assertSame('mail', $result[0]['channel']);
|
||||
$this->assertSame('홍길동', $result[0]['recipient']);
|
||||
$this->assertSame('sent', $result[0]['status']);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Mockery::close();
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
namespace Tests\Unit\Services;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Services\GeoIpService;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Tests\TestCase;
|
||||
|
||||
class GeoIpServiceTest extends TestCase
|
||||
@@ -137,7 +137,7 @@ class GeoIpServiceTest extends TestCase
|
||||
config(['geoip.cache.ttl' => 3600]);
|
||||
|
||||
// CacheInterface 경유 — 실제 사용 키는 'geoip.timezone.'.{ip}
|
||||
$cache = app(\App\Contracts\Extension\CacheInterface::class);
|
||||
$cache = app(CacheInterface::class);
|
||||
$cacheKey = 'geoip.timezone.8.8.8.8';
|
||||
$cache->forget($cacheKey);
|
||||
|
||||
@@ -261,4 +261,154 @@ class GeoIpServiceTest extends TestCase
|
||||
|
||||
$this->assertNull($result);
|
||||
}
|
||||
|
||||
// ───────────────────────────────────────────────
|
||||
// getCountryByIp — 국가 코드 조회 (MP08 유저별 배송국가)
|
||||
// ───────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* GeoIP 비활성화 시 국가 조회가 null을 반환하는지 테스트합니다.
|
||||
*/
|
||||
public function test_country_returns_null_when_disabled(): void
|
||||
{
|
||||
config(['geoip.enabled' => false]);
|
||||
|
||||
$this->assertNull($this->geoIpService->getCountryByIp('8.8.8.8'));
|
||||
}
|
||||
|
||||
/**
|
||||
* mmdb 파일이 없을 때 국가 조회가 null을 반환하는지 테스트합니다.
|
||||
*/
|
||||
public function test_country_returns_null_when_database_file_missing(): void
|
||||
{
|
||||
config(['geoip.enabled' => true]);
|
||||
config(['geoip.database_path' => storage_path('app/geoip/nonexistent.mmdb')]);
|
||||
config(['geoip.cache.enabled' => false]);
|
||||
|
||||
$service = app(GeoIpService::class);
|
||||
|
||||
$this->assertNull($service->getCountryByIp('8.8.8.8'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 미국 IP가 대문자 국가 코드(US)를 반환하는지 테스트합니다.
|
||||
*/
|
||||
public function test_country_us_ip_returns_us(): 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 = app(GeoIpService::class);
|
||||
|
||||
// Google DNS (미국)
|
||||
$result = $service->getCountryByIp('8.8.8.8');
|
||||
|
||||
$this->assertSame('US', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 한국 IP가 대문자 국가 코드(KR)를 반환하는지 테스트합니다.
|
||||
*/
|
||||
public function test_country_korean_ip_returns_kr(): 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 = app(GeoIpService::class);
|
||||
|
||||
// KT DNS (한국)
|
||||
$result = $service->getCountryByIp('168.126.63.1');
|
||||
|
||||
$this->assertSame('KR', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 프라이빗 IP는 국가 조회가 null을 반환하는지 테스트합니다.
|
||||
*/
|
||||
public function test_country_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 = app(GeoIpService::class);
|
||||
|
||||
$this->assertNull($service->getCountryByIp('192.168.1.1'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 국가 조회 캐싱이 별도 키(geoip.country.*)로 동작하는지 테스트합니다.
|
||||
*/
|
||||
public function test_country_caching_uses_separate_key(): 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.ttl' => 3600]);
|
||||
|
||||
// 타임존 캐시와 분리된 키 — 'geoip.country.'.{ip}
|
||||
$cache = app(CacheInterface::class);
|
||||
$cacheKey = 'geoip.country.8.8.8.8';
|
||||
$cache->forget($cacheKey);
|
||||
|
||||
$service = app(GeoIpService::class);
|
||||
|
||||
$result1 = $service->getCountryByIp('8.8.8.8');
|
||||
|
||||
// 캐시에 저장되었는지 확인 (빈 문자열이어도 저장됨 — 음성 캐시)
|
||||
$cached = $cache->get($cacheKey);
|
||||
$this->assertNotNull($cached);
|
||||
|
||||
// 두 번째 조회 (캐시 히트)
|
||||
$result2 = $service->getCountryByIp('8.8.8.8');
|
||||
$this->assertSame($result1, $result2);
|
||||
|
||||
$cache->forget($cacheKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* 조회 실패 시 음성 캐시(빈 문자열)가 저장되어 null로 해석되는지 테스트합니다.
|
||||
*/
|
||||
public function test_country_negative_cache_resolves_to_null(): void
|
||||
{
|
||||
config(['geoip.enabled' => true]);
|
||||
config(['geoip.cache.enabled' => true]);
|
||||
|
||||
// 음성 캐시(빈 문자열)를 미리 주입 → DB 조회 없이 null 반환
|
||||
$cache = app(CacheInterface::class);
|
||||
$cacheKey = 'geoip.country.203.0.113.7';
|
||||
$cache->put($cacheKey, '', 3600);
|
||||
|
||||
$service = app(GeoIpService::class);
|
||||
|
||||
$this->assertNull($service->getCountryByIp('203.0.113.7'));
|
||||
|
||||
$cache->forget($cacheKey);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services;
|
||||
|
||||
use App\Contracts\Extension\IdentityVerificationInterface;
|
||||
use App\Contracts\Repositories\IdentityPolicyRepositoryInterface;
|
||||
use App\Contracts\Repositories\IdentityVerificationLogRepositoryInterface;
|
||||
use App\Extension\IdentityVerification\IdentityVerificationManager;
|
||||
use App\Models\IdentityPolicy;
|
||||
use App\Services\IdentityPolicyService;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* IdentityPolicyService::resolveProviderId 의 fallback 분기 회귀 차단.
|
||||
*
|
||||
* 이슈 #275 — 정책 DB 의 provider_id 가 NULL 인 경우 enforce() 가 던지는 428 응답의
|
||||
* verification.provider_id 가 그대로 NULL 로 흘러가 launcher 가 외부 plugin Extension Point
|
||||
* 슬롯과 매칭 못해 빈 모달이 표시되던 결함을 차단한다.
|
||||
*
|
||||
* 본 테스트는 두 가지 분기를 검증한다:
|
||||
* (1) 정책의 provider_id 가 등록된 provider id 면 그대로 반환
|
||||
* (2) 정책의 provider_id 가 NULL 또는 미등록이면 Manager 의 purpose 기반 fallback 체인을 따름
|
||||
*
|
||||
* resolveProviderId 는 Service::enforce() 가 throw 할 때 IdentityVerificationRequiredException
|
||||
* 의 providerId 인자로 전달되는 값을 결정하므로, 본 회귀 차단이 통과해야 admin UI 의
|
||||
* default_provider 환경설정이 모달 launcher 까지 정상 전달된다.
|
||||
*/
|
||||
class IdentityPolicyServiceResolveProviderIdTest extends TestCase
|
||||
{
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Mockery::close();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_returns_policy_provider_id_when_registered(): void
|
||||
{
|
||||
$policyRepo = Mockery::mock(IdentityPolicyRepositoryInterface::class);
|
||||
$logRepo = Mockery::mock(IdentityVerificationLogRepositoryInterface::class);
|
||||
|
||||
$manager = Mockery::mock(IdentityVerificationManager::class);
|
||||
// 등록된 provider 면 그대로 반환 — Manager fallback 진입 없음
|
||||
$manager->shouldReceive('has')->with('inicis')->andReturn(true);
|
||||
$manager->shouldNotReceive('resolveForPurpose');
|
||||
|
||||
$service = new IdentityPolicyService($policyRepo, $logRepo, $manager);
|
||||
|
||||
$policy = new IdentityPolicy([
|
||||
'purpose' => 'signup',
|
||||
'provider_id' => 'inicis',
|
||||
]);
|
||||
|
||||
$this->assertSame('inicis', $this->invokeResolveProviderId($service, $policy));
|
||||
}
|
||||
|
||||
public function test_falls_back_to_manager_when_policy_provider_id_is_null(): void
|
||||
{
|
||||
$policyRepo = Mockery::mock(IdentityPolicyRepositoryInterface::class);
|
||||
$logRepo = Mockery::mock(IdentityVerificationLogRepositoryInterface::class);
|
||||
|
||||
$resolvedProvider = Mockery::mock(IdentityVerificationInterface::class);
|
||||
$resolvedProvider->shouldReceive('getId')->andReturn('inicis');
|
||||
|
||||
$manager = Mockery::mock(IdentityVerificationManager::class);
|
||||
// 정책 provider_id 가 NULL → 즉시 fallback 분기
|
||||
$manager->shouldReceive('resolveForPurpose')
|
||||
->once()
|
||||
->with('signup', null)
|
||||
->andReturn($resolvedProvider);
|
||||
|
||||
$service = new IdentityPolicyService($policyRepo, $logRepo, $manager);
|
||||
|
||||
$policy = new IdentityPolicy([
|
||||
'purpose' => 'signup',
|
||||
'provider_id' => null,
|
||||
]);
|
||||
|
||||
$this->assertSame('inicis', $this->invokeResolveProviderId($service, $policy));
|
||||
}
|
||||
|
||||
public function test_falls_back_to_manager_when_policy_provider_unregistered(): void
|
||||
{
|
||||
$policyRepo = Mockery::mock(IdentityPolicyRepositoryInterface::class);
|
||||
$logRepo = Mockery::mock(IdentityVerificationLogRepositoryInterface::class);
|
||||
|
||||
$resolvedProvider = Mockery::mock(IdentityVerificationInterface::class);
|
||||
$resolvedProvider->shouldReceive('getId')->andReturn('g7:core.mail');
|
||||
|
||||
$manager = Mockery::mock(IdentityVerificationManager::class);
|
||||
// 정책 provider 가 비활성/언인스톨된 경우 — has()=false → fallback 진입
|
||||
$manager->shouldReceive('has')->with('plugin:disabled')->andReturn(false);
|
||||
// 핵심 회귀 차단: 정책의 provider_id 를 Manager 의 0번 우선순위로 전달
|
||||
$manager->shouldReceive('resolveForPurpose')
|
||||
->once()
|
||||
->with('signup', 'plugin:disabled')
|
||||
->andReturn($resolvedProvider);
|
||||
|
||||
$service = new IdentityPolicyService($policyRepo, $logRepo, $manager);
|
||||
|
||||
$policy = new IdentityPolicy([
|
||||
'purpose' => 'signup',
|
||||
'provider_id' => 'plugin:disabled',
|
||||
]);
|
||||
|
||||
$this->assertSame('g7:core.mail', $this->invokeResolveProviderId($service, $policy));
|
||||
}
|
||||
|
||||
public function test_returns_original_provider_id_when_manager_throws(): void
|
||||
{
|
||||
$policyRepo = Mockery::mock(IdentityPolicyRepositoryInterface::class);
|
||||
$logRepo = Mockery::mock(IdentityVerificationLogRepositoryInterface::class);
|
||||
|
||||
$manager = Mockery::mock(IdentityVerificationManager::class);
|
||||
$manager->shouldReceive('resolveForPurpose')
|
||||
->andThrow(new \InvalidArgumentException('No provider supports purpose'));
|
||||
|
||||
$service = new IdentityPolicyService($policyRepo, $logRepo, $manager);
|
||||
|
||||
$policy = new IdentityPolicy([
|
||||
'purpose' => 'unknown',
|
||||
'provider_id' => 'legacy-id',
|
||||
]);
|
||||
|
||||
// Manager 예외 발생 시 정책의 원본 provider_id 를 그대로 반환 (정책 정보 보존)
|
||||
$this->assertSame('legacy-id', $this->invokeResolveProviderId($service, $policy));
|
||||
}
|
||||
|
||||
private function invokeResolveProviderId(IdentityPolicyService $service, IdentityPolicy $policy): ?string
|
||||
{
|
||||
$reflection = new \ReflectionMethod($service, 'resolveProviderId');
|
||||
$reflection->setAccessible(true);
|
||||
|
||||
return $reflection->invoke($service, $policy);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services;
|
||||
|
||||
use App\Contracts\Repositories\IdentityVerificationLogRepositoryInterface;
|
||||
use App\Contracts\Repositories\UserRepositoryInterface;
|
||||
use App\Extension\HookManager;
|
||||
use App\Extension\IdentityVerification\IdentityVerificationManager;
|
||||
use App\Extension\IdentityVerification\Providers\MailIdentityProvider;
|
||||
use App\Models\IdentityVerificationLog;
|
||||
use App\Services\IdentityVerificationService;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* IdentityVerificationService 의 라이프사이클 hook pair 회귀 차단.
|
||||
*
|
||||
* 이슈 #275 — cancel()/consumeToken() 메서드가 start/verify 와 달리 before/after hook 을
|
||||
* 발행하지 않아 외부 plugin 이 cancel 시점/token 소비 시점에 자기 record 정리 listener 를
|
||||
* 등록할 수 없었던 결함을 차단한다.
|
||||
*
|
||||
* 모든 Service 라이프사이클 메서드는 일관된 before_X / after_X hook pair 를 발행해야 한다.
|
||||
*/
|
||||
class IdentityVerificationServiceHookPairsTest extends TestCase
|
||||
{
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Mockery::close();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_cancel_dispatches_before_and_after_hooks_on_success(): void
|
||||
{
|
||||
$fired = [];
|
||||
|
||||
HookManager::addAction('core.identity.before_cancel', function (...$args) use (&$fired) {
|
||||
$fired[] = ['name' => 'before_cancel', 'args' => $args];
|
||||
});
|
||||
HookManager::addAction('core.identity.after_cancel', function (...$args) use (&$fired) {
|
||||
$fired[] = ['name' => 'after_cancel', 'args' => $args];
|
||||
});
|
||||
|
||||
$log = new IdentityVerificationLog([
|
||||
'id' => 'challenge-uuid',
|
||||
'provider_id' => 'g7:core.mail',
|
||||
]);
|
||||
$log->setRawAttributes(array_merge($log->getAttributes(), ['id' => 'challenge-uuid']), true);
|
||||
|
||||
$logRepo = Mockery::mock(IdentityVerificationLogRepositoryInterface::class);
|
||||
$logRepo->shouldReceive('findById')->with('challenge-uuid')->andReturn($log);
|
||||
|
||||
$userRepo = Mockery::mock(UserRepositoryInterface::class);
|
||||
|
||||
$provider = Mockery::mock(MailIdentityProvider::class);
|
||||
$provider->shouldReceive('cancel')->with('challenge-uuid')->andReturn(true);
|
||||
|
||||
$manager = Mockery::mock(IdentityVerificationManager::class);
|
||||
$manager->shouldReceive('get')->with('g7:core.mail')->andReturn($provider);
|
||||
|
||||
$service = new IdentityVerificationService($manager, $logRepo, $userRepo);
|
||||
|
||||
$result = $service->cancel('challenge-uuid');
|
||||
|
||||
$this->assertTrue($result);
|
||||
$this->assertCount(2, $fired);
|
||||
$this->assertSame('before_cancel', $fired[0]['name']);
|
||||
$this->assertSame('challenge-uuid', $fired[0]['args'][0]);
|
||||
$this->assertSame('after_cancel', $fired[1]['name']);
|
||||
$this->assertSame('challenge-uuid', $fired[1]['args'][0]);
|
||||
$this->assertTrue($fired[1]['args'][2]);
|
||||
}
|
||||
|
||||
public function test_cancel_dispatches_after_hook_with_false_when_log_missing(): void
|
||||
{
|
||||
$fired = [];
|
||||
|
||||
HookManager::addAction('core.identity.before_cancel', function (...$args) use (&$fired) {
|
||||
$fired[] = ['name' => 'before_cancel', 'args' => $args];
|
||||
});
|
||||
HookManager::addAction('core.identity.after_cancel', function (...$args) use (&$fired) {
|
||||
$fired[] = ['name' => 'after_cancel', 'args' => $args];
|
||||
});
|
||||
|
||||
$logRepo = Mockery::mock(IdentityVerificationLogRepositoryInterface::class);
|
||||
$logRepo->shouldReceive('findById')->andReturn(null);
|
||||
|
||||
$userRepo = Mockery::mock(UserRepositoryInterface::class);
|
||||
$manager = Mockery::mock(IdentityVerificationManager::class);
|
||||
|
||||
$service = new IdentityVerificationService($manager, $logRepo, $userRepo);
|
||||
|
||||
$result = $service->cancel('missing-uuid');
|
||||
|
||||
$this->assertFalse($result);
|
||||
$this->assertCount(2, $fired);
|
||||
$this->assertSame('before_cancel', $fired[0]['name']);
|
||||
$this->assertNull($fired[0]['args'][1], 'before_cancel 의 두 번째 인자는 log 가 없을 때 null');
|
||||
$this->assertSame('after_cancel', $fired[1]['name']);
|
||||
$this->assertFalse($fired[1]['args'][2]);
|
||||
}
|
||||
|
||||
public function test_consume_token_dispatches_before_and_after_hooks_on_success(): void
|
||||
{
|
||||
$fired = [];
|
||||
|
||||
HookManager::addAction('core.identity.before_consume_token', function (...$args) use (&$fired) {
|
||||
$fired[] = ['name' => 'before_consume_token', 'args' => $args];
|
||||
});
|
||||
HookManager::addAction('core.identity.after_consume_token', function (...$args) use (&$fired) {
|
||||
$fired[] = ['name' => 'after_consume_token', 'args' => $args];
|
||||
});
|
||||
|
||||
$log = new IdentityVerificationLog(['id' => 'log-uuid']);
|
||||
|
||||
$logRepo = Mockery::mock(IdentityVerificationLogRepositoryInterface::class);
|
||||
$logRepo->shouldReceive('findVerifiedForToken')
|
||||
->with('token-abc', 'signup')
|
||||
->andReturn($log);
|
||||
$logRepo->shouldReceive('updateById')
|
||||
->with(Mockery::any(), Mockery::on(fn ($attrs) => isset($attrs['consumed_at'])))
|
||||
->andReturn(true);
|
||||
|
||||
$userRepo = Mockery::mock(UserRepositoryInterface::class);
|
||||
$manager = Mockery::mock(IdentityVerificationManager::class);
|
||||
|
||||
$service = new IdentityVerificationService($manager, $logRepo, $userRepo);
|
||||
|
||||
$result = $service->consumeToken('token-abc');
|
||||
|
||||
$this->assertTrue($result);
|
||||
$this->assertCount(2, $fired);
|
||||
$this->assertSame('before_consume_token', $fired[0]['name']);
|
||||
$this->assertSame('token-abc', $fired[0]['args'][0]);
|
||||
$this->assertSame('after_consume_token', $fired[1]['name']);
|
||||
$this->assertTrue($fired[1]['args'][2]);
|
||||
}
|
||||
|
||||
public function test_consume_token_dispatches_after_hook_with_false_when_log_missing(): void
|
||||
{
|
||||
$fired = [];
|
||||
|
||||
HookManager::addAction('core.identity.before_consume_token', function (...$args) use (&$fired) {
|
||||
$fired[] = ['name' => 'before_consume_token', 'args' => $args];
|
||||
});
|
||||
HookManager::addAction('core.identity.after_consume_token', function (...$args) use (&$fired) {
|
||||
$fired[] = ['name' => 'after_consume_token', 'args' => $args];
|
||||
});
|
||||
|
||||
$logRepo = Mockery::mock(IdentityVerificationLogRepositoryInterface::class);
|
||||
$logRepo->shouldReceive('findVerifiedForToken')->andReturn(null);
|
||||
|
||||
$userRepo = Mockery::mock(UserRepositoryInterface::class);
|
||||
$manager = Mockery::mock(IdentityVerificationManager::class);
|
||||
|
||||
$service = new IdentityVerificationService($manager, $logRepo, $userRepo);
|
||||
|
||||
$result = $service->consumeToken('missing-token');
|
||||
|
||||
$this->assertFalse($result);
|
||||
$this->assertCount(2, $fired);
|
||||
$this->assertNull($fired[0]['args'][1]);
|
||||
$this->assertFalse($fired[1]['args'][2]);
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,6 @@ class LanguagePackSeedInjectorTest extends TestCase
|
||||
*
|
||||
* @param string $entity 엔티티 이름 (permissions/roles/menus/notifications)
|
||||
* @param array<string, mixed> $seedData seed 데이터
|
||||
* @return void
|
||||
*/
|
||||
private function setupCorePackWithSeed(string $entity, array $seedData): void
|
||||
{
|
||||
@@ -299,4 +298,133 @@ class LanguagePackSeedInjectorTest extends TestCase
|
||||
File::deleteDirectory($packRoot);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* manifest seed(name/description)를 활성 ja 팩 locale 로 주입하고 ko/en 을 보존합니다.
|
||||
*
|
||||
* @param string $scope module|plugin|template
|
||||
*/
|
||||
private function setupExtensionManifestPack(string $scope, string $target, array $seed): string
|
||||
{
|
||||
$packRoot = base_path("lang-packs/g7-{$scope}-{$target}-ja");
|
||||
File::ensureDirectoryExists($packRoot.'/seed');
|
||||
File::put($packRoot.'/seed/manifest.json', json_encode($seed));
|
||||
|
||||
LanguagePack::query()->create([
|
||||
'identifier' => "g7-{$scope}-{$target}-ja",
|
||||
'vendor' => 'g7',
|
||||
'scope' => $scope,
|
||||
'target_identifier' => $target,
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'Japanese',
|
||||
'locale_native_name' => '日本語',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => LanguagePackStatus::Active->value,
|
||||
'is_protected' => false,
|
||||
'manifest' => [],
|
||||
'source_type' => 'bundled',
|
||||
]);
|
||||
$this->registry->invalidate();
|
||||
|
||||
return $packRoot;
|
||||
}
|
||||
|
||||
public function test_inject_extension_manifest_adds_ja_and_preserves_ko_en(): void
|
||||
{
|
||||
$packRoot = $this->setupExtensionManifestPack('plugin', 'sirsoft-gdpr', [
|
||||
'name' => 'GDPR (一般データ保護規則)',
|
||||
'description' => 'クッキー同意バナーを提供します。',
|
||||
]);
|
||||
|
||||
try {
|
||||
$manifest = [
|
||||
'name' => ['ko' => 'GDPR', 'en' => 'GDPR'],
|
||||
'description' => ['ko' => '쿠키 동의 배너', 'en' => 'Cookie consent banner'],
|
||||
];
|
||||
|
||||
$result = $this->injector->injectExtensionManifest($manifest, 'sirsoft-gdpr', LanguagePackScope::Plugin->value);
|
||||
|
||||
$this->assertSame('GDPR (一般データ保護規則)', $result['name']['ja']);
|
||||
$this->assertSame('クッキー同意バナーを提供します。', $result['description']['ja']);
|
||||
// ko/en 보존
|
||||
$this->assertSame('GDPR', $result['name']['ko']);
|
||||
$this->assertSame('Cookie consent banner', $result['description']['en']);
|
||||
} finally {
|
||||
File::deleteDirectory($packRoot);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_inject_extension_manifest_skips_when_no_pack(): void
|
||||
{
|
||||
$manifest = [
|
||||
'name' => ['ko' => '게시판', 'en' => 'Board'],
|
||||
'description' => ['ko' => '게시판 모듈', 'en' => 'Board module'],
|
||||
];
|
||||
|
||||
// 활성 ja 팩 없음 → 입력 그대로
|
||||
$result = $this->injector->injectExtensionManifest($manifest, 'sirsoft-board', LanguagePackScope::Module->value);
|
||||
|
||||
$this->assertSame($manifest, $result);
|
||||
$this->assertArrayNotHasKey('ja', $result['name']);
|
||||
}
|
||||
|
||||
public function test_inject_extension_manifest_skips_other_target(): void
|
||||
{
|
||||
$packRoot = $this->setupExtensionManifestPack('module', 'sirsoft-ecommerce', [
|
||||
'name' => 'eコマース',
|
||||
]);
|
||||
|
||||
try {
|
||||
$manifest = ['name' => ['ko' => '게시판', 'en' => 'Board']];
|
||||
|
||||
// 다른 대상(sirsoft-board) 호출 → ja 병합 없음
|
||||
$result = $this->injector->injectExtensionManifest($manifest, 'sirsoft-board', LanguagePackScope::Module->value);
|
||||
|
||||
$this->assertArrayNotHasKey('ja', $result['name']);
|
||||
} finally {
|
||||
File::deleteDirectory($packRoot);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_inject_extension_manifest_handles_string_name_and_missing_description(): void
|
||||
{
|
||||
$packRoot = $this->setupExtensionManifestPack('template', 'sirsoft-basic', [
|
||||
'name' => 'シルソフトベーシック',
|
||||
'description' => 'ユーザーテンプレート',
|
||||
]);
|
||||
|
||||
try {
|
||||
// name 이 string(비배열) 이고 description 누락된 입력 → 배열로 정규화 후 ja 주입
|
||||
$manifest = ['name' => 'sirsoft-basic'];
|
||||
|
||||
$result = $this->injector->injectExtensionManifest($manifest, 'sirsoft-basic', LanguagePackScope::Template->value);
|
||||
|
||||
$this->assertIsArray($result['name']);
|
||||
$this->assertSame('シルソフトベーシック', $result['name']['ja']);
|
||||
$this->assertSame('ユーザーテンプレート', $result['description']['ja']);
|
||||
} finally {
|
||||
File::deleteDirectory($packRoot);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_inject_extension_manifest_skips_empty_seed_fields(): void
|
||||
{
|
||||
$packRoot = $this->setupExtensionManifestPack('plugin', 'sirsoft-marketing', [
|
||||
'name' => '',
|
||||
'description' => 'マーケティング同意',
|
||||
]);
|
||||
|
||||
try {
|
||||
$manifest = ['name' => ['ko' => '마케팅'], 'description' => ['ko' => '마케팅 동의']];
|
||||
|
||||
$result = $this->injector->injectExtensionManifest($manifest, 'sirsoft-marketing', LanguagePackScope::Plugin->value);
|
||||
|
||||
// 빈 name 은 주입 안 함, description 만 주입
|
||||
$this->assertArrayNotHasKey('ja', $result['name']);
|
||||
$this->assertSame('マーケティング同意', $result['description']['ja']);
|
||||
} finally {
|
||||
File::deleteDirectory($packRoot);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,461 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services;
|
||||
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Enums\LayoutExtensionType;
|
||||
use App\Enums\LayoutSourceType;
|
||||
use App\Extension\Traits\ComputesLayoutContentHash;
|
||||
use App\Models\LayoutExtension;
|
||||
use App\Models\Template;
|
||||
use App\Models\TemplateLayout;
|
||||
use App\Models\TemplateLayoutExtensionVersion;
|
||||
use App\Services\LayoutExtensionService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* LayoutExtensionService 편집/버전관리 메서드 테스트
|
||||
*
|
||||
* 관리자 레이아웃 확장 편집 기능 (updateExtension, hasModifiedExtensions,
|
||||
* registerExtension preserveModified) 을 검증합니다.
|
||||
*/
|
||||
class LayoutExtensionServiceEditingTest extends TestCase
|
||||
{
|
||||
use ComputesLayoutContentHash;
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 같은 스위트의 레이아웃/GDPR 미들웨어 의존 테스트와 migrate:fresh 정합성을
|
||||
* 맞추기 위해 GDPR 플러그인 마이그레이션을 일관 선언한다.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
private LayoutExtensionService $service;
|
||||
|
||||
private Template $template;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->service = app(LayoutExtensionService::class);
|
||||
$this->template = Template::factory()->create([
|
||||
'identifier' => 'test-admin',
|
||||
'type' => 'admin',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* updateExtension - content 갱신 + 버전 2건 생성
|
||||
*/
|
||||
public function test_update_extension_saves_content_and_creates_two_versions(): void
|
||||
{
|
||||
$extension = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'content' => ['extension_point' => 'header', 'components' => []],
|
||||
]);
|
||||
|
||||
$newContent = ['extension_point' => 'header', 'components' => [['type' => 'basic', 'name' => 'Span']]];
|
||||
|
||||
$updated = $this->service->updateExtension($extension->id, ['content' => $newContent]);
|
||||
|
||||
$this->assertEquals($newContent, $updated->content);
|
||||
// 이전 버전 + 현재 버전 = 2건
|
||||
$this->assertEquals(2, TemplateLayoutExtensionVersion::where('extension_id', $extension->id)->count());
|
||||
}
|
||||
|
||||
/**
|
||||
* updateExtension - original_content_hash 는 불변
|
||||
*/
|
||||
public function test_update_extension_keeps_original_content_hash(): void
|
||||
{
|
||||
$originalContent = ['extension_point' => 'header', 'components' => []];
|
||||
$originalHash = $this->computeContentHash($originalContent);
|
||||
|
||||
$extension = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'content' => $originalContent,
|
||||
'original_content_hash' => $originalHash,
|
||||
'original_content_size' => $this->computeContentSize($originalContent),
|
||||
]);
|
||||
|
||||
$this->service->updateExtension($extension->id, [
|
||||
'content' => ['extension_point' => 'header', 'components' => [['type' => 'basic', 'name' => 'Div']]],
|
||||
]);
|
||||
|
||||
$extension->refresh();
|
||||
// 수정 감지를 위해 원본 해시는 유지되어야 함
|
||||
$this->assertEquals($originalHash, $extension->original_content_hash);
|
||||
}
|
||||
|
||||
/**
|
||||
* hasModifiedExtensions - 사용자 수정 확장 감지
|
||||
*/
|
||||
public function test_has_modified_extensions_detects_user_edits(): void
|
||||
{
|
||||
// 미수정 확장 (현재 content 해시 = original)
|
||||
$unmodifiedContent = ['extension_point' => 'sidebar', 'components' => []];
|
||||
LayoutExtension::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'content' => $unmodifiedContent,
|
||||
'original_content_hash' => $this->computeContentHash($unmodifiedContent),
|
||||
]);
|
||||
|
||||
// 수정된 확장 (현재 content 가 original 과 다름)
|
||||
$modified = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'content' => ['extension_point' => 'header', 'components' => [['type' => 'basic', 'name' => 'Span']]],
|
||||
'original_content_hash' => $this->computeContentHash(['extension_point' => 'header', 'components' => []]),
|
||||
]);
|
||||
|
||||
$result = $this->service->hasModifiedExtensions($this->template->id);
|
||||
|
||||
$this->assertCount(1, $result);
|
||||
$this->assertEquals($modified->id, $result[0]['id']);
|
||||
}
|
||||
|
||||
/**
|
||||
* registerExtension preserveModified=true - 사용자 수정 확장은 SKIP
|
||||
*/
|
||||
public function test_register_extension_preserve_modified_skips_user_edited(): void
|
||||
{
|
||||
// 모듈이 처음 만든 원본
|
||||
$originalContent = ['extension_point' => 'header', 'priority' => 100, 'components' => []];
|
||||
$extension = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'header',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-test',
|
||||
'content' => $originalContent,
|
||||
'original_content_hash' => $this->computeContentHash($originalContent),
|
||||
]);
|
||||
|
||||
// 사용자가 편집 (현재 content 변경 → 해시 불일치 발생)
|
||||
$extension->update(['content' => ['extension_point' => 'header', 'priority' => 100, 'components' => [['type' => 'basic', 'name' => 'Span']]]]);
|
||||
|
||||
// 모듈 업데이트 시 새 파일 content 로 register (preserveModified=true)
|
||||
$newFileContent = ['extension_point' => 'header', 'priority' => 200, 'components' => [['type' => 'basic', 'name' => 'Button']]];
|
||||
$result = $this->service->registerExtension(
|
||||
$newFileContent,
|
||||
LayoutSourceType::Module,
|
||||
'sirsoft-test',
|
||||
$this->template->id,
|
||||
true
|
||||
);
|
||||
|
||||
$this->assertEquals('skipped', $result);
|
||||
|
||||
// 사용자 수정 content 가 보존되어야 함 (덮어쓰기 안 됨)
|
||||
$extension->refresh();
|
||||
$this->assertEquals(
|
||||
[['type' => 'basic', 'name' => 'Span']],
|
||||
$extension->content['components']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* registerExtension preserveModified=true - 미수정 확장은 덮어쓰기 + 해시 갱신
|
||||
*/
|
||||
public function test_register_extension_preserve_modified_overwrites_unmodified(): void
|
||||
{
|
||||
$originalContent = ['extension_point' => 'header', 'priority' => 100, 'components' => []];
|
||||
$extension = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'header',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-test',
|
||||
'content' => $originalContent,
|
||||
'original_content_hash' => $this->computeContentHash($originalContent),
|
||||
]);
|
||||
|
||||
// 사용자 수정 없음 → 모듈 업데이트가 덮어씀
|
||||
$newFileContent = ['extension_point' => 'header', 'priority' => 200, 'components' => [['type' => 'basic', 'name' => 'Button']]];
|
||||
$result = $this->service->registerExtension(
|
||||
$newFileContent,
|
||||
LayoutSourceType::Module,
|
||||
'sirsoft-test',
|
||||
$this->template->id,
|
||||
true
|
||||
);
|
||||
|
||||
$this->assertEquals('updated', $result);
|
||||
|
||||
$extension->refresh();
|
||||
$this->assertEquals($newFileContent, $extension->content);
|
||||
// original_content_hash 도 새 파일 기준으로 갱신
|
||||
$this->assertEquals($this->computeContentHash($newFileContent), $extension->original_content_hash);
|
||||
}
|
||||
|
||||
/**
|
||||
* registerExtension - 신규 생성 시 original_content_hash 함께 저장
|
||||
*/
|
||||
public function test_register_extension_creates_with_original_hash(): void
|
||||
{
|
||||
$content = ['target_layout' => 'admin/dashboard', 'injections' => []];
|
||||
|
||||
$result = $this->service->registerExtension(
|
||||
$content,
|
||||
LayoutSourceType::Plugin,
|
||||
'sirsoft-analytics',
|
||||
$this->template->id
|
||||
);
|
||||
|
||||
$this->assertEquals('created', $result);
|
||||
|
||||
$extension = LayoutExtension::where('template_id', $this->template->id)
|
||||
->where('source_identifier', 'sirsoft-analytics')
|
||||
->first();
|
||||
|
||||
$this->assertNotNull($extension);
|
||||
$this->assertEquals($this->computeContentHash($content), $extension->original_content_hash);
|
||||
}
|
||||
|
||||
/**
|
||||
* getExtensionsByTemplateId - 출처별 그룹핑
|
||||
*/
|
||||
public function test_get_extensions_grouped_by_source(): void
|
||||
{
|
||||
LayoutExtension::factory()->count(2)->create([
|
||||
'template_id' => $this->template->id,
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'module-a',
|
||||
]);
|
||||
LayoutExtension::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'source_type' => LayoutSourceType::Plugin,
|
||||
'source_identifier' => 'plugin-b',
|
||||
]);
|
||||
|
||||
$groups = $this->service->getExtensionsByTemplateId($this->template->id);
|
||||
|
||||
$this->assertCount(2, $groups);
|
||||
$sourceIds = array_column($groups, 'source_identifier');
|
||||
$this->assertContains('module-a', $sourceIds);
|
||||
$this->assertContains('plugin-b', $sourceIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* getExtensionsByTemplateId - 템플릿 오버라이드 행에 is_override 플래그 부착
|
||||
*
|
||||
* 오버라이드 행은 트리에서 일반 확장과 동일하게 출처 기준으로 묶이되,
|
||||
* is_override=true 로 오버라이드 상황이 별도 표시되어야 한다.
|
||||
*/
|
||||
public function test_get_extensions_marks_override_rows(): void
|
||||
{
|
||||
// 일반 플러그인 확장
|
||||
LayoutExtension::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'admin/dashboard',
|
||||
'source_type' => LayoutSourceType::Plugin,
|
||||
'source_identifier' => 'plugin-b',
|
||||
'is_active' => true,
|
||||
]);
|
||||
// 템플릿 오버라이드 행
|
||||
LayoutExtension::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'address_search_slot',
|
||||
'source_type' => LayoutSourceType::Template,
|
||||
'source_identifier' => $this->template->identifier,
|
||||
'override_target' => 'some-plugin',
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$groups = $this->service->getExtensionsByTemplateId($this->template->id);
|
||||
|
||||
$allExtensions = collect($groups)->flatMap(fn ($g) => $g['extensions']);
|
||||
$override = $allExtensions->firstWhere('target_name', 'address_search_slot');
|
||||
$normal = $allExtensions->firstWhere('target_name', 'admin/dashboard');
|
||||
|
||||
$this->assertNotNull($override);
|
||||
$this->assertTrue($override->is_override, '오버라이드 행에 is_override 플래그 누락');
|
||||
$this->assertNotNull($normal);
|
||||
$this->assertFalse($normal->is_override, '일반 확장에 is_override 가 true 로 설정됨');
|
||||
}
|
||||
|
||||
/**
|
||||
* isExtensionApplicableToTemplate - overlay: 대상 레이아웃 존재 시 true
|
||||
*/
|
||||
public function test_overlay_applicable_when_target_layout_exists(): void
|
||||
{
|
||||
TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'admin_user_detail',
|
||||
]);
|
||||
|
||||
$content = ['target_layout' => 'admin_user_detail', 'injections' => []];
|
||||
|
||||
$this->assertTrue($this->service->isExtensionApplicableToTemplate($content, $this->template->id));
|
||||
}
|
||||
|
||||
/**
|
||||
* isExtensionApplicableToTemplate - overlay: 대상 레이아웃 부재 시 false
|
||||
*/
|
||||
public function test_overlay_not_applicable_when_target_layout_missing(): void
|
||||
{
|
||||
$content = ['target_layout' => 'admin_user_detail', 'injections' => []];
|
||||
|
||||
// 해당 템플릿에 admin_user_detail 레이아웃이 없음
|
||||
$this->assertFalse($this->service->isExtensionApplicableToTemplate($content, $this->template->id));
|
||||
}
|
||||
|
||||
/**
|
||||
* isExtensionApplicableToTemplate - extension_point: 확장점 정의 존재 시 true
|
||||
*/
|
||||
public function test_extension_point_applicable_when_defined_in_layout(): void
|
||||
{
|
||||
TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'dashboard',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'dashboard',
|
||||
'components' => [
|
||||
[
|
||||
'type' => 'basic',
|
||||
'name' => 'Div',
|
||||
'children' => [
|
||||
['type' => 'extension_point', 'name' => 'admin.dashboard.widgets'],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$content = ['extension_point' => 'admin.dashboard.widgets', 'components' => []];
|
||||
|
||||
$this->assertTrue($this->service->isExtensionApplicableToTemplate($content, $this->template->id));
|
||||
}
|
||||
|
||||
/**
|
||||
* isExtensionApplicableToTemplate - extension_point: 정의 부재 시 false
|
||||
*/
|
||||
public function test_extension_point_not_applicable_when_undefined(): void
|
||||
{
|
||||
TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'dashboard',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'dashboard',
|
||||
'components' => [['type' => 'basic', 'name' => 'Div']],
|
||||
],
|
||||
]);
|
||||
|
||||
$content = ['extension_point' => 'admin.dashboard.widgets', 'components' => []];
|
||||
|
||||
$this->assertFalse($this->service->isExtensionApplicableToTemplate($content, $this->template->id));
|
||||
}
|
||||
|
||||
/**
|
||||
* removeInapplicableExtension - 동일 확장이 다른 템플릿엔 적용 가능할 때만 오등록 삭제.
|
||||
*
|
||||
* cross-template 가드: "이 템플릿엔 부재" 만으로 삭제하지 않는다. 같은 4키 확장이
|
||||
* 다른 템플릿(여기선 user, 대상 레이아웃 존재)엔 적용 가능하면 이 행이 오등록 → 삭제.
|
||||
*/
|
||||
public function test_remove_inapplicable_extension_soft_deletes_orphan_row(): void
|
||||
{
|
||||
// user 템플릿엔 admin_user_detail 레이아웃 존재 + user 행 (= 다른 템플릿엔 적용 가능)
|
||||
$userTemplate = Template::factory()->create(['type' => 'user']);
|
||||
TemplateLayout::factory()->create([
|
||||
'template_id' => $userTemplate->id,
|
||||
'name' => 'admin_user_detail',
|
||||
]);
|
||||
LayoutExtension::factory()->create([
|
||||
'template_id' => $userTemplate->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'admin_user_detail',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-board',
|
||||
]);
|
||||
|
||||
// this->template(admin)엔 admin_user_detail 레이아웃 없음 → 오등록
|
||||
$orphan = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'admin_user_detail',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-board',
|
||||
]);
|
||||
|
||||
$content = ['target_layout' => 'admin_user_detail', 'injections' => []];
|
||||
|
||||
$removed = $this->service->removeInapplicableExtension(
|
||||
$content,
|
||||
LayoutSourceType::Module,
|
||||
'sirsoft-board',
|
||||
$this->template->id
|
||||
);
|
||||
|
||||
$this->assertTrue($removed);
|
||||
$this->assertSoftDeleted('template_layout_extensions', ['id' => $orphan->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* removeInapplicableExtension - 모든 템플릿에서 부재(전부 stale)면 삭제하지 않는다.
|
||||
*
|
||||
* cross-template 가드 핵심: 호스트 레이아웃이 전반적으로 구버전(슬롯 부재)이라 모든
|
||||
* 등록 템플릿에서 동시에 "부재" 가 될 때, 이는 오등록이 아니므로 정상 확장을 보존한다
|
||||
* (관리자 대시보드 위젯 소실 회귀 차단).
|
||||
*/
|
||||
public function test_remove_inapplicable_extension_preserves_when_all_templates_stale(): void
|
||||
{
|
||||
// admin·user 양쪽에 같은 확장 등록 + 어느 템플릿에도 대상 레이아웃 없음(전부 부재)
|
||||
$userTemplate = Template::factory()->create(['type' => 'user']);
|
||||
$adminRow = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'admin_dashboard_commerce',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-ecommerce',
|
||||
]);
|
||||
LayoutExtension::factory()->create([
|
||||
'template_id' => $userTemplate->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'admin_dashboard_commerce',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-ecommerce',
|
||||
]);
|
||||
|
||||
$content = ['extension_point' => 'admin_dashboard_commerce'];
|
||||
|
||||
$removed = $this->service->removeInapplicableExtension(
|
||||
$content,
|
||||
LayoutSourceType::Module,
|
||||
'sirsoft-ecommerce',
|
||||
$this->template->id
|
||||
);
|
||||
|
||||
// 다른 템플릿에서도 적용 불가(전부 stale) → 삭제 보류
|
||||
$this->assertFalse($removed);
|
||||
$this->assertNotSoftDeleted('template_layout_extensions', ['id' => $adminRow->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* removeInapplicableExtension - 해당 행이 없으면 false
|
||||
*/
|
||||
public function test_remove_inapplicable_extension_returns_false_when_no_row(): void
|
||||
{
|
||||
$content = ['target_layout' => 'admin_user_detail', 'injections' => []];
|
||||
|
||||
$removed = $this->service->removeInapplicableExtension(
|
||||
$content,
|
||||
LayoutSourceType::Module,
|
||||
'sirsoft-board',
|
||||
$this->template->id
|
||||
);
|
||||
|
||||
$this->assertFalse($removed);
|
||||
}
|
||||
}
|
||||
@@ -10,10 +10,13 @@ use App\Enums\LayoutSourceType;
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Models\LayoutExtension;
|
||||
use App\Models\Plugin;
|
||||
use App\Models\Template;
|
||||
use App\Models\TemplateLayout;
|
||||
use App\Services\LayoutExtensionService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
@@ -25,6 +28,16 @@ class LayoutExtensionServiceTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 같은 스위트의 레이아웃/GDPR 미들웨어 의존 테스트와 migrate:fresh 정합성을
|
||||
* 맞추기 위해 GDPR 플러그인 마이그레이션을 일관 선언한다.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
private LayoutExtensionService $service;
|
||||
|
||||
private Template $template;
|
||||
@@ -66,6 +79,11 @@ class LayoutExtensionServiceTest extends TestCase
|
||||
|
||||
$mockModuleManager = $this->createMock(ModuleManager::class);
|
||||
$mockModuleManager->method('getActiveModules')->willReturn($activeModules);
|
||||
// getModuleInfo 는 편집 모드 출처 메타의 로케일 표시명 해석에 쓰인다.
|
||||
// 식별자 → "{식별자} 모듈" 형태의 표시명을 돌려주는 스텁.
|
||||
$mockModuleManager->method('getModuleInfo')->willReturnCallback(
|
||||
fn (string $id) => isset($activeModules[$id]) ? ['identifier' => $id, 'name' => $id.' 모듈'] : null
|
||||
);
|
||||
$this->app->instance(ModuleManager::class, $mockModuleManager);
|
||||
|
||||
$activePlugins = [];
|
||||
@@ -135,6 +153,359 @@ class LayoutExtensionServiceTest extends TestCase
|
||||
$this->assertEquals('support_stats', $result['data_sources'][0]['id']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 편집 모드(withSourceMeta=true)에서 주입 노드의 __source 가 출처 타입/식별자를
|
||||
* 함께 담아, 편집기 오버레이가 "어느 확장인지" 표시할 수 있게 하는지 검증한다.
|
||||
*/
|
||||
public function test_marks_extension_source_with_type_and_identifier_in_edit_mode(): void
|
||||
{
|
||||
LayoutExtension::create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'admin.dashboard.widgets',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-support',
|
||||
'content' => [
|
||||
'extension_point' => 'admin.dashboard.widgets',
|
||||
'components' => [
|
||||
[
|
||||
'id' => 'support_widget',
|
||||
'type' => 'composite',
|
||||
'name' => 'Card',
|
||||
'children' => [
|
||||
['id' => 'support_child', 'type' => 'basic', 'name' => 'Span'],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
'priority' => 100,
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$layout = [
|
||||
'layout_name' => 'admin_dashboard',
|
||||
'components' => [
|
||||
[
|
||||
'id' => 'dashboard_widgets',
|
||||
'type' => 'extension_point',
|
||||
'name' => 'admin.dashboard.widgets',
|
||||
'default' => [],
|
||||
],
|
||||
],
|
||||
'data_sources' => [],
|
||||
];
|
||||
|
||||
// withSourceMeta=true 로 편집 모드 출처 메타 부여
|
||||
$result = $this->service->applyExtensions($layout, $this->template->id, true);
|
||||
|
||||
$injected = $result['components'][0]['children'][0];
|
||||
$this->assertSame('extension', $injected['__source']['kind']);
|
||||
$this->assertSame('module', $injected['__source']['extensionSourceType']);
|
||||
$this->assertSame('sirsoft-support', $injected['__source']['extensionIdentifier']);
|
||||
// 로케일 표시명도 함께 부여 — 오버레이가 "표시명 (식별자)" 로 노출
|
||||
$this->assertSame('sirsoft-support 모듈', $injected['__source']['extensionName']);
|
||||
|
||||
// 자식 노드에도 동일 출처 메타가 전파되어야 한다(통짜 잠금/라벨 일관성).
|
||||
$child = $injected['children'][0];
|
||||
$this->assertSame('sirsoft-support', $child['__source']['extensionIdentifier']);
|
||||
$this->assertSame('sirsoft-support 모듈', $child['__source']['extensionName']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 편집 모드에서 확장이 주입한 data_source 에도 출처 메타(__source)가 부여되어,
|
||||
* 데이터 소스 모달이 "어느 확장(모듈/플러그인)이 주입했는지" 표시할 수 있게 한다
|
||||
* 일반 렌더는 메타 미부여.
|
||||
*/
|
||||
public function test_marks_extension_source_on_injected_data_sources_in_edit_mode(): void
|
||||
{
|
||||
LayoutExtension::create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'admin.dashboard.widgets',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-support',
|
||||
'content' => [
|
||||
'extension_point' => 'admin.dashboard.widgets',
|
||||
'components' => [
|
||||
['id' => 'support_widget', 'type' => 'composite', 'name' => 'Card', 'props' => ['title' => 'Support']],
|
||||
],
|
||||
'data_sources' => [
|
||||
['id' => 'supportConsent', 'type' => 'api', 'endpoint' => '/api/modules/sirsoft-support/consent'],
|
||||
],
|
||||
],
|
||||
'priority' => 100,
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$layout = [
|
||||
'layout_name' => 'admin_dashboard',
|
||||
'components' => [
|
||||
['id' => 'dashboard_widgets', 'type' => 'extension_point', 'name' => 'admin.dashboard.widgets', 'default' => []],
|
||||
],
|
||||
'data_sources' => [],
|
||||
];
|
||||
|
||||
// 편집 모드(withSourceMeta=true)
|
||||
$edit = $this->service->applyExtensions($layout, $this->template->id, true);
|
||||
$ds = collect($edit['data_sources'])->firstWhere('id', 'supportConsent');
|
||||
$this->assertNotNull($ds, '주입된 data_source 가 병합되어야 함');
|
||||
$this->assertSame('extension', $ds['__source']['kind']);
|
||||
$this->assertSame('module', $ds['__source']['extensionSourceType']);
|
||||
$this->assertSame('sirsoft-support', $ds['__source']['extensionIdentifier']);
|
||||
|
||||
// 일반 렌더(withSourceMeta=false)는 __source 미부여(운영 화면 영향 0).
|
||||
$render = $this->service->applyExtensions($layout, $this->template->id, false);
|
||||
$dsPlain = collect($render['data_sources'])->firstWhere('id', 'supportConsent');
|
||||
$this->assertNotNull($dsPlain);
|
||||
$this->assertArrayNotHasKey('__source', $dsPlain);
|
||||
}
|
||||
|
||||
/**
|
||||
* 편집 모드(withSourceMeta=true)에서 inject_props 대상 호스트 노드에 `__injectedProps`
|
||||
* 메타가 부여되는지 검증한다.
|
||||
*/
|
||||
public function test_marks_injected_props_on_host_node_in_edit_mode(): void
|
||||
{
|
||||
LayoutExtension::create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'admin_user_detail',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-marketing',
|
||||
'content' => [
|
||||
'target_layout' => 'admin_user_detail',
|
||||
'injections' => [
|
||||
[
|
||||
'target_id' => 'user_detail_tabs',
|
||||
'position' => 'inject_props',
|
||||
'props' => ['tabs' => ['_append' => [['id' => 'ext_tab', 'label' => 'Ext']]]],
|
||||
],
|
||||
],
|
||||
],
|
||||
'priority' => 100,
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$layout = [
|
||||
'layout_name' => 'admin_user_detail',
|
||||
'components' => [
|
||||
['id' => 'user_detail_tabs', 'type' => 'composite', 'name' => 'Tabs', 'props' => ['tabs' => []]],
|
||||
],
|
||||
];
|
||||
|
||||
// 편집 모드 — 호스트 노드에 __injectedProps 부여.
|
||||
$edit = $this->service->applyExtensions($layout, $this->template->id, true);
|
||||
$host = collect($edit['components'])->firstWhere('id', 'user_detail_tabs');
|
||||
$this->assertNotNull($host);
|
||||
$this->assertArrayHasKey('__injectedProps', $host);
|
||||
$this->assertCount(1, $host['__injectedProps']);
|
||||
$injected = $host['__injectedProps'][0];
|
||||
$this->assertSame('module', $injected['extensionSourceType']);
|
||||
$this->assertSame('sirsoft-marketing', $injected['extensionIdentifier']);
|
||||
$this->assertSame(
|
||||
['tabs' => ['_append' => [['id' => 'ext_tab', 'label' => 'Ext']]]],
|
||||
$injected['props'],
|
||||
);
|
||||
// 호스트 props 에 실제 주입도 동작(병합) — _append 가 props.tabs 에 반영.
|
||||
$this->assertNotEmpty($host['props']['tabs']);
|
||||
|
||||
// 일반 렌더(withSourceMeta=false)는 __injectedProps 미부여(운영 화면 무영향).
|
||||
$render = $this->service->applyExtensions($layout, $this->template->id, false);
|
||||
$hostPlain = collect($render['components'])->firstWhere('id', 'user_detail_tabs');
|
||||
$this->assertArrayNotHasKey('__injectedProps', $hostPlain);
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장의 호스트 레이아웃 후보 — overlay 는 target_layout 1개, extension_point 는
|
||||
* 그 확장점을 포함하는 레이아웃 전체.
|
||||
*/
|
||||
public function test_get_extension_host_layouts_overlay_and_extension_point(): void
|
||||
{
|
||||
// overlay — target_layout + 편집 가능 컴포넌트를 실재 target_id 에 주입 → 유효 호스트.
|
||||
TemplateLayout::create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'admin_user_detail',
|
||||
'content' => ['components' => [['name' => 'Div', 'props' => ['id' => 'detail_panel']]]],
|
||||
]);
|
||||
$overlay = LayoutExtension::create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'admin_user_detail',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-marketing',
|
||||
'content' => [
|
||||
'target_layout' => 'admin_user_detail',
|
||||
'injections' => [['target_id' => 'detail_panel', 'position' => 'append_child', 'components' => [['name' => 'Div']]]],
|
||||
],
|
||||
'priority' => 100,
|
||||
'is_active' => true,
|
||||
]);
|
||||
$this->assertSame(['admin_user_detail'], $this->service->getExtensionHostLayouts($overlay));
|
||||
|
||||
// extension_point — 그 확장점을 포함하는 레이아웃 전체 조회(2개 호스트).
|
||||
TemplateLayout::create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'admin_dashboard',
|
||||
'content' => ['components' => [['type' => 'extension_point', 'name' => 'dash.widgets']]],
|
||||
]);
|
||||
TemplateLayout::create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'admin_home',
|
||||
'content' => ['components' => [['type' => 'extension_point', 'name' => 'dash.widgets']]],
|
||||
]);
|
||||
$ep = LayoutExtension::create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'dash.widgets',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-marketing',
|
||||
// extension_point 가 편집 가능 컴포넌트를 실제로 주입해야 시각 편집 호스트로 인정.
|
||||
'content' => ['extension_point' => 'dash.widgets', 'components' => [['name' => 'Div']]],
|
||||
'priority' => 100,
|
||||
'is_active' => true,
|
||||
]);
|
||||
$hosts = $this->service->getExtensionHostLayouts($ep);
|
||||
$this->assertContains('admin_dashboard', $hosts);
|
||||
$this->assertContains('admin_home', $hosts);
|
||||
$this->assertCount(2, $hosts);
|
||||
}
|
||||
|
||||
/**
|
||||
* -1 — 백엔드 게이트는 "주입이 성립하는가" 수준만 판정한다.
|
||||
* modals 만 주입하는 extension_point(예: 토스페이먼츠)도 주입은 성립하므로 호스트로 인정해
|
||||
* 트리에 노출한다(클릭 시 프론트가 시각 조각 유무를 판정해 디그레이드 안내 — 숨김이 아니라
|
||||
* 디그레이드). 완전 빈 content(병합할 payload 없음)만 제외한다.
|
||||
*/
|
||||
public function test_get_extension_host_layouts_extension_point_requires_components(): void
|
||||
{
|
||||
TemplateLayout::create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'shop_checkout',
|
||||
'content' => ['components' => [['type' => 'extension_point', 'name' => 'shop.checkout.ext']]],
|
||||
]);
|
||||
|
||||
// components 없이 modals 만 주입 — 주입 성립 → 호스트 인정(트리 노출, 클릭 시 프론트
|
||||
// editability 판정으로 디그레이드).
|
||||
$modalsOnly = LayoutExtension::create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'shop.checkout.ext',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-tosspayments',
|
||||
'content' => [
|
||||
'extension_point' => 'shop.checkout.ext',
|
||||
'modals' => [['id' => 'toss_modal', 'components' => [['name' => 'Div']]]],
|
||||
],
|
||||
'priority' => 100,
|
||||
'is_active' => true,
|
||||
]);
|
||||
$this->assertSame(['shop_checkout'], $this->service->getExtensionHostLayouts($modalsOnly));
|
||||
|
||||
// 병합할 payload 가 전혀 없는 content(components 빈 배열뿐) — 주입 불성립 → 제외.
|
||||
$emptyComps = LayoutExtension::create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'shop.checkout.ext',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-empty',
|
||||
'content' => ['extension_point' => 'shop.checkout.ext', 'components' => []],
|
||||
'priority' => 100,
|
||||
'is_active' => true,
|
||||
]);
|
||||
$this->assertSame([], $this->service->getExtensionHostLayouts($emptyComps));
|
||||
|
||||
// components 를 실제 주입하면 호스트로 인정.
|
||||
$withComps = LayoutExtension::create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'shop.checkout.ext',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-valid',
|
||||
'content' => ['extension_point' => 'shop.checkout.ext', 'components' => [['name' => 'Div']]],
|
||||
'priority' => 100,
|
||||
'is_active' => true,
|
||||
]);
|
||||
$this->assertSame(['shop_checkout'], $this->service->getExtensionHostLayouts($withComps));
|
||||
}
|
||||
|
||||
/**
|
||||
* overlay 의 injection target_id 가 호스트에 실재할 때만 유효 호스트.
|
||||
* target_id 가 호스트에 없으면 applyExtensions 가 주입하지 못하므로 호스트 후보에서 제외한다
|
||||
* (결제 overlay 가 존재하지 않는 target 을 가리켜 "주입됨"으로 오판되던 결함 방지).
|
||||
*/
|
||||
public function test_get_extension_host_layouts_overlay_requires_existing_target_id(): void
|
||||
{
|
||||
// 호스트 레이아웃: target_id 노드가 실재.
|
||||
TemplateLayout::create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'shop/checkout',
|
||||
'content' => ['components' => [['name' => 'Div', 'props' => ['id' => 'pay_section']]]],
|
||||
]);
|
||||
|
||||
// target_id 가 호스트에 실재 → 유효 호스트.
|
||||
$valid = LayoutExtension::create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'shop/checkout',
|
||||
'source_type' => LayoutSourceType::Plugin,
|
||||
'source_identifier' => 'sirsoft-pay_ok',
|
||||
'content' => [
|
||||
'target_layout' => 'shop/checkout',
|
||||
'injections' => [['target_id' => 'pay_section', 'position' => 'append_child', 'components' => [['name' => 'Div']]]],
|
||||
],
|
||||
'priority' => 100,
|
||||
'is_active' => true,
|
||||
]);
|
||||
$this->assertSame(['shop/checkout'], $this->service->getExtensionHostLayouts($valid));
|
||||
|
||||
// target_id 가 호스트에 없음 → 주입 불가 → 호스트 후보에서 제외.
|
||||
$invalid = LayoutExtension::create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'shop/checkout',
|
||||
'source_type' => LayoutSourceType::Plugin,
|
||||
'source_identifier' => 'sirsoft-pay_broken',
|
||||
'content' => [
|
||||
'target_layout' => 'shop/checkout',
|
||||
'injections' => [['target_id' => 'missing_section', 'position' => 'append_child', 'components' => [['name' => 'Div']]]],
|
||||
],
|
||||
'priority' => 100,
|
||||
'is_active' => true,
|
||||
]);
|
||||
$this->assertSame([], $this->service->getExtensionHostLayouts($invalid));
|
||||
|
||||
// injection 없이 modals 만 주입하는 overlay(예: 일부 결제 플러그인) — 주입은 성립하므로
|
||||
// 호스트 인정.
|
||||
$modalsOnly = LayoutExtension::create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'shop/checkout',
|
||||
'source_type' => LayoutSourceType::Plugin,
|
||||
'source_identifier' => 'sirsoft-pay_modalsonly',
|
||||
'content' => ['target_layout' => 'shop/checkout', 'modals' => [['id' => 'pay_modal']]],
|
||||
'priority' => 100,
|
||||
'is_active' => true,
|
||||
]);
|
||||
$this->assertSame(['shop/checkout'], $this->service->getExtensionHostLayouts($modalsOnly));
|
||||
|
||||
// components 는 있으나 target_id 가 호스트에 없는 injection 만(부수 주입도 없음) → 주입
|
||||
// 불성립 → 제외.
|
||||
$compsNoTarget = LayoutExtension::create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'shop/checkout',
|
||||
'source_type' => LayoutSourceType::Plugin,
|
||||
'source_identifier' => 'sirsoft-pay_compsnotarget',
|
||||
'content' => [
|
||||
'target_layout' => 'shop/checkout',
|
||||
'injections' => [['target_id' => 'nope', 'position' => 'append_child', 'components' => [['name' => 'Div']]]],
|
||||
],
|
||||
'priority' => 100,
|
||||
'is_active' => true,
|
||||
]);
|
||||
$this->assertSame([], $this->service->getExtensionHostLayouts($compsNoTarget));
|
||||
}
|
||||
|
||||
/**
|
||||
* Overlay가 타겟 ID에 올바르게 주입되는지 테스트
|
||||
*/
|
||||
@@ -191,6 +562,167 @@ class LayoutExtensionServiceTest extends TestCase
|
||||
$this->assertEquals('marketing_tab', $result['components'][0]['children'][1]['id']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Overlay 확장이 호스트 레이아웃 init_actions 뒤에 초기화 액션을 병합한다.
|
||||
*
|
||||
* 모듈이 호스트(예: _admin_base)가 모르는 _global 초기화(모듈별 표시 통화 복원 등)를
|
||||
* layout_extensions 로 기여할 수 있게 한다. 호스트 init_actions 뒤에 순서대로 추가된다.
|
||||
*/
|
||||
public function test_merges_overlay_init_actions_after_host(): void
|
||||
{
|
||||
LayoutExtension::create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'admin_user_detail',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-marketing',
|
||||
'content' => [
|
||||
'target_layout' => 'admin_user_detail',
|
||||
'injections' => [
|
||||
[
|
||||
'target_id' => 'user_tabs',
|
||||
'position' => 'append_child',
|
||||
'components' => [
|
||||
['id' => 'marketing_tab', 'type' => 'composite', 'name' => 'Tab'],
|
||||
],
|
||||
],
|
||||
],
|
||||
'init_actions' => [
|
||||
['handler' => 'sirsoft-marketing.initSomething', 'params' => ['x' => 1]],
|
||||
],
|
||||
],
|
||||
'priority' => 100,
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$layout = [
|
||||
'layout_name' => 'admin_user_detail',
|
||||
'components' => [
|
||||
['id' => 'user_tabs', 'type' => 'layout', 'name' => 'Tabs', 'children' => []],
|
||||
],
|
||||
'init_actions' => [
|
||||
['handler' => 'initTheme'],
|
||||
],
|
||||
'data_sources' => [],
|
||||
];
|
||||
|
||||
$result = $this->service->applyExtensions($layout, $this->template->id);
|
||||
|
||||
// 호스트 init 뒤에 확장 init 이 추가됨 (순서 보존).
|
||||
// 결과는 표준 키 initActions 로 통합된다 (deprecated init_actions 입력도 표준 키로 흡수).
|
||||
$this->assertArrayNotHasKey('init_actions', $result, 'deprecated snake 키가 결과에 잔존하면 안 됨');
|
||||
$this->assertCount(2, $result['initActions']);
|
||||
$this->assertSame('initTheme', $result['initActions'][0]['handler']);
|
||||
$this->assertSame('sirsoft-marketing.initSomething', $result['initActions'][1]['handler']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 호스트가 표준 키 initActions(camelCase)를 가지고 overlay 가 deprecated init_actions(snake)를
|
||||
* 기여할 때, 두 키가 공존하지 않고 표준 initActions 단일 배열로 통합되어야 한다.
|
||||
*
|
||||
* 회귀: 두 키 공존 시 엔진(TemplateApp)의 `initActions || init_actions` OR 단락이
|
||||
* snake 배열을 통째로 무시 → overlay 가 기여한 init_actions(헤더 통화 셀렉터 복원 등)가
|
||||
* 실행되지 않아 통화/배송국가 선택기가 자체 initActions 를 가진 화면에서만 미표시되던 결함.
|
||||
* (admin_dashboard 는 자체 initActions 가 없어 정상 표시, admin_ecommerce_settings 등
|
||||
* 자체 initActions 를 가진 화면은 미표시 — Chrome MCP 실측으로 확인)
|
||||
*/
|
||||
public function test_overlay_snake_init_actions_merge_into_standard_camel_key(): void
|
||||
{
|
||||
LayoutExtension::create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'admin_user_detail',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-marketing',
|
||||
'content' => [
|
||||
'target_layout' => 'admin_user_detail',
|
||||
'injections' => [
|
||||
[
|
||||
'target_id' => 'user_tabs',
|
||||
'position' => 'append_child',
|
||||
'components' => [
|
||||
['id' => 'currency_node', 'type' => 'basic', 'name' => 'Div'],
|
||||
],
|
||||
],
|
||||
],
|
||||
// overlay 정의는 deprecated snake 키 사용
|
||||
'init_actions' => [
|
||||
['handler' => 'sirsoft-marketing.initPreferredCurrency'],
|
||||
['handler' => 'sirsoft-marketing.initPreferredShippingCountry'],
|
||||
],
|
||||
],
|
||||
'priority' => 100,
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
// 호스트(자식 레이아웃 병합 결과)는 표준 camel 키를 가진다
|
||||
$layout = [
|
||||
'layout_name' => 'admin_user_detail',
|
||||
'components' => [
|
||||
['id' => 'user_tabs', 'type' => 'layout', 'name' => 'Tabs', 'children' => []],
|
||||
],
|
||||
'initActions' => [
|
||||
['handler' => 'setState', 'params' => ['target' => 'local', 'q' => '']],
|
||||
],
|
||||
'data_sources' => [],
|
||||
];
|
||||
|
||||
$result = $this->service->applyExtensions($layout, $this->template->id);
|
||||
|
||||
// 두 키 공존 금지 — 표준 initActions 단일 배열로 통합
|
||||
$this->assertArrayNotHasKey('init_actions', $result, 'snake 키가 별도로 잔존하면 엔진 OR 단락으로 무시됨');
|
||||
$this->assertCount(3, $result['initActions'], '호스트 1 + overlay 2 = 3개가 한 배열로 통합되어야 함');
|
||||
$this->assertSame('setState', $result['initActions'][0]['handler']);
|
||||
$this->assertSame('sirsoft-marketing.initPreferredCurrency', $result['initActions'][1]['handler']);
|
||||
$this->assertSame('sirsoft-marketing.initPreferredShippingCountry', $result['initActions'][2]['handler']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 호스트에 init_actions 가 없어도 확장 init_actions 만으로 배열을 생성한다.
|
||||
*/
|
||||
public function test_merges_overlay_init_actions_when_host_has_none(): void
|
||||
{
|
||||
LayoutExtension::create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'admin_user_detail',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-marketing',
|
||||
'content' => [
|
||||
'target_layout' => 'admin_user_detail',
|
||||
'injections' => [
|
||||
[
|
||||
'target_id' => 'user_tabs',
|
||||
'position' => 'append_child',
|
||||
'components' => [
|
||||
['id' => 'marketing_tab', 'type' => 'composite', 'name' => 'Tab'],
|
||||
],
|
||||
],
|
||||
],
|
||||
'init_actions' => [
|
||||
['handler' => 'sirsoft-marketing.initSomething'],
|
||||
],
|
||||
],
|
||||
'priority' => 100,
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$layout = [
|
||||
'layout_name' => 'admin_user_detail',
|
||||
'components' => [
|
||||
['id' => 'user_tabs', 'type' => 'layout', 'name' => 'Tabs', 'children' => []],
|
||||
],
|
||||
'data_sources' => [],
|
||||
];
|
||||
|
||||
$result = $this->service->applyExtensions($layout, $this->template->id);
|
||||
|
||||
// 호스트에 init 이 없어도 overlay 의 deprecated snake 입력은 표준 initActions 로 흡수된다.
|
||||
$this->assertArrayNotHasKey('init_actions', $result);
|
||||
$this->assertCount(1, $result['initActions']);
|
||||
$this->assertSame('sirsoft-marketing.initSomething', $result['initActions'][0]['handler']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 등록 테스트 (Extension Point 타입)
|
||||
*/
|
||||
@@ -1281,14 +1813,14 @@ class LayoutExtensionServiceTest extends TestCase
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
\Illuminate\Support\Facades\Log::shouldReceive('warning')
|
||||
Log::shouldReceive('warning')
|
||||
->once()
|
||||
->withArgs(function ($message) {
|
||||
return str_contains($message, 'inject_props _append 대상이 표현식 문자열');
|
||||
});
|
||||
|
||||
// 다른 로그 호출 허용
|
||||
\Illuminate\Support\Facades\Log::shouldReceive('debug')->zeroOrMoreTimes();
|
||||
Log::shouldReceive('debug')->zeroOrMoreTimes();
|
||||
|
||||
$result = $this->service->applyExtensions($layout, $this->template->id);
|
||||
|
||||
@@ -1335,7 +1867,7 @@ class LayoutExtensionServiceTest extends TestCase
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
\Illuminate\Support\Facades\Log::shouldReceive('warning')
|
||||
Log::shouldReceive('warning')
|
||||
->once()
|
||||
->withArgs(function ($message, $context) {
|
||||
return $message === 'Layout extension target not found'
|
||||
@@ -1343,7 +1875,7 @@ class LayoutExtensionServiceTest extends TestCase
|
||||
&& $context['position'] === 'inject_props';
|
||||
});
|
||||
|
||||
\Illuminate\Support\Facades\Log::shouldReceive('debug')->zeroOrMoreTimes();
|
||||
Log::shouldReceive('debug')->zeroOrMoreTimes();
|
||||
|
||||
$this->service->applyExtensions($layout, $this->template->id);
|
||||
}
|
||||
@@ -2286,4 +2818,59 @@ class LayoutExtensionServiceTest extends TestCase
|
||||
$this->assertEquals('default_widget', $childIds[0], 'append 모드에서 default가 앞에 유지되어야 함');
|
||||
$this->assertEquals('appended_widget', $childIds[1], 'append 모드에서 확장이 뒤에 와야 함');
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 출처명(트리 `🔌 {sourceLabel}`)은 DB 레코드의 다국어 name 을
|
||||
* 우선 사용한다. 설치/동기화 시 manifest.translations 필터가 ja 를 DB name 에 병합하므로,
|
||||
* 매니페스트 객체(ko/en 만 보유)가 아니라 DB name 을 읽어야 ja locale 에서 일본어로 표시된다.
|
||||
*/
|
||||
public function test_resolve_source_label_reads_ja_from_db_name(): void
|
||||
{
|
||||
Plugin::factory()->create([
|
||||
'identifier' => 'sirsoft-gdpr',
|
||||
'name' => [
|
||||
'ko' => 'GDPR (일반 데이터 보호 규정)',
|
||||
'en' => 'GDPR (General Data Protection Regulation)',
|
||||
'ja' => 'GDPR (一般データ保護規則)',
|
||||
],
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
|
||||
$ref = new \ReflectionMethod($this->service, 'resolveSourceLabel');
|
||||
$ref->setAccessible(true);
|
||||
|
||||
app()->setLocale('ja');
|
||||
$this->assertSame(
|
||||
'GDPR (一般データ保護規則)',
|
||||
$ref->invoke($this->service, LayoutSourceType::Plugin, 'sirsoft-gdpr'),
|
||||
'ja locale 에서 DB name 의 ja 가 표시돼야 함 (manifest ko 폴백 금지)'
|
||||
);
|
||||
|
||||
app()->setLocale('ko');
|
||||
$this->assertSame(
|
||||
'GDPR (일반 데이터 보호 규정)',
|
||||
$ref->invoke($this->service, LayoutSourceType::Plugin, 'sirsoft-gdpr')
|
||||
);
|
||||
|
||||
app()->setLocale('en');
|
||||
$this->assertSame(
|
||||
'GDPR (General Data Protection Regulation)',
|
||||
$ref->invoke($this->service, LayoutSourceType::Plugin, 'sirsoft-gdpr')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* DB 레코드가 없으면 매니페스트 객체 getName() 으로 폴백한다(역호환, 크래시 없음).
|
||||
*/
|
||||
public function test_resolve_source_label_falls_back_to_manifest_when_no_db_row(): void
|
||||
{
|
||||
$ref = new \ReflectionMethod($this->service, 'resolveSourceLabel');
|
||||
$ref->setAccessible(true);
|
||||
|
||||
app()->setLocale('ja');
|
||||
$label = $ref->invoke($this->service, LayoutSourceType::Plugin, 'sirsoft-payment');
|
||||
|
||||
$this->assertIsString($label);
|
||||
$this->assertNotSame('', $label);
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,8 @@ 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;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* LayoutExtensionService 버전 호환성 테스트
|
||||
@@ -23,6 +23,16 @@ class LayoutExtensionServiceVersionTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 같은 스위트의 레이아웃/GDPR 미들웨어 의존 테스트와 migrate:fresh 정합성을
|
||||
* 맞추기 위해 GDPR 플러그인 마이그레이션을 일관 선언한다.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
private LayoutExtensionService $service;
|
||||
|
||||
private Template $template;
|
||||
@@ -43,7 +53,6 @@ class LayoutExtensionServiceVersionTest extends TestCase
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* version_constraint가 없으면 항상 적용되는지 테스트
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services;
|
||||
|
||||
use App\Services\LayoutService;
|
||||
use ReflectionMethod;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* LayoutServiceMergeComputedTest — mergeComputed + buildComputedSourceMap 단위
|
||||
*
|
||||
* computed 는 shallow merge(자식 우선 — 같은 키 자식 식 유효). withSourceMeta 시 `__computedSource`
|
||||
* 키 출처 맵(부모=base / 자식=route, override 포함)이 정확하고, computed 키와 충돌하지 않음을 검증.
|
||||
*/
|
||||
class LayoutServiceMergeComputedTest extends TestCase
|
||||
{
|
||||
private LayoutService $service;
|
||||
|
||||
private ReflectionMethod $merge;
|
||||
|
||||
private ReflectionMethod $sourceMap;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->service = app(LayoutService::class);
|
||||
$this->merge = new ReflectionMethod(LayoutService::class, 'mergeComputed');
|
||||
$this->merge->setAccessible(true);
|
||||
$this->sourceMap = new ReflectionMethod(LayoutService::class, 'buildComputedSourceMap');
|
||||
$this->sourceMap->setAccessible(true);
|
||||
}
|
||||
|
||||
public function test_shallow_merge_child_wins_same_key(): void
|
||||
{
|
||||
$parent = ['isReadOnly' => '{{ a }}'];
|
||||
$child = ['isReadOnly' => '{{ b }}'];
|
||||
$merged = $this->merge->invoke($this->service, $parent, $child);
|
||||
$this->assertSame('{{ b }}', $merged['isReadOnly']);
|
||||
}
|
||||
|
||||
public function test_parent_only_child_only_both(): void
|
||||
{
|
||||
$this->assertSame(['x' => '1'], $this->merge->invoke($this->service, ['x' => '1'], []));
|
||||
$this->assertSame(['y' => '2'], $this->merge->invoke($this->service, [], ['y' => '2']));
|
||||
$merged = $this->merge->invoke($this->service, ['x' => '1'], ['y' => '2']);
|
||||
$this->assertSame(['x' => '1', 'y' => '2'], $merged);
|
||||
}
|
||||
|
||||
public function test_source_map_marks_base_and_route(): void
|
||||
{
|
||||
$parent = ['common' => '{{ a }}'];
|
||||
$child = ['own' => '{{ b }}'];
|
||||
$map = $this->sourceMap->invoke($this->service, $parent, $child);
|
||||
$this->assertSame('base', $map['common']);
|
||||
$this->assertSame('route', $map['own']);
|
||||
}
|
||||
|
||||
public function test_source_map_overridden_key_is_route_override(): void
|
||||
{
|
||||
// 자식이 부모 키를 덮으면 그 키 출처는 'route-override'(부모+자식 동시 선언 — 덮음).
|
||||
// 순수 자식 키('route')와 구분되어야 ComputedForm 이 〔이 페이지에서 덮음〕
|
||||
// 승격 배지 + 공통값 되돌리기를 그릴 수 있다.
|
||||
$parent = ['isReadOnly' => '{{ a }}'];
|
||||
$child = ['isReadOnly' => '{{ b }}'];
|
||||
$map = $this->sourceMap->invoke($this->service, $parent, $child);
|
||||
$this->assertSame('route-override', $map['isReadOnly']);
|
||||
}
|
||||
|
||||
public function test_source_map_three_kinds_distinct(): void
|
||||
{
|
||||
// 부모만(base) / 자식만(route) / 부모+자식 동시(route-override) 3종이 구분된다.
|
||||
$parent = ['common' => '{{ a }}', 'shared' => '{{ p }}'];
|
||||
$child = ['own' => '{{ b }}', 'shared' => '{{ c }}'];
|
||||
$map = $this->sourceMap->invoke($this->service, $parent, $child);
|
||||
$this->assertSame('base', $map['common'], '부모만 = base');
|
||||
$this->assertSame('route', $map['own'], '자식만 = route');
|
||||
$this->assertSame('route-override', $map['shared'], '부모+자식 동시 = route-override');
|
||||
}
|
||||
|
||||
public function test_source_map_does_not_collide_with_computed_keys(): void
|
||||
{
|
||||
// 출처 맵은 별개 배열 — computed 키 값(식)과 섞이지 않는다.
|
||||
$map = $this->sourceMap->invoke($this->service, ['a' => '{{ x }}'], ['b' => '{{ y }}']);
|
||||
$this->assertArrayNotHasKey('__computedSource', $map);
|
||||
$this->assertSame(['a' => 'base', 'b' => 'route'], $map);
|
||||
}
|
||||
|
||||
public function test_multi_level_inheritance_nearest_layer_wins(): void
|
||||
{
|
||||
// ④ 다단 상속(조부모→부모→자식) — buildComputedSourceMap 은 2-레이어 단위지만
|
||||
// loadAndMergeLayout 은 부모를 재귀 병합한 "부모 병합본"을 parent 로 넘긴다.
|
||||
// 따라서 조부모 키는 부모 병합본에 잔존해 자식 입장에선 모두 'base'(부모 레이어),
|
||||
// 자식 자기 선언 키만 'route'. 같은 키를 자식이 덮으면 자식(가장 가까운) 우선.
|
||||
$grandparentMerged = $this->merge->invoke($this->service, ['fromGrandparent' => '{{ g }}'], ['fromParent' => '{{ p }}']);
|
||||
$this->assertSame(['fromGrandparent' => '{{ g }}', 'fromParent' => '{{ p }}'], $grandparentMerged);
|
||||
|
||||
// 부모 병합본(조부모+부모) + 자식 → 자식 식 병합(자식 우선).
|
||||
$merged = $this->merge->invoke($this->service, $grandparentMerged, ['own' => '{{ c }}', 'fromParent' => '{{ override }}']);
|
||||
$this->assertSame('{{ override }}', $merged['fromParent'], '가장 가까운 레이어(자식)가 같은 키를 덮는다');
|
||||
$this->assertSame('{{ g }}', $merged['fromGrandparent'], '미덮은 상위 키는 보존');
|
||||
|
||||
// 출처 맵 — 부모 병합본 키는 base, 자식 선언/덮은 키는 route.
|
||||
$map = $this->sourceMap->invoke($this->service, $grandparentMerged, ['own' => '{{ c }}', 'fromParent' => '{{ override }}']);
|
||||
$this->assertSame('base', $map['fromGrandparent']);
|
||||
$this->assertSame('route', $map['own']);
|
||||
$this->assertSame('route-override', $map['fromParent'], '자식이 덮은 키 출처 = route-override');
|
||||
}
|
||||
|
||||
public function test_with_source_meta_false_omits_computed_source_map(): void
|
||||
{
|
||||
// ⑥ 운영 경로(sourceMeta=null) — mergeLayouts 결과에 __computedSource 미부착(응답 형식 종전 동일).
|
||||
$parent = ['computed' => ['common' => '{{ a }}']];
|
||||
$child = ['computed' => ['own' => '{{ b }}'], 'layout_name' => 'child'];
|
||||
|
||||
$opMerged = $this->service->mergeLayouts($parent, $child, null);
|
||||
$this->assertArrayNotHasKey('__computedSource', $opMerged, '운영 경로엔 출처 맵 미부착');
|
||||
$this->assertSame(['common' => '{{ a }}', 'own' => '{{ b }}'], $opMerged['computed']);
|
||||
|
||||
// 편집 경로(sourceMeta 비-null) — 출처 맵 부착.
|
||||
$editMerged = $this->service->mergeLayouts($parent, $child, ['kind' => 'base', 'layout' => 'parent']);
|
||||
$this->assertArrayHasKey('__computedSource', $editMerged, '편집 경로엔 출처 맵 부착');
|
||||
$this->assertSame('base', $editMerged['__computedSource']['common']);
|
||||
$this->assertSame('route', $editMerged['__computedSource']['own']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services;
|
||||
|
||||
use App\Services\LayoutService;
|
||||
use ReflectionMethod;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* LayoutServiceMergeInitActionsTest — mergeInitActions 단위
|
||||
*
|
||||
* 부모/자식 init_actions 병합 + 출처 메타(`__source`) 부착 정합을 검증한다. 운영 렌더
|
||||
* (sourceMeta=null) 는 단순 array_merge(부착 0), 편집 모드(sourceMeta!=null) 는 각 항목에
|
||||
* `__source:{kind, layout}` 부착(부모=base / 자식=route). 반사로 private 메서드 직접 검증.
|
||||
*/
|
||||
class LayoutServiceMergeInitActionsTest extends TestCase
|
||||
{
|
||||
private LayoutService $service;
|
||||
|
||||
private ReflectionMethod $merge;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->service = app(LayoutService::class);
|
||||
$this->merge = new ReflectionMethod(LayoutService::class, 'mergeInitActions');
|
||||
$this->merge->setAccessible(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* private mergeInitActions 호출 헬퍼.
|
||||
*
|
||||
* @param array $parent 부모 init_actions
|
||||
* @param array $child 자식 init_actions
|
||||
* @param array|null $sourceMeta 부모 출처 메타(null=운영)
|
||||
* @param string|null $childLayout 자식 레이아웃명
|
||||
* @return array 병합 결과
|
||||
*/
|
||||
private function invokeMerge(array $parent, array $child, ?array $sourceMeta = null, ?string $childLayout = null): array
|
||||
{
|
||||
return $this->merge->invoke($this->service, $parent, $child, $sourceMeta, $childLayout);
|
||||
}
|
||||
|
||||
public function test_parent_only_returns_parent(): void
|
||||
{
|
||||
$parent = [['handler' => 'initTheme']];
|
||||
$this->assertSame($parent, $this->invokeMerge($parent, []));
|
||||
}
|
||||
|
||||
public function test_child_only_returns_child(): void
|
||||
{
|
||||
$child = [['handler' => 'toast']];
|
||||
$this->assertSame($child, $this->invokeMerge([], $child));
|
||||
}
|
||||
|
||||
public function test_parent_first_child_last_order(): void
|
||||
{
|
||||
$parent = [['handler' => 'initTheme'], ['handler' => 'initCartKey']];
|
||||
$child = [['handler' => 'toast']];
|
||||
$merged = $this->invokeMerge($parent, $child);
|
||||
$this->assertCount(3, $merged);
|
||||
$this->assertSame('initTheme', $merged[0]['handler']);
|
||||
$this->assertSame('initCartKey', $merged[1]['handler']);
|
||||
$this->assertSame('toast', $merged[2]['handler']);
|
||||
}
|
||||
|
||||
public function test_source_meta_attaches_base_and_route(): void
|
||||
{
|
||||
$parent = [['handler' => 'initTheme']];
|
||||
$child = [['handler' => 'toast']];
|
||||
$merged = $this->invokeMerge($parent, $child, ['kind' => 'base', 'layout' => '_user_base'], 'home');
|
||||
|
||||
$this->assertSame(['kind' => 'base', 'layout' => '_user_base'], $merged[0]['__source']);
|
||||
$this->assertSame(['kind' => 'route', 'layout' => 'home'], $merged[1]['__source']);
|
||||
}
|
||||
|
||||
public function test_operational_render_has_no_source_meta(): void
|
||||
{
|
||||
$parent = [['handler' => 'initTheme']];
|
||||
$child = [['handler' => 'toast']];
|
||||
$merged = $this->invokeMerge($parent, $child); // sourceMeta=null
|
||||
|
||||
$this->assertArrayNotHasKey('__source', $merged[0]);
|
||||
$this->assertArrayNotHasKey('__source', $merged[1]);
|
||||
}
|
||||
|
||||
public function test_three_level_source_layout_is_nearest(): void
|
||||
{
|
||||
// 조부모→부모 병합 결과를 다시 자식과 병합(가장 가까운 선언 레이어가 출처).
|
||||
$grandparentMerged = $this->invokeMerge(
|
||||
[['handler' => 'initTheme']],
|
||||
[['handler' => 'initParent']],
|
||||
['kind' => 'base', 'layout' => '_root_base'],
|
||||
'_user_base',
|
||||
);
|
||||
// 이제 grandparentMerged 를 부모로, 자식과 병합(편집 모드 — 부모 전체 base).
|
||||
$merged = $this->invokeMerge(
|
||||
$grandparentMerged,
|
||||
[['handler' => 'toast']],
|
||||
['kind' => 'base', 'layout' => '_user_base'],
|
||||
'home',
|
||||
);
|
||||
// 부모 항목 전부 base/_user_base 로 재스탬프(가장 가까운 부모 레이어), 자식만 route/home.
|
||||
$this->assertSame(['kind' => 'base', 'layout' => '_user_base'], $merged[0]['__source']);
|
||||
$this->assertSame(['kind' => 'base', 'layout' => '_user_base'], $merged[1]['__source']);
|
||||
$this->assertSame(['kind' => 'route', 'layout' => 'home'], $merged[2]['__source']);
|
||||
}
|
||||
|
||||
public function test_duplicate_handler_both_preserved(): void
|
||||
{
|
||||
$parent = [['handler' => 'toast']];
|
||||
$child = [['handler' => 'toast']];
|
||||
$merged = $this->invokeMerge($parent, $child);
|
||||
$this->assertCount(2, $merged); // 중복 제거 안 함(실행 2회).
|
||||
}
|
||||
|
||||
public function test_empty_parent_with_child(): void
|
||||
{
|
||||
$merged = $this->invokeMerge([], [['handler' => 'toast']], ['kind' => 'base', 'layout' => '_base'], 'home');
|
||||
$this->assertCount(1, $merged);
|
||||
$this->assertSame(['kind' => 'route', 'layout' => 'home'], $merged[0]['__source']);
|
||||
}
|
||||
|
||||
public function test_parent_with_empty_child(): void
|
||||
{
|
||||
$merged = $this->invokeMerge([['handler' => 'initTheme']], [], ['kind' => 'base', 'layout' => '_base'], 'home');
|
||||
$this->assertCount(1, $merged);
|
||||
$this->assertSame(['kind' => 'base', 'layout' => '_base'], $merged[0]['__source']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services;
|
||||
|
||||
use App\Services\LayoutService;
|
||||
use ReflectionMethod;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* LayoutServiceMergeInitLocalTest — mergeShallow(initLocal/initGlobal/initIsolated) 단위
|
||||
*
|
||||
*
|
||||
* `initLocal`/`initGlobal`/`initIsolated` 는 shallow merge(자식 우선 — 같은 키 자식 값,
|
||||
* 중첩 객체 키는 통째 교체). 반사로 private mergeShallow 직접 검증.
|
||||
*/
|
||||
class LayoutServiceMergeInitLocalTest extends TestCase
|
||||
{
|
||||
private LayoutService $service;
|
||||
|
||||
private ReflectionMethod $merge;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->service = app(LayoutService::class);
|
||||
$this->merge = new ReflectionMethod(LayoutService::class, 'mergeShallow');
|
||||
$this->merge->setAccessible(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $parent 부모 객체
|
||||
* @param array $child 자식 객체
|
||||
* @return array 병합 결과
|
||||
*/
|
||||
private function invokeMerge(array $parent, array $child): array
|
||||
{
|
||||
return $this->merge->invoke($this->service, $parent, $child);
|
||||
}
|
||||
|
||||
public function test_shallow_merge_child_wins_same_key(): void
|
||||
{
|
||||
$merged = $this->invokeMerge(['perPage' => 20], ['perPage' => 50]);
|
||||
$this->assertSame(50, $merged['perPage']);
|
||||
}
|
||||
|
||||
public function test_parent_only_child_only_both(): void
|
||||
{
|
||||
$this->assertSame(['a' => 1], $this->invokeMerge(['a' => 1], []));
|
||||
$this->assertSame(['b' => 2], $this->invokeMerge([], ['b' => 2]));
|
||||
$this->assertSame(['a' => 1, 'b' => 2], $this->invokeMerge(['a' => 1], ['b' => 2]));
|
||||
}
|
||||
|
||||
public function test_nested_object_key_replaced_wholesale_not_deep(): void
|
||||
{
|
||||
// shallow — 중첩 객체 키는 통째 교체(deep merge 아님).
|
||||
$parent = ['filter' => ['status' => 'active', 'page' => 1]];
|
||||
$child = ['filter' => ['status' => 'archived']];
|
||||
$merged = $this->invokeMerge($parent, $child);
|
||||
// 자식 filter 통째 교체 — parent.filter.page 사라짐(shallow 확인).
|
||||
$this->assertSame(['status' => 'archived'], $merged['filter']);
|
||||
}
|
||||
|
||||
public function test_init_global_init_isolated_same_behavior(): void
|
||||
{
|
||||
// initGlobal/initIsolated 도 동일 mergeShallow 경로.
|
||||
$merged = $this->invokeMerge(['theme' => 'light'], ['theme' => 'dark', 'lang' => 'ko']);
|
||||
$this->assertSame(['theme' => 'dark', 'lang' => 'ko'], $merged);
|
||||
}
|
||||
|
||||
public function test_legacy_state_and_init_local_normalized_on_merge(): void
|
||||
{
|
||||
// ⑤ legacy state(부모) + initLocal(자식) 혼재 — mergeLayouts 가 `initLocal ?? state` 로
|
||||
// 정규화 후 shallow merge(LayoutService.php:146-148), 결과는 항상 `initLocal` 키.
|
||||
$parent = ['state' => ['perPage' => 20, 'sort' => 'asc'], 'layout_name' => 'parent'];
|
||||
$child = ['initLocal' => ['perPage' => 50], 'layout_name' => 'child'];
|
||||
|
||||
$merged = $this->service->mergeLayouts($parent, $child, null);
|
||||
|
||||
// 부모 state 가 initLocal 로 취급돼 병합(자식 perPage 우선, 부모 sort 보존).
|
||||
$this->assertArrayHasKey('initLocal', $merged);
|
||||
$this->assertArrayNotHasKey('state', $merged, '저장은 항상 initLocal 로 정규화(state 키 미출력)');
|
||||
$this->assertSame(50, $merged['initLocal']['perPage']);
|
||||
$this->assertSame('asc', $merged['initLocal']['sort']);
|
||||
}
|
||||
|
||||
public function test_with_source_meta_merged_superset_of_child_original(): void
|
||||
{
|
||||
// ⑥⑦ 편집 모드 출처 도출 — 병합본(merged.initLocal)은 자식 자기선언분(child.initLocal,
|
||||
// = __editor.original 의 SSoT)의 상위집합(merged ⊇ original). 차집합 = 부모 상속분.
|
||||
// (실제 __editor.original 영속·strip 은 InitialStateInheritedSaveTest 가 DB 라운드트립으로
|
||||
// 잠근다 — 본 단위는 병합 결과로 출처 비교가 도출 가능함을 확인.)
|
||||
$parent = ['initLocal' => ['fromParent' => 1, 'shared' => 'parent'], 'layout_name' => 'parent'];
|
||||
$childOriginal = ['fromChild' => 2, 'shared' => 'child'];
|
||||
$child = ['initLocal' => $childOriginal, 'layout_name' => 'child'];
|
||||
|
||||
$merged = $this->service->mergeLayouts($parent, $child, ['kind' => 'base', 'layout' => 'parent']);
|
||||
$mergedLocal = $merged['initLocal'];
|
||||
|
||||
// merged ⊇ original(자식 자기선언분 전부 병합본에 존재, 덮은 키는 자식 값).
|
||||
foreach ($childOriginal as $k => $v) {
|
||||
$this->assertArrayHasKey($k, $mergedLocal);
|
||||
$this->assertSame($v, $mergedLocal[$k], "자식 선언 키 {$k} 는 자식 값 유지");
|
||||
}
|
||||
// 차집합(merged − original) = 부모 상속분.
|
||||
$inheritedKeys = array_diff(array_keys($mergedLocal), array_keys($childOriginal));
|
||||
$this->assertSame(['fromParent'], array_values($inheritedKeys), '병합본 − 자기선언분 = 부모 상속 키');
|
||||
}
|
||||
}
|
||||
@@ -1196,7 +1196,7 @@ class LayoutServiceTest extends TestCase
|
||||
/**
|
||||
* transition_overlay 병합 - 자식이 wait_for 만 명시해도 부모의 spinner 설정이 보존되어야 함
|
||||
*
|
||||
* 이슈 #245 — engine-v1.30.0
|
||||
* engine-v1.30.0
|
||||
*/
|
||||
public function test_merge_transition_overlay_shallow_merge_preserves_parent_keys(): void
|
||||
{
|
||||
@@ -1308,4 +1308,124 @@ class LayoutServiceTest extends TestCase
|
||||
|
||||
$this->assertSame(false, $result['transition_overlay']);
|
||||
}
|
||||
|
||||
// ── 편집 모드 출처 메타 ──
|
||||
|
||||
/**
|
||||
* 운영 렌더($sourceMeta 미지정)는 init_actions 에 __source 를 부착하지 않는다.
|
||||
*/
|
||||
public function test_merge_init_actions_no_source_meta_in_render_mode(): void
|
||||
{
|
||||
$parent = [
|
||||
'meta' => [],
|
||||
'data_sources' => [],
|
||||
'components' => [],
|
||||
'init_actions' => [['handler' => 'initTheme']],
|
||||
];
|
||||
$child = [
|
||||
'meta' => [],
|
||||
'data_sources' => [],
|
||||
'components' => [],
|
||||
'init_actions' => [['handler' => 'toast', 'params' => ['message' => 'hi']]],
|
||||
];
|
||||
|
||||
$result = $this->layoutService->mergeLayouts($parent, $child);
|
||||
|
||||
$this->assertCount(2, $result['initActions']);
|
||||
$this->assertArrayNotHasKey('__source', $result['initActions'][0]);
|
||||
$this->assertArrayNotHasKey('__source', $result['initActions'][1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 편집 모드($sourceMeta 지정)는 init_actions 항목에 부모=base / 자식=route __source 를 부착한다.
|
||||
*/
|
||||
public function test_merge_init_actions_attaches_source_meta_in_edit_mode(): void
|
||||
{
|
||||
$parent = [
|
||||
'meta' => [],
|
||||
'data_sources' => [],
|
||||
'components' => [],
|
||||
'init_actions' => [['handler' => 'initTheme']],
|
||||
'layout_name' => '_user_base',
|
||||
];
|
||||
$child = [
|
||||
'meta' => [],
|
||||
'data_sources' => [],
|
||||
'components' => [],
|
||||
'init_actions' => [['handler' => 'toast', 'params' => ['message' => 'hi']]],
|
||||
'layout_name' => 'shop/show',
|
||||
];
|
||||
|
||||
$sourceMeta = ['kind' => 'base', 'layout' => '_user_base'];
|
||||
$result = $this->layoutService->mergeLayouts($parent, $child, $sourceMeta);
|
||||
|
||||
$this->assertCount(2, $result['initActions']);
|
||||
// 부모 항목 = base
|
||||
$this->assertSame(['kind' => 'base', 'layout' => '_user_base'], $result['initActions'][0]['__source']);
|
||||
// 자식 항목 = route + 자식 레이아웃명
|
||||
$this->assertSame(['kind' => 'route', 'layout' => 'shop/show'], $result['initActions'][1]['__source']);
|
||||
// 핸들러/params 는 보존(dispatch 화이트리스트 무영향)
|
||||
$this->assertSame('toast', $result['initActions'][1]['handler']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 편집 모드는 computed 키별 출처 맵을 레이아웃 최상위 __computedSource 에 부착한다.
|
||||
* (computed 객체 내부 아님 — 평가 순회 오평가 회피.)
|
||||
*/
|
||||
public function test_merge_computed_attaches_source_map_at_top_level_in_edit_mode(): void
|
||||
{
|
||||
$parent = [
|
||||
'meta' => [],
|
||||
'data_sources' => [],
|
||||
'components' => [],
|
||||
'computed' => ['parentCalc' => '{{ a ?? 0 }}'],
|
||||
'layout_name' => '_user_base',
|
||||
];
|
||||
$child = [
|
||||
'meta' => [],
|
||||
'data_sources' => [],
|
||||
'components' => [],
|
||||
// childCalc 신규 + parentCalc override
|
||||
'computed' => ['childCalc' => '{{ b ?? 0 }}', 'parentCalc' => '{{ c ?? 0 }}'],
|
||||
'layout_name' => 'shop/show',
|
||||
];
|
||||
|
||||
$sourceMeta = ['kind' => 'base', 'layout' => '_user_base'];
|
||||
$result = $this->layoutService->mergeLayouts($parent, $child, $sourceMeta);
|
||||
|
||||
// computed 객체 안에는 __computedSource 가 없다(평가 순회 안전).
|
||||
$this->assertArrayNotHasKey('__computedSource', $result['computed']);
|
||||
// 최상위에 출처 맵. 부모+자식이 모두 선언한 parentCalc 는 'route-override'(덮음),
|
||||
// 자식만 선언한 childCalc 는 'route'. (route-override 구분은 표현식 분해 트리에서 도입 —
|
||||
// 덮은 키에만 되돌리기 배지를 노출하기 위함. buildComputedSourceMap 참조.)
|
||||
$this->assertSame(
|
||||
['parentCalc' => 'route-override', 'childCalc' => 'route'],
|
||||
$result['__computedSource'],
|
||||
);
|
||||
// 자식 override 된 parentCalc 값은 자식 우선.
|
||||
$this->assertSame('{{ c ?? 0 }}', $result['computed']['parentCalc']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 운영 렌더는 __computedSource 를 부착하지 않는다.
|
||||
*/
|
||||
public function test_merge_computed_no_source_map_in_render_mode(): void
|
||||
{
|
||||
$parent = [
|
||||
'meta' => [],
|
||||
'data_sources' => [],
|
||||
'components' => [],
|
||||
'computed' => ['parentCalc' => '{{ a ?? 0 }}'],
|
||||
];
|
||||
$child = [
|
||||
'meta' => [],
|
||||
'data_sources' => [],
|
||||
'components' => [],
|
||||
'computed' => ['childCalc' => '{{ b ?? 0 }}'],
|
||||
];
|
||||
|
||||
$result = $this->layoutService->mergeLayouts($parent, $child);
|
||||
|
||||
$this->assertArrayNotHasKey('__computedSource', $result);
|
||||
}
|
||||
}
|
||||
@@ -281,4 +281,97 @@ class NotificationRecipientResolverTest extends TestCase
|
||||
$this->assertCount(1, $result);
|
||||
$this->assertEquals($user->id, $result->first()->id);
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────
|
||||
// 비회원(guest) trigger_user 폴백
|
||||
// ──────────────────────────────────────────────
|
||||
|
||||
public function test_trigger_user_falls_back_to_guest_recipient_when_no_user_id(): void
|
||||
{
|
||||
$result = $this->resolver->resolve(
|
||||
[['type' => 'trigger_user']],
|
||||
['guest_recipient' => ['email' => 'guest@example.com', 'name' => '홍길동', 'locale' => 'ko']]
|
||||
);
|
||||
|
||||
$this->assertCount(1, $result);
|
||||
$this->assertInstanceOf(\App\Notifications\GuestNotifiable::class, $result->first());
|
||||
$this->assertSame('guest@example.com', $result->first()->email);
|
||||
}
|
||||
|
||||
public function test_trigger_user_prefers_member_over_guest_recipient(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$result = $this->resolver->resolve(
|
||||
[['type' => 'trigger_user']],
|
||||
[
|
||||
'trigger_user_id' => $user->id,
|
||||
'trigger_user' => $user,
|
||||
'guest_recipient' => ['email' => 'guest@example.com'],
|
||||
]
|
||||
);
|
||||
|
||||
// 회원이 있으면 게스트 폴백을 타지 않는다
|
||||
$this->assertCount(1, $result);
|
||||
$this->assertInstanceOf(User::class, $result->first());
|
||||
$this->assertEquals($user->id, $result->first()->id);
|
||||
}
|
||||
|
||||
public function test_invalid_guest_recipient_yields_no_recipient(): void
|
||||
{
|
||||
$result = $this->resolver->resolve(
|
||||
[['type' => 'trigger_user']],
|
||||
['guest_recipient' => ['email' => '']]
|
||||
);
|
||||
|
||||
$this->assertCount(0, $result);
|
||||
}
|
||||
|
||||
public function test_duplicate_guest_email_dedupes_to_one(): void
|
||||
{
|
||||
// 같은 이메일 게스트가 두 규칙(둘 다 trigger_user)으로 들어와도 1명으로 dedupe
|
||||
$result = $this->resolver->resolve(
|
||||
[['type' => 'trigger_user'], ['type' => 'trigger_user']],
|
||||
['guest_recipient' => ['email' => 'guest@example.com']]
|
||||
);
|
||||
|
||||
$this->assertCount(1, $result);
|
||||
}
|
||||
|
||||
public function test_member_and_guest_coexist_without_collapsing(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
// role 규칙으로 회원, trigger_user 규칙으로 게스트 — null-id 게스트가 회원과 뭉개지지 않아야 함
|
||||
$role = Role::factory()->create(['identifier' => 'guest-coexist-role']);
|
||||
$user->roles()->attach($role->id);
|
||||
|
||||
$result = $this->resolver->resolve(
|
||||
[
|
||||
['type' => 'role', 'value' => 'guest-coexist-role'],
|
||||
['type' => 'trigger_user'],
|
||||
],
|
||||
['guest_recipient' => ['email' => 'guest@example.com']]
|
||||
);
|
||||
|
||||
$this->assertCount(2, $result);
|
||||
}
|
||||
|
||||
public function test_exclude_trigger_user_does_not_break_on_guest(): void
|
||||
{
|
||||
// 게스트 수신자 + exclude_trigger_user 규칙이 함께 있어도 예외 없이 통과
|
||||
$result = $this->resolver->resolve(
|
||||
[
|
||||
['type' => 'trigger_user'],
|
||||
['type' => 'role', 'value' => 'nonexistent-role', 'exclude_trigger_user' => true],
|
||||
],
|
||||
['guest_recipient' => ['email' => 'guest@example.com']]
|
||||
);
|
||||
|
||||
// 게스트는 user_id 가 없어 exclude 대상이 아니므로 그대로 유지
|
||||
$this->assertGreaterThanOrEqual(1, $result->count());
|
||||
$this->assertTrue(
|
||||
$result->contains(fn ($r) => $r instanceof \App\Notifications\GuestNotifiable)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -162,6 +162,79 @@ class NotificationTemplateServiceTest extends TestCase
|
||||
$this->assertFalse($result->is_active);
|
||||
}
|
||||
|
||||
/**
|
||||
* getDefaultTemplateData()가 click_url과 recipients를 포함하는지 확인 (복원 누락 회귀)
|
||||
*
|
||||
* config/core.php 의 welcome/database 채널은 recipients 와 click_url='/mypage' 를 가진다.
|
||||
* 복원 데이터에 두 필드가 누락되면 관리자 수정값이 잔존하므로 추출 화이트리스트를 검증한다.
|
||||
*/
|
||||
public function test_get_default_template_data_includes_click_url_and_recipients(): void
|
||||
{
|
||||
$data = $this->service->getDefaultTemplateData('welcome', 'database');
|
||||
|
||||
$this->assertArrayHasKey('click_url', $data);
|
||||
$this->assertArrayHasKey('recipients', $data);
|
||||
$this->assertEquals('/mypage', $data['click_url']);
|
||||
$this->assertEquals([['type' => 'trigger_user']], $data['recipients']);
|
||||
}
|
||||
|
||||
/**
|
||||
* config에 click_url이 없는 채널은 null로 복원되는지 확인 (정상값 비파괴)
|
||||
*
|
||||
* welcome/mail 채널은 recipients 만 있고 click_url 이 없으므로 null 이어야 한다.
|
||||
*/
|
||||
public function test_get_default_template_data_null_click_url_when_absent_in_config(): void
|
||||
{
|
||||
$data = $this->service->getDefaultTemplateData('welcome', 'mail');
|
||||
|
||||
$this->assertArrayHasKey('click_url', $data);
|
||||
$this->assertNull($data['click_url']);
|
||||
$this->assertEquals([['type' => 'trigger_user']], $data['recipients']);
|
||||
}
|
||||
|
||||
/**
|
||||
* resetToDefault()가 관리자 수정한 click_url/recipients를 기본값으로 복원하는지 확인 (회귀)
|
||||
*
|
||||
* 관리자가 click_url/recipients 를 수정한 뒤 복원하면 config 기본값으로 돌아가야 한다.
|
||||
* 수정 전에는 subject/body 만 복원되고 두 필드는 수정본이 잔존하는 결함이 있었다.
|
||||
*/
|
||||
public function test_reset_to_default_restores_click_url_and_recipients(): void
|
||||
{
|
||||
$definition = NotificationDefinition::create([
|
||||
'type' => 'welcome',
|
||||
'hook_prefix' => 'core.auth',
|
||||
'extension_type' => 'core',
|
||||
'extension_identifier' => 'core',
|
||||
'name' => ['ko' => '회원가입 환영'],
|
||||
'variables' => [],
|
||||
'channels' => ['database'],
|
||||
'hooks' => [],
|
||||
'is_active' => true,
|
||||
'is_default' => true,
|
||||
]);
|
||||
|
||||
// 관리자가 click_url/recipients 를 임의 값으로 수정한 상태
|
||||
$template = NotificationTemplate::create([
|
||||
'definition_id' => $definition->id,
|
||||
'channel' => 'database',
|
||||
'subject' => ['ko' => '수정된 제목'],
|
||||
'body' => ['ko' => '수정된 본문'],
|
||||
'click_url' => '/custom-edited-url',
|
||||
'recipients' => [['type' => 'admin']],
|
||||
'is_active' => true,
|
||||
'is_default' => false,
|
||||
'user_overrides' => ['click_url' => true, 'recipients' => true],
|
||||
]);
|
||||
|
||||
$defaultData = $this->service->getDefaultTemplateData('welcome', 'database');
|
||||
$restored = $this->service->resetToDefault($template, $defaultData);
|
||||
|
||||
$this->assertEquals('/mypage', $restored->click_url);
|
||||
$this->assertEquals([['type' => 'trigger_user']], $restored->recipients);
|
||||
$this->assertNull($restored->user_overrides);
|
||||
$this->assertTrue($restored->is_default);
|
||||
}
|
||||
|
||||
/**
|
||||
* getPreview()가 변수를 치환하는지 확인
|
||||
*/
|
||||
|
||||
@@ -478,4 +478,66 @@ class PermissionServiceTest extends TestCase
|
||||
|
||||
$this->assertFalse($parentNode['is_assignable']);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// getPermissionCandidates — 레이아웃 편집기 표시 권한 후보
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* 후보 목록은 리프(할당 가능) 권한만 포함하고 카테고리(자식 보유)는 제외한다.
|
||||
*/
|
||||
public function test_get_permission_candidates_excludes_category_parents(): void
|
||||
{
|
||||
$parent = Permission::factory()->create([
|
||||
'identifier' => 'cat.users',
|
||||
'name' => ['ko' => '회원 관리', 'en' => 'Users'],
|
||||
'parent_id' => null,
|
||||
]);
|
||||
Permission::factory()->create([
|
||||
'identifier' => 'cat.users.read',
|
||||
'name' => ['ko' => '회원 조회', 'en' => 'Read users'],
|
||||
'parent_id' => $parent->id,
|
||||
]);
|
||||
|
||||
$candidates = $this->permissionService->getPermissionCandidates('ko');
|
||||
$keys = array_column($candidates, 'key');
|
||||
|
||||
$this->assertContains('cat.users.read', $keys, '리프 권한은 후보에 포함되어야 한다');
|
||||
$this->assertNotContains('cat.users', $keys, '카테고리(부모) 권한은 후보에서 제외되어야 한다');
|
||||
}
|
||||
|
||||
/**
|
||||
* 각 후보는 식별자(key)와 로케일 표시명(name)을 함께 반환한다.
|
||||
*/
|
||||
public function test_get_permission_candidates_returns_identifier_and_localized_name(): void
|
||||
{
|
||||
Permission::factory()->create([
|
||||
'identifier' => 'shop.order.refund',
|
||||
'name' => ['ko' => '주문 환불', 'en' => 'Refund order'],
|
||||
'parent_id' => null,
|
||||
]);
|
||||
|
||||
$candidates = $this->permissionService->getPermissionCandidates('ko');
|
||||
$row = collect($candidates)->firstWhere('key', 'shop.order.refund');
|
||||
|
||||
$this->assertNotNull($row);
|
||||
$this->assertSame('shop.order.refund', $row['key']);
|
||||
$this->assertSame('주문 환불', $row['name']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 자식이 없는 단독 권한(루트지만 리프)도 후보에 포함된다.
|
||||
*/
|
||||
public function test_get_permission_candidates_includes_leaf_root_permission(): void
|
||||
{
|
||||
Permission::factory()->create([
|
||||
'identifier' => 'standalone.permission',
|
||||
'name' => ['ko' => '단독 권한', 'en' => 'Standalone'],
|
||||
'parent_id' => null,
|
||||
]);
|
||||
|
||||
$keys = array_column($this->permissionService->getPermissionCandidates('ko'), 'key');
|
||||
|
||||
$this->assertContains('standalone.permission', $keys);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services;
|
||||
|
||||
use App\Models\Template;
|
||||
use App\Models\TemplateCustomTranslation;
|
||||
use App\Services\TemplateCustomTranslationService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* TemplateCustomTranslationService 단위 테스트.
|
||||
*
|
||||
* 키 네이밍 정규화 / 활성 로케일 시드 / 폴백 / seq 증가를 검증합니다.
|
||||
*/
|
||||
class TemplateCustomTranslationServiceTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 같은 스위트의 DB 테스트와 migrate:fresh 정합성을 위해 일관 선언
|
||||
* (requiredExtensions 누락 시 migrate:fresh 1회 함정 — feedback_required_extensions_all_db_tests).
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
private TemplateCustomTranslationService $service;
|
||||
|
||||
private Template $template;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->service = app(TemplateCustomTranslationService::class);
|
||||
$this->template = Template::factory()->create();
|
||||
}
|
||||
|
||||
public function test_create_key_normalizes_layout_name_with_slash(): void
|
||||
{
|
||||
$model = $this->service->createKey($this->template->id, 'board/list', 'ko', '값');
|
||||
|
||||
$this->assertSame('custom.board_list.1', $model->translation_key);
|
||||
$this->assertSame('board/list', $model->layout_name);
|
||||
}
|
||||
|
||||
public function test_create_key_seeds_all_active_locales(): void
|
||||
{
|
||||
$model = $this->service->createKey($this->template->id, 'home', 'ko', '안녕');
|
||||
|
||||
// config('app.supported_locales') = ['ko', 'en']
|
||||
$this->assertArrayHasKey('ko', $model->values);
|
||||
$this->assertArrayHasKey('en', $model->values);
|
||||
$this->assertSame('안녕', $model->values['ko']);
|
||||
$this->assertSame('안녕', $model->values['en']);
|
||||
}
|
||||
|
||||
public function test_create_key_increments_seq(): void
|
||||
{
|
||||
$first = $this->service->createKey($this->template->id, 'home', 'ko', 'a');
|
||||
$second = $this->service->createKey($this->template->id, 'home', 'ko', 'b');
|
||||
$third = $this->service->createKey($this->template->id, 'home', 'ko', 'c');
|
||||
|
||||
$this->assertSame('custom.home.1', $first->translation_key);
|
||||
$this->assertSame('custom.home.2', $second->translation_key);
|
||||
$this->assertSame('custom.home.3', $third->translation_key);
|
||||
}
|
||||
|
||||
public function test_create_key_seq_is_isolated_per_layout(): void
|
||||
{
|
||||
$this->service->createKey($this->template->id, 'home', 'ko', 'a');
|
||||
$boardKey = $this->service->createKey($this->template->id, 'board/list', 'ko', 'b');
|
||||
|
||||
$this->assertSame('custom.board_list.1', $boardKey->translation_key);
|
||||
}
|
||||
|
||||
public function test_create_key_continues_seq_after_existing_rows(): void
|
||||
{
|
||||
TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.5',
|
||||
'values' => ['ko' => 'x', 'en' => 'x'],
|
||||
'status' => 'active',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
$next = $this->service->createKey($this->template->id, 'home', 'ko', 'y');
|
||||
|
||||
$this->assertSame('custom.home.6', $next->translation_key);
|
||||
}
|
||||
|
||||
public function test_update_values_preserves_user_overrides_tracking(): void
|
||||
{
|
||||
$model = $this->service->createKey($this->template->id, 'home', 'ko', 'orig');
|
||||
|
||||
$updated = $this->service->updateValues(
|
||||
$model->id,
|
||||
['ko' => '수정', 'en' => 'edited'],
|
||||
0,
|
||||
);
|
||||
|
||||
$this->assertSame('수정', $updated->values['ko']);
|
||||
$this->assertSame(1, $updated->lock_version);
|
||||
// HasUserOverrides — 사용자가 손댄 로케일이 추적됨
|
||||
$this->assertNotNull($updated->fresh()->user_overrides);
|
||||
}
|
||||
|
||||
public function test_normalize_empty_layout_name_falls_back_to_layout(): void
|
||||
{
|
||||
$model = $this->service->createKey($this->template->id, ' ', 'ko', 'v');
|
||||
|
||||
$this->assertSame('custom.layout.1', $model->translation_key);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services;
|
||||
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Models\Template;
|
||||
use App\Services\TemplateService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* TemplateService::getRoutesDataWithModules source 태깅 Unit 테스트
|
||||
*
|
||||
* 각 라우트에 source { kind, identifier } 메타가 정확히 부여되는지 검증한다.
|
||||
* 모듈/플러그인 라우트는 실제 활성 확장이 없으면 검증 불가하므로
|
||||
* 본 테스트는 템플릿 자체 라우트의 source 태깅에 집중한다(병합 충돌 회귀 가드).
|
||||
*/
|
||||
class TemplateServiceRoutesSourceTaggingTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private TemplateService $service;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->service = app(TemplateService::class);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function template_self_routes_carry_source_kind_template_with_null_identifier(): void
|
||||
{
|
||||
Template::create([
|
||||
'identifier' => 'sirsoft-admin_basic',
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
|
||||
'version' => '1.0.0',
|
||||
'type' => 'admin',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
'description' => ['ko' => '관리자 템플릿', 'en' => 'Admin Template'],
|
||||
]);
|
||||
|
||||
$result = $this->service->getRoutesDataWithModules('sirsoft-admin_basic');
|
||||
|
||||
$this->assertTrue($result['success']);
|
||||
$this->assertIsArray($result['data']['routes']);
|
||||
|
||||
$templateRoutes = array_filter(
|
||||
$result['data']['routes'],
|
||||
fn ($r) => isset($r['source']['kind']) && $r['source']['kind'] === 'template'
|
||||
);
|
||||
|
||||
$this->assertNotEmpty($templateRoutes, '템플릿 자체 라우트 최소 1건이 source.kind=template 으로 부여되어야 함');
|
||||
|
||||
foreach ($templateRoutes as $route) {
|
||||
$this->assertSame('template', $route['source']['kind']);
|
||||
$this->assertNull($route['source']['identifier']);
|
||||
}
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function every_route_in_response_has_source_field_after_merge(): void
|
||||
{
|
||||
Template::create([
|
||||
'identifier' => 'sirsoft-admin_basic',
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => ['ko' => '관리자', 'en' => 'Admin'],
|
||||
'version' => '1.0.0',
|
||||
'type' => 'admin',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
'description' => ['ko' => '관리자', 'en' => 'Admin'],
|
||||
]);
|
||||
|
||||
$result = $this->service->getRoutesDataWithModules('sirsoft-admin_basic');
|
||||
|
||||
$this->assertTrue($result['success']);
|
||||
|
||||
foreach ($result['data']['routes'] as $route) {
|
||||
$this->assertArrayHasKey('source', $route, '병합 후 모든 라우트는 source 키를 보유');
|
||||
$this->assertArrayHasKey('kind', $route['source']);
|
||||
$this->assertContains(
|
||||
$route['source']['kind'],
|
||||
['template', 'module', 'plugin', 'core'],
|
||||
'source.kind 는 template/module/plugin/core(시스템) 중 하나'
|
||||
);
|
||||
$this->assertArrayHasKey('identifier', $route['source']);
|
||||
}
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function inactive_template_returns_error_unchanged_by_source_tagging(): void
|
||||
{
|
||||
Template::create([
|
||||
'identifier' => 'sirsoft-admin_basic',
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => ['ko' => '관리자', 'en' => 'Admin'],
|
||||
'version' => '1.0.0',
|
||||
'type' => 'admin',
|
||||
'status' => ExtensionStatus::Inactive->value,
|
||||
'description' => ['ko' => '관리자', 'en' => 'Admin'],
|
||||
]);
|
||||
|
||||
$result = $this->service->getRoutesDataWithModules('sirsoft-admin_basic');
|
||||
|
||||
$this->assertFalse($result['success']);
|
||||
$this->assertSame('template_not_found', $result['error']);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user