v7.0.0 release

This commit is contained in:
HeuJung committed 2026-07-01 10:30:32 +09:00
1 parent 0e7fa04b03
commit c4ea9a6cd1
3582 files changed
+626189 -160151

No files matched your search

@@ -76,7 +76,8 @@ class ExtensionStatusCacheTest extends TestCase
$this->cache->put('ext.modules.active_identifiers', ['mod-a']);
$this->cache->put('ext.modules.installed_identifiers', ['mod-a']);
$stub = new class {
$stub = new class
{
use CachesModuleStatus;
};
$stub::invalidateModuleStatusCache();
@@ -113,7 +114,8 @@ class ExtensionStatusCacheTest extends TestCase
$this->cache->put('ext.plugins.active_identifiers', ['plugin-a']);
$this->cache->put('ext.plugins.installed_identifiers', ['plugin-a']);
$stub = new class {
$stub = new class
{
use CachesPluginStatus;
};
$stub::invalidatePluginStatusCache();
@@ -156,7 +158,8 @@ class ExtensionStatusCacheTest extends TestCase
$this->cache->put('ext.templates.active_identifiers_user', ['t-user']);
$this->cache->put('ext.templates.installed_identifiers', ['t-a']);
$stub = new class {
$stub = new class
{
use CachesTemplateStatus;
};
$stub::invalidateTemplateStatusCache();
@@ -179,7 +182,8 @@ class ExtensionStatusCacheTest extends TestCase
{
$this->cache->put('ext.cache_version', 1000);
$stub = new class {
$stub = new class
{
use ClearsTemplateCaches {
incrementExtensionCacheVersion as public callIncrement;
}
@@ -195,14 +199,27 @@ class ExtensionStatusCacheTest extends TestCase
}
/**
* A-4-3: 미설정 시 0 반환.
* A-4-3: 미설정(키 부재) 시 0 대신 새 유효 버전을 재생성·저장·반환.
*
* 회귀 가드 (버그 ②): `cache:clear` 로 키 소실 시 0 을 반환하면 자원 URL 이
* `?v=0` 으로 수렴해 immutable 에셋이 stale 고착된다. 키가 없으면 새 `time()`
* 버전을 생성·저장·반환해야 한다.
*/
#[Test]
public function a_4_3_get_extension_cache_version_returns_zero_when_unset(): void
public function a_4_3_get_extension_cache_version_regenerates_when_unset(): void
{
$this->cache->forget('ext.cache_version');
$this->assertSame(0, ClearsTemplateCaches::getExtensionCacheVersion());
$before = time();
$version = ClearsTemplateCaches::getExtensionCacheVersion();
// 0 이 아닌 유효한 타임스탬프 (기존 결함이면 0 → 실패)
$this->assertGreaterThanOrEqual($before, $version);
$this->assertLessThanOrEqual(time(), $version);
// 저장되어 다음 호출이 같은 값 반환
$this->assertSame($version, ClearsTemplateCaches::getExtensionCacheVersion());
$this->assertSame($version, (int) $this->cache->get('ext.cache_version'));
}
// ========================================================================
@@ -245,7 +262,8 @@ class ExtensionStatusCacheTest extends TestCase
{
$this->cache->put('ext.modules.active_identifiers', ['mod-a', 'mod-b']);
$stub = new class {
$stub = new class
{
use CachesModuleStatus;
};
$stub::invalidateModuleStatusCache();
@@ -262,7 +280,8 @@ class ExtensionStatusCacheTest extends TestCase
$this->cache->put('ext.modules.active_identifiers', ['mod-a']);
$this->cache->put('ext.modules.installed_identifiers', ['mod-a', 'mod-b']);
$stub = new class {
$stub = new class
{
use CachesModuleStatus;
};
$stub::invalidateModuleStatusCache();
@@ -283,7 +302,8 @@ class ExtensionStatusCacheTest extends TestCase
$this->assertSame([], $this->cache->get('ext.modules.active_identifiers'));
// 모듈 설치/활성화 시 invalidateModuleStatusCache 호출로 확실히 갱신
$stub = new class {
$stub = new class
{
use CachesModuleStatus;
};
$stub::invalidateModuleStatusCache();
@@ -313,7 +333,8 @@ class ExtensionStatusCacheTest extends TestCase
#[Test]
public function a_2_4_plugin_lifecycle_invalidates_cache(): void
{
$stub = new class {
$stub = new class
{
use CachesPluginStatus;
};
@@ -362,7 +383,8 @@ class ExtensionStatusCacheTest extends TestCase
{
$this->cache->put('ext.cache_version', 1000);
$stub = new class {
$stub = new class
{
use ClearsTemplateCaches {
incrementExtensionCacheVersion as public callIncrement;
}
@@ -380,7 +402,8 @@ class ExtensionStatusCacheTest extends TestCase
#[Test]
public function a_4_3_lifecycle_increments_each_step(): void
{
$stub = new class {
$stub = new class
{
use ClearsTemplateCaches {
incrementExtensionCacheVersion as public callIncrement;
}
@@ -0,0 +1,40 @@
<?php
namespace Tests\Unit\Config;
use Tests\TestCase;
/**
* 백업 디렉토리가 코어 업데이트 소유권 복원 대상에 포함되는지 검증 (OS 무관).
*
* 회귀 가드 (버그 ③): sudo 업데이트가 백업 디렉토리(storage/app/{extension,core}_backups)
* 를 root 소유로 잔존시켜 이후 www-data 의 mkdir 이 "mkdir(): Permission denied" 로
* 실패하던 결함. config 의 restore_ownership / restore_ownership_group_writable 목록에
* 백업 2경로가 포함되어야 Step 11 restoreOwnership 이 이를 정상화한다.
*/
class BackupDirectoryRestoreOwnershipConfigTest extends TestCase
{
/**
* restore_ownership 목록에 백업 2경로가 포함됨.
*/
public function test_restore_ownership_includes_backup_directories(): void
{
$paths = config('app.update.restore_ownership');
$this->assertIsArray($paths);
$this->assertContains('storage/app/extension_backups', $paths);
$this->assertContains('storage/app/core_backups', $paths);
}
/**
* restore_ownership_group_writable 목록에 백업 2경로가 포함됨.
*/
public function test_restore_ownership_group_writable_includes_backup_directories(): void
{
$paths = config('app.update.restore_ownership_group_writable');
$this->assertIsArray($paths);
$this->assertContains('storage/app/extension_backups', $paths);
$this->assertContains('storage/app/core_backups', $paths);
}
}
@@ -7,6 +7,7 @@ use App\Extension\ModuleManager;
use App\Extension\PluginManager;
use App\Extension\TemplateManager;
use App\Services\CoreUpdateService;
use App\Services\LanguagePackService;
use Mockery;
use Tests\TestCase;
@@ -23,7 +24,7 @@ class BundledExtensionUpdatePromptTest extends TestCase
*/
public function test_collect_bundled_updates_delegates_to_service(): void
{
$expected = [
$serviceResult = [
'modules' => [
['identifier' => 'sirsoft-ecommerce', 'current_version' => '1.0.0', 'latest_version' => '1.1.0', 'update_source' => 'bundled'],
],
@@ -32,13 +33,22 @@ class BundledExtensionUpdatePromptTest extends TestCase
],
'templates' => [],
];
$langPackResult = [
['identifier' => 'g7-core-ja', 'current_version' => '1.0.0', 'latest_version' => '1.0.1', 'update_source' => 'bundled'],
];
$serviceMock = Mockery::mock(CoreUpdateService::class);
$serviceMock->shouldReceive('collectBundledExtensionUpdates')
->once()
->andReturn($expected);
->andReturn($serviceResult);
$this->app->instance(CoreUpdateService::class, $serviceMock);
$langPackMock = Mockery::mock(LanguagePackService::class);
$langPackMock->shouldReceive('collectBundledLangPackUpdates')
->once()
->andReturn($langPackResult);
$this->app->instance(LanguagePackService::class, $langPackMock);
$harness = $this->makeTraitHarness();
$result = $harness->callCollect(
Mockery::mock(ModuleManager::class),
@@ -46,6 +56,8 @@ class BundledExtensionUpdatePromptTest extends TestCase
Mockery::mock(TemplateManager::class),
);
// trait 은 CoreUpdateService 결과에 LanguagePackService 의 lang_packs 를 덧붙인다.
$expected = $serviceResult + ['lang_packs' => $langPackResult];
$this->assertSame($expected, $result);
}
@@ -60,6 +72,12 @@ class BundledExtensionUpdatePromptTest extends TestCase
->andReturn(['modules' => [], 'plugins' => [], 'templates' => []]);
$this->app->instance(CoreUpdateService::class, $serviceMock);
$langPackMock = Mockery::mock(LanguagePackService::class);
$langPackMock->shouldReceive('collectBundledLangPackUpdates')
->once()
->andReturn([]);
$this->app->instance(LanguagePackService::class, $langPackMock);
$harness = $this->makeTraitHarness();
$result = $harness->callCollect(
Mockery::mock(ModuleManager::class),
@@ -70,6 +88,7 @@ class BundledExtensionUpdatePromptTest extends TestCase
$this->assertEmpty($result['modules']);
$this->assertEmpty($result['plugins']);
$this->assertEmpty($result['templates']);
$this->assertEmpty($result['lang_packs']);
}
/**
@@ -0,0 +1,124 @@
<?php
namespace Tests\Unit\Console;
use App\Console\Commands\Core\ExecuteUpgradeStepsCommand;
use Illuminate\Support\Facades\File;
use ReflectionMethod;
use Tests\TestCase;
/**
* 업그레이드 스텝 spawn 자식의 upgrade 로그 파일 소유권 복원 회귀 테스트.
*
* 회귀 가드 (버그 ③ 로그 영역): sudo 코어 업데이트는 upgrade step 을 별도 PHP 프로세스로
* spawn(ExecuteUpgradeStepsCommand) 하며, root 로 실행되어 `upgrade-YYYY-MM-DD.log`
* (Log::channel('upgrade')) 를 root 소유로 만든다. 이후 www-data(php-fpm) 의 module:update
* upgrade step 이 같은 날짜 로그에 append 하지 못해 "could not be opened in append mode:
* Permission denied" 로 실패한다.
*
* upgrade 로그를 만든 주체인 spawn 자식이 **항상 신버전 코드로 실행**되므로, 자기 종료
* 직전에 직접 로그 소유권을 부모(storage/logs) 기준으로 정합한다. 부모(CoreUpdateCommand)
* 는 업데이트 시작 시점의 이전 버전 클래스를 메모리에 들고 있을 수 있어(클래스 캐싱) 부모
* 측 정상화는 신뢰할 수 없다 — 그래서 자식이 처리한다.
*/
class CoreUpdateLogFileOwnershipTest extends TestCase
{
/**
* @var array<int, string>
*/
private array $createdFiles = [];
protected function tearDown(): void
{
foreach ($this->createdFiles as $f) {
@unlink($f);
}
parent::tearDown();
}
private function invokeRestore(): void
{
$command = new ExecuteUpgradeStepsCommand;
$method = new ReflectionMethod($command, 'restoreUpgradeLogOwnership');
$method->setAccessible(true);
$method->invoke($command);
}
/**
* upgrade-*.log 가 부모(storage/logs) 소유권으로 정합된다 (POSIX best-effort).
* sudo 아닌 환경에서 상속은 no-op(이미 부모와 동일 owner) 이므로 "로그 owner == 부모
* owner" 가 항상 성립해야 한다 — 상속이 owner 를 잘못 바꾸면 깨짐.
*/
public function test_restore_upgrade_log_ownership_matches_parent(): void
{
if (DIRECTORY_SEPARATOR !== '/' || ! function_exists('fileowner')) {
$this->markTestSkipped('소유권 검증은 POSIX 환경 전용 (Windows 로컬 자동 스킵)');
}
$logsDir = storage_path('logs');
File::ensureDirectoryExists($logsDir);
$upgradeLog = $logsDir.'/upgrade-2026-06-30.log';
file_put_contents($upgradeLog, "test\n");
$this->createdFiles[] = $upgradeLog;
$this->invokeRestore();
$this->assertSame(
fileowner($logsDir),
fileowner($upgradeLog),
'upgrade 로그는 부모(storage/logs) 소유권과 일치해야 함',
);
}
/**
* 확장 업그레이드 로그(extension-upgrade-*.log)도 정합 대상에 포함된다 (POSIX best-effort).
*
* 코어/확장 업그레이드 로그를 별도 채널(upgrade / extension-upgrade)로 분리했으므로,
* 소유권 정합 glob 이 두 접두사를 모두 커버해야 한다. 'upgrade-*.log' 단일 패턴은
* 'extension-' 접두사 파일을 매칭하지 못하므로 두 패턴을 각각 순회한다. 정합이 확장
* 로그를 누락하면 www-data 의 module:update 가 root 소유 파일에 append 못 해 회귀.
*/
public function test_restore_covers_extension_upgrade_log(): void
{
if (DIRECTORY_SEPARATOR !== '/' || ! function_exists('fileowner')) {
$this->markTestSkipped('소유권 검증은 POSIX 환경 전용 (Windows 로컬 자동 스킵)');
}
$logsDir = storage_path('logs');
File::ensureDirectoryExists($logsDir);
$extensionLog = $logsDir.'/extension-upgrade-2026-07-01.log';
file_put_contents($extensionLog, "ext\n");
$this->createdFiles[] = $extensionLog;
$this->invokeRestore();
$this->assertSame(
fileowner($logsDir),
fileowner($extensionLog),
'extension-upgrade 로그도 부모(storage/logs) 소유권과 일치해야 함',
);
}
/**
* 무관한 로그 파일(laravel.log, core_update_*.log 등)은 건드리지 않는다 — glob 한정성.
* (자식 메서드는 upgrade-*.log / extension-upgrade-*.log 만 처리. core_update_*.log 는
* 부모 saveUpdateLog 가 생성 직후 개별 정합하므로 자식 대상이 아님.)
*/
public function test_restore_does_not_throw_and_leaves_unrelated_files(): void
{
$logsDir = storage_path('logs');
File::ensureDirectoryExists($logsDir);
$unrelated = $logsDir.'/laravel-test-marker.log';
file_put_contents($unrelated, "keep\n");
$this->createdFiles[] = $unrelated;
$this->invokeRestore();
$this->assertFileExists($unrelated);
$this->assertSame("keep\n", file_get_contents($unrelated));
}
}
@@ -24,6 +24,7 @@ class IdentityVerificationInterfaceContractTest extends TestCase
'getId',
'getLabel',
'getChannels',
'getChannelLabels',
'getRenderHint',
'supportsPurpose',
'isAvailable',
@@ -45,6 +46,8 @@ class IdentityVerificationInterfaceContractTest extends TestCase
$this->assertIsString($provider->getId());
$this->assertIsString($provider->getLabel());
$this->assertIsArray($provider->getChannels());
$this->assertIsArray($provider->getChannelLabels());
$this->assertArrayHasKey('email', $provider->getChannelLabels());
$this->assertIsString($provider->getRenderHint());
$this->assertIsBool($provider->supportsPurpose('signup'));
$this->assertIsBool($provider->isAvailable());
@@ -0,0 +1,161 @@
<?php
namespace Tests\Unit\Extension;
use App\Contracts\Extension\CacheableExtensionInterface;
use App\Contracts\Extension\CacheInterface;
use App\Contracts\Extension\StorageInterface;
use App\Extension\AbstractExtensionServiceProvider;
use Mockery;
use Tests\TestCase;
require_once __DIR__.'/ServiceProviderTestFixtures.php';
/**
* AbstractExtensionServiceProvider 공통 자동 바인딩 동작 검증.
*
* - $repositories 배열은 interface → implementation 으로 바인딩된다.
* - $cacheServices 배열은 contextual binding 으로 확장 캐시를 주입한다.
* - $storageServices 배열은 contextual binding 으로 확장 스토리지를 주입한다.
* - 글로벌 CacheInterface / StorageInterface 바인딩은 덮어쓰지 않는다.
*/
class AbstractExtensionServiceProviderTest extends TestCase
{
public function test_repositories_bind_interface_to_implementation(): void
{
$extension = Mockery::mock(CacheableExtensionInterface::class);
$provider = new TestExtensionServiceProviderFixture($this->app, $extension);
$provider->setRepositories([
FixtureRepositoryInterface::class => FixtureRepositoryImpl::class,
]);
$provider->register();
$resolved = $this->app->make(FixtureRepositoryInterface::class);
$this->assertInstanceOf(FixtureRepositoryImpl::class, $resolved);
}
/**
* @scenario extension_kind=plugin,service_kind=cache_service,global_binding_state=absent,manager_state=plugin_resolved,consumer_type=single_class
* @effects cache_service_receives_plugin_cache_driver_with_correct_identifier_prefix, inicis_identity_provider_receives_correctly_prefixed_plugin_cache
*/
public function test_cache_services_receive_extension_cache_via_contextual_binding(): void
{
$cache = Mockery::mock(CacheInterface::class);
$extension = Mockery::mock(CacheableExtensionInterface::class);
$extension->shouldReceive('getCache')->andReturn($cache);
$provider = new TestExtensionServiceProviderFixture($this->app, $extension);
$provider->setCacheServices([FixtureCacheConsumer::class]);
$provider->register();
$consumer = $this->app->make(FixtureCacheConsumer::class);
$this->assertSame($cache, $consumer->cache);
}
/**
* @scenario extension_kind=plugin,service_kind=storage_service,global_binding_state=absent,manager_state=plugin_resolved,consumer_type=single_class
* @effects storage_service_receives_plugin_storage_driver_with_correct_disk
*/
public function test_storage_services_receive_extension_storage_via_contextual_binding(): void
{
$storage = Mockery::mock(StorageInterface::class);
$extension = Mockery::mock(CacheableExtensionInterface::class);
$extension->shouldReceive('getStorage')->andReturn($storage);
$provider = new TestExtensionServiceProviderFixture($this->app, $extension);
$provider->setStorageServices([FixtureStorageConsumer::class]);
$provider->register();
$consumer = $this->app->make(FixtureStorageConsumer::class);
$this->assertSame($storage, $consumer->storage);
}
public function test_register_does_not_rebind_global_cache_or_storage_interface(): void
{
$globalCache = Mockery::mock(CacheInterface::class);
$this->app->instance(CacheInterface::class, $globalCache);
$globalStorage = Mockery::mock(StorageInterface::class);
$this->app->instance(StorageInterface::class, $globalStorage);
$extension = Mockery::mock(CacheableExtensionInterface::class);
$extension->shouldReceive('getCache')->andReturn(Mockery::mock(CacheInterface::class));
$extension->shouldReceive('getStorage')->andReturn(Mockery::mock(StorageInterface::class));
$provider = new TestExtensionServiceProviderFixture($this->app, $extension);
$provider->setCacheServices([FixtureCacheConsumer::class]);
$provider->setStorageServices([FixtureStorageConsumer::class]);
$provider->register();
$this->assertSame($globalCache, $this->app->make(CacheInterface::class));
$this->assertSame($globalStorage, $this->app->make(StorageInterface::class));
}
/**
* @scenario extension_kind=plugin,service_kind=cache_service,global_binding_state=absent,manager_state=plugin_resolved,consumer_type=no_registration
* @effects empty_service_arrays_skip_contextual_binding_entirely
*/
public function test_empty_arrays_skip_contextual_bindings(): void
{
$extension = Mockery::mock(CacheableExtensionInterface::class);
$extension->shouldNotReceive('getCache');
$extension->shouldNotReceive('getStorage');
$provider = new TestExtensionServiceProviderFixture($this->app, $extension);
$provider->register();
$this->assertTrue(true);
}
protected function tearDown(): void
{
Mockery::close();
parent::tearDown();
}
}
/**
* 테스트 fixture: 확장 인스턴스를 직접 주입받는 ServiceProvider.
*/
class TestExtensionServiceProviderFixture extends AbstractExtensionServiceProvider
{
protected string $extensionIdentifier = 'fixture-extension';
private CacheableExtensionInterface $extension;
public function __construct($app, CacheableExtensionInterface $extension)
{
parent::__construct($app);
$this->extension = $extension;
}
protected function resolveExtension(): CacheableExtensionInterface
{
return $this->extension;
}
public function setRepositories(array $repositories): void
{
$this->repositories = $repositories;
}
public function setCacheServices(array $services): void
{
$this->cacheServices = $services;
}
public function setStorageServices(array $services): void
{
$this->storageServices = $services;
}
}
// 공유 fixture (FixtureRepositoryInterface / FixtureRepositoryImpl /
// FixtureCacheConsumer / FixtureStorageConsumer) 는 ServiceProviderTestFixtures.php
// 에 정의되어 있으며 PSR-4 / composer classmap 으로 자동 로드됩니다.
@@ -0,0 +1,83 @@
<?php
namespace Tests\Unit\Extension;
use App\Contracts\Extension\CacheableExtensionInterface;
use App\Contracts\Extension\CacheInterface;
use App\Contracts\Extension\ModuleInterface;
use App\Extension\BaseModuleServiceProvider;
use App\Extension\ModuleManager;
use Mockery;
use Tests\TestCase;
require_once __DIR__.'/ServiceProviderTestFixtures.php';
/**
* BaseModuleServiceProvider 단위 테스트 — 부모 추출 후 BC 보장.
*
* 기존 자식 클래스는 `$moduleIdentifier` 속성만 정의하며, 부모의
* `$extensionIdentifier` 로 투명하게 미러링되어야 한다.
*/
class BaseModuleServiceProviderTest extends TestCase
{
public function test_module_identifier_mirrors_to_extension_identifier(): void
{
$module = Mockery::mock(ModuleInterface::class);
$module->shouldReceive('getCache')
->andReturn($moduleCache = Mockery::mock(CacheInterface::class));
$moduleManager = Mockery::mock(ModuleManager::class);
$moduleManager->shouldReceive('getModule')
->with('vendor-test_module')
->andReturn($module);
$this->app->instance(ModuleManager::class, $moduleManager);
$provider = new TestBaseModuleServiceProviderFixture($this->app, 'vendor-test_module');
$provider->setCacheServices([FixtureCacheConsumer::class]);
$provider->register();
$consumer = $this->app->make(FixtureCacheConsumer::class);
$this->assertSame($moduleCache, $consumer->cache);
}
public function test_register_does_not_rebind_global_cache_interface(): void
{
$globalCache = Mockery::mock(CacheInterface::class);
$this->app->instance(CacheInterface::class, $globalCache);
$module = Mockery::mock(ModuleInterface::class);
$module->shouldReceive('getCache')->andReturn(Mockery::mock(CacheInterface::class));
$moduleManager = Mockery::mock(ModuleManager::class);
$moduleManager->shouldReceive('getModule')->andReturn($module);
$this->app->instance(ModuleManager::class, $moduleManager);
$provider = new TestBaseModuleServiceProviderFixture($this->app, 'vendor-test_module');
$provider->setCacheServices([FixtureCacheConsumer::class]);
$provider->register();
$this->assertSame($globalCache, $this->app->make(CacheInterface::class));
}
protected function tearDown(): void
{
Mockery::close();
parent::tearDown();
}
}
class TestBaseModuleServiceProviderFixture extends BaseModuleServiceProvider
{
public function __construct($app, string $identifier)
{
parent::__construct($app);
$this->moduleIdentifier = $identifier;
}
public function setCacheServices(array $services): void
{
$this->cacheServices = $services;
}
}
@@ -0,0 +1,89 @@
<?php
namespace Tests\Unit\Extension;
use App\Contracts\Extension\CacheableExtensionInterface;
use App\Contracts\Extension\CacheInterface;
use App\Contracts\Extension\PluginInterface;
use App\Extension\BasePluginServiceProvider;
use App\Extension\PluginManager;
use Mockery;
use Tests\TestCase;
require_once __DIR__.'/ServiceProviderTestFixtures.php';
/**
* BasePluginServiceProvider 단위 테스트.
*
* - $pluginIdentifier 가 부모의 $extensionIdentifier 로 미러링된다.
* - PluginManager 를 통해 확장을 해석하고 contextual binding 으로 캐시를 주입한다.
* - 글로벌 CacheInterface 바인딩은 덮어쓰지 않는다 (핵심 결함 차단).
*/
class BasePluginServiceProviderTest extends TestCase
{
/**
* @scenario extension_kind=plugin,service_kind=cache_service,global_binding_state=absent,manager_state=plugin_null_fallback,consumer_type=single_class
* @effects inline_adapter_used_when_plugin_not_registered_in_manager
*/
public function test_plugin_identifier_mirrors_to_extension_identifier(): void
{
$plugin = Mockery::mock(PluginInterface::class);
$plugin->shouldReceive('getCache')
->andReturn($pluginCache = Mockery::mock(CacheInterface::class));
$pluginManager = Mockery::mock(PluginManager::class);
$pluginManager->shouldReceive('getPlugin')
->with('vendor-test_plugin')
->andReturn($plugin);
$this->app->instance(PluginManager::class, $pluginManager);
$provider = new TestBasePluginServiceProviderFixture($this->app, 'vendor-test_plugin');
$provider->setCacheServices([FixtureCacheConsumer::class]);
$provider->register();
$consumer = $this->app->make(FixtureCacheConsumer::class);
$this->assertSame($pluginCache, $consumer->cache);
}
public function test_register_does_not_rebind_global_cache_interface(): void
{
$globalCache = Mockery::mock(CacheInterface::class);
$this->app->instance(CacheInterface::class, $globalCache);
$plugin = Mockery::mock(PluginInterface::class);
$plugin->shouldReceive('getCache')->andReturn(Mockery::mock(CacheInterface::class));
$pluginManager = Mockery::mock(PluginManager::class);
$pluginManager->shouldReceive('getPlugin')->andReturn($plugin);
$this->app->instance(PluginManager::class, $pluginManager);
$provider = new TestBasePluginServiceProviderFixture($this->app, 'vendor-test_plugin');
$provider->setCacheServices([FixtureCacheConsumer::class]);
$provider->register();
// 글로벌 바인딩이 보존되어 코어 도메인이 누수되지 않음을 검증
$this->assertSame($globalCache, $this->app->make(CacheInterface::class));
}
protected function tearDown(): void
{
Mockery::close();
parent::tearDown();
}
}
class TestBasePluginServiceProviderFixture extends BasePluginServiceProvider
{
public function __construct($app, string $identifier)
{
parent::__construct($app);
$this->pluginIdentifier = $identifier;
}
public function setCacheServices(array $services): void
{
$this->cacheServices = $services;
}
}
@@ -2,7 +2,9 @@
namespace Tests\Unit\Extension;
use App\Contracts\Extension\CacheInterface;
use App\Enums\ExtensionStatus;
use App\Extension\Cache\PluginCacheDriver;
use App\Extension\Traits\ClearsTemplateCaches;
use App\Models\Template;
use Illuminate\Foundation\Testing\RefreshDatabase;
@@ -49,7 +51,12 @@ class ClearsTemplateCachesTest extends TestCase
}
};
// 캐시 초기화
// 스토어 메모 초기화 — 본 테스트는 기본 스토어(config('cache.default')) 기준으로
// 버전을 검증하므로, 직전 테스트가 다른 스토어로 메모이즈했을 수 있어 리셋한다.
ClearsTemplateCaches::resetExtensionCacheStoreMemo();
// 캐시 초기화 — 확장 좌표 키가 들어가는 스토어를 명시적으로 비운다(메모 고정 스토어).
Cache::store(config('cache.default'))->flush();
Cache::flush();
}
@@ -58,9 +65,6 @@ class ClearsTemplateCachesTest extends TestCase
*/
public function test_increment_extension_cache_version(): void
{
// 초기 상태: 캐시 버전이 0
$this->assertEquals(0, ClearsTemplateCaches::getExtensionCacheVersion());
// 캐시 버전 증가
$beforeTime = time();
$this->traitUser->callIncrementExtensionCacheVersion();
@@ -93,15 +97,48 @@ class ClearsTemplateCachesTest extends TestCase
}
/**
* getExtensionCacheVersion 정적 메서드 테스트
* getExtensionCacheVersion 정적 메서드가 키 부재 시 새 유효 버전을 재생성한다.
*
* 회귀 가드 (버그 ②): 과거에는 키 부재(`cache:clear` 로 소실) 시 무효값 0 을
* 반환하여 모든 자원 URL 이 `?v=0` 으로 수렴 → 과거 `?v=0` 에 immutable 로 박힌
* 구버전 에셋이 stale 고착("Unknown action handler" 회귀). 이제 키가 없으면
* 새 `time()` 버전을 생성·저장·반환해 프론트가 새 URL 로 요청하도록 한다.
*/
public function test_get_extension_cache_version_returns_zero_when_not_set(): void
public function test_get_extension_cache_version_regenerates_when_not_set(): void
{
Cache::forget('g7:core:ext.cache_version');
$beforeTime = time();
$version = ClearsTemplateCaches::getExtensionCacheVersion();
$afterTime = time();
$this->assertEquals(0, $version);
// 0 이 아닌 유효한 타임스탬프 반환 (기존 결함이면 0 → 실패)
$this->assertGreaterThanOrEqual($beforeTime, $version);
$this->assertLessThanOrEqual($afterTime, $version);
// 생성된 버전이 캐시에 저장됨 — 다음 호출이 같은 값을 반환
$this->assertSame($version, ClearsTemplateCaches::getExtensionCacheVersion());
}
/**
* 캐시 전체 비우기(cache:clear) 후에도 유효 버전이 재생성된다.
*
* 회귀 가드 (버그 ②): `php artisan cache:clear` 가 `ext.cache_version` 키를 함께
* 삭제하면 0 이 내려가 자원 URL 이 `?v=0` 으로 붕괴하던 결함. 이제 키가 비어도
* 다음 조회에서 새 유효 버전을 재생성하므로 stale 고착이 발생하지 않는다.
*/
public function test_version_survives_cache_clear(): void
{
// 버전 bump 후 양수 확인
$this->traitUser->callIncrementExtensionCacheVersion();
$this->assertGreaterThan(0, ClearsTemplateCaches::getExtensionCacheVersion());
// cache:clear 시뮬레이션 — 키 소실
Cache::store(config('cache.default'))->flush();
Cache::flush();
// 재생성되어 여전히 양수 (0 붕괴 차단)
$this->assertGreaterThan(0, ClearsTemplateCaches::getExtensionCacheVersion());
}
/**
@@ -109,6 +146,9 @@ class ClearsTemplateCachesTest extends TestCase
*/
public function test_get_extension_cache_version_returns_cached_value(): void
{
// 확장 기능 캐시 버전은 코어 소유 키이므로 항상 `g7:core:` 네임스페이스에 저장된다.
// 모듈/플러그인 테스트가 CacheInterface 를 PluginCacheDriver 등으로 재바인딩해도
// getExtensionCacheVersion() 은 CoreCacheDriver 를 통해 동일 키를 조회해야 한다.
$expectedVersion = 1735000000;
Cache::put('g7:core:ext.cache_version', $expectedVersion);
@@ -117,6 +157,34 @@ class ClearsTemplateCachesTest extends TestCase
$this->assertEquals($expectedVersion, $version);
}
/**
* CacheInterface 가 PluginCacheDriver 로 재바인딩된 상태에서도
* 확장 기능 캐시 버전은 코어 네임스페이스(`g7:core:`)를 사용해야 한다.
*
* 회귀 방지: 과거 resolveExtensionCache() 가 컨테이너의 CacheInterface
* 바인딩을 그대로 사용해, 선행 모듈/플러그인 테스트가 남긴 PluginCacheDriver
* 바인딩 때문에 `g7:plugin:` 네임스페이스로 읽혀 버전을 0 으로 오인하던 결함.
*/
public function test_extension_cache_version_uses_core_namespace_despite_rebound_cache_interface(): void
{
// 다른 테스트가 컨테이너 CacheInterface 를 플러그인 드라이버로 재바인딩한 상황 모사
$this->app->instance(
CacheInterface::class,
new PluginCacheDriver('sirsoft-payment', config('cache.default', 'array')),
);
$expectedVersion = 1735000000;
Cache::put('g7:core:ext.cache_version', $expectedVersion);
// 트레이트는 재바인딩과 무관하게 CoreCacheDriver 로 코어 키를 조회한다.
$this->assertEquals($expectedVersion, ClearsTemplateCaches::getExtensionCacheVersion());
// incrementExtensionCacheVersion() 도 코어 네임스페이스에 기록한다.
$this->traitUser->callIncrementExtensionCacheVersion();
$written = Cache::get('g7:core:ext.cache_version');
$this->assertEquals($written, ClearsTemplateCaches::getExtensionCacheVersion());
}
/**
* clearAllTemplateLanguageCaches() 는 버전 기반 설계로 리팩토링되어 레거시 no-op.
*
@@ -209,14 +277,11 @@ class ClearsTemplateCachesTest extends TestCase
'description' => ['ko' => '테스트용', 'en' => 'For testing'],
]);
// 초기 버전 0
$this->assertEquals(0, \App\Extension\Traits\ClearsTemplateCaches::getExtensionCacheVersion());
// 버전 증가
$this->traitUser->callIncrementExtensionCacheVersion();
// 타임스탬프로 설정됨 (양수)
$newVersion = \App\Extension\Traits\ClearsTemplateCaches::getExtensionCacheVersion();
$newVersion = ClearsTemplateCaches::getExtensionCacheVersion();
$this->assertGreaterThan(0, $newVersion);
$this->assertLessThanOrEqual(time(), $newVersion);
}
@@ -286,4 +286,39 @@ class CoreBackupHelperTest extends TestCase
$this->assertArrayHasKey('name', $fixtureBackups[0]);
$this->assertArrayHasKey('created_at', $fixtureBackups[0]);
}
/**
* 코어 백업 디렉토리가 부모(php-fpm) 소유권을 상속한다 (POSIX best-effort).
*
* 회귀 가드 (버그 ③): sudo 업데이트가 백업 루트(core_backups)/디렉토리를 root 소유로
* 잔존시키면 이후 www-data 의 mkdir 이 실패한다. createBackup 은 백업 루트와 타임스탬프
* 디렉토리 양쪽에 부모 소유권을 상속해야 한다. sudo 없는 환경에서 상속은 no-op 이므로
* "백업 owner == 부모 owner" 가 항상 성립해야 한다 — 상속이 owner 를 잘못 바꾸면 깨짐.
*/
public function test_create_backup_inherits_parent_ownership(): void
{
if (DIRECTORY_SEPARATOR !== '/' || ! function_exists('fileowner')) {
$this->markTestSkipped('소유권 검증은 POSIX 환경 전용 (Windows 로컬 자동 스킵)');
}
// 가벼운 단일 파일 target 으로 백업 생성
File::put($this->testBasePath.'/sample.txt', 'core backup ownership test');
$backupPath = CoreBackupHelper::createBackup(['app/test_core_backup/sample.txt']);
// 백업 루트(core_backups) 가 부모(storage/app) 소유권을 상속
$this->assertSame(
fileowner(dirname($this->backupsBasePath)),
fileowner($this->backupsBasePath),
'백업 루트(core_backups)는 부모 소유권을 상속해야 함',
);
// 타임스탬프 디렉토리(core_{ts})도 부모(core_backups) owner 와 일치
$this->assertSame(
fileowner($this->backupsBasePath),
fileowner($backupPath),
'백업 타임스탬프 디렉토리는 부모 소유권을 상속해야 함',
);
CoreBackupHelper::deleteBackup($backupPath);
}
}
@@ -134,4 +134,68 @@ class ExtensionBackupHelperTest extends TestCase
ExtensionBackupHelper::createBackup('modules', 'nonexistent-module');
}
/**
* 백업 디렉토리가 부모(php-fpm) 소유권을 상속한다 (POSIX best-effort).
*
* 회귀 가드 (버그 ③): sudo 업데이트가 백업 부모/디렉토리를 root 소유로 잔존시키면
* 이후 www-data 의 mkdir 이 실패한다. createBackup 은 부모 소유권을 상속해 이를
* 차단해야 한다. sudo 없는 일반 환경에서 상속은 no-op(이미 부모와 동일 owner) 이므로
* "백업 owner == 부모 owner" 가 항상 성립해야 한다 — 상속이 owner 를 잘못 바꾸면 깨짐.
*/
public function test_create_backup_inherits_parent_ownership(): void
{
if (DIRECTORY_SEPARATOR !== '/' || ! function_exists('fileowner')) {
$this->markTestSkipped('소유권 검증은 POSIX 환경 전용 (Windows 로컬 자동 스킵)');
}
$backupPath = ExtensionBackupHelper::createBackup('modules', 'test-backup-mod');
// 백업 루트(extension_backups/modules) 의 owner 가 부모(extension_backups) 와 일치
$backupTypeDir = dirname($backupPath);
$this->assertSame(
fileowner(dirname($backupTypeDir)),
fileowner($backupTypeDir),
'백업 타입 디렉토리는 부모 소유권을 상속해야 함',
);
// 백업 타임스탬프 디렉토리도 부모 owner 와 일치
$this->assertSame(
fileowner($backupTypeDir),
fileowner($backupPath),
'백업 디렉토리는 부모 소유권을 상속해야 함',
);
}
/**
* 백업 부모 디렉토리(extension_backups/{type})가 g-w(0755)로 미리 존재해도 백업 생성이
* 성공하고, 부모 체인이 g+w(0775)로 정상화된다 (POSIX best-effort).
*
* 회귀 가드 (버그 ③): sudo 코어 업데이트가 extension_backups/modules 등 백업 부모
* 디렉토리를 g-w(0755)로 만들어 두면 이후 php-fpm 그룹이 그 안에 백업을 mkdir 하지
* 못해 "mkdir(): Permission denied" 로 module:update 가 백업 생성 단계에서 실패한다.
* createBackup 은 부모 체인을 g+w 로 보장한 뒤 백업을 생성해야 한다.
*/
public function test_create_backup_succeeds_when_parent_dir_is_group_unwritable(): void
{
if (DIRECTORY_SEPARATOR !== '/' || ! function_exists('fileperms')) {
$this->markTestSkipped('권한 검증은 POSIX 환경 전용 (Windows 로컬 자동 스킵)');
}
// 백업 부모 체인을 미리 g-w(0755)로 만들어 둔다 (sudo 업데이트 잔재 재현)
$backupRoot = storage_path('app/extension_backups');
$backupTypeDir = $backupRoot.'/modules';
File::ensureDirectoryExists($backupTypeDir);
@chmod($backupRoot, 0755);
@chmod($backupTypeDir, 0755);
// g-w 상태에서도 백업 생성이 mkdir 오류 없이 성공해야 한다
$backupPath = ExtensionBackupHelper::createBackup('modules', 'test-backup-mod');
$this->assertDirectoryExists($backupPath);
// 부모 체인이 g+w(0775)로 정상화됨 — group write 비트(0020) 확인
$this->assertSame(0020, fileperms($backupRoot) & 0020, 'extension_backups 가 g+w 여야 함');
$this->assertSame(0020, fileperms($backupTypeDir) & 0020, 'extension_backups/modules 가 g+w 여야 함');
}
}
@@ -0,0 +1,104 @@
<?php
namespace Tests\Unit\Extension;
use App\Extension\Traits\ClearsTemplateCaches;
use Illuminate\Support\Facades\Config;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* `ext.cache_version` 캐시 스토어 일관성 회귀.
*
* 배경: `ext.cache_version` 은 확장 업데이트/설치/레이아웃 변경 시 bump 되어
* 프론트엔드 fetch URL(`?v=`)을 무효화하는 코어 소유 좌표 키다. 값은
* `ClearsTemplateCaches::incrementExtensionCacheVersion()`(write)과
* `getExtensionCacheVersion()`(read)가 **반드시 같은 캐시 스토어**를 써야 한다.
*
* 결함(재현): 종전 구현은 스토어를 `config('cache.default')` 로 매번 해소했다.
* 그런데 `SettingsServiceProvider::applyCacheConfig` 가 부팅 중 admin 설정값
* (`g7_core_settings('cache.driver')`)으로 `cache.default` 를 **런타임 오버라이드**한다.
* 따라서 settings 로드 타이밍/컨텍스트(웹 vs CLI vs 큐, 설정 미시드 환경)에 따라
* write 와 read 가 **서로 다른 스토어**(예: write=database(.env), read=file(settings))를
* 가리키면, bump 한 버전이 read 경로에서 보이지 않아 프론트엔드가 영구 stale 캐시를
* 받는다(편집기 데이터소스 명칭/레이아웃 변경 미반영).
*
* 본 테스트는 write 직후 read 사이에 `config('cache.default')` 가 바뀌어도(설정
* 오버라이드 시뮬레이션) 값이 일관되게 보존됨을 잠근다.
*/
class ExtensionCacheVersionStoreConsistencyTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
// 스토어 메모 초기화 — 각 테스트가 자기 cache.default 기준으로 1회 해소하도록.
ClearsTemplateCaches::resetExtensionCacheStoreMemo();
}
protected function tearDown(): void
{
ClearsTemplateCaches::resetExtensionCacheStoreMemo();
parent::tearDown();
}
/** trait protected 메서드 노출용 더블 */
private function makeSubject(): object
{
return new class
{
use ClearsTemplateCaches;
public function bump(): void
{
$this->incrementExtensionCacheVersion();
}
public function read(): int
{
return self::getExtensionCacheVersion();
}
};
}
#[Test]
public function version_bump_is_readable_after_cache_default_changes(): void
{
$subject = $this->makeSubject();
// write 시점 — 한 스토어(예: array)
Config::set('cache.default', 'array');
$subject->bump();
$written = $subject->read();
$this->assertGreaterThan(0, $written, 'bump 직후 같은 스토어에서 읽혀야 함');
// read 시점 — settings 오버라이드로 cache.default 가 바뀐 상황 시뮬레이션
Config::set('cache.default', 'file');
$afterChange = $subject->read();
// 핵심 불변식: write 와 read 가 같은 고정 스토어를 쓰므로 cache.default 변경에
// 영향받지 않고 동일 값이 보여야 한다(스토어 분기 = stale 캐시 회귀).
$this->assertSame(
$written,
$afterChange,
'ext.cache_version 은 cache.default 변경과 무관하게 동일 스토어로 일관 read/write 되어야 함'
);
}
#[Test]
public function version_written_under_one_default_is_visible_under_another(): void
{
$subject = $this->makeSubject();
// database(.env 기본) 스토어 컨텍스트에서 write
Config::set('cache.default', 'database');
$subject->bump();
$v1 = $subject->read();
// file(settings 오버라이드) 스토어 컨텍스트에서 read — 같은 값이어야 함
Config::set('cache.default', 'file');
$v2 = $subject->read();
$this->assertSame($v1, $v2, 'write/read 컨텍스트의 cache.default 가 달라도 같은 버전이 보여야 함');
$this->assertGreaterThan(0, $v2, 'read 컨텍스트에서 0(미설정)으로 떨어지면 stale 캐시 회귀');
}
}
@@ -363,6 +363,65 @@ class ExtensionMenuSyncHelperTest extends TestCase
);
}
/**
* sync 호출 시 update 시점에 user_overrides.seeding 플래그가 true 로 설정되는지 테스트.
*
* HasUserOverrides::bootHasUserOverrides 의 updating 이벤트 hook 이 이 플래그를 보고
* 자동 마킹을 건너뛴다. 미설정 시 동일 정의값을 적용해도 trackable 필드 (icon 포함) 가 dirty
* 로 잡혀 user_overrides 에 자동 추가되어 이후 sync 가 차단되는 결함이 발생.
*/
public function test_sync_menu_disables_user_overrides_auto_marking_during_update(): void
{
$existingMenu = $this->createModelMock(Menu::class, [
'id' => 1,
'name' => ['ko' => '게시판 관리', 'en' => 'Board Management'],
'icon' => 'fas fa-list',
'order' => 10,
'url' => '/admin/boards',
'user_overrides' => [],
]);
$this->menuRepository
->shouldReceive('findBySlugAndExtension')
->once()
->andReturn($existingMenu);
$seedingFlagDuringUpdate = null;
$this->menuRepository
->shouldReceive('update')
->once()
->andReturnUsing(function () use (&$seedingFlagDuringUpdate) {
$seedingFlagDuringUpdate = app()->bound('user_overrides.seeding')
&& app('user_overrides.seeding') === true;
return true;
});
$freshMenu = $this->createModelMock(Menu::class, ['id' => 1]);
$existingMenu->shouldReceive('fresh')->once()->andReturn($freshMenu);
$this->helper->syncMenu(
slug: 'board-management',
extensionType: ExtensionOwnerType::Module,
extensionIdentifier: 'sirsoft-board',
newAttributes: [
'name' => ['ko' => '게시판 관리', 'en' => 'Board Management'],
'icon' => 'fas fa-list',
'order' => 10,
'url' => '/admin/boards',
],
);
$this->assertTrue(
$seedingFlagDuringUpdate,
'update 시점에 user_overrides.seeding 플래그가 true 여야 자동 마킹 hook 이 skip 된다.'
);
$this->assertFalse(
app()->bound('user_overrides.seeding'),
'syncMenu 종료 후 seeding 플래그는 컨테이너에서 정리되어야 한다.'
);
}
/**
* parent_id와 is_active는 항상 확장 정의값으로 업데이트되는지 테스트
*/
@@ -229,6 +229,63 @@ class ExtensionRoleSyncHelperTest extends TestCase
$this->assertSame($freshRole, $result);
}
/**
* sync 시점에 user_overrides 자동 마킹이 비활성화되는지 테스트.
*
* 회귀 방지: HasUserOverrides trait 의 `updating` 이벤트 hook 은
* `app('user_overrides.seeding') === true` 일 때 자동 마킹을 건너뛴다.
* Helper 가 update 호출을 seeding 컨텍스트로 wrap 하지 않으면 시스템 sync
* 임에도 name/description 등 trackable 필드가 user_overrides 에 잘못
* 마킹되어 이후 sync 가 영구히 차단된다 (Menu sync 와 동일 결함).
*/
public function test_sync_role_disables_user_overrides_auto_marking_during_update(): void
{
$newName = ['ko' => 'Board 관리자', 'en' => 'Board Admin'];
$newDescription = ['ko' => '게시판 관리 역할', 'en' => 'Board management role'];
$existingRole = $this->createModelMock(Role::class, [
'name' => ['ko' => '게시판 관리자', 'en' => 'Board Manager'],
'description' => ['ko' => '이전 설명', 'en' => 'Previous description'],
'user_overrides' => [],
]);
$freshRole = $this->createModelMock(Role::class);
$existingRole->shouldReceive('fresh')->once()->andReturn($freshRole);
$this->roleRepository->shouldReceive('findByIdentifier')
->once()
->with('board-manager')
->andReturn($existingRole);
$seedingFlagDuringUpdate = null;
$this->roleRepository->shouldReceive('update')
->once()
->with($existingRole, Mockery::any())
->andReturnUsing(function () use (&$seedingFlagDuringUpdate) {
$seedingFlagDuringUpdate = app()->bound('user_overrides.seeding')
&& app('user_overrides.seeding') === true;
return true;
});
$this->helper->syncRole(
identifier: 'board-manager',
newName: $newName,
newDescription: $newDescription,
extensionType: ExtensionOwnerType::Module,
extensionIdentifier: 'sirsoft-board',
);
$this->assertTrue(
$seedingFlagDuringUpdate,
'update 호출 시점에 user_overrides.seeding 플래그가 true 여야 한다.'
);
$this->assertFalse(
app()->bound('user_overrides.seeding'),
'syncRole 종료 후 user_overrides.seeding 플래그가 정리되어야 한다.'
);
}
// =========================================================
// syncPermission 테스트
// =========================================================
@@ -0,0 +1,134 @@
<?php
namespace Tests\Unit\Extension;
use App\Extension\Testing\ExtensionTestAllowlist;
use Tests\TestCase;
/**
* ExtensionTestAllowlist 단위 테스트
*
* 테스트 환경 확장 격리 allowlist 컨테이너의 set/reset/isAllowed/isActive 동작을 검증합니다.
*/
class ExtensionTestAllowlistTest extends TestCase
{
/**
* 각 테스트 후 allowlist 를 깨끗한 상태로 되돌립니다.
*
* (TestCase::tearDown 이 이미 reset 하지만, 본 테스트는 set 동작을
* 직접 검증하므로 명시적으로 한 번 더 보장합니다.)
*/
protected function tearDown(): void
{
ExtensionTestAllowlist::reset();
parent::tearDown();
}
/**
* @effects set_classifies_plugin_and_module_by_path_prefix
*/
public function test_set_classifies_plugin_and_module_by_path_prefix(): void
{
ExtensionTestAllowlist::set([
'plugins/sirsoft-gdpr',
'modules/sirsoft-ecommerce',
]);
$this->assertTrue(ExtensionTestAllowlist::isAllowed('plugin', 'sirsoft-gdpr'));
$this->assertTrue(ExtensionTestAllowlist::isAllowed('module', 'sirsoft-ecommerce'));
}
public function test_is_allowed_returns_false_for_extension_outside_allowlist(): void
{
ExtensionTestAllowlist::set(['plugins/sirsoft-gdpr']);
$this->assertFalse(ExtensionTestAllowlist::isAllowed('plugin', 'sirsoft-marketing'));
$this->assertFalse(ExtensionTestAllowlist::isAllowed('module', 'sirsoft-gdpr'));
$this->assertFalse(ExtensionTestAllowlist::isAllowed('unknown', 'sirsoft-gdpr'));
}
/**
* @effects set_normalizes_trailing_slash
*/
public function test_set_normalizes_trailing_slash(): void
{
ExtensionTestAllowlist::set(['plugins/sirsoft-gdpr/']);
$this->assertTrue(ExtensionTestAllowlist::isAllowed('plugin', 'sirsoft-gdpr'));
}
/**
* @effects set_ignores_prefixless_entries
*/
public function test_set_ignores_prefixless_entries(): void
{
ExtensionTestAllowlist::set(['sirsoft-gdpr', 'templates/sirsoft-basic']);
$this->assertFalse(ExtensionTestAllowlist::isAllowed('plugin', 'sirsoft-gdpr'));
$this->assertFalse(ExtensionTestAllowlist::isAllowed('module', 'sirsoft-gdpr'));
}
/**
* @effects allowlist_active_when_testing_and_configured
*/
public function test_is_active_returns_true_when_testing_env_and_configured(): void
{
ExtensionTestAllowlist::set([]);
// phpunit.xml 의 APP_ENV=testing + 명시적 set → 가드 활성
$this->assertTrue(ExtensionTestAllowlist::isActive());
}
/**
* @effects empty_allowlist_is_active_and_blocks_all_extensions
*/
public function test_empty_allowlist_is_active_and_blocks_all_extensions(): void
{
// 빈 allowlist = core-only 테스트 → 가드는 활성, 모든 확장이 차단됨
ExtensionTestAllowlist::set([]);
$this->assertTrue(ExtensionTestAllowlist::isActive());
$this->assertFalse(ExtensionTestAllowlist::isAllowed('plugin', 'sirsoft-gdpr'));
}
/**
* @effects reset_deactivates_guard
*/
public function test_reset_deactivates_guard(): void
{
ExtensionTestAllowlist::set(['plugins/sirsoft-gdpr']);
ExtensionTestAllowlist::reset();
$this->assertFalse(ExtensionTestAllowlist::isActive());
$this->assertFalse(ExtensionTestAllowlist::isAllowed('plugin', 'sirsoft-gdpr'));
}
/**
* @effects set_recall_replaces_previous_allowlist
*/
public function test_set_recall_replaces_previous_allowlist(): void
{
ExtensionTestAllowlist::set(['plugins/sirsoft-gdpr']);
ExtensionTestAllowlist::set(['plugins/sirsoft-marketing']);
$this->assertFalse(ExtensionTestAllowlist::isAllowed('plugin', 'sirsoft-gdpr'));
$this->assertTrue(ExtensionTestAllowlist::isAllowed('plugin', 'sirsoft-marketing'));
}
/**
* @effects allowlist_inactive_when_app_env_not_testing, production_env_keeps_full_extension_loading
*/
public function test_is_active_returns_false_in_non_testing_env_even_when_configured(): void
{
ExtensionTestAllowlist::set(['plugins/sirsoft-gdpr']);
// 운영/개발 환경에서는 가드가 비활성 → 확장 전수 로딩 보존
$this->app['env'] = 'production';
$this->assertFalse(ExtensionTestAllowlist::isActive());
// 후속 테스트 보호: 환경 복원
$this->app['env'] = 'testing';
}
}
@@ -0,0 +1,213 @@
<?php
namespace Tests\Unit\Extension\Helpers;
use App\Extension\Helpers\EditorSpecAssembler;
use Illuminate\Support\Facades\File;
use Tests\TestCase;
/**
* EditorSpecAssembler 단위 테스트.
*
* editor-spec.json 분할(manifest + `$include` 블록) 합본의 정확성·하위 호환·
* 폴백·디그레이드를 검증한다. BASE_PATH 를 건드리지 않고 storage/app 하위 임시
* fixture 디렉토리에 manifest/블록 파일을 구성한 뒤 절대 경로로 합본을 호출한다.
*/
class EditorSpecAssemblerTest extends TestCase
{
private string $testRoot;
protected function setUp(): void
{
parent::setUp();
$this->testRoot = storage_path('app/test_editor_spec_assembler');
File::deleteDirectory($this->testRoot);
File::makeDirectory($this->testRoot, 0755, true);
}
protected function tearDown(): void
{
File::deleteDirectory($this->testRoot);
parent::tearDown();
}
/**
* manifest + `$include` 블록을 top-level merge 로 합본한다.
*/
public function test_assembles_include_blocks_into_single_spec(): void
{
$this->writeJson('editor-spec.json', [
'templateId' => 'demo',
'version' => '1.0.0',
'darkMode' => ['strategy' => 'ancestor-class'],
'$include' => [
'componentPalette' => 'editor-spec/componentPalette.json',
'controls' => 'editor-spec/controls.json',
],
]);
$this->writeJson('editor-spec/componentPalette.json', [
'groups' => [['label' => 'Layout', 'components' => ['Div']]],
'entries' => ['Div' => ['label' => 'Div']],
]);
$this->writeJson('editor-spec/controls.json', [
'textAlign' => ['widget' => 'segmented'],
]);
$spec = EditorSpecAssembler::assemble($this->path('editor-spec.json'));
$this->assertIsArray($spec);
// manifest 인라인 메타 보존
$this->assertSame('demo', $spec['templateId']);
$this->assertSame('1.0.0', $spec['version']);
$this->assertSame(['strategy' => 'ancestor-class'], $spec['darkMode']);
// include 블록이 해당 키 값으로 합본됨
$this->assertSame(['Div' => ['label' => 'Div']], $spec['componentPalette']['entries']);
$this->assertSame(['widget' => 'segmented'], $spec['controls']['textAlign']);
// `$include` 키 자체는 결과에 남지 않음
$this->assertArrayNotHasKey('$include', $spec);
}
/**
* `$include` 없는 미분할 manifest 는 원본 그대로 반환한다(하위 호환).
*/
public function test_returns_manifest_as_is_when_no_include(): void
{
$original = [
'templateId' => 'legacy',
'version' => '1.0.0',
'componentPalette' => ['entries' => ['Div' => ['label' => 'Div']]],
'controls' => ['textAlign' => ['widget' => 'segmented']],
];
$this->writeJson('editor-spec.json', $original);
$spec = EditorSpecAssembler::assemble($this->path('editor-spec.json'));
$this->assertSame($original, $spec);
}
/**
* include 파일 미존재 시 해당 키만 누락하고 나머지는 합본한다(무손실 디그레이드).
*/
public function test_skips_missing_include_block(): void
{
$this->writeJson('editor-spec.json', [
'templateId' => 'demo',
'$include' => [
'controls' => 'editor-spec/controls.json',
'missing' => 'editor-spec/does-not-exist.json',
],
]);
$this->writeJson('editor-spec/controls.json', ['textAlign' => ['widget' => 'segmented']]);
$spec = EditorSpecAssembler::assemble($this->path('editor-spec.json'));
$this->assertIsArray($spec);
$this->assertArrayHasKey('controls', $spec);
$this->assertArrayNotHasKey('missing', $spec);
}
/**
* include 분할본이 manifest 인라인 동일 키를 덮어쓴다(분할본이 정본).
*/
public function test_include_block_overrides_inline_value(): void
{
$this->writeJson('editor-spec.json', [
'controls' => ['textAlign' => ['widget' => 'STALE']],
'$include' => ['controls' => 'editor-spec/controls.json'],
]);
$this->writeJson('editor-spec/controls.json', ['textAlign' => ['widget' => 'segmented']]);
$spec = EditorSpecAssembler::assemble($this->path('editor-spec.json'));
$this->assertSame(['textAlign' => ['widget' => 'segmented']], $spec['controls']);
}
/**
* 합본 결과가 분할 전 단일 파일과 deep-equal 함을 검증한다(분할 무손실 보장).
*/
public function test_assembled_spec_deep_equals_monolithic(): void
{
$monolithic = [
'templateId' => 'demo',
'version' => '1.0.0',
'darkMode' => ['strategy' => 'media-query'],
'componentPalette' => [
'groups' => [['label' => 'L', 'components' => ['Div', 'Span']]],
'entries' => ['Div' => ['label' => 'Div'], 'Span' => ['label' => 'Span']],
],
'controls' => ['textAlign' => ['widget' => 'segmented', 'options' => [1, 2, 3]]],
'sampleData' => ['byDataSourceId' => ['users' => ['data' => [['id' => 1]]]]],
];
// 분할본 구성: 메타+darkMode 인라인, 나머지 블록은 include.
$manifest = [
'templateId' => 'demo',
'version' => '1.0.0',
'darkMode' => ['strategy' => 'media-query'],
'$include' => [
'componentPalette' => 'editor-spec/componentPalette.json',
'controls' => 'editor-spec/controls.json',
'sampleData' => 'editor-spec/sampleData.json',
],
];
$this->writeJson('editor-spec.json', $manifest);
$this->writeJson('editor-spec/componentPalette.json', $monolithic['componentPalette']);
$this->writeJson('editor-spec/controls.json', $monolithic['controls']);
$this->writeJson('editor-spec/sampleData.json', $monolithic['sampleData']);
$spec = EditorSpecAssembler::assemble($this->path('editor-spec.json'));
$this->assertEquals($monolithic, $spec);
}
/**
* 활성 디렉토리에 파일이 없으면 null 을 반환한다(편집 컨트롤 부재 폴백).
*
* _bundled 폴백은 없다 — 활성 경로 단일 기준이므로 미존재 시 즉시 null.
*/
public function test_returns_null_when_active_file_missing(): void
{
// _bundled 에 파일이 있어도 활성 단일 경로만 보므로 무관(폴백 없음).
$this->writeJson('_bundled/editor-spec.json', ['templateId' => 'bundled']);
$spec = EditorSpecAssembler::assemble($this->path('active/editor-spec.json'));
$this->assertNull($spec);
}
/**
* 파싱 실패(비 JSON) manifest 는 null 을 반환한다.
*/
public function test_returns_null_on_invalid_json(): void
{
File::put($this->path('editor-spec.json'), '{ this is not valid json ]');
$spec = EditorSpecAssembler::assemble($this->path('editor-spec.json'));
$this->assertNull($spec);
}
/**
* 테스트 루트 기준 상대 경로에 JSON 을 기록합니다.
*
* @param string $relative testRoot 기준 상대 경로
* @param array<string, mixed> $data 기록할 배열
*/
private function writeJson(string $relative, array $data): void
{
$path = $this->path($relative);
File::ensureDirectoryExists(\dirname($path));
File::put($path, (string) json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
}
/**
* 테스트 루트 기준 상대 경로의 절대 경로를 반환합니다.
*
* @param string $relative testRoot 기준 상대 경로
* @return string 절대 경로
*/
private function path(string $relative): string
{
return $this->testRoot.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $relative);
}
}
@@ -0,0 +1,70 @@
<?php
namespace Tests\Unit\Extension\IdentityVerification\DTO;
use App\Extension\IdentityVerification\DTO\VerificationChallenge;
use Carbon\Carbon;
use Tests\TestCase;
/**
* VerificationChallenge DTO 의 maxAttempts 필드 회귀 차단.
*
* 이슈 #275 — DB 의 max_attempts 가 환경설정값으로 정상 저장되었음에도 응답 페이로드에
* 노출되지 않아 프론트 launcher 가 maxAttempts:5 하드코딩으로 fallback 하여 사용자
* 모달에 "5회 남음" 으로 표시되던 결함을 차단한다.
*
* DTO 가 maxAttempts 필드를 보유 + toArray() 가 max_attempts 키로 노출하는지 검증.
*/
class VerificationChallengeMaxAttemptsTest extends TestCase
{
public function test_dto_accepts_max_attempts_via_named_argument(): void
{
$challenge = new VerificationChallenge(
id: 'uuid-1',
providerId: 'g7:core.mail',
purpose: 'signup',
channel: 'email',
targetHash: hash('sha256', 'user@example.com'),
expiresAt: Carbon::parse('2026-05-14T10:00:00+00:00'),
renderHint: 'text_code',
maxAttempts: 12,
);
$this->assertSame(12, $challenge->maxAttempts);
}
public function test_dto_defaults_max_attempts_to_zero(): void
{
// 기본값 0 — popup/SDK 형 provider (이니시스 등) 가 named args 로 호출 시 별도 지정 없이도 동작
$challenge = new VerificationChallenge(
id: 'uuid-2',
providerId: 'inicis',
purpose: 'signup',
channel: 'ipin',
targetHash: hash('sha256', 'user@example.com'),
expiresAt: Carbon::now(),
renderHint: 'text_code',
);
$this->assertSame(0, $challenge->maxAttempts);
}
public function test_to_array_exposes_max_attempts_key(): void
{
$challenge = new VerificationChallenge(
id: 'uuid-3',
providerId: 'g7:core.mail',
purpose: 'signup',
channel: 'email',
targetHash: hash('sha256', 'a@b.com'),
expiresAt: Carbon::parse('2026-05-14T11:00:00+00:00'),
renderHint: 'text_code',
maxAttempts: 7,
);
$arr = $challenge->toArray();
$this->assertArrayHasKey('max_attempts', $arr);
$this->assertSame(7, $arr['max_attempts']);
}
}
@@ -195,6 +195,11 @@ class IdentityVerificationManagerTest extends TestCase
return ['email'];
}
public function getChannelLabels(): array
{
return ['email' => 'Email'];
}
public function getRenderHint(): string
{
return 'text_code';
@@ -123,6 +123,65 @@ class MailIdentityProviderTest extends TestCase
$this->assertSame(1, $log->attempts);
}
public function test_verify_returns_max_attempts_on_final_wrong_attempt(): void
{
/** @var IdentityVerificationLogRepositoryInterface $repo */
$repo = $this->app->make(IdentityVerificationLogRepositoryInterface::class);
$challenge = $this->provider->requestChallenge(
['email' => 'user@example.com'],
['purpose' => 'sensitive_action'],
);
// max_attempts 를 2 로 낮춰 빠르게 소진. 1회차는 INVALID_CODE, 2회차(소진)는 MAX_ATTEMPTS 안내.
$repo->updateById($challenge->id, [
'metadata' => ['code_hash' => password_hash('123456', PASSWORD_BCRYPT)],
'status' => IdentityVerificationStatus::Sent->value,
'max_attempts' => 2,
]);
// 1회차 오답 — 아직 소진 전이므로 일반 오답 안내.
$first = $this->provider->verify($challenge->id, ['code' => '999999']);
$this->assertFalse($first->success);
$this->assertSame('INVALID_CODE', $first->failureCode);
$this->assertSame('identity.errors.invalid_code', $first->failureReason);
// 2회차 오답 — 이번 시도로 max_attempts 도달(소진). 사용자에게 "최대 시도 초과 + 재요청" 안내가 도달해야 함.
$second = $this->provider->verify($challenge->id, ['code' => '999999']);
$this->assertFalse($second->success);
$this->assertSame('MAX_ATTEMPTS', $second->failureCode);
$this->assertSame('identity.errors.max_attempts', $second->failureReason);
$log = IdentityVerificationLog::find($challenge->id);
$this->assertSame(2, $log->attempts);
$this->assertSame(IdentityVerificationStatus::Failed, $log->status);
}
public function test_verify_returns_max_attempts_when_already_exhausted(): void
{
/** @var IdentityVerificationLogRepositoryInterface $repo */
$repo = $this->app->make(IdentityVerificationLogRepositoryInterface::class);
$challenge = $this->provider->requestChallenge(
['email' => 'user@example.com'],
['purpose' => 'sensitive_action'],
);
// 이미 소진된 상태(attempts == max_attempts)에서 또 시도 — 코드 대조 전에 차단.
$repo->updateById($challenge->id, [
'metadata' => ['code_hash' => password_hash('123456', PASSWORD_BCRYPT)],
'status' => IdentityVerificationStatus::Sent->value,
'attempts' => 5,
'max_attempts' => 5,
]);
$result = $this->provider->verify($challenge->id, ['code' => '123456']);
$this->assertFalse($result->success);
$this->assertSame('MAX_ATTEMPTS', $result->failureCode);
$this->assertSame('identity.errors.max_attempts', $result->failureReason);
}
public function test_cancel_marks_status_as_cancelled(): void
{
$challenge = $this->provider->requestChallenge(
@@ -0,0 +1,27 @@
<?php
namespace Tests\Unit\Extension;
use App\Contracts\Extension\CacheInterface;
use App\Contracts\Extension\StorageInterface;
/**
* AbstractExtensionServiceProvider 계열 단위 테스트가 공유하는 fixture 클래스 모음.
*
* 본 파일은 각 테스트 클래스에서 단독 실행될 때도 동일 fixture 가 로드되도록
* 별도 파일로 분리되어 있습니다 (개별 테스트가 다른 테스트에 정의된 fixture
* 클래스를 require 받지 않으면 BindingResolutionException 발생).
*/
interface FixtureRepositoryInterface {}
class FixtureRepositoryImpl implements FixtureRepositoryInterface {}
class FixtureCacheConsumer
{
public function __construct(public CacheInterface $cache) {}
}
class FixtureStorageConsumer
{
public function __construct(public StorageInterface $storage) {}
}
@@ -0,0 +1,94 @@
<?php
namespace Tests\Unit\Extension;
use App\Extension\UpgradeContext;
use Psr\Log\LoggerInterface;
use Tests\TestCase;
/**
* 업그레이드 로그 채널 분리 회귀 테스트 (버그 ③ 로그 영역).
*
* 코어 업그레이드(sudo/root 실행)와 확장 업그레이드(php-fpm/www-data 실행)가 같은
* daily 로그 파일(upgrade-YYYY-MM-DD.log)을 공유하면, root 가 만든 파일에 www-data 가
* append 하지 못해 "Permission denied" 로 실패한다. UpgradeContext 에 로그 채널을 주입
* 가능하게 하여 코어는 'upgrade'(logs/upgrade.log), 확장은 'extension-upgrade'
* (logs/extension-upgrade.log) 로 파일을 분리 — 각 실행 주체가 자기 소유 파일에만 쓰도록
* 하여 교차 소유권 충돌을 원천 차단한다.
*/
class UpgradeContextLogChannelTest extends TestCase
{
/**
* 기본 채널은 'upgrade' — 코어 업그레이드 경로가 사용한다 (기존 동작 보존).
*/
public function test_default_channel_is_upgrade(): void
{
$context = new UpgradeContext(fromVersion: '1.0.0', toVersion: '2.0.0');
$this->assertSame('upgrade', $context->logChannel);
}
/**
* 확장(모듈/플러그인) 경로는 'extension-upgrade' 채널을 명시 주입한다.
*/
public function test_extension_channel_can_be_injected(): void
{
$context = new UpgradeContext(
fromVersion: '1.0.0',
toVersion: '2.0.0',
logChannel: 'extension-upgrade',
);
$this->assertSame('extension-upgrade', $context->logChannel);
}
/**
* withCurrentStep 은 채널을 승계한다 — step 별 파생 컨텍스트가 원본과 다른 파일에 쓰면
* 확장 업그레이드 로그가 코어 'upgrade' 파일로 새어 소유권 충돌이 재발한다.
*/
public function test_with_current_step_preserves_channel(): void
{
$context = new UpgradeContext(
fromVersion: '1.0.0',
toVersion: '2.0.0',
logChannel: 'extension-upgrade',
);
$stepContext = $context->withCurrentStep('1.5.0');
$this->assertSame('extension-upgrade', $stepContext->logChannel);
$this->assertSame('1.5.0', $stepContext->currentStep);
}
/**
* 두 채널이 서로 다른 daily 로그 파일 경로로 매핑되는지 config 로 검증.
* 같은 경로면 파일 분리가 무의미해지므로 회귀 가드로 확정한다.
*/
public function test_core_and_extension_channels_map_to_distinct_files(): void
{
$corePath = config('logging.channels.upgrade.path');
$extensionPath = config('logging.channels.extension-upgrade.path');
$this->assertNotNull($extensionPath, 'extension-upgrade 채널이 정의되어야 함');
$this->assertNotSame($corePath, $extensionPath, '코어/확장 로그 파일 경로는 달라야 함');
$this->assertStringEndsWith('upgrade.log', $corePath);
$this->assertStringEndsWith('extension-upgrade.log', $extensionPath);
}
/**
* 주입된 채널로 logger 가 실제 LoggerInterface 로 해석되고 예외 없이 로깅되는지 스모크 검증.
*/
public function test_logger_resolves_and_logs_without_error(): void
{
$context = new UpgradeContext(
fromVersion: '1.0.0',
toVersion: '2.0.0',
logChannel: 'extension-upgrade',
);
$this->assertInstanceOf(LoggerInterface::class, $context->logger);
// 예외 없이 로깅 가능해야 함 (채널이 실제로 해석됨).
$context->logger->info('테스트 로그');
}
}
+82 -34
View File
@@ -51,8 +51,6 @@ class FilePermissionHelperTest extends TestCase
/**
* removeOrphans 기본값(false)일 때 소스에 없는 대상 파일이 유지되는지 검증합니다.
*
* @return void
*/
public function test_copy_directory_does_not_remove_orphans_by_default(): void
{
@@ -82,8 +80,6 @@ class FilePermissionHelperTest extends TestCase
/**
* removeOrphans=true일 때 소스에 없는 파일이 삭제되는지 검증합니다.
*
* @return void
*/
public function test_copy_directory_removes_orphans_when_enabled(): void
{
@@ -112,8 +108,6 @@ class FilePermissionHelperTest extends TestCase
/**
* removeOrphans=true일 때 소스에 없는 디렉토리가 재귀 삭제되는지 검증합니다.
*
* @return void
*/
public function test_copy_directory_removes_orphan_directories(): void
{
@@ -146,8 +140,6 @@ class FilePermissionHelperTest extends TestCase
/**
* removeOrphans=true일 때 하위 디렉토리 내 소스에 없는 파일도 삭제되는지 검증합니다.
*
* @return void
*/
public function test_copy_directory_removes_orphans_in_subdirectories(): void
{
@@ -178,8 +170,6 @@ class FilePermissionHelperTest extends TestCase
/**
* removeOrphans=true이더라도 excludes 대상은 삭제하지 않는지 검증합니다.
*
* @return void
*/
public function test_copy_directory_preserves_excluded_orphans(): void
{
@@ -212,8 +202,6 @@ class FilePermissionHelperTest extends TestCase
/**
* 기존 파일의 퍼미션이 보존되는지 검증합니다. (Linux/Mac에서만 의미있음)
*
* @return void
*/
public function test_copy_file_preserves_permissions_on_existing_files(): void
{
@@ -266,8 +254,6 @@ class FilePermissionHelperTest extends TestCase
/**
* 루트 0775 + 자식·손자 0755 + 파일 0644 → 호출 후 자식·손자·파일 모두 g+w 승격.
*
* @return void
*/
public function test_sync_group_writability_recovers_child_dirs_and_files(): void
{
@@ -298,8 +284,6 @@ class FilePermissionHelperTest extends TestCase
/**
* 루트가 g-w (0755) 인 경우 — no-op. 운영자 정책 보존.
*
* @return void
*/
public function test_sync_group_writability_respects_root_policy_without_group_write(): void
{
@@ -320,8 +304,6 @@ class FilePermissionHelperTest extends TestCase
/**
* 이미 정상 (자식·손자 모두 g+w) → no-op (멱등).
*
* @return void
*/
public function test_sync_group_writability_is_idempotent(): void
{
@@ -346,8 +328,6 @@ class FilePermissionHelperTest extends TestCase
/**
* 다른 비트(other, owner, sticky 등) 무변경 — g+w 만 OR.
*
* @return void
*/
public function test_sync_group_writability_only_adds_group_write_bit(): void
{
@@ -375,8 +355,6 @@ class FilePermissionHelperTest extends TestCase
/**
* chownRecursiveDetailed — chown 미지원 환경 (Windows) 에서는 supported=false.
*
* @return void
*/
public function test_chown_recursive_detailed_returns_supported_false_when_chown_missing(): void
{
@@ -396,8 +374,6 @@ class FilePermissionHelperTest extends TestCase
* chownRecursiveDetailed — POSIX 환경에서 자기 자신을 owner 로 호출 시 changed=0, failed=0.
*
* 자기 소유자와 일치하면 chown 호출 자체가 발생하지 않으므로 멱등.
*
* @return void
*/
public function test_chown_recursive_detailed_idempotent_when_owner_matches(): void
{
@@ -417,8 +393,6 @@ class FilePermissionHelperTest extends TestCase
/**
* syncGroupWritabilityDetailed — 루트 g-w 환경은 skipped=true 로 보고.
*
* @return void
*/
public function test_sync_group_writability_detailed_skipped_when_root_no_group_write(): void
{
@@ -436,8 +410,6 @@ class FilePermissionHelperTest extends TestCase
/**
* syncGroupWritabilityDetailed — 정상 승격 시 changed>0, failed=0, skipped=false.
*
* @return void
*/
public function test_sync_group_writability_detailed_reports_changed(): void
{
@@ -469,8 +441,6 @@ class FilePermissionHelperTest extends TestCase
/**
* `chownRecursiveDetailed` 가 `respectPreservationMarker` 옵션을 지원해야 함.
*
* @return void
*/
public function test_chown_recursive_detailed_supports_respect_preservation_marker_option(): void
{
@@ -487,8 +457,6 @@ class FilePermissionHelperTest extends TestCase
/**
* 마커가 있는 디렉토리 트리는 chownRecursiveDetailed 가 skip — 자기 자신/하위 모두 chown 안 함.
*
* @return void
*/
public function test_chown_recursive_detailed_skips_subtree_when_preservation_marker_present(): void
{
@@ -526,8 +494,6 @@ class FilePermissionHelperTest extends TestCase
/**
* 마커 옵션이 false 이면 (기본값) — 기존 동작 그대로 (호환성 유지).
*
* @return void
*/
public function test_chown_recursive_detailed_backward_compatible_without_marker_option(): void
{
@@ -542,4 +508,86 @@ class FilePermissionHelperTest extends TestCase
$this->assertTrue($report['supported']);
$this->assertSame(0, $report['failed']);
}
// ========================================================================
// preserveTopLevelOrphans — 최상위 레벨 orphan 보존
// ========================================================================
/**
* preserveTopLevelOrphans=true 일 때 최상위 레벨에 소스에 없는 디렉토리/파일이
* 보존되는지 검증합니다.
*/
public function test_preserve_top_level_orphans_keeps_top_level_dir_and_file(): void
{
$source = $this->createTempDir();
$dest = $this->createTempDir();
// 소스: bundled_ext/manifest.json 만 존재
File::ensureDirectoryExists($source.DIRECTORY_SEPARATOR.'bundled_ext');
File::put($source.DIRECTORY_SEPARATOR.'bundled_ext'.DIRECTORY_SEPARATOR.'manifest.json', 'new');
// 대상: bundled_ext + user_dir(소스에 없음) + user_file.txt(소스에 없음)
File::ensureDirectoryExists($dest.DIRECTORY_SEPARATOR.'bundled_ext');
File::put($dest.DIRECTORY_SEPARATOR.'bundled_ext'.DIRECTORY_SEPARATOR.'manifest.json', 'old');
File::ensureDirectoryExists($dest.DIRECTORY_SEPARATOR.'user_dir');
File::put($dest.DIRECTORY_SEPARATOR.'user_dir'.DIRECTORY_SEPARATOR.'custom.txt', 'mine');
File::put($dest.DIRECTORY_SEPARATOR.'user_file.txt', 'keep me');
FilePermissionHelper::copyDirectory($source, $dest, removeOrphans: true, preserveTopLevelOrphans: true);
// 최상위 사용자 디렉토리 보존
$this->assertTrue(File::isDirectory($dest.DIRECTORY_SEPARATOR.'user_dir'));
$this->assertEquals('mine', File::get($dest.DIRECTORY_SEPARATOR.'user_dir'.DIRECTORY_SEPARATOR.'custom.txt'));
// 최상위 사용자 단일 파일 보존
$this->assertTrue(File::exists($dest.DIRECTORY_SEPARATOR.'user_file.txt'));
// 번들 확장은 source 기준 갱신
$this->assertEquals('new', File::get($dest.DIRECTORY_SEPARATOR.'bundled_ext'.DIRECTORY_SEPARATOR.'manifest.json'));
}
/**
* preserveTopLevelOrphans=true 라도 소스에 존재하는 디렉토리 *내부* 의 orphan 은
* 정상적으로 삭제되는지 검증합니다 (최상위 한 레벨만 보존).
*/
public function test_preserve_top_level_orphans_still_cleans_nested_orphans(): void
{
$source = $this->createTempDir();
$dest = $this->createTempDir();
// 소스: bundled_ext/manifest.json 만 (old.json 없음)
File::ensureDirectoryExists($source.DIRECTORY_SEPARATOR.'bundled_ext');
File::put($source.DIRECTORY_SEPARATOR.'bundled_ext'.DIRECTORY_SEPARATOR.'manifest.json', 'new');
// 대상: bundled_ext/manifest.json + bundled_ext/old.json(소스에 없는 중첩 orphan)
File::ensureDirectoryExists($dest.DIRECTORY_SEPARATOR.'bundled_ext');
File::put($dest.DIRECTORY_SEPARATOR.'bundled_ext'.DIRECTORY_SEPARATOR.'manifest.json', 'old');
File::put($dest.DIRECTORY_SEPARATOR.'bundled_ext'.DIRECTORY_SEPARATOR.'old.json', 'stale');
FilePermissionHelper::copyDirectory($source, $dest, removeOrphans: true, preserveTopLevelOrphans: true);
// 소스에 존재하는 디렉토리 내부의 stale 파일은 삭제 (중첩 레벨)
$this->assertFalse(File::exists($dest.DIRECTORY_SEPARATOR.'bundled_ext'.DIRECTORY_SEPARATOR.'old.json'));
$this->assertEquals('new', File::get($dest.DIRECTORY_SEPARATOR.'bundled_ext'.DIRECTORY_SEPARATOR.'manifest.json'));
}
/**
* preserveTopLevelOrphans 기본값(false)이면 기존 동작(최상위 orphan 삭제)이
* 그대로 유지되는지 검증합니다 (하위호환).
*/
public function test_preserve_top_level_orphans_defaults_to_existing_behavior(): void
{
$source = $this->createTempDir();
$dest = $this->createTempDir();
File::put($source.DIRECTORY_SEPARATOR.'file_a.txt', 'source_a');
File::put($dest.DIRECTORY_SEPARATOR.'file_a.txt', 'old_a');
File::put($dest.DIRECTORY_SEPARATOR.'orphan.txt', 'orphan_content');
// preserveTopLevelOrphans 미지정 → 기존 동작 (최상위 orphan 삭제)
FilePermissionHelper::copyDirectory($source, $dest, removeOrphans: true);
$this->assertFalse(File::exists($dest.DIRECTORY_SEPARATOR.'orphan.txt'));
}
}
@@ -0,0 +1,61 @@
<?php
namespace Tests\Unit\Http\Resources\Identity;
use App\Extension\IdentityVerification\DTO\VerificationChallenge;
use App\Http\Resources\Identity\ChallengeResource;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Tests\TestCase;
/**
* ChallengeResource 의 max_attempts 응답 노출 회귀 차단.
*
* 이슈 #275 — POST /api/identity/challenges 응답 페이로드에 max_attempts 가 없어 프론트
* launcher 가 하드코딩 5 로 fallback 하던 결함을 차단한다.
*
* Resource → 응답 JSON 의 max_attempts 키 노출이 깨지면 사용자 모달의 "남은 시도 횟수"
* 표시가 항상 5 로 굳어지는 회귀가 발생한다.
*/
class ChallengeResourceMaxAttemptsTest extends TestCase
{
public function test_resource_exposes_max_attempts_from_dto(): void
{
$challenge = new VerificationChallenge(
id: 'uuid-1',
providerId: 'g7:core.mail',
purpose: 'signup',
channel: 'email',
targetHash: hash('sha256', 'a@b.com'),
expiresAt: Carbon::parse('2026-05-14T10:00:00+00:00'),
renderHint: 'text_code',
maxAttempts: 12,
);
$resource = new ChallengeResource($challenge);
$array = $resource->toArray(Request::create('/test', 'GET'));
$this->assertArrayHasKey('max_attempts', $array);
$this->assertSame(12, $array['max_attempts']);
}
public function test_resource_exposes_zero_for_unlimited_attempts(): void
{
// popup/SDK 형 provider (이니시스 등) — max_attempts=0 (무제한) 케이스
$challenge = new VerificationChallenge(
id: 'uuid-2',
providerId: 'inicis',
purpose: 'signup',
channel: 'ipin',
targetHash: hash('sha256', 'a@b.com'),
expiresAt: Carbon::now(),
renderHint: 'text_code',
);
$resource = new ChallengeResource($challenge);
$array = $resource->toArray(Request::create('/test', 'GET'));
$this->assertArrayHasKey('max_attempts', $array);
$this->assertSame(0, $array['max_attempts']);
}
}
@@ -0,0 +1,79 @@
<?php
namespace Tests\Unit\Installer;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
/**
* 인스톨러 DB 접두사 길이 가드 회귀 테스트
*
* DB prefix 가 길면 자동 생성 인덱스명이 MySQL identifier 한도(64자)를 초과해
* 일부 확장(sirsoft-ecommerce 등) 설치 시 마이그레이션이 실패한다.
* 코어 인스톨러가 prefix 길이를 MAX_DB_PREFIX_LENGTH 로 제한하는지 보장한다.
*
* 검증 축:
* - 상수 MAX_DB_PREFIX_LENGTH 가 6 으로 정의됨 (자동명 최대 58자 + 6 = 64)
* - 경계: 6자 이하 통과 / 7자 이상 거부
* - 가장 긴 자동 생성 인덱스명(58자)이 허용 최대 prefix 와 합쳐 64자를 넘지 않음
*/
class DbPrefixLengthGuardTest extends TestCase
{
public static function setUpBeforeClass(): void
{
require_once dirname(__DIR__, 3) . '/public/install/includes/config.php';
}
public function test_max_db_prefix_length_constant_is_defined_as_six(): void
{
$this->assertTrue(defined('MAX_DB_PREFIX_LENGTH'), 'MAX_DB_PREFIX_LENGTH 상수가 정의되지 않았습니다.');
$this->assertSame(6, MAX_DB_PREFIX_LENGTH);
}
/**
* 인스톨러 서버 검증과 동일한 판정식: strlen($prefix) > MAX_DB_PREFIX_LENGTH 면 거부.
*/
#[DataProvider('prefixProvider')]
public function test_prefix_length_boundary(string $prefix, bool $shouldPass): void
{
$isRejected = strlen($prefix) > MAX_DB_PREFIX_LENGTH;
$this->assertSame(
$shouldPass,
! $isRejected,
sprintf('prefix "%s" (%d자) 판정이 기대와 다릅니다.', $prefix, strlen($prefix))
);
}
/**
* @return array<string, array{0: string, 1: bool}>
*/
public static function prefixProvider(): array
{
return [
'default g7_ (3자)' => ['g7_', true],
'g72_ (4자) — 이슈 재현 prefix' => ['g72_', true],
'5자' => ['shop_', true],
'경계 6자 통과' => ['mycomp', true],
'경계 7자 거부' => ['mycomp_', false],
'명백히 긴 10자 거부' => ['mycompany_', false],
'빈 문자열 통과' => ['', true],
];
}
/**
* 허용 최대 prefix(6자) 와 가장 긴 자동 생성 인덱스명(58자)의 합이
* MySQL identifier 한도(64자) 이내임을 보장한다.
*/
public function test_max_prefix_plus_longest_auto_index_name_fits_identifier_limit(): void
{
$longestAutoIndexBaseLength = 58; // 작업1 이후 전역 자동 생성 인덱스명 최대치
$mysqlIdentifierLimit = 64;
$this->assertLessThanOrEqual(
$mysqlIdentifierLimit,
MAX_DB_PREFIX_LENGTH + $longestAutoIndexBaseLength,
'허용 최대 prefix + 최장 자동 인덱스명이 MySQL 한도를 초과합니다.'
);
}
}
@@ -0,0 +1,95 @@
<?php
namespace Tests\Unit\Installer;
use PHPUnit\Framework\TestCase;
/**
* 인스톨러 기존 테이블 삭제 시 db_prefix 필터링 회귀 테스트
*
* 회귀 시나리오:
* - drop_tables 동의 시 cleanupExistingTablesSSE() 가 SHOW TABLES 로 조회한
* DB 안의 모든 테이블을 db_prefix 필터 없이 전부 DROP 했음.
* - 같은 DB 를 다른 애플리케이션과 공유하거나 다른 prefix 로 재설치할 때
* G7 과 무관한 테이블까지 삭제되는 데이터 손실 결함.
*
* 수정: filterTablesByPrefix() 가 입력한 prefix 로 시작하는 테이블만 선별하고,
* 빈 prefix 는 전체 삭제 위험 방어로 빈 목록을 반환한다.
*/
class InstallerDropTablePrefixTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
require_once dirname(__DIR__, 3) . '/public/install/includes/functions.php';
}
public function test_filters_only_tables_with_default_prefix(): void
{
$tables = ['g7_users', 'g7_migrations', 'wp_posts', 'legacy_orders'];
$result = filterTablesByPrefix($tables, 'g7_');
$this->assertSame(['g7_users', 'g7_migrations'], $result);
}
public function test_preserves_non_prefixed_tables(): void
{
$tables = ['wp_posts', 'wp_users', 'legacy_orders'];
$result = filterTablesByPrefix($tables, 'g7_');
$this->assertSame([], $result, 'prefix 가 다른 테이블은 삭제 대상에서 제외되어야 한다');
}
public function test_supports_custom_prefix(): void
{
$tables = ['shop_users', 'shop_products', 'g7_users', 'other_table'];
$result = filterTablesByPrefix($tables, 'shop_');
$this->assertSame(['shop_users', 'shop_products'], $result);
}
public function test_empty_prefix_returns_no_tables(): void
{
$tables = ['g7_users', 'wp_posts', 'anything'];
$result = filterTablesByPrefix($tables, '');
$this->assertSame(
[],
$result,
'빈 prefix 는 전체 일치로 모든 테이블이 삭제되는 위험이 있어 빈 목록을 반환해야 한다'
);
}
public function test_empty_table_list_returns_empty(): void
{
$result = filterTablesByPrefix([], 'g7_');
$this->assertSame([], $result);
}
public function test_returns_sequentially_indexed_array(): void
{
// array_filter 가 원본 키를 보존하지 않도록 재인덱싱되어야 한다 (foreach DROP 안정성)
$tables = ['other_a', 'g7_users', 'other_b', 'g7_posts'];
$result = filterTablesByPrefix($tables, 'g7_');
$this->assertSame([0, 1], array_keys($result));
$this->assertSame(['g7_users', 'g7_posts'], $result);
}
public function test_prefix_must_match_at_start_not_substring(): void
{
// 중간에 prefix 문자열을 포함하는 테이블은 삭제 대상이 아니다
$tables = ['my_g7_data', 'g7_users'];
$result = filterTablesByPrefix($tables, 'g7_');
$this->assertSame(['g7_users'], $result);
}
}
+148 -33
View File
@@ -22,30 +22,46 @@ class InstallerGuardTest extends TestCase
{
private static string $tempBase = '';
private static string $skipReason = '';
public static function setUpBeforeClass(): void
{
self::$tempBase = sys_get_temp_dir() . '/g7-installer-guard-test-' . bin2hex(random_bytes(4));
mkdir(self::$tempBase . '/storage/app', 0755, true);
// 안전 가드: 본 테스트는 BASE_PATH/.env 와 BASE_PATH/storage/app/g7_installed 를
// 직접 write/unlink 한다. BASE_PATH 는 PHP 상수라 한 프로세스에서 단 한 번만 정의되며,
// 다른 Installer 테스트가 먼저 프로젝트 루트로 박으면 본 테스트의 cleanup() 이
// 실제 운영 .env 를 삭제하게 된다. BASE_PATH 가 시스템 temp 하위가 아니면 skip 한다.
$tempPrefix = realpath(sys_get_temp_dir()) ?: sys_get_temp_dir();
// BASE_PATH 가 다른 테스트에서 이미 정의되었을 수 있다.
// 그 경우 폴백 (installer_resolve_base_path) 가 본 파일 위치 기준으로 결정되므로
// 본 테스트는 정의된 BASE_PATH 를 그대로 사용하고, 그 안에 격리 디렉토리를 만든다.
if (! defined('BASE_PATH')) {
define('BASE_PATH', self::$tempBase);
} else {
// 다른 테스트의 BASE_PATH 와 공존 — 그 디렉토리 안에 lock/.env 를 두고 정리.
self::$tempBase = BASE_PATH;
if (! is_dir(BASE_PATH . '/storage/app')) {
@mkdir(BASE_PATH . '/storage/app', 0755, true);
if (defined('BASE_PATH')) {
$resolved = realpath((string) BASE_PATH) ?: (string) BASE_PATH;
if (strpos($resolved, $tempPrefix) !== 0) {
self::$skipReason = 'BASE_PATH ('.$resolved.') 가 시스템 temp 하위가 아님 — '
.'다른 Installer 테스트의 BASE_PATH 정의가 선행됨. 실제 .env 파괴 방지를 위해 skip. '
.'격리 실행: php vendor/bin/phpunit --filter=InstallerGuardTest';
return;
}
self::$tempBase = (string) BASE_PATH;
} else {
self::$tempBase = sys_get_temp_dir().'/g7-installer-guard-test-'.bin2hex(random_bytes(4));
define('BASE_PATH', self::$tempBase);
}
require_once dirname(__DIR__, 3) . '/public/install/api/_guard.php';
if (! is_dir(self::$tempBase.'/storage/app')) {
@mkdir(self::$tempBase.'/storage/app', 0755, true);
}
require_once dirname(__DIR__, 3).'/public/install/api/_guard.php';
}
protected function setUp(): void
{
parent::setUp();
if (self::$skipReason !== '') {
$this->markTestSkipped(self::$skipReason);
}
$this->cleanup();
}
@@ -57,11 +73,16 @@ class InstallerGuardTest extends TestCase
private function cleanup(): void
{
$lock = BASE_PATH . '/storage/app/g7_installed';
// skip 상태(= BASE_PATH 가 실 루트)면 파괴적 정리를 절대 수행하지 않는다.
if (self::$skipReason !== '') {
return;
}
$lock = BASE_PATH.'/storage/app/g7_installed';
if (is_file($lock)) {
@unlink($lock);
}
$env = BASE_PATH . '/.env';
$env = BASE_PATH.'/.env';
if (is_file($env)) {
@unlink($env);
}
@@ -74,50 +95,50 @@ class InstallerGuardTest extends TestCase
public function test_lock_file_only_marks_completed(): void
{
file_put_contents(BASE_PATH . '/storage/app/g7_installed', '');
file_put_contents(BASE_PATH.'/storage/app/g7_installed', '');
$this->assertTrue(installer_is_completed());
}
public function test_env_flag_only_marks_completed(): void
{
file_put_contents(BASE_PATH . '/.env', "APP_ENV=local\nINSTALLER_COMPLETED=true\n");
file_put_contents(BASE_PATH.'/.env', "APP_ENV=local\nINSTALLER_COMPLETED=true\n");
$this->assertTrue(installer_is_completed());
}
public function test_env_flag_accepts_quoted_true(): void
{
file_put_contents(BASE_PATH . '/.env', 'INSTALLER_COMPLETED="true"' . "\n");
file_put_contents(BASE_PATH.'/.env', 'INSTALLER_COMPLETED="true"'."\n");
$this->assertTrue(installer_is_completed());
}
public function test_env_flag_accepts_one(): void
{
file_put_contents(BASE_PATH . '/.env', 'INSTALLER_COMPLETED=1' . "\n");
file_put_contents(BASE_PATH.'/.env', 'INSTALLER_COMPLETED=1'."\n");
$this->assertTrue(installer_is_completed());
}
public function test_env_flag_false_does_not_mark_completed(): void
{
file_put_contents(BASE_PATH . '/.env', "APP_ENV=local\nINSTALLER_COMPLETED=false\n");
file_put_contents(BASE_PATH.'/.env', "APP_ENV=local\nINSTALLER_COMPLETED=false\n");
$this->assertFalse(installer_is_completed());
}
public function test_env_flag_missing_does_not_mark_completed(): void
{
file_put_contents(BASE_PATH . '/.env', "APP_ENV=local\n");
file_put_contents(BASE_PATH.'/.env', "APP_ENV=local\n");
$this->assertFalse(installer_is_completed());
}
public function test_both_signals_present_marks_completed(): void
{
file_put_contents(BASE_PATH . '/storage/app/g7_installed', '');
file_put_contents(BASE_PATH . '/.env', 'INSTALLER_COMPLETED=true' . "\n");
file_put_contents(BASE_PATH.'/storage/app/g7_installed', '');
file_put_contents(BASE_PATH.'/.env', 'INSTALLER_COMPLETED=true'."\n");
$this->assertTrue(installer_is_completed());
}
@@ -127,17 +148,17 @@ class InstallerGuardTest extends TestCase
//
// 일반 가드와 달리 g7_installed 락 파일은 차단 사유에서 제외되어야 한다
// (complete_flag task 가 락 파일을 먼저 생성한 직후 finalize 가 호출되는
// 설계상의 호출 순서 때문 — 이슈 #371 자가 차단 회귀 가드).
// 설계상의 호출 순서 때문 — 자가 차단 회귀 가드).
// ------------------------------------------------------------------------
public function test_finalize_guard_passes_with_lock_only(): void
{
// 정상 1회차 finalize 시나리오: 락 파일은 존재하나 .env 머지 아직 안 됨
file_put_contents(BASE_PATH . '/storage/app/g7_installed', '');
file_put_contents(BASE_PATH.'/storage/app/g7_installed', '');
$this->assertFalse(
installer_finalize_is_completed(),
'g7_installed 락 파일 단독 존재 시 finalize 차단되면 자가 차단 회귀 (이슈 #371)'
'g7_installed 락 파일 단독 존재 시 finalize 차단되면 자가 차단 회귀'
);
}
@@ -150,7 +171,7 @@ class InstallerGuardTest extends TestCase
public function test_finalize_guard_blocks_when_env_completed_true(): void
{
// 이미 finalize 된 상태 — 멱등 차단
file_put_contents(BASE_PATH . '/.env', "APP_ENV=local\nINSTALLER_COMPLETED=true\n");
file_put_contents(BASE_PATH.'/.env', "APP_ENV=local\nINSTALLER_COMPLETED=true\n");
$this->assertTrue(installer_finalize_is_completed());
}
@@ -158,28 +179,122 @@ class InstallerGuardTest extends TestCase
public function test_finalize_guard_blocks_with_lock_and_env_completed(): void
{
// 락 + .env true 동시 존재 → 차단 (멱등)
file_put_contents(BASE_PATH . '/storage/app/g7_installed', '');
file_put_contents(BASE_PATH . '/.env', 'INSTALLER_COMPLETED=true' . "\n");
file_put_contents(BASE_PATH.'/storage/app/g7_installed', '');
file_put_contents(BASE_PATH.'/.env', 'INSTALLER_COMPLETED=true'."\n");
$this->assertTrue(installer_finalize_is_completed());
}
public function test_finalize_guard_passes_when_env_completed_false(): void
{
file_put_contents(BASE_PATH . '/.env', "INSTALLER_COMPLETED=false\n");
file_put_contents(BASE_PATH.'/.env', "INSTALLER_COMPLETED=false\n");
$this->assertFalse(installer_finalize_is_completed());
}
public function test_finalize_guard_accepts_quoted_and_alt_truthy_values(): void
{
file_put_contents(BASE_PATH . '/.env', 'INSTALLER_COMPLETED="true"' . "\n");
file_put_contents(BASE_PATH.'/.env', 'INSTALLER_COMPLETED="true"'."\n");
$this->assertTrue(installer_finalize_is_completed());
file_put_contents(BASE_PATH . '/.env', 'INSTALLER_COMPLETED=1' . "\n");
file_put_contents(BASE_PATH.'/.env', 'INSTALLER_COMPLETED=1'."\n");
$this->assertTrue(installer_finalize_is_completed());
file_put_contents(BASE_PATH . '/.env', 'INSTALLER_COMPLETED=yes' . "\n");
file_put_contents(BASE_PATH.'/.env', 'INSTALLER_COMPLETED=yes'."\n");
$this->assertTrue(installer_finalize_is_completed());
}
// ------------------------------------------------------------------------
// state-management.php 진입 가드 정적 회귀 (KVE-2026-1056)
//
// state-management.php?action=get 은 정상 설치 흐름의 1초 폴링이며,
// complete_flag task 가 g7_installed 락 파일을 finalize 보다 먼저 생성한다.
// 따라서 일반 가드(installer_guard_or_410, 락 파일도 차단 사유)를 적용하면
// "락만 있고 .env 플래그는 아직 없는" 폴링 구간이 410 으로 끊겨 완료 화면이
// 표시되지 않는 자가 차단 회귀가 발생한다.
//
// 올바른 조치: finalize 전용 가드(installer_guard_finalize_or_410,
// .env INSTALLER_COMPLETED=true 단독 판정)를 객체 생성 전에 호출한다.
// exit/header 는 단위에서 검증 불가하므로 소스 정적 검사로 회귀를 못박는다.
// ------------------------------------------------------------------------
private function stateManagementSource(): string
{
$path = dirname(__DIR__, 3).'/public/install/api/state-management.php';
$this->assertFileExists($path, 'state-management.php 가 존재해야 한다');
return (string) file_get_contents($path);
}
public function test_state_management_loads_guard_file(): void
{
$src = $this->stateManagementSource();
$this->assertMatchesRegularExpression(
'/require(?:_once)?\s+__DIR__\s*\.\s*[\'"]\/_guard\.php[\'"]/',
$src,
'state-management.php 가 _guard.php 를 로드해야 한다'
);
}
public function test_state_management_calls_finalize_guard_not_general_guard(): void
{
$src = $this->stateManagementSource();
$this->assertStringContainsString(
'installer_guard_finalize_or_410()',
$src,
'state-management.php 는 finalize 전용 가드를 호출해야 한다 (.env 플래그 단독 판정)'
);
// 일반 가드를 쓰면 락-only 폴링 구간이 410 으로 끊겨 정상 설치가 깨진다.
$this->assertDoesNotMatchRegularExpression(
'/(?<!finalize_)installer_guard_or_410\s*\(\s*\)/',
$src,
'state-management.php 는 일반 installer_guard_or_410() 을 호출하면 안 된다 '
.'(complete_flag 락 파일로 인한 폴링 자가 차단 회귀)'
);
}
public function test_state_management_guard_runs_before_api_instantiation(): void
{
$src = $this->stateManagementSource();
$guardPos = strpos($src, 'installer_guard_finalize_or_410()');
$instantiatePos = strpos($src, 'new StateManagementApi');
$this->assertNotFalse($guardPos, 'finalize 가드 호출이 존재해야 한다');
$this->assertNotFalse($instantiatePos, 'StateManagementApi 인스턴스화가 존재해야 한다');
$this->assertLessThan(
$instantiatePos,
$guardPos,
'가드는 StateManagementApi 객체 생성 전에 호출되어야 한다 (모든 action 일괄 차단)'
);
}
public function test_state_management_polling_passes_with_lock_only(): void
{
// 핵심 비파괴 불변식: complete_flag 직후~finalize 전 구간(락만 존재)에서
// finalize 가드는 통과해야 한다 — 폴링이 completed 상태를 받아야 완료 화면 전환.
file_put_contents(BASE_PATH.'/storage/app/g7_installed', '');
$this->assertFalse(
installer_finalize_is_completed(),
'g7_installed 락 단독 존재 시 state-management 폴링이 차단되면 '
.'정상 설치가 "진행 중"에 고착된다 (KVE-2026-1056 조치의 비파괴 조건)'
);
}
public function test_state_management_blocks_when_env_completed(): void
{
// 완전 완료 상태(.env 플래그 set)에서는 get/reset/abort 가 차단되어야 한다 —
// KVE-2026-1056 의 보호장치 우회·상태 변조 공격 표면 제거.
file_put_contents(BASE_PATH.'/.env', "APP_ENV=local\nINSTALLER_COMPLETED=true\n");
$this->assertTrue(
installer_finalize_is_completed(),
'완전 설치 완료 상태에서 state-management 가 차단되어야 한다 (KVE-2026-1056)'
);
}
}
@@ -15,7 +15,8 @@ use PHPUnit\Framework\TestCase;
*/
class InstallerRuntimeHelperTest extends TestCase
{
private string $tempBase;
private string $tempBase = '';
private string $skipReason = '';
protected function setUp(): void
{
@@ -23,12 +24,30 @@ class InstallerRuntimeHelperTest extends TestCase
// 격리된 BASE_PATH — 운영 환경 storage/installer 와 충돌 방지
$this->tempBase = sys_get_temp_dir() . '/g7-installer-runtime-test-' . bin2hex(random_bytes(4));
mkdir($this->tempBase . '/storage/installer', 0755, true);
if (! defined('BASE_PATH')) {
// 안전 가드: INSTALLER_RUNTIME_PATH(= BASE_PATH/storage/installer/runtime.php) 는
// PHP 상수라 한 프로세스에서 단 한 번만 정의된다. 다른 Installer 테스트가 먼저
// 프로젝트 루트로 BASE_PATH 를 박으면 tearDown 의 @unlink 가 실제 운영 runtime.php
// (DB 자격증명/APP_KEY 임시 보관 파일)를 삭제하게 된다. temp 하위가 아니면 skip.
$tempPrefix = realpath(sys_get_temp_dir()) ?: sys_get_temp_dir();
if (defined('BASE_PATH')) {
$resolved = realpath((string) BASE_PATH) ?: (string) BASE_PATH;
if (strpos($resolved, $tempPrefix) !== 0) {
$this->skipReason = 'BASE_PATH (' . $resolved . ') 가 시스템 temp 하위가 아님 — '
. '다른 Installer 테스트의 BASE_PATH 정의가 선행됨. 실제 storage/installer/runtime.php '
. '파괴 방지를 위해 skip. 격리 실행: php vendor/bin/phpunit --filter=InstallerRuntimeHelperTest';
$this->markTestSkipped($this->skipReason);
}
$this->tempBase = (string) BASE_PATH;
} else {
define('BASE_PATH', $this->tempBase);
}
if (! is_dir($this->tempBase . '/storage/installer')) {
@mkdir($this->tempBase . '/storage/installer', 0755, true);
}
// INSTALLER_RUNTIME_PATH 는 BASE_PATH 기반으로 한 번만 정의되므로,
// 첫 테스트가 끝까지 책임진다 (BASE_PATH 자체가 const 라 재정의 불가).
// installer-runtime.php 자체에 escapeEnvValue polyfill 이 있어 functions.php
@@ -38,9 +57,8 @@ class InstallerRuntimeHelperTest extends TestCase
protected function tearDown(): void
{
// INSTALLER_RUNTIME_PATH 는 첫 정의된 BASE_PATH 에 묶여있으므로
// 그 파일만 정리하고, 임시 디렉토리는 시스템 temp cleaner 에 위임
if (defined('INSTALLER_RUNTIME_PATH') && is_file(INSTALLER_RUNTIME_PATH)) {
// skip 상태(= BASE_PATH 가 실 루트)면 파괴적 정리를 절대 수행하지 않는다.
if ($this->skipReason === '' && defined('INSTALLER_RUNTIME_PATH') && is_file(INSTALLER_RUNTIME_PATH)) {
@unlink(INSTALLER_RUNTIME_PATH);
}
@@ -20,6 +20,7 @@ class InstallerSecurityHardeningTest extends TestCase
{
private static bool $loaded = false;
private static string $tempBase = '';
private static string $skipReason = '';
public static function setUpBeforeClass(): void
{
@@ -51,6 +52,21 @@ class InstallerSecurityHardeningTest extends TestCase
define('STATE_PATH', self::$tempBase . '/storage/installer-state.json');
}
// 안전 가드: STATE_PATH 는 PHP 상수라 한 프로세스에서 단 한 번만 정의된다.
// 다른 Installer 테스트(ComposerPathValidationTest 등)가 먼저 BASE_PATH 기반
// 루트 경로로 STATE_PATH 를 박으면 본 테스트의 writeState/clearState 가 실제 운영
// installer-state.json 을 파괴하게 된다. STATE_PATH 가 시스템 temp 하위가 아니면 skip.
$tempPrefix = realpath(sys_get_temp_dir()) ?: sys_get_temp_dir();
$resolvedState = realpath(dirname((string) STATE_PATH)) ?: dirname((string) STATE_PATH);
if (strpos($resolvedState, $tempPrefix) !== 0) {
self::$skipReason = 'STATE_PATH (' . STATE_PATH . ') 가 시스템 temp 하위가 아님 — '
. '다른 Installer 테스트의 상수 정의가 선행됨. 실제 installer-state.json 파괴 방지를 위해 skip. '
. '격리 실행: php vendor/bin/phpunit --filter=InstallerSecurityHardeningTest';
self::$loaded = true;
return;
}
require_once $projectRoot . '/public/install/api/check-configuration.php';
require_once $projectRoot . '/public/install/includes/installer-state.php';
require_once $projectRoot . '/public/install/includes/functions.php';
@@ -59,6 +75,15 @@ class InstallerSecurityHardeningTest extends TestCase
self::$loaded = true;
}
protected function setUp(): void
{
parent::setUp();
if (self::$skipReason !== '') {
$this->markTestSkipped(self::$skipReason);
}
}
private function invokePrivate(object $obj, string $method, array $args)
{
$ref = new ReflectionClass($obj);
@@ -67,19 +92,16 @@ class InstallerSecurityHardeningTest extends TestCase
}
/**
* 테스트가 도중 종료되어도 사용자 작업 디렉토리에 state.json 잔여물이 남지 않도록 항상 정리.
* BASE_PATH 가 다른 테스트 인프라에 의해 프로젝트 루트로 바인딩되는 경우를 대비해
* 프로젝트 루트의 storage/installer-state.json 도 함께 정리.
* 테스트가 도중 종료되어도 임시 디렉토리에 state.json 잔여물이 남지 않도록 정리.
* STATE_PATH 는 setUpBeforeClass 의 안전 가드로 시스템 temp 하위임이 보장된 경우에만
* 이 지점에 도달하므로, 운영 storage/installer-state.json 은 절대 건드리지 않는다.
* (과거 루트 state 를 무조건 @unlink 하던 코드는 실제 운영 설치 상태를 파괴할 수 있어 제거)
*/
protected function tearDown(): void
{
if (is_file(STATE_PATH)) {
if (self::$skipReason === '' && is_file(STATE_PATH)) {
@unlink(STATE_PATH);
}
$projectStateFile = dirname(__DIR__, 3) . '/storage/installer-state.json';
if (is_file($projectStateFile)) {
@unlink($projectStateFile);
}
parent::tearDown();
}
+28 -11
View File
@@ -7,7 +7,7 @@ use PHPUnit\Framework\TestCase;
/**
* 워커 동시 실행 방지 lock/heartbeat 가드 회귀 테스트
*
* 시나리오 B (이슈 #319 race condition 본질 차단):
* 시나리오 B (race condition 본질 차단):
* - 환경 (예: mod_fcgid + FcgidOutputBufferSize 미설정) 에서 SSE 가 client 까지
* 도달 못해 사용자가 폴링으로 풀백. 그 사이 SSE 워커는 백그라운드 진행.
* - 새 폴링 워커가 진입하면 두 워커가 동일 인스톨러 state + DB 를 동시 조작.
@@ -23,20 +23,38 @@ use PHPUnit\Framework\TestCase;
*/
class WorkerLockGuardTest extends TestCase
{
private string $tempBase;
private string $stateFile;
private string $tempBase = '';
private string $stateFile = '';
private string $skipReason = '';
protected function setUp(): void
{
parent::setUp();
$this->tempBase = sys_get_temp_dir() . '/g7-worker-lock-test-' . bin2hex(random_bytes(4));
mkdir($this->tempBase . '/storage', 0755, true);
// 안전 가드: 본 테스트는 BASE_PATH/storage/installer-state.json 을 write/unlink 한다.
// BASE_PATH 는 PHP 상수라 한 프로세스에서 단 한 번만 정의되며, 다른 Installer 테스트가
// 먼저 프로젝트 루트로 박으면 본 테스트가 실제 운영 installer-state.json 을 파괴하게 된다.
// BASE_PATH 가 시스템 temp 하위가 아니면 skip 한다.
$tempPrefix = realpath(sys_get_temp_dir()) ?: sys_get_temp_dir();
if (! defined('BASE_PATH')) {
if (defined('BASE_PATH')) {
$resolved = realpath((string) BASE_PATH) ?: (string) BASE_PATH;
if (strpos($resolved, $tempPrefix) !== 0) {
$this->skipReason = 'BASE_PATH (' . $resolved . ') 가 시스템 temp 하위가 아님 — '
. '다른 Installer 테스트의 BASE_PATH 정의가 선행됨. 실제 installer-state.json 파괴 방지를 위해 skip. '
. '격리 실행: php vendor/bin/phpunit --filter=WorkerLockGuardTest';
$this->markTestSkipped($this->skipReason);
}
$this->tempBase = (string) BASE_PATH;
} else {
$this->tempBase = sys_get_temp_dir() . '/g7-worker-lock-test-' . bin2hex(random_bytes(4));
define('BASE_PATH', $this->tempBase);
}
if (! is_dir($this->tempBase . '/storage')) {
@mkdir($this->tempBase . '/storage', 0755, true);
}
$this->stateFile = BASE_PATH . '/storage/installer-state.json';
@file_put_contents($this->stateFile, json_encode(['installation_status' => 'pending']));
@@ -46,11 +64,10 @@ class WorkerLockGuardTest extends TestCase
protected function tearDown(): void
{
// $this->stateFile 은 setUp 시점의 BASE_PATH 로 이미 결정되어 있으므로
// 그 경로를 그대로 정리. 이전 코드는 BASE_PATH 가 self::tempBase 와 다를 때
// (다른 테스트가 먼저 바인딩한 경우) 정리를 skip 하여 사용자 작업 디렉토리에
// 잔여물을 남겼다.
@unlink($this->stateFile);
// skip 상태(= BASE_PATH 가 실 루트)면 파괴적 정리를 절대 수행하지 않는다.
if ($this->skipReason === '' && $this->stateFile !== '') {
@unlink($this->stateFile);
}
parent::tearDown();
}
@@ -139,4 +139,41 @@ class MergeFrontendLanguageTest extends TestCase
// ja 활성 팩 없음 → base 그대로
$this->assertSame('저장', $result['common']['save']);
}
/**
* core scope 언어팩이 코어 frontend 베이스 레이어(`core.*` 키)를 덮어쓰는지 검증.
*
* 본 PR 도입 후 TemplateService 가 `lang/{locale}.json` 을 베이스로 합치므로,
* 응답 base 에는 `core.errors.*` 같은 코어 키가 이미 포함된 상태로 본 필터 진입.
* 외부 사용자가 g7-core-{locale} 언어팩으로 `core.errors.*` 번역을 제공하면
* 그것이 베이스를 덮어써야 한다.
*/
public function test_core_lang_pack_overrides_core_frontend_base_layer(): void
{
// 코어 ja 팩이 core.errors.* 키 제공
$this->setupJaPack('test-core-frontend-ja', LanguagePackScope::Core->value, null, [
'core' => [
'errors' => [
'template_not_found' => 'アクティブなテンプレートがありません',
],
],
]);
$this->registry->invalidate();
// TemplateService 가 lang/ko.json 으로부터 합친 base 시뮬레이션
$base = [
'core' => [
'errors' => [
'template_not_found' => '활성화된 템플릿이 없습니다',
'layout_load_failed' => '레이아웃을 불러오는데 실패했습니다',
],
],
];
$result = ($this->listener)($base, 'sirsoft-admin_basic', 'ja');
// ja 팩이 코어 키 덮어씀
$this->assertSame('アクティブなテンプレートがありません', $result['core']['errors']['template_not_found']);
// ja 팩이 정의하지 않은 키는 base 보존
$this->assertSame('레이아웃을 불러오는데 실패했습니다', $result['core']['errors']['layout_load_failed']);
}
}
@@ -433,4 +433,97 @@ class NotificationDispatchIntegrationTest extends TestCase
Notification::assertSentTo($superAdmin, \App\Notifications\GenericNotification::class);
}
// ──────────────────────────────────────────────
// 9. 비회원(guest) 발송: trigger_user 폴백 → GuestNotifiable
// ──────────────────────────────────────────────
/**
* mail 채널 템플릿을 가진 알림 정의를 생성하는 헬퍼.
*/
private function createMailDefinition(string $type, string $hook, array $recipients): NotificationDefinition
{
$definition = NotificationDefinition::create([
'type' => $type,
'hook_prefix' => 'core.test',
'extension_type' => 'core',
'extension_identifier' => 'core',
'name' => ['ko' => $type],
'variables' => [],
'channels' => ['mail', 'database'],
'hooks' => [$hook],
'is_active' => true,
'is_default' => true,
]);
foreach (['mail', 'database'] as $ch) {
NotificationTemplate::create([
'definition_id' => $definition->id,
'channel' => $ch,
'subject' => ['ko' => '제목', 'en' => 'Subject'],
'body' => ['ko' => '본문', 'en' => 'Body'],
'recipients' => $recipients,
'is_active' => true,
'is_default' => true,
]);
}
return $definition;
}
public function test_guest_recipient_receives_mail_notification(): void
{
$this->createMailDefinition(
'test_guest_send',
'core.test.after_guest',
[['type' => 'trigger_user']]
);
// 비회원 컨텍스트: trigger_user_id 없음 + guest_recipient 표준 키
HookManager::addFilter('core.test.notification.extract_data', function ($default) {
return [
'notifiable' => null,
'notifiables' => null,
'data' => ['name' => '비회원주문자'],
'context' => [
'trigger_user_id' => null,
'guest_recipient' => ['email' => 'guest@example.com', 'name' => '비회원주문자', 'locale' => 'ko'],
],
];
}, priority: 20);
$this->registerAndFire('core.test.after_guest', null);
// 비회원은 GuestNotifiable 수신자로 발송된다 (회원과 동일한 notify 경로).
// fake 는 같은 클래스 + getKey() 로 매칭하므로 동일 이메일 게스트로 단언한다.
Notification::assertSentTo(
new \App\Notifications\GuestNotifiable('guest@example.com'),
\App\Notifications\GenericNotification::class
);
}
public function test_guest_recipient_without_email_sends_nothing(): void
{
$this->createMailDefinition(
'test_guest_noemail',
'core.test.after_guest_noemail',
[['type' => 'trigger_user']]
);
HookManager::addFilter('core.test.notification.extract_data', function ($default) {
return [
'notifiable' => null,
'notifiables' => null,
'data' => ['name' => 'x'],
'context' => [
'trigger_user_id' => null,
'guest_recipient' => ['email' => ''],
],
];
}, priority: 20);
$this->registerAndFire('core.test.after_guest_noemail', null);
Notification::assertNothingSent();
}
}
@@ -2,10 +2,13 @@
namespace Tests\Unit\Listeners;
use App\Extension\HookManager;
use App\Jobs\DispatchHookListenerJob;
use App\Listeners\NotificationHookListener;
use App\Models\NotificationDefinition;
use App\Services\NotificationDefinitionService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;
/**
@@ -95,4 +98,44 @@ class NotificationHookListenerTest extends TestCase
// getAllActive()는 비활성 제외이므로 등록 안됨
$this->assertTrue(true);
}
/**
* 동적 등록된 알림 훅이 발화될 때 발송 작업이 큐(DispatchHookListenerJob)로
* 디스패치되어야 한다 — 요청 스레드에서 동기 발송하면 수신자가 많을 때
* 호출 요청(주문 등)이 발송 완료까지 막힌다.
*
* 회귀 배경: registerDynamicHooks 가 다른 리스너(HookListenerRegistrar 경유)와 달리
* DispatchHookListenerJob 래핑 없이 $this->dispatch() 를 직접 호출해 동기 실행되던 결함.
* admin 수신자 1,000여 명에게 요청 스레드에서 순차 메일 발송 → 무통장 주문 hang.
*/
public function test_dynamic_notification_hook_dispatches_to_queue_on_fire(): void
{
Queue::fake();
NotificationDefinition::create([
'type' => 'queued_hook_test',
'hook_prefix' => 'core.test',
'extension_type' => 'core',
'extension_identifier' => 'core',
'name' => ['ko' => '큐 발송 테스트'],
'variables' => [],
'channels' => ['mail'],
'hooks' => ['core.test.queued_action'],
'is_active' => true,
'is_default' => true,
]);
app(NotificationDefinitionService::class)->invalidateAllCache();
$listener = app(NotificationHookListener::class);
$listener->registerDynamicHooks();
// 훅 발화 → 발송 작업이 직접 실행되지 않고 큐로 디스패치되어야 함
HookManager::doAction('core.test.queued_action', null);
Queue::assertPushed(
DispatchHookListenerJob::class,
fn (DispatchHookListenerJob $job) => $job->listenerClass === NotificationHookListener::class
);
}
}
@@ -13,6 +13,16 @@ class TemplateLayoutVersionTest extends TestCase
{
use RefreshDatabase;
/**
* 같은 스위트의 레이아웃/GDPR 미들웨어 의존 테스트와 migrate:fresh 정합성을
* 맞추기 위해 GDPR 플러그인 마이그레이션을 일관 선언한다.
*
* @var array<string>
*/
protected array $requiredExtensions = [
'plugins/sirsoft-gdpr',
];
/**
* 레이아웃 버전 관계 테스트
*/
@@ -0,0 +1,114 @@
<?php
namespace Tests\Unit\Notifications;
use App\Models\NotificationDefinition;
use App\Models\NotificationTemplate;
use App\Notifications\GuestNotifiable;
use App\Notifications\GenericNotification;
use App\Services\NotificationChannelService;
use App\Services\NotificationTemplateService;
use Tests\TestCase;
/**
* 비회원(게스트) 채널 게이트 테스트
*
* GenericNotification::via() 가 게스트 수신자에 대해 채널 allow_guest 정책을 적용하는지,
* NotificationChannelService::isChannelGuestAllowed() 가 config/훅 기반으로 동작하는지 검증.
*/
class GenericNotificationGuestGateTest extends TestCase
{
private NotificationDefinition $definition;
protected function setUp(): void
{
parent::setUp();
$templateService = app(NotificationTemplateService::class);
foreach (['mail', 'database'] as $ch) {
$templateService->invalidateCache('guest_gate_check', $ch);
}
$this->definition = NotificationDefinition::updateOrCreate(
['type' => 'guest_gate_check'],
[
'hook_prefix' => 'core.test',
'extension_type' => 'core',
'extension_identifier' => 'core',
'name' => ['ko' => '테스트', 'en' => 'Test'],
'variables' => [],
'channels' => ['mail', 'database'],
'hooks' => [],
'is_active' => true,
'is_default' => false,
]
);
foreach (['mail', 'database'] as $ch) {
NotificationTemplate::updateOrCreate(
['definition_id' => $this->definition->id, 'channel' => $ch],
[
'subject' => ['ko' => '제목', 'en' => 'Subject'],
'body' => ['ko' => '본문', 'en' => 'Body'],
'is_active' => true,
'is_default' => false,
]
);
}
}
protected function tearDown(): void
{
NotificationTemplate::where('definition_id', $this->definition->id)->delete();
$this->definition->delete();
parent::tearDown();
}
private function notification(string $channel): GenericNotification
{
return new GenericNotification(
type: 'guest_gate_check',
hookPrefix: 'core.test',
data: [],
extensionType: 'core',
extensionIdentifier: 'core',
channel: $channel,
);
}
// ── isChannelGuestAllowed (config 기반) ──
public function test_channel_guest_allowed_reads_config(): void
{
$service = app(NotificationChannelService::class);
$this->assertTrue($service->isChannelGuestAllowed('mail'));
$this->assertFalse($service->isChannelGuestAllowed('database'));
// 미선언 채널은 기본 차단(false)
$this->assertFalse($service->isChannelGuestAllowed('nonexistent_channel'));
}
// ── via() 게스트 게이트 ──
public function test_guest_passes_mail_channel(): void
{
$guest = new GuestNotifiable('guest@example.com', '홍길동', 'ko');
$this->assertSame(['mail'], $this->notification('mail')->via($guest));
}
public function test_guest_blocked_on_database_channel(): void
{
$guest = new GuestNotifiable('guest@example.com', '홍길동', 'ko');
$this->assertSame([], $this->notification('database')->via($guest));
}
public function test_member_is_unaffected_by_guest_gate(): void
{
$member = \App\Models\User::factory()->make();
// 회원은 게스트 게이트 무영향 — database 채널도 정상 통과(템플릿 존재 + readiness)
$this->assertSame(['database'], $this->notification('database')->via($member));
}
}
@@ -0,0 +1,96 @@
<?php
namespace Tests\Unit\Notifications;
use App\Contracts\Notifications\GuestRecipientInterface;
use App\Notifications\GuestNotifiable;
use Illuminate\Contracts\Translation\HasLocalePreference;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\App;
use Tests\TestCase;
/**
* GuestNotifiable 테스트
*
* 비회원 1급 수신자 값 객체의 계약(Notifiable + HasLocalePreference + GuestRecipientInterface),
* fromContext 유효성, 합성 키, 로케일 폴백을 검증합니다.
*/
class GuestNotifiableTest extends TestCase
{
public function test_implements_required_contracts(): void
{
$guest = new GuestNotifiable('guest@example.com', '홍길동', 'ko');
$this->assertInstanceOf(HasLocalePreference::class, $guest);
$this->assertInstanceOf(GuestRecipientInterface::class, $guest);
$this->assertContains(Notifiable::class, class_uses($guest));
$this->assertTrue($guest->isGuest());
}
public function test_from_context_builds_valid_recipient(): void
{
$guest = GuestNotifiable::fromContext([
'email' => 'guest@example.com',
'name' => '홍길동',
'locale' => 'ko',
]);
$this->assertNotNull($guest);
$this->assertSame('guest@example.com', $guest->email);
$this->assertSame('홍길동', $guest->name);
}
public function test_from_context_returns_null_for_empty_email(): void
{
$this->assertNull(GuestNotifiable::fromContext(['email' => '', 'name' => 'X']));
$this->assertNull(GuestNotifiable::fromContext(['name' => 'X']));
}
public function test_from_context_returns_null_for_invalid_email(): void
{
$this->assertNull(GuestNotifiable::fromContext(['email' => 'not-an-email']));
}
public function test_get_key_is_deterministic_and_case_insensitive(): void
{
$a = new GuestNotifiable('Guest@Example.com');
$b = new GuestNotifiable('guest@example.com');
$this->assertSame($a->getKey(), $b->getKey());
$this->assertStringStartsWith('guest:', $a->getKey());
}
public function test_route_notification_for_mail_uses_name_when_present(): void
{
$withName = new GuestNotifiable('guest@example.com', '홍길동');
$this->assertSame(['guest@example.com' => '홍길동'], $withName->routeNotificationForMail());
$withoutName = new GuestNotifiable('guest@example.com');
$this->assertSame('guest@example.com', $withoutName->routeNotificationForMail());
}
public function test_preferred_locale_returns_supported_locale(): void
{
$guest = new GuestNotifiable('guest@example.com', null, 'en');
$this->assertSame('en', $guest->preferredLocale());
}
public function test_preferred_locale_returns_null_for_unsupported_or_empty(): void
{
$this->assertNull((new GuestNotifiable('guest@example.com', null, 'xx'))->preferredLocale());
$this->assertNull((new GuestNotifiable('guest@example.com'))->preferredLocale());
}
public function test_resolve_notifiable_locale_falls_back_to_app_locale(): void
{
App::setLocale('en');
// locale 미지정 게스트 → preferredLocale() null → app locale 폴백
$guest = new GuestNotifiable('guest@example.com');
$this->assertSame('en', \App\Notifications\BaseNotification::resolveNotifiableLocale($guest));
// locale 지정 게스트 → 그 값 우선
$ko = new GuestNotifiable('guest@example.com', null, 'ko');
$this->assertSame('ko', \App\Notifications\BaseNotification::resolveNotifiableLocale($ko));
}
}
@@ -0,0 +1,94 @@
<?php
namespace Tests\Unit\Providers;
use App\Providers\SettingsServiceProvider;
use App\Repositories\JsonConfigRepository;
use Illuminate\Support\Facades\Config;
use ReflectionMethod;
use Tests\TestCase;
/**
* SettingsServiceProvider 앱 설정(site_name) 다국어 안전화 테스트 (공개#49).
*
* applyAppConfig()가 general.site_name 을 config('app.name')에 주입할 때,
* 다국어 JSON array 면 현재/폴백 로케일 string 으로 정규화해 SPA <title>
* ({{ config('app.name') }} → Blade e() → htmlspecialchars) TypeError 를 차단하는지 검증.
*/
class SettingsServiceProviderAppConfigTest extends TestCase
{
/**
* applyAppConfig 를 리플렉션으로 호출합니다.
*
* @param array $generalSettings general 카테고리 설정 데이터
*/
private function callApplyAppConfig(array $generalSettings): void
{
$configRepository = $this->createMock(JsonConfigRepository::class);
$configRepository->method('getCategory')
->with('general')
->willReturn($generalSettings);
$provider = new SettingsServiceProvider($this->app);
$method = new ReflectionMethod($provider, 'applyAppConfig');
$method->invoke($provider, $configRepository);
}
/**
* 단일 문자열 site_name 은 그대로 config('app.name')에 적용됩니다.
*/
public function test_string_site_name_applied_as_is(): void
{
$this->callApplyAppConfig(['site_name' => '그누보드7']);
$this->assertSame('그누보드7', config('app.name'));
}
/**
* 다국어 array site_name 은 현재 로케일 string 으로 정규화되어 적용됩니다.
*/
public function test_multilingual_site_name_normalized_to_current_locale(): void
{
Config::set('app.locale', 'ko');
Config::set('app.fallback_locale', 'en');
$this->callApplyAppConfig([
'site_name' => ['ko' => '한글몰', 'en' => 'EngMall'],
]);
$name = config('app.name');
$this->assertIsString($name, 'config(app.name)은 항상 string 이어야 함 (SPA title TypeError 방지)');
$this->assertSame('한글몰', $name);
}
/**
* 현재 로케일 키가 없으면 폴백 로케일 string 으로 적용됩니다.
*/
public function test_multilingual_site_name_falls_back_to_fallback_locale(): void
{
Config::set('app.locale', 'ja');
Config::set('app.fallback_locale', 'en');
$this->callApplyAppConfig([
'site_name' => ['en' => 'EngMall'],
]);
$this->assertSame('EngMall', config('app.name'));
}
/**
* 정규화 결과가 Blade e() (htmlspecialchars)에서 TypeError 없이 string 으로 렌더됩니다.
*/
public function test_normalized_site_name_renders_without_type_error(): void
{
Config::set('app.locale', 'ko');
$this->callApplyAppConfig([
'site_name' => ['ko' => '한글몰', 'en' => 'EngMall'],
]);
// app.blade.php 의 {{ config('app.name') }} 와 동일 경로
$rendered = e(config('app.name', '그누보드7'));
$this->assertSame('한글몰', $rendered);
}
}
@@ -0,0 +1,135 @@
<?php
namespace Tests\Unit\Providers;
use App\Providers\SettingsServiceProvider;
use App\Repositories\JsonConfigRepository;
use Illuminate\Support\Facades\Config;
use ReflectionClass;
use Tests\TestCase;
/**
* SettingsServiceProvider 의 디버그 설정 환경별 분기 동작 테스트.
*
* 의도:
* - production/local 운영 환경에서는 admin UI 의 debug 토글(storage/app/settings/debug.json) 이 SSoT 로
* 동작하여 .env 의 APP_DEBUG 보다 우선 적용되어야 한다.
* - testing 환경(PHPUnit, .env.testing) 에서는 settings JSON 의 mode 값이 .env.testing 의 APP_DEBUG 를
* 덮어쓰지 않아야 한다. 그렇지 않으면 운영 PC 의 settings 값(debug=false) 때문에 PHPUnit / E2E 인프라
* (PlaywrightIssueToken 등) 가 의도치 않게 차단된다.
*
* 회귀 컨텍스트: 이슈 #238 Playwright 도입 작업 중 PO 환경(APP_ENV=production, debug.json mode=false) 에서
* --env=testing 으로 artisan 명령을 실행해도 SettingsServiceProvider 가 settings JSON 의 mode=false 로
* config('app.debug') 를 false 로 덮어쓰는 문제가 발견됨.
*/
class SettingsServiceProviderDebugConfigTest extends TestCase
{
/**
* testing 환경에서는 settings JSON 의 debug.mode 가 config('app.debug') 를 덮어쓰지 않아야 한다.
*
* 검증:
* 1. config('app.debug') 를 true 로 사전 설정 (= .env.testing APP_DEBUG=true 상태 시뮬레이션)
* 2. settings JSON 에서 debug.mode=false 를 반환하는 가짜 repository 주입
* 3. applyDebugConfig 호출
* 4. config('app.debug') 가 true 그대로 유지되어야 함 (testing 가드가 settings 덮어쓰기 차단)
*/
public function test_applyDebugConfig_does_not_override_in_testing_environment(): void
{
// 현재 PHPUnit 환경은 APP_ENV=testing 이어야 함
$this->assertSame('testing', app()->environment(), '본 테스트는 testing 환경에서만 의미를 가진다.');
Config::set('app.debug', true);
$fakeRepository = new class extends JsonConfigRepository
{
public function getCategory(string $category): array
{
if ($category === 'debug') {
return ['mode' => false, 'log_level' => 'error'];
}
return [];
}
};
$provider = new SettingsServiceProvider(app());
$reflection = new ReflectionClass($provider);
$method = $reflection->getMethod('applyDebugConfig');
$method->setAccessible(true);
$method->invoke($provider, $fakeRepository);
$this->assertTrue(
config('app.debug'),
'testing 환경에서는 settings JSON 의 debug.mode 가 config(app.debug) 를 덮어쓰지 않아야 한다.'
);
}
/**
* G7_PLAYWRIGHT_BYPASS=1 환경변수가 부여된 호출에서도 settings JSON 의 debug.mode 가 덮어쓰지 않아야 한다.
*
* 의도:
* production 환경에서 Playwright E2E 가 토큰 발급 시 PlaywrightIssueToken 이
* `Config::set('app.debug', true)` 로 inline override 를 적용한다. 이 시점에 settings JSON
* 덮어쓰기가 발생하면 inline override 가 무력화되어 토큰 발급 후 layout JSON 보호 인증 등이
* 디버그 정보 누락으로 실패한다. 따라서 bypass flag 가 있으면 settings JSON 분기를 건너뛴다.
*/
public function test_applyDebugConfig_does_not_override_when_playwright_bypass_flag_is_set(): void
{
Config::set('app.debug', true);
$fakeRepository = new class extends JsonConfigRepository
{
public function getCategory(string $category): array
{
if ($category === 'debug') {
return ['mode' => false, 'log_level' => 'error'];
}
return [];
}
};
// G7_PLAYWRIGHT_BYPASS=1 를 임시 부여하고 종료 시 원복
$previous = getenv('G7_PLAYWRIGHT_BYPASS');
putenv('G7_PLAYWRIGHT_BYPASS=1');
$_ENV['G7_PLAYWRIGHT_BYPASS'] = '1';
$_SERVER['G7_PLAYWRIGHT_BYPASS'] = '1';
try {
$provider = new SettingsServiceProvider(app());
$reflection = new ReflectionClass($provider);
$method = $reflection->getMethod('applyDebugConfig');
$method->setAccessible(true);
$method->invoke($provider, $fakeRepository);
$this->assertTrue(
config('app.debug'),
'G7_PLAYWRIGHT_BYPASS=1 이면 settings JSON 의 debug.mode 가 config(app.debug) 를 덮어쓰지 않아야 한다.'
);
} finally {
if ($previous === false) {
putenv('G7_PLAYWRIGHT_BYPASS');
unset($_ENV['G7_PLAYWRIGHT_BYPASS'], $_SERVER['G7_PLAYWRIGHT_BYPASS']);
} else {
putenv('G7_PLAYWRIGHT_BYPASS='.$previous);
$_ENV['G7_PLAYWRIGHT_BYPASS'] = $previous;
$_SERVER['G7_PLAYWRIGHT_BYPASS'] = $previous;
}
}
}
/**
* production 환경 시뮬레이션 에서는 settings JSON 의 debug.mode 가 여전히 SSoT 로 적용되어야 한다.
*
* (운영 환경 회귀 차단 — testing 가드가 production 동작을 망가뜨리지 않는지 확인)
*/
public function test_applyDebugConfig_still_overrides_outside_testing_environment(): void
{
// 본 테스트는 app environment 를 명시적으로 production 으로 모킹할 수 없으므로
// SettingsServiceProvider 가 환경 분기 후에도 settings 를 읽는다는 사실만 검증한다.
// 자세한 분기 동작은 본 메서드의 testing 케이스가 커버한다.
$this->markTestSkipped('production 환경 분기는 통합 테스트 또는 수동 검증으로 커버 (PHPUnit 부팅 환경 강제 변경 불가)');
}
}
@@ -76,4 +76,38 @@ class SettingsServiceProviderTest extends TestCase
// 설정값이 null이 아님 = seo 카테고리가 정상 로딩됨
$this->assertNotNull($botDetectionEnabled, 'seo.bot_detection_enabled 설정이 로딩되어야 합니다.');
}
/**
* CORE_CATEGORIES 에 identity 카테고리가 포함되어 admin UI 본인인증 설정이 로딩되는지 테스트합니다.
*
* 회귀 차단 (이슈 #275): identity 가 CORE_CATEGORIES 에서 누락되면 admin UI 의
* 본인인증 환경설정(기본 프로바이더 / 목적별 / TTL / 최대 시도 횟수) 4개 항목이 모두 무시됨.
*/
public function test_identity_category_included_in_core_categories(): void
{
$reflection = new ReflectionClass(SettingsServiceProvider::class);
$categories = $reflection->getConstant('CORE_CATEGORIES');
$this->assertContains('identity', $categories, 'CORE_CATEGORIES 에 identity 카테고리가 포함되어야 합니다.');
}
/**
* 본인인증 설정이 config('settings.identity.*') dot-path 로 hydrate 되는지 테스트합니다.
*
* 회귀 차단 (이슈 #275): IdentityVerificationManager / MailIdentityProvider /
* InicisIdentityProvider 등이 `config('settings.identity.*')` 경로로 직접 read 한다.
* 이 경로 hydration 이 누락되면 admin UI 저장값이 모두 무시되고 코드 fallback 만 사용된다.
*/
public function test_settings_identity_dot_path_hydrated(): void
{
// storage/app/settings/identity.json 이 존재하는 환경에서는 hydrate 되어 array
// 부재 환경에서도 최소 null 이어야 함 (Config::set('settings.identity', ...) 의 cover 범위)
$identityConfig = config('settings.identity');
// 카테고리 자체가 등록되어 있어야 함. 빈 배열일 수도 있지만 false 또는 'string' 류는 부적합
$this->assertTrue(
$identityConfig === null || is_array($identityConfig),
'config(\'settings.identity\') 는 null 또는 array 여야 합니다.'
);
}
}
@@ -90,4 +90,47 @@ class SettingsServiceProviderWebsocketConfigTest extends TestCase
$this->assertSame('null', config('broadcasting.default'));
}
/**
* 웹소켓 OFF + .env REVERB_APP_KEY 존재 시 reverb.key가 비워지는지 테스트합니다 (공개#50).
*
* 프론트(admin/app.blade.php)가 @if(reverb.key)로 연결을 결정하므로, OFF 시 key를 비워야
* .env REVERB_APP_KEY가 살아 있어도 브라우저 WebSocket 연결을 차단할 수 있다.
*/
public function test_reverb_key_blanked_when_websocket_disabled(): void
{
// .env 초기 상태: REVERB_APP_KEY가 살아 있어 reverb.key가 채워진 상태
Config::set('broadcasting.default', 'reverb');
Config::set('broadcasting.connections.reverb.key', 'env-reverb-key');
$this->callApplyWebsocketConfig([
'websocket_enabled' => false,
]);
$this->assertSame(
'',
config('broadcasting.connections.reverb.key'),
'웹소켓 OFF 시 reverb.key는 비워져야 함 (프론트 @if(reverb.key) 연결 차단)'
);
}
/**
* 웹소켓 ON 시 reverb.key가 설정값으로 유지되는지 테스트합니다 (회귀 방지, 공개#50).
*/
public function test_reverb_key_preserved_when_websocket_enabled(): void
{
Config::set('broadcasting.default', 'reverb');
Config::set('broadcasting.connections.reverb.key', 'env-reverb-key');
$this->callApplyWebsocketConfig([
'websocket_enabled' => true,
'websocket_app_key' => 'admin-set-key',
]);
$this->assertSame(
'admin-set-key',
config('broadcasting.connections.reverb.key'),
'웹소켓 ON 시 reverb.key는 환경설정/.env 값으로 유지되어야 함'
);
}
}
@@ -0,0 +1,242 @@
<?php
namespace Tests\Unit\Repositories;
use App\Contracts\Repositories\IdentityPolicyRepositoryInterface;
use App\Enums\ExtensionStatus;
use App\Models\IdentityPolicy;
use App\Models\Module;
use App\Models\Plugin;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* IdentityPolicyRepository 의 비활성 확장 정책 제외(applyActiveExtensionScope) 검증.
*
* 회귀 배경: 모듈/플러그인을 비활성화해도 그 확장이 선언한 IDV 정책이 enforce 쿼리에
* 그대로 남아 계속 강제되던 결함. enforce 두 경로(resolveByScopeTarget=hook,
* getRouteScopeIndex=route)가 source_type/source_identifier 기준으로 비활성 확장
* 정책을 제외하는지, 그리고 재활성화 시 다시 포함되는지(3-state)를 검증한다.
*
* @group identity
* @group unit
*/
class IdentityPolicyRepositoryActiveExtensionScopeTest extends TestCase
{
use RefreshDatabase;
private IdentityPolicyRepositoryInterface $repository;
protected function setUp(): void
{
parent::setUp();
$this->repository = app(IdentityPolicyRepositoryInterface::class);
}
/**
* 모듈 레코드를 생성합니다.
*/
private function makeModule(string $identifier, string $status): Module
{
return Module::create([
'identifier' => $identifier,
'vendor' => 'sirsoft',
'name' => ['ko' => $identifier, 'en' => $identifier],
'version' => '1.0.0',
'status' => $status,
]);
}
/**
* 플러그인 레코드를 생성합니다.
*/
private function makePlugin(string $identifier, string $status): Plugin
{
return Plugin::create([
'identifier' => $identifier,
'vendor' => 'sirsoft',
'name' => ['ko' => $identifier, 'en' => $identifier],
'version' => '1.0.0',
'status' => $status,
]);
}
/**
* 정책을 생성합니다.
*/
private function makePolicy(array $overrides = []): IdentityPolicy
{
return IdentityPolicy::create(array_merge([
'key' => 'test.policy.'.uniqid(),
'scope' => 'hook',
'target' => 'test.hook.target',
'purpose' => 'sensitive_action',
'grace_minutes' => 5,
'enabled' => true,
'priority' => 0,
'source_type' => 'core',
'source_identifier' => 'core',
'applies_to' => 'both',
'fail_mode' => 'block',
], $overrides));
}
/**
* hook scope: 활성 모듈의 정책은 enforce 대상에 포함된다
*/
public function test_hook_scope_includes_active_module_policy(): void
{
$this->makeModule('sirsoft-fake', ExtensionStatus::Active->value);
$this->makePolicy([
'scope' => 'hook',
'target' => 'fake.hook',
'source_type' => 'module',
'source_identifier' => 'sirsoft-fake',
]);
$result = $this->repository->resolveByScopeTarget('hook', 'fake.hook');
$this->assertCount(1, $result);
}
/**
* hook scope: 비활성 모듈의 정책은 enforce 대상에서 제외된다 (회귀)
*/
public function test_hook_scope_excludes_inactive_module_policy(): void
{
$this->makeModule('sirsoft-fake', ExtensionStatus::Inactive->value);
$this->makePolicy([
'scope' => 'hook',
'target' => 'fake.hook',
'source_type' => 'module',
'source_identifier' => 'sirsoft-fake',
]);
$result = $this->repository->resolveByScopeTarget('hook', 'fake.hook');
$this->assertCount(0, $result);
}
/**
* hook scope: 모듈 재활성화 시 정책이 다시 enforce 대상에 포함된다 (3-state)
*/
public function test_hook_scope_reincludes_policy_after_reactivation(): void
{
$module = $this->makeModule('sirsoft-fake', ExtensionStatus::Inactive->value);
$this->makePolicy([
'scope' => 'hook',
'target' => 'fake.hook',
'source_type' => 'module',
'source_identifier' => 'sirsoft-fake',
]);
// 비활성: 제외
$this->assertCount(0, $this->repository->resolveByScopeTarget('hook', 'fake.hook'));
// 재활성화: 다시 포함
$module->update(['status' => ExtensionStatus::Active->value]);
$this->assertCount(1, $this->repository->resolveByScopeTarget('hook', 'fake.hook'));
}
/**
* hook scope: 비활성 플러그인의 정책도 제외된다
*/
public function test_hook_scope_excludes_inactive_plugin_policy(): void
{
$this->makePlugin('sirsoft-fakeplugin', ExtensionStatus::Inactive->value);
$this->makePolicy([
'scope' => 'hook',
'target' => 'fakeplugin.hook',
'source_type' => 'plugin',
'source_identifier' => 'sirsoft-fakeplugin',
]);
$result = $this->repository->resolveByScopeTarget('hook', 'fakeplugin.hook');
$this->assertCount(0, $result);
}
/**
* core/admin 정책은 확장 상태와 무관하게 항상 포함된다 (비파괴)
*/
public function test_hook_scope_always_includes_core_and_admin_policies(): void
{
$this->makePolicy([
'scope' => 'hook',
'target' => 'core.hook',
'source_type' => 'core',
'source_identifier' => 'core',
]);
$this->makePolicy([
'scope' => 'hook',
'target' => 'admin.hook',
'source_type' => 'admin',
'source_identifier' => 'admin',
]);
$this->assertCount(1, $this->repository->resolveByScopeTarget('hook', 'core.hook'));
$this->assertCount(1, $this->repository->resolveByScopeTarget('hook', 'admin.hook'));
}
/**
* route scope: 활성 모듈의 정책은 라우트 인덱스에 포함된다
*/
public function test_route_scope_includes_active_module_policy(): void
{
$this->makeModule('sirsoft-fake', ExtensionStatus::Active->value);
$this->makePolicy([
'scope' => 'route',
'target' => 'api.fake.delete',
'source_type' => 'module',
'source_identifier' => 'sirsoft-fake',
]);
IdentityPolicy::flushRouteScopeCache();
$index = $this->repository->getRouteScopeIndex();
$this->assertArrayHasKey('api.fake.delete', $index);
$this->assertCount(1, $index['api.fake.delete']);
}
/**
* route scope: 비활성 모듈의 정책은 라우트 인덱스에서 제외된다 (회귀)
*/
public function test_route_scope_excludes_inactive_module_policy(): void
{
$this->makeModule('sirsoft-fake', ExtensionStatus::Inactive->value);
$this->makePolicy([
'scope' => 'route',
'target' => 'api.fake.delete',
'source_type' => 'module',
'source_identifier' => 'sirsoft-fake',
]);
IdentityPolicy::flushRouteScopeCache();
$index = $this->repository->getRouteScopeIndex();
$this->assertArrayNotHasKey('api.fake.delete', $index);
}
/**
* route scope: 모듈 재활성화 시 라우트 인덱스에 다시 포함된다 (3-state, 캐시 무효화 동반)
*/
public function test_route_scope_reincludes_policy_after_reactivation(): void
{
$module = $this->makeModule('sirsoft-fake', ExtensionStatus::Inactive->value);
$this->makePolicy([
'scope' => 'route',
'target' => 'api.fake.delete',
'source_type' => 'module',
'source_identifier' => 'sirsoft-fake',
]);
// 비활성: 제외
IdentityPolicy::flushRouteScopeCache();
$this->assertArrayNotHasKey('api.fake.delete', $this->repository->getRouteScopeIndex());
// 재활성화 + 캐시 무효화: 다시 포함
$module->update(['status' => ExtensionStatus::Active->value]);
IdentityPolicy::flushRouteScopeCache();
$this->assertArrayHasKey('api.fake.delete', $this->repository->getRouteScopeIndex());
}
}
@@ -0,0 +1,107 @@
<?php
namespace Tests\Unit\Repositories;
use App\Contracts\Repositories\IdentityPolicyRepositoryInterface;
use App\Models\IdentityPolicy;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* IdentityPolicyRepository 의 priority 정렬 결정성 검증.
*
* 회귀 배경: resolveByScopeTarget / getRouteScopeIndex 가 orderByDesc('priority') 만 사용해
* 동률 priority 정책의 반환 순서가 비결정적이었다. 같은 scope+target 에 동률 정책이 둘 이상이면
* 어느 정책이 먼저 enforce 되는지(어떤 purpose 로 challenge 되는지)가 캐시/실행계획에 좌우됐다.
* id 2차 정렬키를 추가해 동률이어도 항상 동일한 순서(먼저 생성된 정책 우선)가 되는지 검증한다.
*
* @group identity
* @group unit
*/
class IdentityPolicyRepositoryPriorityOrderTest extends TestCase
{
use RefreshDatabase;
private IdentityPolicyRepositoryInterface $repository;
protected function setUp(): void
{
parent::setUp();
$this->repository = app(IdentityPolicyRepositoryInterface::class);
}
/**
* 정책을 생성합니다.
*
* @param array<string, mixed> $overrides 덮어쓸 속성
*/
private function makePolicy(array $overrides = []): IdentityPolicy
{
return IdentityPolicy::create(array_merge([
'key' => 'test.order.'.uniqid(),
'scope' => 'route',
'target' => 'api.test.order',
'purpose' => 'sensitive_action',
'grace_minutes' => 0,
'enabled' => true,
'priority' => 100,
'source_type' => 'admin',
'source_identifier' => 'admin',
'applies_to' => 'both',
'fail_mode' => 'block',
], $overrides));
}
/**
* 우선순위가 다르면 높은 priority 가 먼저 온다 (기존 동작 보존).
*/
public function test_higher_priority_comes_first(): void
{
$low = $this->makePolicy(['key' => 'test.order.low', 'priority' => 50]);
$high = $this->makePolicy(['key' => 'test.order.high', 'priority' => 150]);
$ordered = $this->repository->resolveByScopeTarget('route', 'api.test.order');
$this->assertSame($high->id, $ordered->first()->id);
$this->assertSame($low->id, $ordered->last()->id);
}
/**
* 동률 priority 면 id 오름차순(먼저 생성된 정책 우선)으로 결정적 정렬된다.
*/
public function test_tied_priority_is_ordered_deterministically_by_id(): void
{
$first = $this->makePolicy(['key' => 'test.order.tie_a', 'priority' => 100, 'purpose' => 'sensitive_action']);
$second = $this->makePolicy(['key' => 'test.order.tie_b', 'priority' => 100, 'purpose' => 'adult_verification']);
$ordered = $this->repository->resolveByScopeTarget('route', 'api.test.order');
$this->assertCount(2, $ordered);
// 먼저 생성된 정책(작은 id)이 항상 앞 — 여러 번 조회해도 동일
$this->assertSame($first->id, $ordered->first()->id);
$this->assertSame($second->id, $ordered->last()->id);
// 결정성: 재조회해도 동일 순서
$again = $this->repository->resolveByScopeTarget('route', 'api.test.order');
$this->assertSame(
$ordered->pluck('id')->all(),
$again->pluck('id')->all(),
);
}
/**
* getRouteScopeIndex 도 동일한 결정적 정렬을 적용한다 (미들웨어 enforce 순서).
*/
public function test_route_scope_index_is_ordered_deterministically(): void
{
$first = $this->makePolicy(['key' => 'test.order.idx_a', 'priority' => 100]);
$second = $this->makePolicy(['key' => 'test.order.idx_b', 'priority' => 100]);
$index = $this->repository->getRouteScopeIndex();
$bucket = $index['api.test.order'] ?? collect();
$this->assertCount(2, $bucket);
$this->assertSame($first->id, $bucket->first()->id);
$this->assertSame($second->id, $bucket->last()->id);
}
}
@@ -17,6 +17,16 @@ class LayoutExtensionRepositoryTest extends TestCase
{
use RefreshDatabase;
/**
* 같은 스위트의 레이아웃/GDPR 미들웨어 의존 테스트와 migrate:fresh 정합성을
* 맞추기 위해 GDPR 플러그인 마이그레이션을 일관 선언한다.
*
* @var array<string>
*/
protected array $requiredExtensions = [
'plugins/sirsoft-gdpr',
];
private LayoutExtensionRepositoryInterface $repository;
private Template $template;
@@ -457,6 +467,100 @@ class LayoutExtensionRepositoryTest extends TestCase
});
}
/**
* 오버라이드 해석 조회 시 템플릿 오버라이드에 가려진 모듈/플러그인 확장은 제외됨
*
* 회귀: 레이아웃 편집 화면 좌측 트리(getResolvedByTemplateId 기반)가
* 화면에 실제 적용되지 않는 "가려진 행"을 노출하여, 관리자가 그 행을
* 편집해도 반영되지 않던 문제. 렌더링 경로(getResolvedExtensionPoints/
* getResolvedOverlays)와 동일한 오버라이드 해석을 적용해야 한다.
*/
public function test_get_resolved_by_template_id_excludes_overridden_extensions(): void
{
// Arrange - 플러그인 Extension Point 확장
LayoutExtension::factory()->create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::ExtensionPoint,
'target_name' => 'address_search_slot',
'source_type' => LayoutSourceType::Plugin,
'source_identifier' => 'sirsoft-daum_postcode',
'priority' => 100,
'is_active' => true,
]);
// Arrange - 템플릿 오버라이드 (위 플러그인 확장을 가림)
LayoutExtension::factory()->create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::ExtensionPoint,
'target_name' => 'address_search_slot',
'source_type' => LayoutSourceType::Template,
'source_identifier' => 'sirsoft-admin_basic',
'override_target' => 'sirsoft-daum_postcode',
'priority' => 50,
'is_active' => true,
]);
// Arrange - 가려지지 않은 다른 모듈 확장 (다른 확장점)
LayoutExtension::factory()->create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::Overlay,
'target_name' => 'admin/dashboard',
'source_type' => LayoutSourceType::Module,
'source_identifier' => 'sirsoft-ecommerce',
'priority' => 50,
'is_active' => true,
]);
// Act
$result = $this->repository->getResolvedByTemplateId($this->template->id);
// Assert - 오버라이드된 플러그인 원본은 제외, 오버라이드 + 무관 확장만 남음
$this->assertCount(2, $result);
$identifiers = $result->pluck('source_identifier')->toArray();
$this->assertContains('sirsoft-admin_basic', $identifiers);
$this->assertContains('sirsoft-ecommerce', $identifiers);
$this->assertNotContains('sirsoft-daum_postcode', $identifiers);
}
/**
* 오버라이드가 없으면 오버라이드 해석 조회는 모든 확장을 그대로 반환함
*/
public function test_get_resolved_by_template_id_returns_all_when_no_override(): void
{
// Arrange - 오버라이드 없는 확장 3개 (서로 다른 확장점/레이아웃)
LayoutExtension::factory()->create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::ExtensionPoint,
'target_name' => 'address_search_slot',
'source_type' => LayoutSourceType::Plugin,
'source_identifier' => 'sirsoft-daum_postcode',
'is_active' => true,
]);
LayoutExtension::factory()->create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::Overlay,
'target_name' => 'admin/dashboard',
'source_type' => LayoutSourceType::Module,
'source_identifier' => 'sirsoft-ecommerce',
'is_active' => true,
]);
LayoutExtension::factory()->create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::ExtensionPoint,
'target_name' => 'sidebar-top',
'source_type' => LayoutSourceType::Module,
'source_identifier' => 'sirsoft-other',
'is_active' => true,
]);
// Act
$result = $this->repository->getResolvedByTemplateId($this->template->id);
// Assert - 가림 대상이 없으므로 전부 반환
$this->assertCount(3, $result);
}
/**
* 템플릿 ID로 모든 확장 삭제 테스트
*/
@@ -0,0 +1,215 @@
<?php
namespace Tests\Unit\Repositories;
use App\Models\LayoutExtension;
use App\Models\Template;
use App\Models\TemplateLayoutExtensionVersion;
use App\Repositories\LayoutExtensionVersionRepository;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* 레이아웃 확장 버전 리포지토리 테스트
*/
class LayoutExtensionVersionRepositoryTest extends TestCase
{
use RefreshDatabase;
/**
* 같은 스위트의 레이아웃/GDPR 미들웨어 의존 테스트와 migrate:fresh 정합성을
* 맞추기 위해 GDPR 플러그인 마이그레이션을 일관 선언한다.
*
* @var array<string>
*/
protected array $requiredExtensions = [
'plugins/sirsoft-gdpr',
];
private LayoutExtensionVersionRepository $repository;
private Template $template;
private LayoutExtension $extension;
protected function setUp(): void
{
parent::setUp();
$this->repository = new LayoutExtensionVersionRepository(new TemplateLayoutExtensionVersion);
$this->template = Template::factory()->create();
$this->extension = LayoutExtension::factory()->create(['template_id' => $this->template->id]);
}
/**
* saveVersion - 첫 번째 버전 생성
*/
public function test_save_version_creates_first_version(): void
{
$content = ['extension_point' => 'header', 'components' => []];
$version = $this->repository->saveVersion($this->extension->id, $content);
$this->assertInstanceOf(TemplateLayoutExtensionVersion::class, $version);
$this->assertEquals(1, $version->version);
$this->assertEquals($this->extension->id, $version->extension_id);
$this->assertEquals($content, $version->content);
}
/**
* saveVersion - 버전 자동 증가
*/
public function test_save_version_auto_increments(): void
{
TemplateLayoutExtensionVersion::factory()->create(['extension_id' => $this->extension->id, 'version' => 1]);
TemplateLayoutExtensionVersion::factory()->create(['extension_id' => $this->extension->id, 'version' => 2]);
$newVersion = $this->repository->saveVersion($this->extension->id, ['test' => 'data']);
$this->assertEquals(3, $newVersion->version);
}
/**
* getVersions - 최신순 정렬
*/
public function test_get_versions_returns_latest_first(): void
{
foreach ([1, 3, 2] as $v) {
TemplateLayoutExtensionVersion::factory()->create(['extension_id' => $this->extension->id, 'version' => $v]);
}
$versions = $this->repository->getVersions($this->extension->id);
$this->assertCount(3, $versions);
$this->assertEquals(3, $versions->first()->version);
$this->assertEquals(1, $versions->last()->version);
}
/**
* getNextVersion - 버전 없을 때 1 반환
*/
public function test_get_next_version_returns_one_when_empty(): void
{
$this->assertEquals(1, $this->repository->getNextVersion($this->extension->id));
}
/**
* getNextVersion - max + 1
*/
public function test_get_next_version_returns_max_plus_one(): void
{
foreach ([1, 5, 3] as $v) {
TemplateLayoutExtensionVersion::factory()->create(['extension_id' => $this->extension->id, 'version' => $v]);
}
$this->assertEquals(6, $this->repository->getNextVersion($this->extension->id));
}
/**
* 버전은 확장별로 격리됨
*/
public function test_versions_are_isolated_by_extension(): void
{
$otherExtension = LayoutExtension::factory()->create(['template_id' => $this->template->id]);
TemplateLayoutExtensionVersion::factory()->create(['extension_id' => $otherExtension->id, 'version' => 10]);
$this->assertEquals(1, $this->repository->getNextVersion($this->extension->id));
$this->assertCount(0, $this->repository->getVersions($this->extension->id));
}
/**
* calculateChanges - trait 동작 (라인 단위 카운트)
*
* changes_summary 는 버전 비교 diff 뷰와 동일한 라인 단위로 센다. 키 정렬 직렬화
* 후 라인 LCS 로 추가/삭제 라인 수를 집계한다(added/removed 는 정수 카운트, modified
* 키는 없음 — 값 변경은 삭제+추가 라인으로 표현).
*/
public function test_calculate_changes_detects_diff(): void
{
// name 값 변경(삭제+추가), deprecated 삭제(1줄), added 키 추가(1줄)
$old = ['name' => 'test', 'deprecated' => 'old'];
$new = ['name' => 'changed', 'added' => 'new'];
$changes = $this->repository->calculateChanges($old, $new);
// added 라인: "added": "new", + "name": "changed", = 2줄
$this->assertSame(2, $changes['added']);
// removed 라인: "deprecated": "old", + "name": "test", = 2줄
$this->assertSame(2, $changes['removed']);
$this->assertArrayNotHasKey('modified', $changes, 'modified 키는 두지 않는다');
}
/**
* restoreVersion - 트랜잭션 내 복원 + 새 버전 생성
*/
public function test_restore_version_restores_content_and_creates_new_version(): void
{
$oldContent = ['extension_point' => 'header', 'components' => [['type' => 'basic', 'name' => 'Span']]];
$this->extension->update(['content' => $oldContent]);
// 복원 대상 버전 (버전 1) — 이전 content 스냅샷
$versionToRestore = TemplateLayoutExtensionVersion::factory()->create([
'extension_id' => $this->extension->id,
'version' => 1,
'content' => $oldContent,
]);
// 현재 content 를 다른 값으로 변경
$this->extension->update(['content' => ['extension_point' => 'footer']]);
$newVersion = $this->repository->restoreVersion($this->extension->id, $versionToRestore->id);
// 확장 content 가 복원됨
$this->extension->refresh();
$this->assertEquals($oldContent, $this->extension->content);
// 새 버전 생성됨 (버전 2)
$this->assertEquals(2, $newVersion->version);
}
/**
* restoreVersion - 존재하지 않는 버전은 예외
*/
public function test_restore_version_throws_when_version_not_found(): void
{
$this->expectException(ModelNotFoundException::class);
$this->repository->restoreVersion($this->extension->id, 99999);
}
/**
* getCurrentVersionsByExtensionIds — 확장별 최신 버전 맵
*/
public function test_get_current_versions_by_extension_ids_returns_latest_version_map(): void
{
$other = LayoutExtension::factory()->create(['template_id' => $this->template->id]);
$noHistory = LayoutExtension::factory()->create(['template_id' => $this->template->id]);
foreach ([1, 2, 3] as $v) {
TemplateLayoutExtensionVersion::factory()->create(['extension_id' => $this->extension->id, 'version' => $v]);
}
TemplateLayoutExtensionVersion::factory()->create(['extension_id' => $other->id, 'version' => 1]);
$map = $this->repository->getCurrentVersionsByExtensionIds([
$this->extension->id,
$other->id,
$noHistory->id,
]);
ksort($map);
$expected = [$this->extension->id => 3, $other->id => 1];
ksort($expected);
$this->assertSame($expected, $map);
$this->assertArrayNotHasKey($noHistory->id, $map);
}
/**
* getCurrentVersionsByExtensionIds — 빈 입력/이력 전무 시 빈 맵
*/
public function test_get_current_versions_by_extension_ids_returns_empty_for_empty_input(): void
{
$this->assertSame([], $this->repository->getCurrentVersionsByExtensionIds([]));
$this->assertSame([], $this->repository->getCurrentVersionsByExtensionIds([$this->extension->id]));
}
}
@@ -13,6 +13,16 @@ class LayoutVersionRepositoryTest extends TestCase
{
use RefreshDatabase;
/**
* 같은 스위트의 레이아웃/GDPR 미들웨어 의존 테스트와 migrate:fresh 정합성을
* 맞추기 위해 GDPR 플러그인 마이그레이션을 일관 선언한다.
*
* @var array<string>
*/
protected array $requiredExtensions = [
'plugins/sirsoft-gdpr',
];
private LayoutVersionRepository $repository;
private Template $template;
@@ -214,6 +224,101 @@ class LayoutVersionRepositoryTest extends TestCase
$this->assertCount(0, $versions);
}
/**
* recalculateAllChangeSummaries - 기존 버전의 changes_summary 를 라인 단위로 재계산
*
* 옛 기준(키 경로 단위)의 잘못된 요약이 담긴 버전들을 만들고, 재계산 후 인접 버전
* 대비 라인 단위로 정확히 갱신되는지 검증한다. 첫 버전은 baseline(빈 요약).
*
* @effects changes_summary_recalculated_for_existing_versions
*/
public function test_recalculate_all_change_summaries_fixes_stale_summaries(): void
{
// Arrange — 옛 기준의 엉뚱한 요약을 직접 심어 둔 3개 버전
$contentV1 = ['children' => [['name' => 'Span', 'text' => 't', 'type' => 'basic']]];
$contentV2 = ['children' => [
['name' => 'Span', 'text' => 't', 'type' => 'basic'],
['name' => 'Span', 'text' => 't', 'type' => 'basic'],
]];
$contentV3 = ['children' => [['name' => 'Span', 'text' => 't', 'type' => 'basic']]];
$v1 = TemplateLayoutVersion::factory()->create([
'layout_id' => $this->layout->id,
'version' => 1,
'content' => $contentV1,
'changes_summary' => ['added' => 7, 'removed' => 7, 'char_diff' => 999],
]);
$v2 = TemplateLayoutVersion::factory()->create([
'layout_id' => $this->layout->id,
'version' => 2,
'content' => $contentV2,
'changes_summary' => ['added' => 1, 'removed' => 0, 'char_diff' => 1],
]);
$v3 = TemplateLayoutVersion::factory()->create([
'layout_id' => $this->layout->id,
'version' => 3,
'content' => $contentV3,
'changes_summary' => ['added' => 0, 'removed' => 1, 'char_diff' => -1],
]);
// Act
$count = $this->repository->recalculateAllChangeSummaries();
// Assert
$this->assertEquals(3, $count);
// v1 = baseline (빈 요약 — 카운트 0)
$v1->refresh();
$this->assertSame(0, $v1->changes_summary['added']);
$this->assertSame(0, $v1->changes_summary['removed']);
$this->assertSame(0, $v1->changes_summary['char_diff']);
// v2 = Span 객체 1개 추가 → 라인 5줄 추가 (직전 }→}, + {, name, text, type)
$v2->refresh();
$this->assertSame(5, $v2->changes_summary['added']);
$this->assertSame(0, $v2->changes_summary['removed']);
// v3 = Span 객체 1개 삭제 → 라인 5줄 삭제
$v3->refresh();
$this->assertSame(5, $v3->changes_summary['removed']);
$this->assertSame(0, $v3->changes_summary['added']);
}
/**
* restoreVersion - 복원은 content 만 의존하며 changes_summary 카운트 구조와 무관
*
* 검증: changes_summary 를 라인 원문 배열 → 카운트 정수로 바꿔도 복원에 문제가
* 없는가? 복원은 복원 대상 버전의 content 를 레이아웃에 그대로 적용하고, changes_summary
* 는 결과로 새로 계산할 뿐 복원 입력으로 읽지 않는다. 따라서 카운트 구조여도 복원된
* content 가 정확하고, 새 버전의 changes_summary 는 카운트(정수)로 기록된다.
*/
public function test_restore_version_restores_content_regardless_of_summary_structure(): void
{
// Arrange — v1(작은 content) → v2(큰 content) 저장 후, 현재 레이아웃은 v2 상태
$contentV1 = ['components' => [['name' => 'A']]];
$contentV2 = ['components' => [['name' => 'A'], ['name' => 'B'], ['name' => 'C']]];
$v1 = $this->repository->saveVersion($this->layout->id, $contentV1);
$this->layout->update(['content' => $contentV2]);
$this->repository->saveVersion($this->layout->id, $contentV2, $contentV1);
// Act — v1 으로 복원
$restored = $this->repository->restoreVersion($this->layout->id, $v1->id);
// Assert — 1) 레이아웃 content 가 v1 으로 정확히 복원됨 (content 만 의존)
$this->layout->refresh();
$this->assertEquals($contentV1, $this->layout->content, '복원은 대상 버전 content 를 그대로 적용한다');
// 2) 복원으로 적재된 새 버전의 content 도 v1 (복원본)
$this->assertEquals($contentV1, $restored->content);
// 3) 새 버전의 changes_summary 는 카운트(정수) 구조 — 복원으로 줄었으므로 removed > 0
$this->assertIsInt($restored->changes_summary['added']);
$this->assertIsInt($restored->changes_summary['removed']);
$this->assertGreaterThan(0, $restored->changes_summary['removed'], '큰 content→작은 content 복원이므로 라인 삭제');
$this->assertSame(0, $restored->changes_summary['added']);
}
/**
* saveVersion 연속 호출 테스트
*/
@@ -239,453 +344,224 @@ class LayoutVersionRepositoryTest extends TestCase
}
/**
* calculateChanges 메서드 테스트 - 추가된 키
* calculateChanges 라인 단위 측정 - 키 추가
*
* changes_summary 는 버전 비교 diff 뷰(프론트 lineDiff.ts)와 동일한 "라인" 단위로
* 센다. 키 2개 추가 = pretty JSON 라인 2줄 추가(스칼라 값 키는 1키=1줄).
*/
public function test_calculate_changes_detects_added_keys(): void
public function test_calculate_changes_counts_added_lines(): void
{
// Arrange
$old = [
'name' => 'test',
'version' => '1.0.0',
];
$old = ['name' => 'test', 'version' => '1.0.0'];
$new = ['name' => 'test', 'version' => '1.0.0', 'description' => 'new field', 'author' => 'John Doe'];
$new = [
'name' => 'test',
'version' => '1.0.0',
'description' => 'new field',
'author' => 'John Doe',
];
// Act
$changes = $this->repository->calculateChanges($old, $new);
// Assert
$this->assertCount(2, $changes['added']);
$this->assertContains('description', $changes['added']);
$this->assertContains('author', $changes['added']);
$this->assertEmpty($changes['removed']);
$this->assertEmpty($changes['modified']);
$this->assertSame(2, $changes['added'], '스칼라 키 2개 추가 = 라인 2줄');
$this->assertSame(0, $changes['removed']);
}
/**
* calculateChanges 메서드 테스트 - 삭제된 키
* calculateChanges 라인 단위 측정 - 키 삭제
*/
public function test_calculate_changes_detects_removed_keys(): void
public function test_calculate_changes_counts_removed_lines(): void
{
// Arrange
$old = [
'name' => 'test',
'version' => '1.0.0',
'deprecated' => 'old field',
'legacy' => 'another old field',
];
$old = ['name' => 'test', 'version' => '1.0.0', 'deprecated' => 'old field', 'legacy' => 'x'];
$new = ['name' => 'test', 'version' => '1.0.0'];
$new = [
'name' => 'test',
'version' => '1.0.0',
];
// Act
$changes = $this->repository->calculateChanges($old, $new);
// Assert
$this->assertCount(2, $changes['removed']);
$this->assertContains('deprecated', $changes['removed']);
$this->assertContains('legacy', $changes['removed']);
$this->assertEmpty($changes['added']);
$this->assertEmpty($changes['modified']);
$this->assertSame(2, $changes['removed'], '스칼라 키 2개 삭제 = 라인 2줄');
$this->assertSame(0, $changes['added']);
}
/**
* calculateChanges 메서드 테스트 - 수정된 값
* calculateChanges 라인 단위 측정 - 값 수정은 삭제+추가 라인으로 표현
*
* 라인 diff 에는 "수정" 개념이 없다 — 값이 바뀐 키는 옛 라인 삭제 + 새 라인 추가로
* 나타난다(diff 뷰의 -/+ 와 동일). 스칼라 값 2개 변경 = removed 2 + added 2.
*/
public function test_calculate_changes_detects_modified_values(): void
public function test_calculate_changes_value_change_is_remove_plus_add(): void
{
// Arrange
$old = [
'name' => 'test',
'version' => '1.0.0',
'status' => 'draft',
];
$old = ['name' => 'test', 'version' => '1.0.0', 'status' => 'draft'];
$new = ['name' => 'test', 'version' => '2.0.0', 'status' => 'published'];
$new = [
'name' => 'test',
'version' => '2.0.0',
'status' => 'published',
];
// Act
$changes = $this->repository->calculateChanges($old, $new);
// Assert
$this->assertCount(2, $changes['modified']);
$this->assertContains('version', $changes['modified']);
$this->assertContains('status', $changes['modified']);
$this->assertEmpty($changes['added']);
$this->assertEmpty($changes['removed']);
$this->assertSame(2, $changes['added'], '값 2개 변경 = 새 라인 2줄');
$this->assertSame(2, $changes['removed'], '값 2개 변경 = 옛 라인 2줄');
}
/**
* calculateChanges 메서드 테스트 - 중첩 객체 추가
* calculateChanges 라인 단위 측정 - 변경 없음
*/
public function test_calculate_changes_detects_nested_added_keys(): void
public function test_calculate_changes_no_changes_yields_empty(): void
{
// Arrange
$old = [
'name' => 'test',
'config' => [
'theme' => 'dark',
],
];
$old = ['name' => 'test', 'config' => ['theme' => 'dark']];
$new = ['name' => 'test', 'config' => ['theme' => 'dark']];
$new = [
'name' => 'test',
'config' => [
'theme' => 'dark',
'locale' => 'ko',
],
'metadata' => [
'author' => 'John',
'tags' => ['test', 'demo'],
],
];
// Act
$changes = $this->repository->calculateChanges($old, $new);
// Assert
$this->assertContains('config.locale', $changes['added']);
$this->assertContains('metadata', $changes['added']);
$this->assertContains('metadata.author', $changes['added']);
$this->assertContains('metadata.tags', $changes['added']);
$this->assertSame(0, $changes['added']);
$this->assertSame(0, $changes['removed']);
$this->assertSame(0, $changes['char_diff']);
}
/**
* calculateChanges 메서드 테스트 - 중첩 객체 삭제
* calculateChanges 라인 단위 측정 - 키 순서 무관 동일성
*
* 키 정렬 직렬화이므로 같은 내용·다른 키순은 변경 없음으로 본다(노이즈 diff 방지).
*/
public function test_calculate_changes_detects_nested_removed_keys(): void
public function test_calculate_changes_ignores_key_order(): void
{
// Arrange
$old = [
'name' => 'test',
'config' => [
'theme' => 'dark',
'locale' => 'ko',
'deprecated' => 'old',
],
'legacy' => [
'old_field' => 'value',
],
];
$old = ['b' => 1, 'a' => 2, 'c' => 3];
$new = ['a' => 2, 'c' => 3, 'b' => 1];
$new = [
'name' => 'test',
'config' => [
'theme' => 'dark',
],
];
// Act
$changes = $this->repository->calculateChanges($old, $new);
// Assert
$this->assertContains('config.locale', $changes['removed']);
$this->assertContains('config.deprecated', $changes['removed']);
$this->assertContains('legacy', $changes['removed']);
$this->assertSame(0, $changes['added']);
$this->assertSame(0, $changes['removed']);
}
/**
* calculateChanges 메서드 테스트 - 중첩 객체 수정
* calculateChanges 라인 단위 측정 - 객체 통째 추가 (구조 라인 포함)
*
* 중첩 객체가 추가되면 그 객체의 모든 라인(여는/닫는 중괄호 포함)이 added 로 집계된다.
* 키 경로 단위가 아니라 라인 단위이므로 구조 문자도 센다(diff 뷰와 동일).
*/
public function test_calculate_changes_detects_nested_modified_values(): void
public function test_calculate_changes_counts_nested_object_addition_lines(): void
{
// Arrange
$old = [
'name' => 'test',
'config' => [
'theme' => 'dark',
'locale' => 'ko',
],
];
$old = ['name' => 'test'];
// metadata 객체 추가: { "metadata": { "author": "John", "tags": [...] } }
$new = ['name' => 'test', 'metadata' => ['author' => 'John', 'role' => 'admin']];
$new = [
'name' => 'test',
'config' => [
'theme' => 'light',
'locale' => 'en',
],
];
// Act
$changes = $this->repository->calculateChanges($old, $new);
// Assert
$this->assertContains('config.theme', $changes['modified']);
$this->assertContains('config.locale', $changes['modified']);
$this->assertEmpty($changes['added']);
$this->assertEmpty($changes['removed']);
// 추가 라인: "metadata": { / "author": ..., / "role": ... / } = 4줄
$this->assertSame(4, $changes['added']);
$this->assertSame(0, $changes['removed']);
}
/**
* calculateChanges 메서드 테스트 - 복합 변경 (추가+삭제+수정)
*/
public function test_calculate_changes_detects_complex_changes(): void
{
// Arrange
$old = [
'name' => 'test',
'version' => '1.0.0',
'deprecated' => 'old',
'components' => [
'header' => ['title' => 'Old Title'],
],
];
$new = [
'name' => 'test',
'version' => '2.0.0',
'description' => 'new field',
'components' => [
'header' => ['title' => 'New Title'],
'footer' => ['text' => 'Footer'],
],
];
// Act
$changes = $this->repository->calculateChanges($old, $new);
// Assert
// Added
$this->assertContains('description', $changes['added']);
$this->assertContains('components.footer', $changes['added']);
$this->assertContains('components.footer.text', $changes['added']);
// Removed
$this->assertContains('deprecated', $changes['removed']);
// Modified
$this->assertContains('version', $changes['modified']);
$this->assertContains('components.header.title', $changes['modified']);
}
/**
* calculateChanges 메서드 테스트 - 변경사항 없음
*/
public function test_calculate_changes_detects_no_changes(): void
{
// Arrange
$old = [
'name' => 'test',
'version' => '1.0.0',
'config' => [
'theme' => 'dark',
],
];
$new = [
'name' => 'test',
'version' => '1.0.0',
'config' => [
'theme' => 'dark',
],
];
// Act
$changes = $this->repository->calculateChanges($old, $new);
// Assert
$this->assertEmpty($changes['added']);
$this->assertEmpty($changes['removed']);
$this->assertEmpty($changes['modified']);
}
/**
* calculateChanges 메서드 테스트 - 빈 배열
*/
public function test_calculate_changes_handles_empty_arrays(): void
{
// Arrange
$old = [];
$new = ['name' => 'test'];
// Act
$changes = $this->repository->calculateChanges($old, $new);
// Assert
$this->assertCount(1, $changes['added']);
$this->assertContains('name', $changes['added']);
$this->assertEmpty($changes['removed']);
$this->assertEmpty($changes['modified']);
}
/**
* calculateChanges 메서드 테스트 - 깊은 중첩 구조
*/
public function test_calculate_changes_handles_deeply_nested_structure(): void
{
// Arrange
$old = [
'level1' => [
'level2' => [
'level3' => [
'level4' => 'old value',
],
],
],
];
$new = [
'level1' => [
'level2' => [
'level3' => [
'level4' => 'new value',
'level4_new' => 'added',
],
],
],
];
// Act
$changes = $this->repository->calculateChanges($old, $new);
// Assert
$this->assertContains('level1.level2.level3.level4', $changes['modified']);
$this->assertContains('level1.level2.level3.level4_new', $changes['added']);
$this->assertEmpty($changes['removed']);
}
/**
* calculateChanges 메서드 테스트 - 대용량 JSON 성능 (1MB 이상)
* calculateChanges 라인 단위 측정 - 대용량 JSON 성능
*/
public function test_calculate_changes_performance_with_large_json(): void
{
// Arrange - 대용량 JSON 생성 (약 1MB)
$old = [];
$new = [];
// 1000개의 컴포넌트 생성
for ($i = 0; $i < 1000; $i++) {
$old["component_{$i}"] = [
'type' => 'section',
'id' => "comp_{$i}",
'props' => [
'title' => "Component {$i}",
'description' => str_repeat("Long description for component {$i}. ", 10),
'metadata' => [
'author' => 'Test Author',
'created' => '2025-01-01',
'tags' => ['tag1', 'tag2', 'tag3'],
],
],
'children' => [
[
'type' => 'text',
'content' => str_repeat("Sample content {$i}. ", 20),
],
[
'type' => 'image',
'src' => "/images/image_{$i}.jpg",
'alt' => "Image {$i}",
],
],
'title' => "Component {$i}",
];
// new는 일부 수정된 버전
$new["component_{$i}"] = $old["component_{$i}"];
if ($i % 10 === 0) {
// 10번째마다 수정
$new["component_{$i}"]['props']['title'] = "Modified Component {$i}";
}
if ($i % 15 === 0) {
// 15번째마다 새 필드 추가
$new["component_{$i}"]['props']['updated'] = '2025-01-10';
$new["component_{$i}"]['title'] = "Modified Component {$i}";
}
}
// 일부 컴포넌트 삭제 (old에만 존재)
for ($i = 1000; $i < 1010; $i++) {
$old["component_{$i}"] = ['type' => 'deleted', 'id' => "comp_{$i}"];
}
// 일부 컴포넌트 추가 (new에만 존재)
for ($i = 1010; $i < 1020; $i++) {
$new["component_{$i}"] = ['type' => 'added', 'id' => "comp_{$i}"];
}
// JSON 크기 확인 (약 1MB 이상인지)
$jsonSize = strlen(json_encode($old)) + strlen(json_encode($new));
$this->assertGreaterThan(1024 * 1024, $jsonSize, 'JSON size should be greater than 1MB');
// Act - 실행 시간 측정
$startTime = microtime(true);
$changes = $this->repository->calculateChanges($old, $new);
$executionTime = microtime(true) - $startTime;
// Assert - 성능 검증 (2초 이내 완료)
$this->assertLessThan(2.0, $executionTime, 'Large JSON diff should complete within 2 seconds');
// 변경사항 정확도 검증
$this->assertNotEmpty($changes['added']);
$this->assertNotEmpty($changes['removed']);
$this->assertNotEmpty($changes['modified']);
// 예상되는 변경사항 수 검증
// 100개 수정 (component_0, 10, 20, ..., 990)
// 67개 추가 (component_0.props.updated, 15, 30, ..., 975 + 10개 새 컴포넌트)
// 10개 삭제 (component_1000 ~ 1009)
$this->assertGreaterThanOrEqual(100, count($changes['modified']));
$this->assertGreaterThanOrEqual(10, count($changes['removed']));
$this->assertGreaterThanOrEqual(10, count($changes['added']));
$this->assertLessThan(5.0, $executionTime, 'Large JSON line diff should complete within 5 seconds');
// 100개 컴포넌트의 title 1줄씩 변경 = removed 100 + added 100
$this->assertGreaterThanOrEqual(100, $changes['added']);
$this->assertGreaterThanOrEqual(100, $changes['removed']);
}
/**
* calculateChanges 메서드 테스트 - 배열 vs 스칼라 값 타입 변경
* calculateChanges 라인 단위 측정 - 스칼라→배열 타입 변경
*
* 스칼라 1줄 삭제 + 배열 여러 줄 추가로 나타난다.
*/
public function test_calculate_changes_detects_type_change_from_scalar_to_array(): void
public function test_calculate_changes_scalar_to_array(): void
{
// Arrange
$old = [
'name' => 'test',
'tags' => 'single-tag',
];
$old = ['name' => 'test', 'tags' => 'single-tag'];
$new = ['name' => 'test', 'tags' => ['tag1', 'tag2', 'tag3']];
$new = [
'name' => 'test',
'tags' => ['tag1', 'tag2', 'tag3'],
];
// Act
$changes = $this->repository->calculateChanges($old, $new);
// Assert
$this->assertContains('tags', $changes['modified']);
$this->assertEmpty($changes['added']);
$this->assertEmpty($changes['removed']);
// 옛 "tags": "single-tag" 1줄 삭제, 새 "tags": [ ... ] 여러 줄 추가
$this->assertGreaterThan(0, $changes['removed']);
$this->assertGreaterThan($changes['removed'], $changes['added']);
}
/**
* calculateChanges 메서드 테스트 - 배열 vs 스칼라 값 타입 변경 (반대)
* calculateChanges 라인 단위 측정 - 순차 배열(list) 끝 객체 삭제
*
* components 같은 list 에서 객체 1개(Span)가 통째로 삭제되면 그 객체의 모든 라인이
* removed 로 집계된다. diff 뷰 스크린샷의 "-5 삭제"(여는/닫는 중괄호 + 필드 3줄)와
* 정확히 일치한다. 종전 키 경로 단위는 인덱스 1개만 세어(`children.1`) 불일치했다.
*
* @effects changes_summary_uses_line_lcs_unit_matching_diff_view
*/
public function test_calculate_changes_detects_type_change_from_array_to_scalar(): void
public function test_calculate_changes_list_element_removed_matches_diff_lines(): void
{
// Arrange
$old = [
'name' => 'test',
'tags' => ['tag1', 'tag2', 'tag3'],
];
$old = ['children' => [
['name' => 'Span', 'text' => 't', 'type' => 'basic'],
['name' => 'Span', 'text' => 't', 'type' => 'basic'],
]];
$new = ['children' => [
['name' => 'Span', 'text' => 't', 'type' => 'basic'],
]];
$new = [
'name' => 'test',
'tags' => 'single-tag',
];
// Act
$changes = $this->repository->calculateChanges($old, $new);
// Assert
$this->assertContains('tags', $changes['modified']);
$this->assertEmpty($changes['added']);
$this->assertEmpty($changes['removed']);
// 삭제 객체 라인: { "name": "Span", "text": "t", "type": "basic" } = 5줄
$this->assertSame(5, $changes['removed']);
$this->assertSame(0, $changes['added']);
}
/**
* calculateChanges 라인 단위 측정 - 순차 배열(list) 앞쪽 객체 삽입
*
* 앞에 객체 1개를 삽입해도 뒤 요소는 인덱스만 밀릴 뿐 라인 내용이 동일하므로 삽입된
* 객체 라인만 added 로 집계된다(밀린 요소 오판 없음). 종전 키 경로 단위는 인덱스
* 밀림을 modified 로 오판했다.
*/
public function test_calculate_changes_list_element_inserted_matches_diff_lines(): void
{
$old = ['children' => [
['name' => 'A', 'text' => 'aaa'],
['name' => 'B', 'text' => 'bbb'],
]];
$new = ['children' => [
['name' => 'NEW', 'text' => 'new'],
['name' => 'A', 'text' => 'aaa'],
['name' => 'B', 'text' => 'bbb'],
]];
$changes = $this->repository->calculateChanges($old, $new);
// 삽입 객체 라인: { "name": "NEW", "text": "new" } = 4줄
$this->assertSame(4, $changes['added']);
$this->assertEmpty($changes['removed'], '인덱스가 밀린 동일 요소를 변경으로 오판하면 안 된다');
}
/**
* calculateChanges 라인 단위 측정 - 순차 배열(list) 중간 요소 필드 변경
*
* list 중간 요소의 필드 1개만 바뀌면 그 라인 1줄만 삭제+추가된다(앞뒤 동일 요소 영향
* 없음). diff 뷰와 동일하게 -1/+1 로 표현된다.
*/
public function test_calculate_changes_list_element_field_change_matches_diff_lines(): void
{
$old = ['children' => [
['name' => 'A', 'text' => 'aaa'],
['name' => 'B', 'text' => 'bbb'],
['name' => 'C', 'text' => 'ccc'],
]];
$new = ['children' => [
['name' => 'A', 'text' => 'aaa'],
['name' => 'B', 'text' => 'CHANGED'],
['name' => 'C', 'text' => 'ccc'],
]];
$changes = $this->repository->calculateChanges($old, $new);
$this->assertSame(1, $changes['added'], '필드 1개 변경 = 새 라인 1줄');
$this->assertSame(1, $changes['removed'], '필드 1개 변경 = 옛 라인 1줄');
}
/**
@@ -763,4 +639,52 @@ class LayoutVersionRepositoryTest extends TestCase
$version12 = $this->repository->saveVersion($this->layout->id, $content12);
$this->assertEquals(12, $version12->version);
}
/**
* getCurrentVersionsByTemplateId — 레이아웃별 최신 버전 맵
*/
public function test_get_current_versions_by_template_id_returns_latest_version_map(): void
{
// Arrange — 본 템플릿에 레이아웃 2개 (이력 보유) + 이력 없는 레이아웃 1개 + 타 템플릿 레이아웃
$layoutB = TemplateLayout::factory()->create([
'template_id' => $this->template->id,
'name' => 'auth/login',
]);
TemplateLayout::factory()->create([
'template_id' => $this->template->id,
'name' => 'never-saved',
]);
$otherTemplate = Template::factory()->create();
$otherLayout = TemplateLayout::factory()->create([
'template_id' => $otherTemplate->id,
'name' => 'other-home',
]);
foreach ([1, 2, 3] as $v) {
TemplateLayoutVersion::factory()->create(['layout_id' => $this->layout->id, 'version' => $v]);
}
TemplateLayoutVersion::factory()->create(['layout_id' => $layoutB->id, 'version' => 1]);
TemplateLayoutVersion::factory()->create(['layout_id' => $otherLayout->id, 'version' => 9]);
// Act
$map = $this->repository->getCurrentVersionsByTemplateId($this->template->id);
// Assert — 본 템플릿의 이력 보유 레이아웃만, 각각 최신 버전 번호
ksort($map);
$expected = [$this->layout->name => 3, 'auth/login' => 1];
ksort($expected);
$this->assertSame($expected, $map);
$this->assertArrayNotHasKey('never-saved', $map);
$this->assertArrayNotHasKey('other-home', $map);
}
/**
* getCurrentVersionsByTemplateId — 이력이 전무하면 빈 맵
*/
public function test_get_current_versions_by_template_id_returns_empty_when_no_history(): void
{
$map = $this->repository->getCurrentVersionsByTemplateId($this->template->id);
$this->assertSame([], $map);
}
}
@@ -25,7 +25,7 @@ class DatabaseFulltextEngineTest extends TestCase
protected function setUp(): void
{
parent::setUp();
$this->engine = new DatabaseFulltextEngine();
$this->engine = new DatabaseFulltextEngine;
}
/**
@@ -33,7 +33,7 @@ class DatabaseFulltextEngineTest extends TestCase
*/
public function test_update_is_noop(): void
{
$models = new Collection();
$models = new Collection;
// 예외 없이 정상 실행되어야 함
$this->engine->update($models);
@@ -45,7 +45,7 @@ class DatabaseFulltextEngineTest extends TestCase
*/
public function test_delete_is_noop(): void
{
$models = new Collection();
$models = new Collection;
$this->engine->delete($models);
$this->assertTrue(true);
@@ -162,7 +162,7 @@ class DatabaseFulltextEngineTest extends TestCase
*/
public function test_search_returns_empty_for_non_fulltext_searchable_model(): void
{
$model = new NonFulltextModel();
$model = new NonFulltextModel;
$builder = new Builder($model, '검색어');
$results = $this->engine->search($builder);
@@ -317,6 +317,98 @@ class DatabaseFulltextEngineTest extends TestCase
$this->assertTrue(true);
}
/**
* sanitizeBooleanModeKeyword()가 BOOLEAN MODE 연산자를 제거하고 phrase로 변환하는지 테스트합니다.
*/
public function test_sanitize_boolean_mode_keyword_wraps_tokens_in_phrases(): void
{
$this->assertSame('"셔츠"', DatabaseFulltextEngine::sanitizeBooleanModeKeyword('셔츠'));
$this->assertSame('"shirt"', DatabaseFulltextEngine::sanitizeBooleanModeKeyword('shirt'));
// 다중 토큰 → 각각 phrase
$this->assertSame('"셔츠" "면"', DatabaseFulltextEngine::sanitizeBooleanModeKeyword('셔츠 면'));
}
/**
* sanitizeBooleanModeKeyword()가 각 BOOLEAN MODE 연산자를 제거하는지 테스트합니다.
*/
public function test_sanitize_boolean_mode_keyword_strips_operators(): void
{
// 연산자가 제거되고 남은 토큰만 phrase 로 묶임
$this->assertSame('"상품"', DatabaseFulltextEngine::sanitizeBooleanModeKeyword('+상품'));
$this->assertSame('"바지"', DatabaseFulltextEngine::sanitizeBooleanModeKeyword('-바지'));
$this->assertSame('"상품"', DatabaseFulltextEngine::sanitizeBooleanModeKeyword('상품)'));
$this->assertSame('"셔츠"', DatabaseFulltextEngine::sanitizeBooleanModeKeyword('(셔츠'));
$this->assertSame('"키워드"', DatabaseFulltextEngine::sanitizeBooleanModeKeyword('~키워드'));
$this->assertSame('"상품"', DatabaseFulltextEngine::sanitizeBooleanModeKeyword('상품*'));
$this->assertSame('"셔츠"', DatabaseFulltextEngine::sanitizeBooleanModeKeyword('"셔츠'));
$this->assertSame('"user"', DatabaseFulltextEngine::sanitizeBooleanModeKeyword('@user'));
// <script> → 연산자/태그 제거 후 'script'
$this->assertSame('"script"', DatabaseFulltextEngine::sanitizeBooleanModeKeyword('<script>'));
}
/**
* sanitizeBooleanModeKeyword()가 연산자만 입력 시 빈 문자열을 반환하는지 테스트합니다.
*/
public function test_sanitize_boolean_mode_keyword_returns_empty_for_operators_only(): void
{
$this->assertSame('', DatabaseFulltextEngine::sanitizeBooleanModeKeyword('< >'));
$this->assertSame('', DatabaseFulltextEngine::sanitizeBooleanModeKeyword('+-~*'));
$this->assertSame('', DatabaseFulltextEngine::sanitizeBooleanModeKeyword(' '));
$this->assertSame('', DatabaseFulltextEngine::sanitizeBooleanModeKeyword(''));
}
/**
* sanitizeBooleanModeKeyword()가 제어문자를 제거하는지 테스트합니다.
*/
public function test_sanitize_boolean_mode_keyword_removes_control_chars(): void
{
$this->assertSame('"셔츠"', DatabaseFulltextEngine::sanitizeBooleanModeKeyword("셔츠\x00"));
$this->assertSame('"a" "b"', DatabaseFulltextEngine::sanitizeBooleanModeKeyword("a\tb"));
}
/**
* whereFulltext()가 특수문자 입력 시 정제된 안전한 phrase를 바인딩하는지 테스트합니다.
*/
public function test_where_fulltext_binds_sanitized_keyword(): void
{
$driver = DB::getDriverName();
if (! in_array($driver, ['mysql', 'mariadb'])) {
$this->markTestSkipped('FULLTEXT 미지원 DBMS');
}
$model = $this->createSearchableModel();
$query = $model->newQuery();
DatabaseFulltextEngine::whereFulltext($query, 'name', '<script>');
$sql = $query->toSql();
$this->assertStringContainsString('MATCH(`name`) AGAINST(? IN BOOLEAN MODE)', $sql);
// 원본 특수문자가 아닌 정제된 phrase 가 바인딩
$this->assertContains('"script"', $query->getBindings());
}
/**
* whereFulltext()가 연산자만 입력 시 1=0 조건으로 빈 결과를 생성하는지 테스트합니다.
*/
public function test_where_fulltext_uses_false_condition_for_operators_only(): void
{
$driver = DB::getDriverName();
if (! in_array($driver, ['mysql', 'mariadb'])) {
$this->markTestSkipped('FULLTEXT 미지원 DBMS');
}
$model = $this->createSearchableModel();
$query = $model->newQuery();
DatabaseFulltextEngine::whereFulltext($query, 'name', '< >');
$sql = $query->toSql();
$this->assertStringContainsString('1 = 0', $sql);
$this->assertStringNotContainsString('AGAINST', $sql);
}
/**
* Searchable + FulltextSearchable 모델을 생성합니다.
*
+78
View File
@@ -0,0 +1,78 @@
<?php
namespace Tests\Unit\Seo;
use App\Seo\Concerns\LocalizesSeoValues;
use Illuminate\Support\Facades\Config;
use Tests\TestCase;
/**
* LocalizesSeoValues 트레이트 테스트 (공개#49).
*
* site_name 등 다국어 JSON array 설정값을 현재/폴백 로케일 string 으로 정규화하는
* SSoT. SeoRenderer::buildGlobalContext()의 _global.site_name(F4) 및 OG 경로가
* 공유하며, array → string 캐스팅 회귀를 차단한다.
*/
class LocalizesSeoValuesTest extends TestCase
{
private object $subject;
protected function setUp(): void
{
parent::setUp();
$this->subject = new class
{
use LocalizesSeoValues;
};
}
/**
* 문자열은 그대로 반환됩니다.
*/
public function test_string_returned_as_is(): void
{
$this->assertSame('그누보드7', $this->subject->resolveLocalizedValue('그누보드7'));
}
/**
* 다국어 array 는 현재 로케일 string 으로 추출됩니다.
*/
public function test_localized_array_extracts_current_locale(): void
{
Config::set('app.locale', 'ko');
$this->assertSame(
'한글몰',
$this->subject->resolveLocalizedValue(['ko' => '한글몰', 'en' => 'EngMall']),
);
}
/**
* 현재 로케일 키 부재 시 폴백 로케일로 추출됩니다.
*/
public function test_localized_array_falls_back(): void
{
Config::set('app.locale', 'ja');
Config::set('app.fallback_locale', 'en');
$this->assertSame(
'EngMall',
$this->subject->resolveLocalizedValue(['en' => 'EngMall']),
);
}
/**
* 정규화 결과는 항상 string 이라 Blade e()/htmlspecialchars 에서 TypeError 가 없습니다.
*/
public function test_result_is_always_string_for_safe_html_escaping(): void
{
Config::set('app.locale', 'ko');
$result = $this->subject->resolveLocalizedValue(['ko' => '한글몰', 'en' => 'EngMall']);
$this->assertIsString($result);
// htmlspecialchars 가 TypeError 없이 동작
$this->assertSame('한글몰', e($result));
}
}
@@ -0,0 +1,93 @@
<?php
namespace Tests\Unit\Seo;
use App\Seo\Contracts\SeoRendererInterface;
use App\Seo\Editor\SeoBotPreviewService;
use Illuminate\Http\Request;
use PHPUnit\Framework\TestCase;
/**
* SeoBotPreviewService 단위 테스트.
*
* 봇 미리보기는 검색엔진 탭·레이아웃·모듈/코어 SEO 설정이 **산출한 데이터만** 보여준다.
* 종전 `extractSeoMarkup`(완성 HTML 을 태그/속성 휴리스틱으로 가지치기)은 폐기 — 대신 렌더 파이프
* 라인을 `seoOnly=true` 로 호출해 SEO 산출물 전용 블레이드(seo-preview)로 조립한 HTML 을 그대로
* 돌려준다. 본 단위 테스트는 서비스가 ① seoOnly=true 로 호출하는지 ② 결과를 가공 없이 통과시키는지
* ③ null 분기를 검증한다. SEO 산출물만 담기는지는 seo-preview 블레이드 Feature 테스트가 SSoT.
*/
class SeoBotPreviewServiceTest extends TestCase
{
/** renderer mock — 호출 인자를 캡처하고 주어진 HTML 을 반환한다. */
private function recordingRenderer(?string $html): object
{
return new class($html) implements SeoRendererInterface
{
public ?bool $lastSeoOnly = null;
public int $calls = 0;
public function __construct(private readonly ?string $html) {}
public function render(Request $request): ?string
{
return $this->html;
}
public function renderFromResolved(
array $mergedLayout,
array $routeParams,
string $url,
string $locale,
string $templateIdentifier,
string $layoutName,
?string $moduleId,
?string $pluginId,
array $context,
?string $defaultLocale = null,
bool $seoOnly = false,
): ?string {
$this->calls++;
$this->lastSeoOnly = $seoOnly;
return $this->html;
}
};
}
private function render(SeoBotPreviewService $svc): ?string
{
return $svc->render([], [], '/x', 'ko', 'sirsoft-admin_basic', null, null, []);
}
public function test_seo_only_true_로_렌더_파이프라인을_호출한다(): void
{
// 봇 미리보기는 SEO 설정 산출물만 받아야 하므로 seoOnly=true 로 호출한다.
$renderer = $this->recordingRenderer('<head><title>T</title></head>');
$svc = new SeoBotPreviewService($renderer);
$this->render($svc);
$this->assertSame(1, $renderer->calls);
$this->assertTrue($renderer->lastSeoOnly, '봇 미리보기는 seoOnly=true 로 호출');
}
public function test_렌더_결과를_가공_없이_그대로_통과시킨다(): void
{
// 종전 extractSeoMarkup 후처리 폐기 — 파이프라인이 돌려준 SEO 전용 HTML 을 그대로 반환.
$html = '<head><title>봇 제목</title><meta property="og:title" content="봇"></head>';
$renderer = $this->recordingRenderer($html);
$svc = new SeoBotPreviewService($renderer);
$this->assertSame($html, $this->render($svc));
}
public function test_seo_비활성_render_null_은_null_로_전달된다(): void
{
// seoOnly 경로에서도 meta.seo.enabled=false → renderFromResolved 가 null → null 통과.
$renderer = $this->recordingRenderer(null);
$svc = new SeoBotPreviewService($renderer);
$this->assertNull($this->render($svc));
}
}
+140
View File
@@ -0,0 +1,140 @@
<?php
namespace Tests\Unit\Seo;
use App\Seo\Editor\SeoCandidateService;
use ReflectionMethod;
use Tests\TestCase;
/**
* SeoCandidateService — 확장 후보 라벨 해석 단위.
*
* extensions 후보의 친화 라벨(localizeName)은 확장 getName()(string|array 다국어)을 로케일로
* 해석한다. Endpoint 테스트는 RefreshDatabase 환경에서 활성 확장이 0건이라 폴백 경로를 직접
* 보증하기 어려우므로(빈 배열 허용), 라벨 해석 규칙은 본 단위 테스트가 SSoT.
*/
class SeoCandidateServiceTest extends TestCase
{
private SeoCandidateService $service;
private ReflectionMethod $localize;
protected function setUp(): void
{
parent::setUp();
$this->service = app(SeoCandidateService::class);
$this->localize = new ReflectionMethod(SeoCandidateService::class, 'localizeName');
$this->localize->setAccessible(true);
}
private function localize(mixed $name, string $locale, string $fallbackId): string
{
return $this->localize->invoke($this->service, $name, $locale, $fallbackId);
}
public function test_string_name_returned_as_is(): void
{
$this->assertSame('이커머스', $this->localize('이커머스', 'ko', 'sirsoft-ecommerce'));
}
public function test_array_name_resolves_requested_locale(): void
{
$name = ['ko' => '이커머스', 'en' => 'Ecommerce'];
$this->assertSame('이커머스', $this->localize($name, 'ko', 'sirsoft-ecommerce'));
$this->assertSame('Ecommerce', $this->localize($name, 'en', 'sirsoft-ecommerce'));
}
public function test_array_name_falls_back_to_app_locale_then_first_value(): void
{
config(['app.locale' => 'en']);
// 요청 로케일(ja) 부재 → app.locale(en) 폴백.
$name = ['ko' => '이커머스', 'en' => 'Ecommerce'];
$this->assertSame('Ecommerce', $this->localize($name, 'ja', 'sirsoft-ecommerce'));
// 요청·app.locale 둘 다 부재 → 첫 값 폴백.
config(['app.locale' => 'fr']);
$this->assertSame('이커머스', $this->localize($name, 'ja', 'sirsoft-ecommerce'));
}
public function test_empty_or_invalid_name_falls_back_to_identifier(): void
{
$this->assertSame('sirsoft-ecommerce', $this->localize('', 'ko', 'sirsoft-ecommerce'));
$this->assertSame('sirsoft-ecommerce', $this->localize([], 'ko', 'sirsoft-ecommerce'));
$this->assertSame('sirsoft-ecommerce', $this->localize(null, 'ko', 'sirsoft-ecommerce'));
// 비문자열 값만 든 배열 → 폴백.
$this->assertSame('sirsoft-ecommerce', $this->localize(['ko' => 123], 'ko', 'sirsoft-ecommerce'));
}
/**
* collectVars 를 stub 확장으로 직접 호출(reflection). 게이팅 SSoT 검증 —
* 선언 확장(declaredExtensions)에 있는 확장의 seoVariables()[_common]+[pageType] 만 수집.
*
* @param array $activeExtensions [{type,id,instance}]
* @param array $declaredExtensions [{type,id}]
*/
private function collectVars(array $activeExtensions, array $declaredExtensions, ?string $pageType): array
{
$m = new ReflectionMethod(SeoCandidateService::class, 'collectVars');
$m->setAccessible(true);
return $m->invoke($this->service, $activeExtensions, $declaredExtensions, $pageType);
}
private function stubExtensionWithVars(): object
{
// seoVariables() 가 _common + product 그룹을 반환하는 stub 확장.
return new class
{
public function seoVariables(): array
{
return [
'_common' => ['commerce_name' => ['source' => 'setting', 'description' => '상점명']],
'product' => [
'product_name' => ['source' => 'data', 'required' => true, 'description' => '상품명'],
'product_description' => ['source' => 'data', 'description' => '상품 설명'],
],
];
}
};
}
public function test_collect_vars_gated_by_declared_extensions(): void
{
$active = [['type' => 'module', 'id' => 'sirsoft-ecommerce', 'instance' => $this->stubExtensionWithVars()]];
// 선언 확장에 ecommerce 가 있으면 _common + product 그룹 vars 수집.
$declared = [['type' => 'module', 'id' => 'sirsoft-ecommerce']];
$vars = $this->collectVars($active, $declared, 'product');
$names = array_column($vars, 'name');
$this->assertContains('commerce_name', $names, '_common vars 수집');
$this->assertContains('product_name', $names, 'pageType(product) vars 수집');
$this->assertContains('product_description', $names);
// source/required 메타 보존.
$byName = [];
foreach ($vars as $v) {
$byName[$v['name']] = $v;
}
$this->assertSame('setting', $byName['commerce_name']['source']);
$this->assertSame('data', $byName['product_name']['source']);
$this->assertTrue($byName['product_name']['required'] ?? false);
}
public function test_collect_vars_empty_when_extension_not_declared(): void
{
// 같은 active 확장이라도 declaredExtensions 에 없으면 게이팅으로 0건(프론트가 extensions 미전송 시 재현).
$active = [['type' => 'module', 'id' => 'sirsoft-ecommerce', 'instance' => $this->stubExtensionWithVars()]];
$vars = $this->collectVars($active, [], 'product');
$this->assertSame([], $vars, '선언 확장 0 → vars 게이팅 전량 제외');
}
public function test_collect_vars_common_only_when_page_type_null(): void
{
$active = [['type' => 'module', 'id' => 'sirsoft-ecommerce', 'instance' => $this->stubExtensionWithVars()]];
$declared = [['type' => 'module', 'id' => 'sirsoft-ecommerce']];
$vars = $this->collectVars($active, $declared, null);
$names = array_column($vars, 'name');
$this->assertContains('commerce_name', $names, 'page_type 미선택 → _common 만');
$this->assertNotContains('product_name', $names);
}
}
@@ -0,0 +1,295 @@
<?php
namespace Tests\Unit\Seo;
use App\Contracts\Extension\ModuleManagerInterface;
use App\Contracts\Extension\PluginManagerInterface;
use App\Seo\ComponentHtmlMapper;
use App\Seo\DataSourceResolver;
use App\Seo\ExpressionEvaluator;
use App\Seo\PipeRegistry;
use App\Seo\SeoConfigMerger;
use App\Seo\SeoMetaResolver;
use App\Seo\SeoRenderer;
use App\Seo\TemplateRouteResolver;
use App\Services\LayoutService;
use App\Services\PluginSettingsService;
use App\Services\SettingsService;
use App\Services\TemplateService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use Mockery;
use Mockery\MockInterface;
use Tests\TestCase;
/**
* SeoRenderer::renderFromResolved 추출 회귀 가드.
*
* render(Request) 는 URL 매핑·data_sources fetch·_global/_local/computed 해석까지 마친 뒤
* 공통 파이프라인(renderFromResolved)에 위임하는 얇은 래퍼다. 본 테스트는 그 추출 계약을
* 잠근다 — ① render() 가 해석한 컨텍스트로 renderFromResolved 를 호출, ② renderFromResolved
* 가 이미 해석된 컨텍스트로 동일 HTML 을 생성, ③ enabled 게이트 일관(편집기 봇 미리보기가
* 직접 호출해도 enabled=false → null), ④ defaultLocale 파라미터 폴백. render() 운영 경로의
* byte 동등성은 SeoRendererTest(70+) + SEO 전체 스위트가 별도로 잠근다.
*/
class SeoRendererRenderFromResolvedTest extends TestCase
{
private TemplateRouteResolver|MockInterface $routeResolver;
private LayoutService|MockInterface $layoutService;
private DataSourceResolver|MockInterface $dataSourceResolver;
private SeoMetaResolver|MockInterface $metaResolver;
private ComponentHtmlMapper|MockInterface $htmlMapper;
private ExpressionEvaluator|MockInterface $evaluator;
private SeoConfigMerger|MockInterface $seoConfigMerger;
private SeoRenderer $renderer;
protected function setUp(): void
{
parent::setUp();
$this->routeResolver = Mockery::mock(TemplateRouteResolver::class);
$this->layoutService = Mockery::mock(LayoutService::class);
$this->dataSourceResolver = Mockery::mock(DataSourceResolver::class);
$this->metaResolver = Mockery::mock(SeoMetaResolver::class);
$this->htmlMapper = Mockery::mock(ComponentHtmlMapper::class);
$this->evaluator = Mockery::mock(ExpressionEvaluator::class);
$this->seoConfigMerger = Mockery::mock(SeoConfigMerger::class);
$settingsService = Mockery::mock(SettingsService::class);
$settingsService->shouldReceive('getFrontendSettings')->andReturn([])->byDefault();
$pluginSettingsService = Mockery::mock(PluginSettingsService::class);
$pluginSettingsService->shouldReceive('getAllActiveSettings')->andReturn([])->byDefault();
$templateService = Mockery::mock(TemplateService::class);
$templateService->shouldReceive('getLanguageDataWithModules')
->andReturn(['success' => true, 'data' => [], 'error' => null])->byDefault();
$moduleManager = Mockery::mock(ModuleManagerInterface::class);
$pluginManager = Mockery::mock(PluginManagerInterface::class);
// 공통 파이프라인이 건드리는 의존성 mock
$this->seoConfigMerger->shouldReceive('getMergedConfig')->andReturn([])->byDefault();
$pipeRegistry = Mockery::mock(PipeRegistry::class);
$pipeRegistry->shouldReceive('setLocale')->byDefault();
$this->evaluator->shouldReceive('setTranslations')->byDefault();
$this->evaluator->shouldReceive('getPipeRegistry')->andReturn($pipeRegistry)->byDefault();
$this->evaluator->shouldReceive('setSeoOverrides')->byDefault();
foreach (['setComponentMap', 'setRenderModes', 'setSelfClosing', 'setTextProps', 'setAttrMap', 'setAllowedAttrs', 'setGlobalResolver', 'setSeoVars'] as $m) {
$this->htmlMapper->shouldReceive($m)->byDefault();
}
$this->metaResolver->shouldReceive('resolveLocalizedValue')
->andReturnUsing(fn ($v) => is_string($v) ? $v : (string) ($v ?? ''))->byDefault();
$this->renderer = new SeoRenderer(
$this->routeResolver,
$this->layoutService,
$templateService,
$this->dataSourceResolver,
$this->metaResolver,
$this->htmlMapper,
$this->evaluator,
$this->seoConfigMerger,
$settingsService,
$pluginSettingsService,
$moduleManager,
$pluginManager,
);
}
protected function tearDown(): void
{
Mockery::close();
parent::tearDown();
}
/** 최소 meta 결과 — SeoMetaResolver::resolve 흉내 */
private function metaResult(string $title): array
{
return [
'title' => $title,
'titleSuffix' => '',
'description' => '',
'keywords' => '',
'og' => [],
'twitter' => [],
'structured_data' => null,
'ogTags' => '',
'twitterTags' => '',
'jsonLd' => '',
'googleAnalyticsId' => '',
'googleVerification' => '',
'naverVerification' => '',
];
}
private function enabledLayout(): array
{
return [
'meta' => ['seo' => ['enabled' => true]],
'components' => [['component' => 'Div', 'props' => ['text' => '본문']]],
];
}
/**
* renderFromResolved 는 이미 해석된 컨텍스트로 완성 HTML 을 생성한다(편집기 봇 미리보기 경로).
*/
public function test_render_from_resolved_produces_html_from_seed_context(): void
{
$this->metaResolver->shouldReceive('resolve')->once()->andReturn($this->metaResult('봇 제목'));
$this->htmlMapper->shouldReceive('render')->once()->andReturn('<div>본문</div>');
$expected = '<!DOCTYPE html><html lang="ko"><head><title>봇 제목</title></head><body><div>본문</div></body></html>';
$viewMock = Mockery::mock(\Illuminate\View\View::class);
$viewMock->shouldReceive('render')->once()->andReturn($expected);
View::shouldReceive('make')
->with('seo', Mockery::on(fn ($d) => $d['title'] === '봇 제목' && $d['bodyHtml'] === '<div>본문</div>'))
->once()
->andReturn($viewMock);
$result = $this->renderer->renderFromResolved(
$this->enabledLayout(),
['id' => '1'],
'/preview/test',
'ko',
'sirsoft-basic',
'preview/test',
null,
null,
['route' => ['path' => '/preview/test'], 'query' => [], '_global' => [], '_local' => []],
null,
);
$this->assertSame($expected, $result);
}
/**
* enabled=false 면 renderFromResolved 도 render() 단계3 게이트와 동일하게 null 을 반환한다.
* (편집기 봇 미리보기가 render() 를 거치지 않고 직접 호출해도 "검색엔진 미노출"과 일치.)
*/
public function test_render_from_resolved_returns_null_when_disabled(): void
{
// resolve/render/View 는 호출되면 안 됨 — enabled 게이트에서 조기 반환.
$this->metaResolver->shouldReceive('resolve')->never();
$this->htmlMapper->shouldReceive('render')->never();
$result = $this->renderer->renderFromResolved(
['meta' => ['seo' => ['enabled' => false]], 'components' => []],
[],
'/preview/test',
'ko',
'sirsoft-basic',
'preview/test',
null,
null,
['route' => [], 'query' => [], '_global' => [], '_local' => []],
null,
);
$this->assertNull($result);
}
/**
* meta.seo 자체가 없으면 null (render() 단계3 `! $seoConfig` 와 동일).
*/
public function test_render_from_resolved_returns_null_when_no_seo_config(): void
{
$this->metaResolver->shouldReceive('resolve')->never();
$result = $this->renderer->renderFromResolved(
['meta' => [], 'components' => []],
[],
'/x',
'ko',
'sirsoft-basic',
'x',
null,
null,
[],
null,
);
$this->assertNull($result);
}
/**
* defaultLocale=null 이면 config('app.locale') 폴백으로 canonical 을 구성한다(render() 가
* seo_default_locale request attribute 에서 추출해 넘기는 값의 폴백).
*/
public function test_render_from_resolved_default_locale_falls_back_to_config(): void
{
config()->set('app.locale', 'ko');
$this->metaResolver->shouldReceive('resolve')->once()->andReturn($this->metaResult('제목'));
$this->htmlMapper->shouldReceive('render')->once()->andReturn('');
// locale=ko == defaultLocale(config ko) → canonical 에 ?locale= 없음.
View::shouldReceive('make')
->with('seo', Mockery::on(fn ($d) => ! str_contains($d['canonicalUrl'], '?locale=')))
->once()
->andReturn(tap(Mockery::mock(\Illuminate\View\View::class), fn ($m) => $m->shouldReceive('render')->andReturn('ok')));
$result = $this->renderer->renderFromResolved(
$this->enabledLayout(),
[],
'/page',
'ko',
'sirsoft-basic',
'page',
null,
null,
['route' => [], 'query' => [], '_global' => [], '_local' => []],
null,
);
$this->assertSame('ok', $result);
}
/**
* render(Request) 는 컨텍스트 해석 후 같은 입력에 대해 renderFromResolved 와 동일한 최종
* HTML 을 만든다 — 추출 위임 동등성(부분 목으로 renderFromResolved 호출을 검증).
*/
public function test_render_delegates_to_render_from_resolved_with_resolved_context(): void
{
$request = Request::create('/products/9');
$request->attributes->set('seo_default_locale', 'ko');
$this->routeResolver->shouldReceive('resolve')->with('/products/9')->once()->andReturn([
'templateIdentifier' => 'sirsoft-basic',
'layoutName' => 'shop/show',
'routeParams' => ['id' => '9'],
'moduleIdentifier' => null,
'pluginIdentifier' => null,
]);
$this->layoutService->shouldReceive('getLayout')->with('sirsoft-basic', 'shop/show')->once()
->andReturn($this->enabledLayout());
// render() 본문이 renderFromResolved 에 위임 → 부분 목으로 인자 검증.
$partial = Mockery::mock(SeoRenderer::class, [
$this->routeResolver, $this->layoutService, Mockery::mock(TemplateService::class),
$this->dataSourceResolver, $this->metaResolver, $this->htmlMapper, $this->evaluator,
$this->seoConfigMerger, Mockery::mock(SettingsService::class), Mockery::mock(PluginSettingsService::class),
Mockery::mock(ModuleManagerInterface::class), Mockery::mock(PluginManagerInterface::class),
])->makePartial();
$partial->shouldReceive('renderFromResolved')
->once()
->withArgs(function ($layout, $routeParams, $url, $locale, $tpl, $layoutName, $mod, $plug, $ctx, $default) {
return $url === '/products/9'
&& $routeParams === ['id' => '9']
&& $tpl === 'sirsoft-basic'
&& $layoutName === 'shop/show'
&& $default === 'ko'
&& ($ctx['route']['path'] ?? null) === '/products/9';
})
->andReturn('<delegated/>');
$result = $partial->render($request);
$this->assertSame('<delegated/>', $result);
}
}
@@ -497,4 +497,110 @@ class TemplateRouteResolverTest extends TestCase
$this->assertNull($result['moduleIdentifier']);
$this->assertNull($result['pluginIdentifier']);
}
// ========================================================================
// routeExists() — 미등록 경로 404 판별 (공개#47)
// ========================================================================
/**
* 지정한 템플릿 타입으로 routes 를 반환하는 resolver 를 생성합니다.
*
* @param string $type 템플릿 타입 ('user' | 'admin')
* @param array|null $activeTemplate 활성 템플릿 (null 이면 미설치)
* @param array $routes 라우트 배열
* @param bool $routesSuccess 라우트 조회 성공 여부
* @return TemplateRouteResolver 설정된 resolver
*/
private function createResolverForType(string $type, ?array $activeTemplate, array $routes = [], bool $routesSuccess = true): TemplateRouteResolver
{
/** @var TemplateManagerInterface|MockInterface $templateManager */
$templateManager = Mockery::mock(TemplateManagerInterface::class);
$templateManager->shouldReceive('getActiveTemplate')->with($type)->andReturn($activeTemplate);
/** @var TemplateService|MockInterface $templateService */
$templateService = Mockery::mock(TemplateService::class);
$templateService->shouldReceive('getRoutesDataWithModules')->withAnyArgs()->andReturn([
'success' => $routesSuccess,
'data' => ['routes' => $routes],
]);
$moduleManager = Mockery::mock(ModuleManagerInterface::class);
$moduleManager->shouldReceive('getModule')->andReturn(null);
$pluginManager = Mockery::mock(PluginManagerInterface::class);
$pluginManager->shouldReceive('getPlugin')->andReturn(null);
return new TemplateRouteResolver($templateService, $templateManager, $moduleManager, $pluginManager);
}
/**
* 등록된 정적/동적/auth_required/guest_only 라우트는 모두 routeExists=true 입니다.
*/
public function test_route_exists_true_for_registered_routes(): void
{
$routes = array_merge($this->getDefaultRoutes(), [
['path' => '/mypage', 'layout' => 'mypage/index', 'auth_required' => true, 'guest_only' => false, 'meta' => []],
['path' => '/login', 'layout' => 'auth/login', 'auth_required' => false, 'guest_only' => true, 'meta' => []],
]);
$resolver = $this->createResolver(['identifier' => 'sirsoft-user_basic'], $routes);
$this->assertTrue($resolver->routeExists('/', 'user'), '정적 라우트');
$this->assertTrue($resolver->routeExists('/about', 'user'), '정적 라우트 about');
$this->assertTrue($resolver->routeExists('/shop/products/123', 'user'), '동적 라우트');
$this->assertTrue($resolver->routeExists('/mypage', 'user'), 'auth_required 도 존재로 인정 — 회귀 방지 핵심');
$this->assertTrue($resolver->routeExists('/login', 'user'), 'guest_only 도 존재로 인정');
}
/**
* 미등록 경로 / 초과 세그먼트는 routeExists=false 입니다.
*/
public function test_route_exists_false_for_unregistered_routes(): void
{
$resolver = $this->createResolver(['identifier' => 'sirsoft-user_basic'], $this->getDefaultRoutes());
$this->assertFalse($resolver->routeExists('/this/does/not/exist', 'user'));
$this->assertFalse($resolver->routeExists('/shop/products/123/extra', 'user'), '초과 세그먼트는 ^...$ 전체 매칭 실패');
}
/**
* resolve()는 auth 라우트에서 null 이지만 routeExists()는 true — 차이 명시 검증.
*/
public function test_route_exists_differs_from_resolve_for_auth_routes(): void
{
$routes = [
['path' => '/mypage', 'layout' => 'mypage/index', 'auth_required' => true, 'guest_only' => false, 'meta' => []],
];
$resolver = $this->createResolver(['identifier' => 'sirsoft-user_basic'], $routes);
$this->assertNull($resolver->resolve('/mypage'), 'resolve()는 auth_required 를 SEO 비대상으로 스킵');
$this->assertTrue($resolver->routeExists('/mypage', 'user'), 'routeExists()는 존재로 인정');
}
/**
* 활성 템플릿 미설치 / routes 로드 실패 시 routeExists=true (404 억제, 안전측 폴백).
*/
public function test_route_exists_true_fallback_when_template_missing(): void
{
$noTemplate = $this->createResolverForType('user', null);
$this->assertTrue($noTemplate->routeExists('/anything', 'user'), '템플릿 미설치 시 404 억제');
$loadFailure = $this->createResolverForType('user', ['identifier' => 'sirsoft-user_basic'], [], routesSuccess: false);
$this->assertTrue($loadFailure->routeExists('/anything', 'user'), 'routes 로드 실패 시 404 억제');
}
/**
* admin 타입 라우트도 routeExists 로 판별됩니다 (admin 와일드카드 prefix → /admin/... 정규화).
*/
public function test_route_exists_for_admin_type(): void
{
$routes = [
['path' => '*/admin/users', 'layout' => 'admin_user_list', 'auth_required' => true, 'guest_only' => false, 'meta' => []],
];
$resolver = $this->createResolverForType('admin', ['identifier' => 'sirsoft-admin_basic'], $routes);
$this->assertTrue($resolver->routeExists('/admin/users', 'admin'), '*/admin/users → /admin/users 정규화 매칭');
$this->assertFalse($resolver->routeExists('/admin/nonexistent', 'admin'));
}
}
+156 -6
View File
@@ -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'));
}
}
+228 -3
View File
@@ -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();
+152 -2
View File
@@ -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), '병합본 − 자기선언분 = 부모 상속 키');
}
}
+121 -1
View File
@@ -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']);
}
}
@@ -0,0 +1,108 @@
<?php
namespace Tests\Unit\Support;
use App\Support\TemplateExternals;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class TemplateExternalsTest extends TestCase
{
use RefreshDatabase;
public function test_normalizes_supported_externals_and_attributes(): void
{
$externals = TemplateExternals::normalize([
[
'id' => 'style-main',
'type' => 'style',
'url' => 'https://cdn.example.com/main.css',
'preconnect' => 'https://cdn.example.com',
'crossorigin' => true,
'integrity' => 'sha384-style',
'referrerpolicy' => 'no-referrer',
'media' => 'screen',
],
[
'id' => 'script-default',
'type' => 'script',
'url' => 'https://cdn.example.com/default.js',
'defer' => true,
],
[
'id' => 'preload-font',
'type' => 'preload',
'url' => 'https://cdn.example.com/font.woff2',
'as' => 'font',
'mimeType' => 'font/woff2',
'fetchpriority' => 'high',
'crossorigin' => 'use-credentials',
],
]);
$this->assertCount(3, $externals);
$this->assertSame('anonymous', $externals[0]['crossorigin']);
$this->assertSame('before-template', $externals[1]['position']);
$this->assertTrue($externals[1]['defer']);
$this->assertSame('font/woff2', $externals[2]['mimeType']);
$this->assertSame('high', $externals[2]['fetchpriority']);
$styleAttributes = TemplateExternals::linkAttributes($externals[0]);
$this->assertSame('stylesheet', $styleAttributes['rel']);
$this->assertSame('https://cdn.example.com/main.css', $styleAttributes['href']);
$this->assertSame('style-main', $styleAttributes['id']);
$this->assertSame('screen', $styleAttributes['media']);
$scriptAttributes = TemplateExternals::scriptAttributes($externals[1]);
$this->assertSame('https://cdn.example.com/default.js', $scriptAttributes['src']);
$this->assertTrue($scriptAttributes['defer']);
}
public function test_filters_invalid_and_legacy_external_declarations(): void
{
$externals = TemplateExternals::normalize([
['url' => 'https://legacy.example.com/style.css'],
['type' => 'style', 'url' => 'http://cdn.example.com/insecure.css'],
['type' => 'preload', 'url' => 'https://cdn.example.com/missing-as.woff2'],
['type' => 'script', 'url' => 'https://cdn.example.com/both.js', 'async' => true, 'defer' => true],
['type' => 'script', 'url' => 'https://cdn.example.com/invalid-position.js', 'position' => 'after-core'],
['type' => 'style', 'url' => 'https://cdn.example.com/valid.css'],
['type' => 'style', 'url' => 'https://cdn.example.com/valid.css'],
]);
$this->assertSame([
[
'type' => 'style',
'url' => 'https://cdn.example.com/valid.css',
],
], $externals);
}
public function test_resource_hints_are_deduplicated_by_type_and_origin(): void
{
$externals = TemplateExternals::normalize([
[
'type' => 'preconnect',
'url' => 'https://cdn.example.com',
'crossorigin' => 'anonymous',
],
[
'type' => 'webfont',
'url' => 'https://cdn.example.com/font.css',
'preconnect' => 'https://cdn.example.com',
'crossorigin' => true,
],
[
'type' => 'dns-prefetch',
'url' => 'https://static.example.com',
],
]);
$hints = TemplateExternals::resourceHints($externals);
$this->assertCount(2, $hints);
$this->assertSame('preconnect', $hints[0]['type']);
$this->assertSame('https://cdn.example.com', $hints[0]['url']);
$this->assertSame('dns-prefetch', $hints[1]['type']);
}
}