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;
}
}
}
}
}