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

@@ -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('테스트 로그');
}
}