v7.0.0-beta.5 release

This commit is contained in:
HeuJung committed 2026-05-12 17:58:34 +09:00
1 parent 1db039ff34
commit eb467aca79
159 files changed
+7599 -218

No files matched your search

@@ -0,0 +1,158 @@
<?php
namespace Tests\Unit\Extension;
use App\Extension\AbstractUpgradeStep;
use App\Extension\Upgrade\DataMigration;
use App\Extension\UpgradeContext;
use Illuminate\Support\Facades\File;
use Tests\TestCase;
/**
* AbstractUpgradeStep 의 데이터 스냅샷 위임 흐름 검증.
*
* 본 테스트는 fixture 디렉토리에 manifest/appliers/migrations 를 임시 작성하여
* 실제 DB 변경 없이 위임 순서 / Migration 파일명 prefix 제거 / dataDir 계산을 검증한다.
*/
class AbstractUpgradeStepTest extends TestCase
{
private string $tempStepDir;
protected function setUp(): void
{
parent::setUp();
$this->tempStepDir = storage_path('framework/testing/abstract-upgrade-'.uniqid());
File::ensureDirectoryExists($this->tempStepDir);
}
protected function tearDown(): void
{
if (File::isDirectory($this->tempStepDir)) {
File::deleteDirectory($this->tempStepDir);
}
parent::tearDown();
}
public function test_run_executes_migrations_in_filename_sorted_order(): void
{
$version = '0.0.10-test.order';
$token = 'V'.str_replace(['.', '-'], '_', $version);
$dataDir = $this->tempStepDir.'/data/'.$version;
File::ensureDirectoryExists($dataDir.'/migrations');
// 일부러 알파벳 역순으로 prefix 부여하여 파일명 정렬이 실제 실행 순서를 결정함을 검증
$this->writeMigrationFixture($dataDir.'/migrations/02_SecondStep.php', $token, 'SecondStep');
$this->writeMigrationFixture($dataDir.'/migrations/01_FirstStep.php', $token, 'FirstStep');
$this->writeMigrationFixture($dataDir.'/migrations/03_ThirdStep.php', $token, 'ThirdStep');
$step = $this->makeAnonymousStep($this->tempStepDir);
$context = new UpgradeContext(
fromVersion: '0.0.9',
toVersion: $version,
currentStep: $version,
);
$captured = $this->captureMigrationCalls();
$step->run($context);
$this->assertSame(
['FirstStep', 'SecondStep', 'ThirdStep'],
$captured(),
'migrations 는 파일명 정렬 순서로 실행되어야 한다 (01 → 02 → 03)',
);
}
public function test_dataMigrations_strips_numeric_prefix_when_resolving_class_name(): void
{
$version = '0.0.11-test.prefix';
$token = 'V'.str_replace(['.', '-'], '_', $version);
$dataDir = $this->tempStepDir.'/data/'.$version;
File::ensureDirectoryExists($dataDir.'/migrations');
// 파일명: 01_PrefixStripped.php, 클래스명: PrefixStripped (prefix 없음)
$this->writeMigrationFixture($dataDir.'/migrations/01_PrefixStripped.php', $token, 'PrefixStripped');
$step = $this->makeAnonymousStep($this->tempStepDir);
$context = new UpgradeContext(
fromVersion: '0.0.10',
toVersion: $version,
currentStep: $version,
);
$captured = $this->captureMigrationCalls();
$step->run($context);
$this->assertSame(['PrefixStripped'], $captured());
}
public function test_run_skips_when_data_dir_absent(): void
{
$version = '0.0.12-test.empty';
$step = $this->makeAnonymousStep($this->tempStepDir);
$context = new UpgradeContext(
fromVersion: '0.0.11',
toVersion: $version,
currentStep: $version,
);
// data/{version}/ 디렉토리 부재 — 예외 없이 silent return 되어야 한다
$step->run($context);
$this->assertTrue(true);
}
/**
* @param string $token 버전 namespace token (예: V0_0_10_test_order)
*/
private function writeMigrationFixture(string $filePath, string $token, string $className): void
{
$contents = <<<PHP
<?php
namespace App\Upgrades\Data\\{$token}\Migrations;
use App\Extension\Upgrade\DataMigration;
use App\Extension\UpgradeContext;
class {$className} implements DataMigration
{
public function name(): string { return '{$className}'; }
public function run(UpgradeContext \$context): void
{
\$GLOBALS['__abstract_upgrade_step_test_calls'][] = '{$className}';
}
}
PHP;
File::put($filePath, $contents);
}
private function makeAnonymousStep(string $stepDir): AbstractUpgradeStep
{
// 임시 step 파일을 실제 디렉토리에 작성하여 ReflectionClass::getFileName() 이
// 본 디렉토리를 가리키도록 한다. 클래스명은 테스트 케이스별 고유 — 재선언 회피.
$unique = 'AnonymousStep_'.bin2hex(random_bytes(8));
$stepFile = $stepDir.'/'.$unique.'.php';
$contents = <<<PHP
<?php
namespace App\Upgrades\Data\TestFixtures;
use App\Extension\AbstractUpgradeStep;
class {$unique} extends AbstractUpgradeStep
{
}
PHP;
File::put($stepFile, $contents);
require_once $stepFile;
$fqcn = 'App\\Upgrades\\Data\\TestFixtures\\'.$unique;
return new $fqcn;
}
private function captureMigrationCalls(): \Closure
{
$GLOBALS['__abstract_upgrade_step_test_calls'] = [];
return fn () => $GLOBALS['__abstract_upgrade_step_test_calls'] ?? [];
}
}
@@ -16,7 +16,7 @@ use Tests\TestCase;
/**
* Phase C.1 (v6) 회귀 방지: helper `cleanupStale*` 가 user_overrides **무관** 으로 삭제하는지.
*
* PO 요구사항 재정의 (v6):
* 요구사항 재정의 (v6):
* - config/확장 정의에 없는 row 는 user_overrides 유무 무관 삭제
* - 필드 단위 보존은 upsert 시점(`syncMenu`/`syncRole`) 에서만 작동
* - 예외: Role 에 `user_roles` 피벗 참조 사용자 있으면 삭제 차단 (안전 가드)
@@ -0,0 +1,213 @@
<?php
namespace Tests\Unit\Extension\Helpers;
use App\Contracts\Extension\UpgradeStepInterface;
use App\Extension\AbstractUpgradeStep;
use App\Extension\Helpers\ExtensionUpgradeGuardHelper;
use App\Extension\UpgradeContext;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* ExtensionUpgradeGuardHelper 단위 테스트.
*
* 검증 대상:
* - resolveSinceVersion: g7_version 제약 → 의무 시작 버전 분기
* - assertAbstractInheritance: stepVersion + sinceVersion + step 상속 조합 전수
*/
class ExtensionUpgradeGuardHelperTest extends TestCase
{
// ── resolveSinceVersion ─────────────────────────────────────────────
#[Test]
public function resolveSinceVersion_g7_version_제약이_null이면_null을_반환합니다(): void
{
$this->assertNull(ExtensionUpgradeGuardHelper::resolveSinceVersion(null, '1.0.0'));
}
#[Test]
public function resolveSinceVersion_g7_version_제약이_빈_문자열이면_null을_반환합니다(): void
{
$this->assertNull(ExtensionUpgradeGuardHelper::resolveSinceVersion('', '1.0.0'));
$this->assertNull(ExtensionUpgradeGuardHelper::resolveSinceVersion(' ', '1.0.0'));
}
#[Test]
public function resolveSinceVersion_제약_최소가_beta5_미만이면_null(): void
{
$cases = [
'>=7.0.0-beta.4',
'>=7.0.0-beta.1',
'^7.0.0-beta.4',
'~7.0.0-beta.4',
'7.0.0-alpha.1',
'>=6.0.0',
];
foreach ($cases as $constraint) {
$this->assertNull(
ExtensionUpgradeGuardHelper::resolveSinceVersion($constraint, '1.2.3'),
"constraint={$constraint} 는 legacy 로 판정되어야 함 (가드 미발동)"
);
}
}
#[Test]
public function resolveSinceVersion_제약_최소가_beta5_이상이면_working_version_반환(): void
{
$cases = [
'>=7.0.0-beta.5' => '1.0.0-beta.5',
'>=7.0.0' => '2.5.0',
'^7.0.0' => '0.1.0',
'~7.0.0-beta.5' => '3.0.0-rc.1',
'7.0.0-beta.5' => '1.0.0',
'=7.0.0-beta.5' => '1.0.0',
];
foreach ($cases as $constraint => $workingVersion) {
$this->assertSame(
$workingVersion,
ExtensionUpgradeGuardHelper::resolveSinceVersion($constraint, $workingVersion),
"constraint={$constraint} 는 working version={$workingVersion} 반환해야 함"
);
}
}
#[Test]
public function resolveSinceVersion_OR_제약은_첫_후보_기준으로_판정(): void
{
$this->assertSame(
'1.0.0',
ExtensionUpgradeGuardHelper::resolveSinceVersion('>=7.0.0-beta.5|>=8.0.0', '1.0.0'),
'OR 의 첫 후보가 beta.5 이상이면 가드 발동',
);
$this->assertNull(
ExtensionUpgradeGuardHelper::resolveSinceVersion('>=7.0.0-beta.4|>=7.0.0-beta.5', '1.0.0'),
'OR 의 첫 후보가 beta.5 미만이면 legacy 로 판정',
);
}
#[Test]
public function resolveSinceVersion_파싱_실패는_보수적으로_null(): void
{
$cases = [
'not-a-version',
'beta',
'>=',
'v1',
];
foreach ($cases as $constraint) {
$this->assertNull(
ExtensionUpgradeGuardHelper::resolveSinceVersion($constraint, '1.0.0'),
"constraint={$constraint} 는 파싱 실패 → 가드 미발동",
);
}
}
// ── assertAbstractInheritance ───────────────────────────────────────
#[Test]
public function assertAbstractInheritance_stepVersion이_sinceVersion보다_낮으면_상속_없어도_통과(): void
{
$step = $this->createLegacyStep();
ExtensionUpgradeGuardHelper::assertAbstractInheritance(
stepVersion: '1.0.0',
sinceVersion: '1.2.0',
step: $step,
extensionType: 'module',
extensionIdentifier: 'vendor-foo',
);
$this->assertTrue(true, '예외 미발생');
}
#[Test]
public function assertAbstractInheritance_stepVersion이_sinceVersion_이상이고_상속_OK면_통과(): void
{
$step = $this->createAbstractStep();
ExtensionUpgradeGuardHelper::assertAbstractInheritance(
stepVersion: '1.2.0',
sinceVersion: '1.2.0',
step: $step,
extensionType: 'module',
extensionIdentifier: 'vendor-foo',
);
$this->assertTrue(true, '예외 미발생');
}
#[Test]
public function assertAbstractInheritance_stepVersion이_sinceVersion_이상이고_상속_없으면_throw(): void
{
$step = $this->createLegacyStep();
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessageMatches('/must extend App\\\\Extension\\\\AbstractUpgradeStep/');
$this->expectExceptionMessageMatches('/vendor-foo/');
ExtensionUpgradeGuardHelper::assertAbstractInheritance(
stepVersion: '1.2.0',
sinceVersion: '1.2.0',
step: $step,
extensionType: 'module',
extensionIdentifier: 'vendor-foo',
);
}
#[Test]
public function assertAbstractInheritance_stepVersion이_sinceVersion보다_높고_상속_없으면_throw(): void
{
$step = $this->createLegacyStep();
$this->expectException(\RuntimeException::class);
ExtensionUpgradeGuardHelper::assertAbstractInheritance(
stepVersion: '2.0.0',
sinceVersion: '1.2.0',
step: $step,
extensionType: 'plugin',
extensionIdentifier: 'vendor-bar',
);
}
#[Test]
public function assertAbstractInheritance_예외_메시지에_확장_타입과_식별자_그리고_step_버전_포함(): void
{
$step = $this->createLegacyStep();
try {
ExtensionUpgradeGuardHelper::assertAbstractInheritance(
stepVersion: '3.1.4',
sinceVersion: '1.0.0',
step: $step,
extensionType: 'plugin',
extensionIdentifier: 'sirsoft-payment',
);
$this->fail('Expected RuntimeException');
} catch (\RuntimeException $e) {
$this->assertStringContainsString('plugin', $e->getMessage());
$this->assertStringContainsString('sirsoft-payment', $e->getMessage());
$this->assertStringContainsString('3.1.4', $e->getMessage());
$this->assertStringContainsString('1.0.0', $e->getMessage());
$this->assertStringContainsString('7.0.0-beta.5', $e->getMessage());
}
}
private function createLegacyStep(): UpgradeStepInterface
{
return new class implements UpgradeStepInterface
{
public function run(UpgradeContext $context): void {}
};
}
private function createAbstractStep(): AbstractUpgradeStep
{
return new class extends AbstractUpgradeStep {};
}
}
@@ -0,0 +1,137 @@
<?php
namespace Tests\Unit\Extension\Helpers;
use App\Extension\Helpers\FilePermissionHelper;
use Illuminate\Support\Facades\File;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* `FilePermissionHelper::copyDirectory` / `removeOrphanItems` 의 symlink 보존 동작 회귀 가드.
*
* 회귀 시나리오 (이슈 #28 + 본 계획 §1):
* - 코어 자동 롤백 시 `public/storage` symlink 가 target 디렉토리 내용으로 추적 복사되어
* symlink 가 일반 디렉토리로 변질 → 운영자가 `storage:link` 재실행 필요
* - `removeOrphanItems` 가 source 부재 symlink 를 디렉토리로 인식하여 target 의 모든 파일을
* 재귀 삭제하는 사고 가능성
*
* Windows: PHP `symlink()` 는 `SeCreateSymbolicLink` 권한 필요. 일반 사용자 환경에서는
* 권한 부족으로 symlink 생성 자체가 실패할 가능성이 높으므로 symlink 가 생성되지 않으면 skip.
*/
class FilePermissionHelperSymlinkTest extends TestCase
{
private string $tempRoot;
protected function setUp(): void
{
parent::setUp();
$this->tempRoot = storage_path('app/testing/file_permission_symlink_'.uniqid('', true));
File::ensureDirectoryExists($this->tempRoot);
}
protected function tearDown(): void
{
if (File::isDirectory($this->tempRoot)) {
File::deleteDirectory($this->tempRoot);
}
parent::tearDown();
}
#[Test]
public function copyDirectory_는_symlink_를_target_추적_없이_그대로_보존합니다(): void
{
$source = $this->tempRoot.'/src';
$dest = $this->tempRoot.'/dst';
$linkTarget = $this->tempRoot.'/link_target';
File::ensureDirectoryExists($source);
File::ensureDirectoryExists($linkTarget);
File::put($linkTarget.'/inside.txt', '링크 대상 안 파일');
$linkPath = $source.'/storage';
if (! @symlink($linkTarget, $linkPath)) {
$this->markTestSkipped('symlink 생성 실패 (Windows SeCreateSymbolicLink 권한 부족 가능)');
}
FilePermissionHelper::copyDirectory($source, $dest);
$this->assertTrue(is_link($dest.'/storage'), 'dest 의 storage 는 symlink 로 유지되어야 한다');
$this->assertSame($linkTarget, readlink($dest.'/storage'));
// target 내용이 dest 의 storage 디렉토리에 복사되어선 안 된다 — symlink 통한 간접 접근만 허용
// 검증: dest/storage 를 link 가 아닌 일반 디렉토리로 직접 열어보면 0 entry
$entries = scandir($dest.'/storage');
$entries = array_values(array_diff($entries, ['.', '..']));
// 링크가 살아있다면 symlink 통과해서 inside.txt 가 보임 (정상)
$this->assertContains('inside.txt', $entries, 'symlink 통과 시 target 의 inside.txt 접근 가능');
// 그러나 dest/storage 자체는 디렉토리 inode 가 아닌 link
$this->assertTrue(is_link($dest.'/storage'));
}
#[Test]
public function copyDirectory_는_기존_dest_디렉토리를_symlink_로_교체할_때_dest_먼저_정리합니다(): void
{
$source = $this->tempRoot.'/src';
$dest = $this->tempRoot.'/dst';
$linkTarget = $this->tempRoot.'/link_target';
File::ensureDirectoryExists($source);
File::ensureDirectoryExists($linkTarget);
File::put($linkTarget.'/inside.txt', 'x');
$linkPath = $source.'/storage';
if (! @symlink($linkTarget, $linkPath)) {
$this->markTestSkipped('symlink 생성 실패');
}
// dest 에 동일 이름의 일반 디렉토리 미리 생성 (백업 복원 직전 상태 시뮬)
File::ensureDirectoryExists($dest.'/storage');
File::put($dest.'/storage/stale.txt', '구버전 잔재');
FilePermissionHelper::copyDirectory($source, $dest);
$this->assertTrue(is_link($dest.'/storage'), '기존 디렉토리는 symlink 로 교체되어야 한다');
}
#[Test]
public function removeOrphanItems_는_source_부재_symlink_를_unlink_로_삭제합니다(): void
{
$source = $this->tempRoot.'/src';
$dest = $this->tempRoot.'/dst';
$linkTarget = $this->tempRoot.'/link_target';
File::ensureDirectoryExists($source);
File::ensureDirectoryExists($dest);
File::ensureDirectoryExists($linkTarget);
File::put($linkTarget.'/precious.txt', '중요한 파일');
// dest 에만 존재하는 symlink (source 에는 없음)
if (! @symlink($linkTarget, $dest.'/orphan_link')) {
$this->markTestSkipped('symlink 생성 실패');
}
FilePermissionHelper::copyDirectory($source, $dest, null, [], '', true);
$this->assertFalse(is_link($dest.'/orphan_link'), 'orphan symlink 는 제거되어야 한다');
$this->assertFileExists($linkTarget.'/precious.txt', 'symlink target 의 파일은 보존되어야 한다 (재귀 삭제 사고 차단)');
}
#[Test]
public function copyDirectory_는_심볼릭링크_없는_일반_디렉토리는_기존_동작을_유지합니다(): void
{
$source = $this->tempRoot.'/src';
$dest = $this->tempRoot.'/dst';
File::ensureDirectoryExists($source.'/sub');
File::put($source.'/file.txt', 'hi');
File::put($source.'/sub/nested.txt', 'world');
FilePermissionHelper::copyDirectory($source, $dest);
$this->assertSame('hi', File::get($dest.'/file.txt'));
$this->assertSame('world', File::get($dest.'/sub/nested.txt'));
}
}
@@ -24,16 +24,13 @@ class IdentityVerificationManagerTest extends TestCase
protected function setUp(): void
{
parent::setUp();
HookManager::resetAll();
// HookManager::resetAll() 호출 금지 — 코어 ServiceProvider 가 부트 시 등록한 listener
// (CoreActivityLogListener 등) 도 함께 날아가 동일 PHP 프로세스 내 다른 테스트에 누수된다.
// 본 클래스는 `new IdentityVerificationManager()` 로 독립 인스턴스를 만들고 그 위에서만 동작하므로
// 정적 hook 전역 상태를 초기화할 필요가 없다.
$this->manager = new IdentityVerificationManager();
}
protected function tearDown(): void
{
HookManager::resetAll();
parent::tearDown();
}
public function test_register_and_get_provider(): void
{
$provider = $this->makeProvider('dummy', true, true);
@@ -64,16 +61,22 @@ class IdentityVerificationManagerTest extends TestCase
$this->manager->register($mail);
$injected = $this->makeProvider('plugin:fake', true, true);
HookManager::addFilter('core.identity.registered_providers', function (array $providers) use ($injected) {
$filter = function (array $providers) use ($injected) {
$providers[$injected->getId()] = $injected;
return $providers;
});
};
HookManager::addFilter('core.identity.registered_providers', $filter);
$all = $this->manager->all();
try {
$all = $this->manager->all();
$this->assertArrayHasKey('g7:core.mail', $all);
$this->assertArrayHasKey('plugin:fake', $all);
$this->assertArrayHasKey('g7:core.mail', $all);
$this->assertArrayHasKey('plugin:fake', $all);
} finally {
// 테스트 격리 — 동일 PHP 프로세스 내 후속 테스트가 본 filter 의 영향을 받지 않도록 정리.
HookManager::removeFilter('core.identity.registered_providers', $filter);
}
}
public function test_resolve_for_purpose_returns_provider_supporting_purpose(): void
@@ -99,6 +102,71 @@ class IdentityVerificationManagerTest extends TestCase
$this->assertSame('plugin:kcp', $resolved->getId());
}
/**
* 명시 $providerId 가 등록 + purpose 지원 시 settings/default 보다 우선 적용 (0번 우선순위, refs #275).
*/
public function test_resolve_for_purpose_prefers_explicit_provider_id(): void
{
$mail = $this->makeProvider('g7:core.mail', true, true);
$external = $this->makeProvider('plugin:fake_external', true, true);
$this->manager->register($mail);
$this->manager->register($external);
// settings.identity.purpose_providers.signup = mail 로 강제 — 명시 providerId 가 이걸 덮어야 한다.
config(['settings.identity.purpose_providers.signup' => 'g7:core.mail']);
$resolved = $this->manager->resolveForPurpose('signup', 'plugin:fake_external');
$this->assertSame('plugin:fake_external', $resolved->getId());
}
/**
* 명시 $providerId 가 미등록이면 silent fallback (기존 우선순위 체인 진행, refs #275).
*/
public function test_resolve_for_purpose_falls_back_when_explicit_provider_unregistered(): void
{
$mail = $this->makeProvider('g7:core.mail', true, true);
$this->manager->register($mail);
$resolved = $this->manager->resolveForPurpose('signup', 'plugin:nonexistent');
$this->assertSame('g7:core.mail', $resolved->getId());
}
/**
* 명시 $providerId 가 등록되어 있어도 supportsPurpose() false 면 silent fallback (refs #275).
*/
public function test_resolve_for_purpose_falls_back_when_explicit_provider_does_not_support_purpose(): void
{
$mail = $this->makeProvider('g7:core.mail', true, true);
$passwordOnly = $this->makeProvider('plugin:password_only', true, false);
$this->manager->register($mail);
$this->manager->register($passwordOnly);
$resolved = $this->manager->resolveForPurpose('signup', 'plugin:password_only');
$this->assertSame('g7:core.mail', $resolved->getId());
}
/**
* $providerId = null (기본값) 시 기존 우선순위 유지 — BC 회귀 차단 (refs #275).
*/
public function test_resolve_for_purpose_with_null_provider_id_preserves_legacy_order(): void
{
$mail = $this->makeProvider('g7:core.mail', true, true);
$external = $this->makeProvider('plugin:fake_external', true, true);
$this->manager->register($mail);
$this->manager->register($external);
// default = g7:core.mail (Manager 의 defaultId) — null providerId 이면 default 로 해석되어야 한다.
$resolved = $this->manager->resolveForPurpose('signup', null);
$this->assertSame('g7:core.mail', $resolved->getId());
}
/**
* IdentityVerificationInterface 더블을 생성합니다.
*/
@@ -192,7 +192,7 @@ class ModuleCleanupStaleEntriesTest extends TestCase
/**
* uninstall(deleteData=false) 시 권한·메뉴·역할이 보존되어 재설치 경로를 비파괴적으로 만드는지 검증.
* PO 정책: "동적 권한/메뉴는 데이터 삭제 옵션 체크 시에만 삭제".
* 운영 정책: "동적 권한/메뉴는 데이터 삭제 옵션 체크 시에만 삭제".
*/
public function test_uninstall_without_delete_data_preserves_permissions(): void
{
@@ -11,7 +11,7 @@ use Tests\TestCase;
/**
* resolveForceUpdateSource() 회귀 테스트.
*
* PO 정책 (2026-04-14): --force 시 번들 우선, 번들 없으면 GitHub 폴백.
* 운영 정책 (2026-04-14): --force 시 번들 우선, 번들 없으면 GitHub 폴백.
*
* 본 테스트는 ModuleManager 의 private 메서드를 Reflection으로 직접 검증한다.
* AbstractModule 은 getIdentifier/getVendor 가 final 이므로 Mockery 로 모킹한다.
@@ -92,7 +92,7 @@ class ModuleForceUpdateSourceTest extends TestCase
public function test_prefers_bundled_over_github_when_both_exist(): void
{
$manager = app(ModuleManager::class);
// 번들과 GitHub 모두 존재하는 시나리오 — PO 정책상 bundled 우선
// 번들과 GitHub 모두 존재하는 시나리오 — 운영 정책상 bundled 우선
$this->setBundledModules($manager, [
'test-mod' => ['version' => '1.0.0'],
]);
@@ -0,0 +1,242 @@
<?php
namespace Tests\Unit\Extension\Upgrade;
use App\Extension\Upgrade\DataSnapshot;
use App\Extension\Upgrade\SnapshotApplier;
use App\Extension\UpgradeContext;
use Illuminate\Support\Facades\File;
use RuntimeException;
use Tests\TestCase;
/**
* DataSnapshot 의 manifest 로딩 / Applier 동적 로드 / versionedNamespace 검증.
*
* 본 테스트는 실제 DB 를 건드리지 않고 fixture 디렉토리만 사용.
*/
class DataSnapshotTest extends TestCase
{
private string $fixtureDir;
protected function setUp(): void
{
parent::setUp();
$this->fixtureDir = storage_path('framework/testing/datasnapshot-'.uniqid());
File::ensureDirectoryExists($this->fixtureDir);
}
protected function tearDown(): void
{
if (File::isDirectory($this->fixtureDir)) {
File::deleteDirectory($this->fixtureDir);
}
parent::tearDown();
}
public function test_empty_returns_no_appliers(): void
{
$snapshot = DataSnapshot::empty();
$this->assertSame([], $snapshot->appliers);
}
public function test_fromManifest_returns_empty_when_manifest_absent(): void
{
$context = $this->makeContext('9.9.9-test.empty');
$snapshot = DataSnapshot::fromManifest($this->fixtureDir, $context);
$this->assertSame([], $snapshot->appliers);
}
public function test_versionedNamespace_converts_version_to_namespace(): void
{
$context = $this->makeContext('7.0.0-beta.5');
$this->assertSame(
'App\\Upgrades\\Data\\V7_0_0_beta_5',
DataSnapshot::versionedNamespace($context),
);
$context2 = $this->makeContext('1.2.3');
$this->assertSame(
'App\\Upgrades\\Data\\V1_2_3',
DataSnapshot::versionedNamespace($context2),
);
}
public function test_versionedNamespace_uses_core_pattern_when_source_path_is_core(): void
{
$context = $this->makeContext('7.0.0-beta.5');
$this->assertSame(
'App\\Upgrades\\Data\\V7_0_0_beta_5',
DataSnapshot::versionedNamespace(
$context,
'/var/www/upgrades/data/7.0.0-beta.5',
),
);
}
public function test_versionedNamespace_inserts_module_segment_when_source_path_is_bundled_module(): void
{
$context = $this->makeContext('1.2.0');
$this->assertSame(
'App\\Upgrades\\Data\\Ext\\Modules\\SirsoftEcommerce\\V1_2_0',
DataSnapshot::versionedNamespace(
$context,
'/var/www/modules/_bundled/sirsoft-ecommerce/upgrades/data/1.2.0',
),
);
}
public function test_versionedNamespace_inserts_plugin_segment_when_source_path_is_bundled_plugin(): void
{
$context = $this->makeContext('2.0.0');
$this->assertSame(
'App\\Upgrades\\Data\\Ext\\Plugins\\SirsoftPayment\\V2_0_0',
DataSnapshot::versionedNamespace(
$context,
'/var/www/plugins/_bundled/sirsoft-payment/upgrades/data/2.0.0',
),
);
}
public function test_versionedNamespace_uses_ext_segment_for_external_extension_paths(): void
{
$context = $this->makeContext('0.3.1');
// 외부 확장 (modules/{not _bundled}) 도 동일 격리 패턴
$this->assertSame(
'App\\Upgrades\\Data\\Ext\\Modules\\VendorExternalMod\\V0_3_1',
DataSnapshot::versionedNamespace(
$context,
'/var/www/modules/vendor-external-mod/upgrades/data/0.3.1',
),
);
}
public function test_versionedNamespace_different_extensions_same_step_version_produce_different_namespaces(): void
{
// 본 PR 이 해결한 namespace 충돌 회귀 — 같은 step 버전 + 다른 확장 → 다른 namespace.
$context = $this->makeContext('1.0.0');
$nsA = DataSnapshot::versionedNamespace(
$context,
'/var/www/modules/_bundled/vendor-foo/upgrades/data/1.0.0',
);
$nsB = DataSnapshot::versionedNamespace(
$context,
'/var/www/modules/_bundled/vendor-bar/upgrades/data/1.0.0',
);
$nsCore = DataSnapshot::versionedNamespace(
$context,
'/var/www/upgrades/data/1.0.0',
);
$this->assertNotSame($nsA, $nsB, '두 다른 확장은 같은 step 버전이라도 다른 namespace 가 되어야 함');
$this->assertNotSame($nsA, $nsCore);
$this->assertNotSame($nsB, $nsCore);
}
public function test_fromManifest_loads_applier_with_versioned_namespace(): void
{
$version = '0.0.1-snapshot.test';
$context = $this->makeContext($version);
// fixture: manifest + delta JSON + Applier (버전 namespace)
File::put($this->fixtureDir.'/manifest.json', json_encode([
'version' => $version,
'files' => [
['kind' => 'sample', 'file' => 'sample.delta.json'],
],
]));
File::put($this->fixtureDir.'/sample.delta.json', json_encode(['added' => []]));
File::ensureDirectoryExists($this->fixtureDir.'/appliers');
$token = 'V'.str_replace(['.', '-'], '_', $version);
File::put($this->fixtureDir.'/appliers/SampleApplier.php', <<<PHP
<?php
namespace App\Upgrades\Data\\{$token}\Appliers;
use App\Extension\Upgrade\SnapshotApplier;
use App\Extension\UpgradeContext;
class SampleApplier implements SnapshotApplier
{
public function __construct(public readonly string \$jsonPath) {}
public function apply(UpgradeContext \$context): void
{
// no-op
}
}
PHP);
$snapshot = DataSnapshot::fromManifest($this->fixtureDir, $context);
$this->assertCount(1, $snapshot->appliers);
$this->assertInstanceOf(SnapshotApplier::class, $snapshot->appliers[0]);
$this->assertSame(
$this->fixtureDir.'/sample.delta.json',
$snapshot->appliers[0]->jsonPath,
);
}
public function test_fromManifest_throws_when_applier_file_missing(): void
{
$context = $this->makeContext('0.0.2-missing.applier');
File::put($this->fixtureDir.'/manifest.json', json_encode([
'version' => '0.0.2-missing.applier',
'files' => [
['kind' => 'permissions', 'file' => 'permissions.delta.json'],
],
]));
File::put($this->fixtureDir.'/permissions.delta.json', json_encode(['added' => []]));
// appliers/ 디렉토리에 PermissionsApplier 파일 미작성
$this->expectException(RuntimeException::class);
$this->expectExceptionMessageMatches('/Applier file not found/');
DataSnapshot::fromManifest($this->fixtureDir, $context);
}
public function test_fromManifest_throws_when_namespace_mismatch(): void
{
$version = '0.0.3-wrong.ns';
$context = $this->makeContext($version);
File::put($this->fixtureDir.'/manifest.json', json_encode([
'version' => $version,
'files' => [
['kind' => 'foo', 'file' => 'foo.delta.json'],
],
]));
File::put($this->fixtureDir.'/foo.delta.json', json_encode(['added' => []]));
File::ensureDirectoryExists($this->fixtureDir.'/appliers');
// 잘못된 namespace 로 클래스 선언 (V0_0_3_wrong_ns 가 아닌 임의 namespace)
File::put($this->fixtureDir.'/appliers/FooApplier.php', <<<'PHP'
<?php
namespace App\Upgrades\Data\WrongNamespace\Appliers;
use App\Extension\Upgrade\SnapshotApplier;
use App\Extension\UpgradeContext;
class FooApplier implements SnapshotApplier
{
public function __construct(public readonly string $jsonPath) {}
public function apply(UpgradeContext $context): void {}
}
PHP);
$this->expectException(RuntimeException::class);
$this->expectExceptionMessageMatches('/Applier class not declared in expected namespace/');
DataSnapshot::fromManifest($this->fixtureDir, $context);
}
private function makeContext(string $version): UpgradeContext
{
return new UpgradeContext(
fromVersion: '0.0.0',
toVersion: $version,
currentStep: $version,
);
}
}
+59
View File
@@ -92,4 +92,63 @@ class EnvironmentDetectorTest extends TestCase
$result = $this->detector->canExecuteComposer();
$this->assertIsBool($result);
}
public function test_build_composer_env_includes_superuser_flag(): void
{
$env = EnvironmentDetector::buildComposerEnv();
$this->assertArrayHasKey('COMPOSER_ALLOW_SUPERUSER', $env);
$this->assertSame('1', $env['COMPOSER_ALLOW_SUPERUSER']);
}
public function test_build_composer_env_includes_no_interaction_flag(): void
{
$env = EnvironmentDetector::buildComposerEnv();
$this->assertArrayHasKey('COMPOSER_NO_INTERACTION', $env);
$this->assertSame('1', $env['COMPOSER_NO_INTERACTION']);
}
public function test_build_composer_env_preserves_existing_env(): void
{
$original = $_ENV['PATH'] ?? null;
$_ENV['PATH'] = '/sentinel/test/path';
try {
$env = EnvironmentDetector::buildComposerEnv();
$this->assertArrayHasKey('PATH', $env);
$this->assertSame('/sentinel/test/path', $env['PATH']);
} finally {
if ($original === null) {
unset($_ENV['PATH']);
} else {
$_ENV['PATH'] = $original;
}
}
}
public function test_build_composer_env_overrides_external_false_values(): void
{
$originalAllow = $_ENV['COMPOSER_ALLOW_SUPERUSER'] ?? null;
$originalNoInteraction = $_ENV['COMPOSER_NO_INTERACTION'] ?? null;
$_ENV['COMPOSER_ALLOW_SUPERUSER'] = '0';
$_ENV['COMPOSER_NO_INTERACTION'] = '0';
try {
$env = EnvironmentDetector::buildComposerEnv();
$this->assertSame('1', $env['COMPOSER_ALLOW_SUPERUSER']);
$this->assertSame('1', $env['COMPOSER_NO_INTERACTION']);
} finally {
foreach (['COMPOSER_ALLOW_SUPERUSER' => $originalAllow, 'COMPOSER_NO_INTERACTION' => $originalNoInteraction] as $key => $value) {
if ($value === null) {
unset($_ENV[$key]);
} else {
$_ENV[$key] = $value;
}
}
}
}
}
@@ -41,7 +41,11 @@ class IdentityMessageSyncHelperTest extends TestCase
$definition->update(['name' => ['ko' => '운영자 변경 이름', 'en' => 'Custom Name']]);
$definition->refresh();
$this->assertContains('name', $definition->user_overrides ?? []);
// HasUserOverrides Trait 가 다국어 trackable 컬럼을 sub-key dot-path 단위로 기록한다 (7.0.0-beta.4+).
// name 의 ko/en 모두 변경되었으므로 두 sub-key 가 모두 user_overrides 에 들어있어야 한다.
$overrides = $definition->user_overrides ?? [];
$this->assertContains('name.ko', $overrides);
$this->assertContains('name.en', $overrides);
$reseeded = $this->helper->syncDefinition($this->definitionData('signup'));
@@ -66,7 +66,7 @@ class InstallerSecurityHardeningTest extends TestCase
}
/**
* 테스트가 도중 종료되어도 PO 작업 디렉토리에 state.json 잔여물이 남지 않도록 항상 정리.
* 테스트가 도중 종료되어도 사용자 작업 디렉토리에 state.json 잔여물이 남지 않도록 항상 정리.
* BASE_PATH 가 다른 테스트 인프라에 의해 프로젝트 루트로 바인딩되는 경우를 대비해
* 프로젝트 루트의 storage/installer-state.json 도 함께 정리.
*/
+1 -1
View File
@@ -48,7 +48,7 @@ class WorkerLockGuardTest extends TestCase
{
// $this->stateFile 은 setUp 시점의 BASE_PATH 로 이미 결정되어 있으므로
// 그 경로를 그대로 정리. 이전 코드는 BASE_PATH 가 self::tempBase 와 다를 때
// (다른 테스트가 먼저 바인딩한 경우) 정리를 skip 하여 PO 작업 디렉토리에
// (다른 테스트가 먼저 바인딩한 경우) 정리를 skip 하여 사용자 작업 디렉토리에
// 잔여물을 남겼다.
@unlink($this->stateFile);
parent::tearDown();
@@ -41,7 +41,7 @@ class SettingsServiceProviderWebsocketConfigTest extends TestCase
Config::set('broadcasting.default', 'reverb');
Config::set('broadcasting.connections.reverb.options.host', 'localhost');
// PO 설정: 웹소켓 OFF
// 사용자 설정: 웹소켓 OFF
$this->callApplyWebsocketConfig([
'websocket_enabled' => false,
'websocket_host' => 'g7.dev',
+3 -3
View File
@@ -9,7 +9,7 @@ use Tests\TestCase;
/**
* 실제 상품 상세 페이지 렌더링 시나리오를 검증합니다.
*
* PO 피드백 기반: 실제 SEO 페이지에서 발생한 문제들을 재현하여 검증합니다.
* 사용자 피드백 기반: 실제 SEO 페이지에서 발생한 문제들을 재현하여 검증합니다.
* - Icon이 <div> 대신 <i>로 렌더링되는지
* - Img가 <img> 셀프 클로징 태그로 렌더링되는지
* - 상품 데이터 바인딩 (이름, 가격, 이미지) 적용 여부
@@ -76,7 +76,7 @@ class RealWorldRenderingTest extends TestCase
// ========================================================
/**
* Icon 컴포넌트가 <i> 태그로 렌더링됩니다 (PO 버그: <div>로 렌더링됨).
* Icon 컴포넌트가 <i> 태그로 렌더링됩니다 (재현 시 발생한 버그: <div>로 렌더링됨).
*/
public function test_icon_renders_as_i_tag(): void
{
@@ -407,7 +407,7 @@ class RealWorldRenderingTest extends TestCase
// ========================================================
/**
* $t: 번역 키가 해석됩니다 (PO 버그: $t:shop.product.reviews_count 그대로 노출).
* $t: 번역 키가 해석됩니다 (재현 시 발생한 버그: $t:shop.product.reviews_count 그대로 노출).
*/
public function test_translation_key_resolved(): void
{
@@ -1181,6 +1181,152 @@ MD;
}
}
/**
* targets 에 `templates/_bundled` 만 있고 source 의 `templates/` 디렉토리에 `_bundled`
* 만 있을 때, 활성 디렉토리(`templates/sirsoft-basic` 등) 가 자동 발견 폴백의
* removeOrphans 로 삭제되지 않아야 한다.
*
* 회귀 시나리오 (#347): beta.4 의 `isCoveredByApplied` 가 단방향 검사만 수행하여
* applied=['templates/_bundled'] 일 때 source 의 'templates' 자체를 신규 항목으로
* 오인 → `copyDirectory(removeOrphans:true)` 가 base 의 활성 sirsoft-* 서브디렉토리를
* orphan 으로 판정하여 삭제.
*/
public function test_apply_update_preserves_active_extension_dirs_when_source_only_has_bundled(): void
{
$sourcePath = storage_path('test_apply_preserve_src_'.uniqid());
$this->tempDirs[] = $sourcePath;
File::ensureDirectoryExists($sourcePath);
// source: templates/_bundled/{shared-id}/manifest.json 만 보유
File::ensureDirectoryExists($sourcePath.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.'sirsoft-basic');
File::put(
$sourcePath.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.'sirsoft-basic'.DIRECTORY_SEPARATOR.'manifest.json',
'{"identifier":"sirsoft-basic","version":"1.0.0"}'
);
// base: templates/_bundled/sirsoft-basic + templates/sirsoft-basic (활성 디렉토리)
$fakeBase = storage_path('test_apply_preserve_base_'.uniqid());
$this->tempDirs[] = $fakeBase;
File::ensureDirectoryExists($fakeBase);
$originalBasePath = base_path();
app()->setBasePath($fakeBase);
File::ensureDirectoryExists($fakeBase.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.'sirsoft-basic');
File::put(
$fakeBase.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.'sirsoft-basic'.DIRECTORY_SEPARATOR.'manifest.json',
'{"identifier":"sirsoft-basic","version":"0.9.0"}'
);
File::ensureDirectoryExists($fakeBase.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.'sirsoft-basic');
File::put(
$fakeBase.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.'sirsoft-basic'.DIRECTORY_SEPARATOR.'manifest.json',
'{"identifier":"sirsoft-basic","installed":true}'
);
try {
config([
'app.update.targets' => ['templates/_bundled'],
'app.update.excludes' => [],
'app.update.protected_paths' => ['.env', 'storage', 'vendor', 'node_modules', '.git'],
]);
$this->service->applyUpdate($sourcePath);
// _bundled 는 source 기준으로 정상 sync
$this->assertFileExists(
$fakeBase.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.'sirsoft-basic'.DIRECTORY_SEPARATOR.'manifest.json'
);
// 활성 디렉토리는 source 에 부재하지만 base 에 보존되어야 함 (회귀 차단)
$this->assertFileExists(
$fakeBase.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.'sirsoft-basic'.DIRECTORY_SEPARATOR.'manifest.json',
'활성 templates/sirsoft-basic 이 자동 발견 폴백에 의해 삭제되어서는 안 된다 (#347 회귀)'
);
} finally {
app()->setBasePath($originalBasePath);
}
}
/**
* modules/, plugins/ 에도 동일 패턴 보존 확인 (#347 회귀).
*/
public function test_apply_update_preserves_active_module_and_plugin_dirs_same_pattern(): void
{
$sourcePath = storage_path('test_apply_preserve_mp_src_'.uniqid());
$this->tempDirs[] = $sourcePath;
File::ensureDirectoryExists($sourcePath);
// source: modules/_bundled, plugins/_bundled 만 보유
File::ensureDirectoryExists($sourcePath.DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.'sirsoft-ecommerce');
File::put(
$sourcePath.DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.'sirsoft-ecommerce'.DIRECTORY_SEPARATOR.'module.json',
'{"identifier":"sirsoft-ecommerce","version":"1.0.0"}'
);
File::ensureDirectoryExists($sourcePath.DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.'sirsoft-payment');
File::put(
$sourcePath.DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.'sirsoft-payment'.DIRECTORY_SEPARATOR.'plugin.json',
'{"identifier":"sirsoft-payment","version":"1.0.0"}'
);
$fakeBase = storage_path('test_apply_preserve_mp_base_'.uniqid());
$this->tempDirs[] = $fakeBase;
File::ensureDirectoryExists($fakeBase);
$originalBasePath = base_path();
app()->setBasePath($fakeBase);
// base 활성 디렉토리 + _bundled 모두 있는 상태
File::ensureDirectoryExists($fakeBase.DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.'sirsoft-ecommerce');
File::put(
$fakeBase.DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.'sirsoft-ecommerce'.DIRECTORY_SEPARATOR.'module.json',
'{"identifier":"sirsoft-ecommerce","version":"0.9.0"}'
);
File::ensureDirectoryExists($fakeBase.DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR.'sirsoft-ecommerce');
File::put(
$fakeBase.DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR.'sirsoft-ecommerce'.DIRECTORY_SEPARATOR.'module.json',
'{"installed":true}'
);
File::ensureDirectoryExists($fakeBase.DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.'sirsoft-payment');
File::put(
$fakeBase.DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.'sirsoft-payment'.DIRECTORY_SEPARATOR.'plugin.json',
'{"identifier":"sirsoft-payment","version":"0.9.0"}'
);
File::ensureDirectoryExists($fakeBase.DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'sirsoft-payment');
File::put(
$fakeBase.DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'sirsoft-payment'.DIRECTORY_SEPARATOR.'plugin.json',
'{"installed":true}'
);
try {
config([
'app.update.targets' => ['modules/_bundled', 'plugins/_bundled'],
'app.update.excludes' => [],
'app.update.protected_paths' => ['.env', 'storage', 'vendor', 'node_modules', '.git'],
]);
$this->service->applyUpdate($sourcePath);
// 활성 모듈/플러그인 디렉토리 보존
$this->assertFileExists(
$fakeBase.DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR.'sirsoft-ecommerce'.DIRECTORY_SEPARATOR.'module.json',
'활성 modules/sirsoft-ecommerce 이 보존되어야 한다 (#347 회귀)'
);
$this->assertFileExists(
$fakeBase.DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'sirsoft-payment'.DIRECTORY_SEPARATOR.'plugin.json',
'활성 plugins/sirsoft-payment 이 보존되어야 한다 (#347 회귀)'
);
// _bundled sync 정상
$this->assertStringContainsString(
'"version":"1.0.0"',
File::get($fakeBase.DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.'sirsoft-ecommerce'.DIRECTORY_SEPARATOR.'module.json')
);
} finally {
app()->setBasePath($originalBasePath);
}
}
/**
* 자동 발견 폴백이 protected_paths 와 user excludes 양쪽을 존중하는지 검증합니다.
*/
@@ -0,0 +1,129 @@
<?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::resolveRenderHint 의 fallback 분기 정합성 회귀 차단.
*
* 호출자 명시 인자(정책의 provider_id) 가 4계층(Service → Manager) 통과 중 silent drop
* 되던 결함을 cherry-pick 으로 가져온 4c723e154 가 Service::start 경로에서 수정했다.
* 본 테스트는 동일 패턴이 resolveRenderHint 의 fallback 분기에서도 회귀하지 않도록
* Manager::resolveForPurpose 호출 시 정책의 provider_id 가 두 번째 인자로 전달되는지를
* spy 로 직접 검증한다.
*
* 실질 동작 결과는 수정 전후 동일 (Manager 의 0번 우선순위는 미등록 provider 를 매치하지
* 않으므로 fallback chain 결과가 같음). 정합성 차원의 회귀 차단 목적.
*/
class IdentityPolicyServiceResolveRenderHintTest extends TestCase
{
protected function tearDown(): void
{
Mockery::close();
parent::tearDown();
}
public function test_fallback_branch_passes_policy_provider_id_to_manager(): void
{
$policyRepo = Mockery::mock(IdentityPolicyRepositoryInterface::class);
$logRepo = Mockery::mock(IdentityVerificationLogRepositoryInterface::class);
$resolvedProvider = Mockery::mock(IdentityVerificationInterface::class);
$resolvedProvider->shouldReceive('getRenderHint')->andReturn('text_code');
$manager = Mockery::mock(IdentityVerificationManager::class);
// 첫 분기: manager->has(provider) === false → fallback 진입 유도
$manager->shouldReceive('has')->with('plugin:disabled')->andReturn(false);
// 핵심 검증: fallback 분기에서 두 번째 인자로 정책의 provider_id 가 전달되어야 함
$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',
]);
$hint = $this->invokeResolveRenderHint($service, $policy);
$this->assertSame('text_code', $hint);
}
public function test_fallback_branch_passes_null_when_policy_has_no_provider_id(): void
{
$policyRepo = Mockery::mock(IdentityPolicyRepositoryInterface::class);
$logRepo = Mockery::mock(IdentityVerificationLogRepositoryInterface::class);
$resolvedProvider = Mockery::mock(IdentityVerificationInterface::class);
$resolvedProvider->shouldReceive('getRenderHint')->andReturn('text_code');
$manager = Mockery::mock(IdentityVerificationManager::class);
// provider_id 가 falsy 면 첫 if 조건 자체에서 fallback 진입 (manager->has 미호출)
$manager->shouldReceive('resolveForPurpose')
->once()
->with('signup', null)
->andReturn($resolvedProvider);
$service = new IdentityPolicyService($policyRepo, $logRepo, $manager);
$policy = new IdentityPolicy([
'purpose' => 'signup',
'provider_id' => null,
]);
$hint = $this->invokeResolveRenderHint($service, $policy);
$this->assertSame('text_code', $hint);
}
public function test_first_branch_returns_provider_hint_without_fallback(): void
{
$policyRepo = Mockery::mock(IdentityPolicyRepositoryInterface::class);
$logRepo = Mockery::mock(IdentityVerificationLogRepositoryInterface::class);
$directProvider = Mockery::mock(IdentityVerificationInterface::class);
$directProvider->shouldReceive('getRenderHint')->andReturn('redirect_oauth');
$manager = Mockery::mock(IdentityVerificationManager::class);
$manager->shouldReceive('has')->with('plugin:active')->andReturn(true);
$manager->shouldReceive('get')->with('plugin:active')->andReturn($directProvider);
// 첫 분기 통과 시 resolveForPurpose 는 호출되어선 안 됨 (회귀 차단)
$manager->shouldNotReceive('resolveForPurpose');
$service = new IdentityPolicyService($policyRepo, $logRepo, $manager);
$policy = new IdentityPolicy([
'purpose' => 'signup',
'provider_id' => 'plugin:active',
]);
$hint = $this->invokeResolveRenderHint($service, $policy);
$this->assertSame('redirect_oauth', $hint);
}
/**
* protected resolveRenderHint 를 reflection 으로 직접 호출합니다.
*/
private function invokeResolveRenderHint(IdentityPolicyService $service, IdentityPolicy $policy): ?string
{
$reflection = new \ReflectionMethod(IdentityPolicyService::class, 'resolveRenderHint');
$reflection->setAccessible(true);
/** @var string|null $hint */
$hint = $reflection->invoke($service, $policy);
return $hint;
}
}
@@ -387,13 +387,19 @@ class LanguagePackServiceTest extends TestCase
$this->markTestSkipped('g7-core-ja 번들이 아직 빌드되지 않음 — build-language-pack-ja.cjs 실행 후 재시도');
}
// 번들 manifest 의 현재 버전을 기준으로 설치 결과 검증
// (코어 lang 변경 시 g7-core-ja 버전이 patch bump 되므로 하드코딩 회피)
$bundledManifest = json_decode(file_get_contents($bundledPath.'/language-pack.json'), true);
$bundledVersion = $bundledManifest['version'] ?? null;
$this->assertNotNull($bundledVersion, '번들 manifest 에 version 누락');
$pack = $this->service->installFromBundled('g7-core-ja', autoActivate: true);
$this->assertSame('g7-core-ja', $pack->identifier);
$this->assertSame(LanguagePackScope::Core->value, $pack->scope);
$this->assertNull($pack->target_identifier);
$this->assertSame('ja', $pack->locale);
$this->assertSame('1.0.0-beta.1', $pack->version);
$this->assertSame($bundledVersion, $pack->version);
$this->assertSame(LanguagePackStatus::Active->value, $pack->status);
$this->assertSame('bundled', $pack->source_type);
// is_protected 는 모든 install 흐름에서 항상 false (보호 행은 코어/번들 확장의 lang/ 디렉토리를 가상 행으로 합성하는 경로에서만 true)