v7.0.0-beta.5 release
This commit is contained in:
1 parent
1db039ff34
commit
eb467aca79
159 files changed
+7599
-218
No files matched your search
@@ -0,0 +1,215 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin\Identity;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Enums\PermissionType;
|
||||
use App\Models\IdentityPolicy;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Database\Seeders\RolePermissionSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 관리자 — IDV 정책 API 의 read / update 권한 분리 검증.
|
||||
*
|
||||
* 회귀 가드: 운영자가 "정책 조회" 권한만 받은 상태에서
|
||||
* GET /api/admin/identity/policies 가 200 으로 응답해야 한다.
|
||||
* 수정/생성/삭제는 `core.admin.identity.policies.update` 권한 필요.
|
||||
*/
|
||||
class AdminIdentityPolicyPermissionTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->seed(RolePermissionSeeder::class);
|
||||
}
|
||||
|
||||
private function makeUserWithPermissions(array $identifiers): string
|
||||
{
|
||||
$user = User::factory()->create(['is_super' => false]);
|
||||
|
||||
$role = Role::create([
|
||||
'identifier' => 'test-pol-role-'.uniqid(),
|
||||
'name' => ['ko' => '테스트 정책 역할', 'en' => 'Test Policy Role'],
|
||||
'description' => ['ko' => '', 'en' => ''],
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
]);
|
||||
|
||||
foreach ($identifiers as $identifier) {
|
||||
$perm = Permission::firstOrCreate(
|
||||
['identifier' => $identifier],
|
||||
[
|
||||
'name' => ['ko' => $identifier, 'en' => $identifier],
|
||||
'description' => ['ko' => '', 'en' => ''],
|
||||
'type' => PermissionType::Admin,
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'order' => 0,
|
||||
]
|
||||
);
|
||||
$role->permissions()->attach($perm->id, [
|
||||
'granted_at' => now(),
|
||||
'granted_by' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
$user->roles()->attach($role->id, [
|
||||
'assigned_at' => now(),
|
||||
'assigned_by' => null,
|
||||
]);
|
||||
|
||||
return $user->fresh()->createToken('test')->plainTextToken;
|
||||
}
|
||||
|
||||
private function auth(string $token): array
|
||||
{
|
||||
return [
|
||||
'Authorization' => 'Bearer '.$token,
|
||||
'Accept' => 'application/json',
|
||||
];
|
||||
}
|
||||
|
||||
private function makePolicy(): IdentityPolicy
|
||||
{
|
||||
return IdentityPolicy::create([
|
||||
'key' => 'perm.test.'.uniqid(),
|
||||
'scope' => 'route',
|
||||
'target' => 'api.perm.test',
|
||||
'purpose' => 'sensitive_action',
|
||||
'grace_minutes' => 0,
|
||||
'enabled' => true,
|
||||
'priority' => 100,
|
||||
'source_type' => 'admin',
|
||||
'source_identifier' => 'admin',
|
||||
'applies_to' => 'both',
|
||||
'fail_mode' => 'block',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_policies_read_only_user_can_list(): void
|
||||
{
|
||||
$token = $this->makeUserWithPermissions(['core.admin.identity.policies.read']);
|
||||
|
||||
$response = $this->withHeaders($this->auth($token))
|
||||
->getJson('/api/admin/identity/policies');
|
||||
|
||||
$response->assertStatus(200);
|
||||
}
|
||||
|
||||
public function test_policies_read_only_user_cannot_create(): void
|
||||
{
|
||||
$token = $this->makeUserWithPermissions(['core.admin.identity.policies.read']);
|
||||
|
||||
$response = $this->withHeaders($this->auth($token))
|
||||
->postJson('/api/admin/identity/policies', [
|
||||
'key' => 'forbidden.create',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.forbid',
|
||||
'purpose' => 'sensitive_action',
|
||||
'grace_minutes' => 0,
|
||||
'applies_to' => 'both',
|
||||
'fail_mode' => 'block',
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
public function test_policies_read_only_user_cannot_update(): void
|
||||
{
|
||||
$token = $this->makeUserWithPermissions(['core.admin.identity.policies.read']);
|
||||
$policy = $this->makePolicy();
|
||||
|
||||
$response = $this->withHeaders($this->auth($token))
|
||||
->putJson("/api/admin/identity/policies/{$policy->id}", ['grace_minutes' => 42]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
public function test_policies_read_only_user_cannot_delete(): void
|
||||
{
|
||||
$token = $this->makeUserWithPermissions(['core.admin.identity.policies.read']);
|
||||
$policy = $this->makePolicy();
|
||||
|
||||
$response = $this->withHeaders($this->auth($token))
|
||||
->deleteJson("/api/admin/identity/policies/{$policy->id}");
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
public function test_policies_update_only_user_cannot_list(): void
|
||||
{
|
||||
$token = $this->makeUserWithPermissions(['core.admin.identity.policies.update']);
|
||||
|
||||
$response = $this->withHeaders($this->auth($token))
|
||||
->getJson('/api/admin/identity/policies');
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
public function test_policies_update_only_user_can_create(): void
|
||||
{
|
||||
$token = $this->makeUserWithPermissions(['core.admin.identity.policies.update']);
|
||||
|
||||
$response = $this->withHeaders($this->auth($token))
|
||||
->postJson('/api/admin/identity/policies', [
|
||||
'key' => 'update.only.create',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.upd.only',
|
||||
'purpose' => 'sensitive_action',
|
||||
'grace_minutes' => 0,
|
||||
'applies_to' => 'both',
|
||||
'fail_mode' => 'block',
|
||||
]);
|
||||
|
||||
$response->assertStatus(201);
|
||||
}
|
||||
|
||||
public function test_policies_no_permission_user_blocked_on_all(): void
|
||||
{
|
||||
$token = $this->makeUserWithPermissions([]);
|
||||
$policy = $this->makePolicy();
|
||||
|
||||
$this->withHeaders($this->auth($token))
|
||||
->getJson('/api/admin/identity/policies')
|
||||
->assertStatus(403);
|
||||
|
||||
$this->withHeaders($this->auth($token))
|
||||
->postJson('/api/admin/identity/policies', ['key' => 'no.perm'])
|
||||
->assertStatus(403);
|
||||
|
||||
$this->withHeaders($this->auth($token))
|
||||
->putJson("/api/admin/identity/policies/{$policy->id}", ['grace_minutes' => 1])
|
||||
->assertStatus(403);
|
||||
|
||||
$this->withHeaders($this->auth($token))
|
||||
->deleteJson("/api/admin/identity/policies/{$policy->id}")
|
||||
->assertStatus(403);
|
||||
}
|
||||
|
||||
public function test_policies_full_access_user_can_all(): void
|
||||
{
|
||||
$token = $this->makeUserWithPermissions([
|
||||
'core.admin.identity.policies.read',
|
||||
'core.admin.identity.policies.update',
|
||||
]);
|
||||
$policy = $this->makePolicy();
|
||||
|
||||
$this->withHeaders($this->auth($token))
|
||||
->getJson('/api/admin/identity/policies')
|
||||
->assertStatus(200);
|
||||
|
||||
$this->withHeaders($this->auth($token))
|
||||
->putJson("/api/admin/identity/policies/{$policy->id}", ['grace_minutes' => 33])
|
||||
->assertStatus(200);
|
||||
|
||||
$this->withHeaders($this->auth($token))
|
||||
->deleteJson("/api/admin/identity/policies/{$policy->id}")
|
||||
->assertStatus(200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin\Identity;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Enums\PermissionType;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Database\Seeders\RolePermissionSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 관리자 — IDV 프로바이더 API 의 read / update 권한 분리 검증.
|
||||
*
|
||||
* 회귀 가드: 운영자가 "프로바이더 설정 조회" 권한만 받은 상태에서
|
||||
* GET /api/admin/identity/providers 가 200 으로 응답해야 한다.
|
||||
* 이전에는 GET 도 `core.admin.identity.manage` 를 요구해 조회 전용 운영자에게 403 발생.
|
||||
*/
|
||||
class AdminIdentityProviderPermissionTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->seed(RolePermissionSeeder::class);
|
||||
}
|
||||
|
||||
private function makeUserWithPermissions(array $identifiers): array
|
||||
{
|
||||
$user = User::factory()->create(['is_super' => false]);
|
||||
|
||||
$role = Role::create([
|
||||
'identifier' => 'test-idv-role-'.uniqid(),
|
||||
'name' => ['ko' => '테스트 IDV 역할', 'en' => 'Test IDV Role'],
|
||||
'description' => ['ko' => '', 'en' => ''],
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
]);
|
||||
|
||||
foreach ($identifiers as $identifier) {
|
||||
$perm = Permission::firstOrCreate(
|
||||
['identifier' => $identifier],
|
||||
[
|
||||
'name' => ['ko' => $identifier, 'en' => $identifier],
|
||||
'description' => ['ko' => '', 'en' => ''],
|
||||
'type' => PermissionType::Admin,
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'order' => 0,
|
||||
]
|
||||
);
|
||||
$role->permissions()->attach($perm->id, [
|
||||
'granted_at' => now(),
|
||||
'granted_by' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
$user->roles()->attach($role->id, [
|
||||
'assigned_at' => now(),
|
||||
'assigned_by' => null,
|
||||
]);
|
||||
|
||||
return [$user->fresh(), $user->createToken('test')->plainTextToken];
|
||||
}
|
||||
|
||||
private function auth(string $token): array
|
||||
{
|
||||
return [
|
||||
'Authorization' => 'Bearer '.$token,
|
||||
'Accept' => 'application/json',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀: providers.read 권한만 가진 운영자가 GET 으로 200 을 받아야 한다.
|
||||
* 현재 라우트가 `.manage` 만 체크하므로 fail (403) → 수정 후 green (200).
|
||||
*/
|
||||
public function test_user_with_only_providers_read_can_list_providers(): void
|
||||
{
|
||||
[, $token] = $this->makeUserWithPermissions(['core.admin.identity.providers.read']);
|
||||
|
||||
$response = $this->withHeaders($this->auth($token))
|
||||
->getJson('/api/admin/identity/providers');
|
||||
|
||||
$response->assertStatus(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* 권한이 전혀 없는 운영자는 403.
|
||||
*/
|
||||
public function test_user_with_no_identity_permissions_cannot_list_providers(): void
|
||||
{
|
||||
[, $token] = $this->makeUserWithPermissions([]);
|
||||
|
||||
$response = $this->withHeaders($this->auth($token))
|
||||
->getJson('/api/admin/identity/providers');
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
/**
|
||||
* providers.update 만 가진 운영자는 GET 차단 (read 가 없으므로).
|
||||
*/
|
||||
public function test_user_with_only_providers_update_cannot_list_providers(): void
|
||||
{
|
||||
[, $token] = $this->makeUserWithPermissions(['core.admin.identity.providers.update']);
|
||||
|
||||
$response = $this->withHeaders($this->auth($token))
|
||||
->getJson('/api/admin/identity/providers');
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
/**
|
||||
* read + update 둘 다 있으면 통과.
|
||||
*/
|
||||
public function test_user_with_both_read_and_update_can_list_providers(): void
|
||||
{
|
||||
[, $token] = $this->makeUserWithPermissions([
|
||||
'core.admin.identity.providers.read',
|
||||
'core.admin.identity.providers.update',
|
||||
]);
|
||||
|
||||
$response = $this->withHeaders($this->auth($token))
|
||||
->getJson('/api/admin/identity/providers');
|
||||
|
||||
$response->assertStatus(200);
|
||||
}
|
||||
}
|
||||
@@ -338,7 +338,7 @@ class ModuleArtisanCommandsTest extends TestCase
|
||||
'identifier' => $identifier,
|
||||
]);
|
||||
|
||||
// 권한은 보존됨 — PO 정책: 권한/메뉴 삭제는 --delete-data 옵션 시에만.
|
||||
// 권한은 보존됨 — 운영 정책: 권한/메뉴 삭제는 --delete-data 옵션 시에만.
|
||||
// (재설치 시 기존 역할 할당/커스터마이징이 복원 가능하도록 보존)
|
||||
$this->assertGreaterThan(0, Permission::byExtension(ExtensionOwnerType::Module, $identifier)->count());
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ use Tests\TestCase;
|
||||
*
|
||||
* handle() catch 블록 내부 cleanup 시퀀스 (updateVersionInEnv(toVersion),
|
||||
* clearAllCaches, restoreOwnership, cleanupPending, disableMaintenanceMode,
|
||||
* 사용자 안내) 는 본 테스트 범위에서 제외되며, PO Linux 서버 수동 검증으로 보완한다.
|
||||
* 사용자 안내) 는 본 테스트 범위에서 제외되며, 운영자 Linux 서버 수동 검증으로 보완한다.
|
||||
*
|
||||
* 본 테스트는 실제 proc_open 으로 자식 PHP 프로세스를 띄우므로 proc_open 미지원
|
||||
* 환경에서는 skip.
|
||||
@@ -109,6 +109,9 @@ PHP);
|
||||
/**
|
||||
* 자식 프로세스가 정상 완료(exit 0)되면 spawn 은 true 를 반환한다.
|
||||
* Handoff 파싱 로직이 정상 경로를 손상시키지 않는지 회귀 가드.
|
||||
*
|
||||
* 본 테스트는 실 step 1건이 실행되는 시나리오 — `spawn_failure_mode` 의 silent skip 가드
|
||||
* (step 0건 차단) 을 통과하기 위해 동일 버전 + --force 로 무해한 step 1건만 실행시킨다.
|
||||
*/
|
||||
public function test_spawn_returns_true_on_normal_exit(): void
|
||||
{
|
||||
@@ -116,12 +119,28 @@ PHP);
|
||||
$this->markTestSkipped('proc_open 미지원 환경');
|
||||
}
|
||||
|
||||
// upgrade 파일 없이 실행 → runUpgradeSteps 가 조용히 no-op → exit 0
|
||||
File::put($this->handoffStepPath, <<<'PHP'
|
||||
<?php
|
||||
|
||||
namespace App\Upgrades;
|
||||
|
||||
use App\Contracts\Extension\UpgradeStepInterface;
|
||||
use App\Extension\UpgradeContext;
|
||||
|
||||
class Upgrade_0_0_1_test_integration_handoff implements UpgradeStepInterface
|
||||
{
|
||||
public function run(UpgradeContext $context): void
|
||||
{
|
||||
// no-op — step 1건 실행되도록만 보장
|
||||
}
|
||||
}
|
||||
PHP);
|
||||
|
||||
$command = $this->makeCommandWithDummyIo();
|
||||
$method = new \ReflectionMethod(CoreUpdateCommand::class, 'spawnUpgradeStepsProcess');
|
||||
$method->setAccessible(true);
|
||||
|
||||
$result = $method->invoke($command, '9.9.8', '9.9.9', true, fn () => null);
|
||||
$result = $method->invoke($command, '0.0.0', '0.0.1', true, fn () => null);
|
||||
|
||||
$this->assertTrue($result, '정상 종료 시 true 반환해야 한다');
|
||||
}
|
||||
@@ -129,6 +148,9 @@ PHP);
|
||||
/**
|
||||
* 자식 프로세스가 일반 실패(exit != 0, != 75)면 spawn 은 false 를 반환하여
|
||||
* 상위 호출자가 in-process fallback 경로로 전환할 수 있게 한다.
|
||||
*
|
||||
* 본 회귀 가드는 `spawn_failure_mode=fallback` 의 호환 모드 동작을 검증한다.
|
||||
* 기본 abort 모드 동작은 `CoreUpdateCommandSpawnFailureTest` 가 별도로 검증한다.
|
||||
*/
|
||||
public function test_spawn_returns_false_on_generic_failure(): void
|
||||
{
|
||||
@@ -136,6 +158,8 @@ PHP);
|
||||
$this->markTestSkipped('proc_open 미지원 환경');
|
||||
}
|
||||
|
||||
config(['app.update.spawn_failure_mode' => 'fallback']);
|
||||
|
||||
File::put($this->failingStepPath, <<<'PHP'
|
||||
<?php
|
||||
|
||||
@@ -210,6 +234,106 @@ PHP);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* isValidHandoffPayload — 빈 afterVersion 거부.
|
||||
*
|
||||
* 회귀 시나리오: 자식 stdout 의 [HANDOFF] 라인이 `afterVersion=""` 으로 도착하면
|
||||
* Step 11 fromVersion 해석이 혼란스러워진다 (CoreUpdateCommand catch 분기의 sprintf
|
||||
* 자동 생성에서도 비정상 명령어 출력). 검증 거부 후 정상 출력으로 fall through.
|
||||
*/
|
||||
public function test_isValidHandoffPayload_rejects_empty_after_version(): void
|
||||
{
|
||||
$command = app(CoreUpdateCommand::class);
|
||||
$method = new \ReflectionMethod(CoreUpdateCommand::class, 'isValidHandoffPayload');
|
||||
$method->setAccessible(true);
|
||||
|
||||
$this->assertFalse($method->invoke($command, [
|
||||
'afterVersion' => '',
|
||||
'reason' => '정상 사유',
|
||||
'resumeCommand' => null,
|
||||
]));
|
||||
|
||||
$this->assertFalse($method->invoke($command, [
|
||||
'afterVersion' => 'not-a-version',
|
||||
'reason' => '정상 사유',
|
||||
'resumeCommand' => null,
|
||||
]));
|
||||
|
||||
$this->assertTrue($method->invoke($command, [
|
||||
'afterVersion' => '7.0.0-beta.4',
|
||||
'reason' => '정상 사유',
|
||||
'resumeCommand' => null,
|
||||
]));
|
||||
}
|
||||
|
||||
/**
|
||||
* isValidHandoffPayload — reason 과도 길이 거부.
|
||||
*
|
||||
* 회귀 시나리오: 자식이 비정상적으로 긴 reason 문자열을 보내면 부모 로그 / 운영자
|
||||
* 안내 출력이 폭증한다. 500자 이상은 비정상으로 간주하고 거부.
|
||||
*/
|
||||
public function test_isValidHandoffPayload_rejects_oversized_reason(): void
|
||||
{
|
||||
$command = app(CoreUpdateCommand::class);
|
||||
$method = new \ReflectionMethod(CoreUpdateCommand::class, 'isValidHandoffPayload');
|
||||
$method->setAccessible(true);
|
||||
|
||||
$this->assertFalse($method->invoke($command, [
|
||||
'afterVersion' => '7.0.0-beta.4',
|
||||
'reason' => str_repeat('a', 500),
|
||||
'resumeCommand' => null,
|
||||
]));
|
||||
|
||||
$this->assertTrue($method->invoke($command, [
|
||||
'afterVersion' => '7.0.0-beta.4',
|
||||
'reason' => str_repeat('a', 499),
|
||||
'resumeCommand' => null,
|
||||
]));
|
||||
}
|
||||
|
||||
/**
|
||||
* isValidHandoffPayload — resumeCommand shell metacharacter / 과도 길이 거부.
|
||||
*
|
||||
* 회귀 시나리오: 자식이 손상되거나 악의적으로 조작된 resumeCommand 를 보내면
|
||||
* 부모가 운영자 안내에 shell injection 문자열을 출력. 정상 명령(`php artisan ...`)
|
||||
* 에 등장하지 않는 metacharacter 가 포함되면 거부.
|
||||
*/
|
||||
public function test_isValidHandoffPayload_rejects_shell_metacharacters_in_resume_command(): void
|
||||
{
|
||||
$command = app(CoreUpdateCommand::class);
|
||||
$method = new \ReflectionMethod(CoreUpdateCommand::class, 'isValidHandoffPayload');
|
||||
$method->setAccessible(true);
|
||||
|
||||
foreach (['; rm -rf /', '`whoami`', '$(id)', 'php a && php b', 'php a | tee x', 'php a > x'] as $bad) {
|
||||
$this->assertFalse(
|
||||
$method->invoke($command, [
|
||||
'afterVersion' => '7.0.0-beta.4',
|
||||
'reason' => '정상 사유',
|
||||
'resumeCommand' => $bad,
|
||||
]),
|
||||
"shell metacharacter 가 포함된 resumeCommand 거부: {$bad}",
|
||||
);
|
||||
}
|
||||
|
||||
$this->assertFalse($method->invoke($command, [
|
||||
'afterVersion' => '7.0.0-beta.4',
|
||||
'reason' => '정상 사유',
|
||||
'resumeCommand' => str_repeat('a', 1000),
|
||||
]));
|
||||
|
||||
$this->assertTrue($method->invoke($command, [
|
||||
'afterVersion' => '7.0.0-beta.4',
|
||||
'reason' => '정상 사유',
|
||||
'resumeCommand' => 'php artisan core:update --force --from=7.0.0-beta.4',
|
||||
]));
|
||||
|
||||
$this->assertTrue($method->invoke($command, [
|
||||
'afterVersion' => '7.0.0-beta.4',
|
||||
'reason' => '정상 사유',
|
||||
'resumeCommand' => null,
|
||||
]));
|
||||
}
|
||||
|
||||
/**
|
||||
* CoreUpdateCommand 를 OutputStyle 주입 없이 리플렉션 호출 가능한 형태로 준비.
|
||||
* spawnUpgradeStepsProcess 내부에서 $this->line / $this->info 를 호출하므로
|
||||
|
||||
@@ -0,0 +1,333 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Console;
|
||||
|
||||
use App\Console\Commands\Core\CoreUpdateCommand;
|
||||
use App\Exceptions\UpgradeHandoffException;
|
||||
use App\Services\CoreUpdateService;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* `spawn_failure_mode` + `[STEPS_EXECUTED]` 신호 + stale 메모리 가드 회귀 테스트 (§2/§2.1/§6).
|
||||
*
|
||||
* 회귀 시나리오 (이슈 #28):
|
||||
* - spawn 자식 실패 → in-process fallback 진입 → 부모 메모리 stale → upgrade step
|
||||
* 안에서 신규 메서드 호출 fatal (예: `Call to undefined method ensureWritableDirectories()`)
|
||||
*
|
||||
* 본 테스트는 `spawnUpgradeStepsProcess` 의 mode 분기 + `failSpawnWithMode` + 자식의
|
||||
* `[STEPS_EXECUTED]` 발행 + `runUpgradeSteps` 의 stale 메모리 가드를 단위 수준에서 검증한다.
|
||||
* 실제 `core:update` 통합 흐름은 운영자의 Linux 서버 수동 검증 (계획서 §"통합 시나리오") 으로 보완.
|
||||
*/
|
||||
class CoreUpdateCommandSpawnFailureTest extends TestCase
|
||||
{
|
||||
private string $failingStepPath;
|
||||
|
||||
private string $silentStepPath;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->failingStepPath = base_path('upgrades/Upgrade_0_0_1_test_spawn_failure_fail.php');
|
||||
$this->silentStepPath = base_path('upgrades/Upgrade_0_0_1_test_spawn_failure_silent.php');
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
foreach ([$this->failingStepPath, $this->silentStepPath] as $p) {
|
||||
if (File::exists($p)) {
|
||||
File::delete($p);
|
||||
}
|
||||
}
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function failSpawnWithMode_abort_모드는_UpgradeHandoffException_을_throw_한다(): void
|
||||
{
|
||||
config(['app.update.spawn_failure_mode' => 'abort']);
|
||||
|
||||
$command = $this->makeCommandWithDummyIo();
|
||||
$method = new \ReflectionMethod(CoreUpdateCommand::class, 'failSpawnWithMode');
|
||||
$method->setAccessible(true);
|
||||
|
||||
try {
|
||||
$method->invoke($command, '테스트 사유', fn () => null, '7.0.0-beta.3', '7.0.0-beta.5');
|
||||
$this->fail('mode=abort 일 때 UpgradeHandoffException 이 throw 되어야 한다');
|
||||
} catch (UpgradeHandoffException $e) {
|
||||
$this->assertSame('7.0.0-beta.3', $e->afterVersion);
|
||||
$this->assertStringContainsString('테스트 사유', $e->reason);
|
||||
$this->assertStringContainsString('fail-fast', $e->reason);
|
||||
$this->assertNotNull($e->resumeCommand);
|
||||
$this->assertStringContainsString('core:execute-upgrade-steps', $e->resumeCommand);
|
||||
$this->assertStringContainsString('--from=7.0.0-beta.3', $e->resumeCommand);
|
||||
$this->assertStringContainsString('--to=7.0.0-beta.5', $e->resumeCommand);
|
||||
}
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function failSpawnWithMode_fallback_모드는_false_를_반환한다(): void
|
||||
{
|
||||
config(['app.update.spawn_failure_mode' => 'fallback']);
|
||||
|
||||
$command = $this->makeCommandWithDummyIo();
|
||||
$method = new \ReflectionMethod(CoreUpdateCommand::class, 'failSpawnWithMode');
|
||||
$method->setAccessible(true);
|
||||
|
||||
$logs = [];
|
||||
$result = $method->invoke(
|
||||
$command,
|
||||
'테스트 사유',
|
||||
function (string $msg) use (&$logs): void {
|
||||
$logs[] = $msg;
|
||||
},
|
||||
'7.0.0-beta.3',
|
||||
'7.0.0-beta.5',
|
||||
);
|
||||
|
||||
$this->assertFalse($result, 'fallback 모드는 false 반환 (in-process fallback 진입)');
|
||||
$this->assertNotEmpty($logs, '로그 기록 필요');
|
||||
$allLogs = implode("\n", $logs);
|
||||
$this->assertStringContainsString('테스트 사유', $allLogs);
|
||||
$this->assertStringContainsString('stale 메모리 위험', $allLogs);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function spawn_자식_silent_skip_시_abort_모드는_throw_한다(): void
|
||||
{
|
||||
if (! function_exists('proc_open')) {
|
||||
$this->markTestSkipped('proc_open 미지원 환경');
|
||||
}
|
||||
|
||||
// upgrade 파일 없이 호출 → 자식은 [STEPS_EXECUTED] count=0 발행 + exit=0
|
||||
// from < to 인 상태에서 0건 실행은 비정상 → mode=abort 시 throw
|
||||
config(['app.update.spawn_failure_mode' => 'abort']);
|
||||
|
||||
$command = $this->makeCommandWithDummyIo();
|
||||
$method = new \ReflectionMethod(CoreUpdateCommand::class, 'spawnUpgradeStepsProcess');
|
||||
$method->setAccessible(true);
|
||||
|
||||
try {
|
||||
$method->invoke($command, '9.9.8', '9.9.9', true, fn () => null);
|
||||
$this->fail('step 0건 실행 시 mode=abort 에서 throw 되어야 한다');
|
||||
} catch (UpgradeHandoffException $e) {
|
||||
$this->assertStringContainsString('step 0건 실행', $e->reason);
|
||||
$this->assertSame('9.9.8', $e->afterVersion);
|
||||
}
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function spawn_자식_silent_skip_시_fallback_모드는_false_반환한다(): void
|
||||
{
|
||||
if (! function_exists('proc_open')) {
|
||||
$this->markTestSkipped('proc_open 미지원 환경');
|
||||
}
|
||||
|
||||
config(['app.update.spawn_failure_mode' => 'fallback']);
|
||||
|
||||
$command = $this->makeCommandWithDummyIo();
|
||||
$method = new \ReflectionMethod(CoreUpdateCommand::class, 'spawnUpgradeStepsProcess');
|
||||
$method->setAccessible(true);
|
||||
|
||||
$result = $method->invoke($command, '9.9.8', '9.9.9', true, fn () => null);
|
||||
|
||||
$this->assertFalse($result, 'mode=fallback 에서 step 0건 실행은 false 반환');
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function spawn_자식_정상_종료_시_STEPS_EXECUTED_파싱_후_true_반환한다(): void
|
||||
{
|
||||
if (! function_exists('proc_open')) {
|
||||
$this->markTestSkipped('proc_open 미지원 환경');
|
||||
}
|
||||
|
||||
config(['app.update.spawn_failure_mode' => 'abort']);
|
||||
|
||||
// 실제 step 1건이 실행되는 시나리오 — fromVersion == toVersion + --force 로
|
||||
// 동일 버전 step 만 실행되게 함. but no test step exists → 0건. 회피하려면
|
||||
// 실제 step 파일을 생성:
|
||||
File::put($this->silentStepPath, <<<'PHP'
|
||||
<?php
|
||||
|
||||
namespace App\Upgrades;
|
||||
|
||||
use App\Contracts\Extension\UpgradeStepInterface;
|
||||
use App\Extension\UpgradeContext;
|
||||
|
||||
class Upgrade_0_0_1_test_spawn_failure_silent implements UpgradeStepInterface
|
||||
{
|
||||
public function run(UpgradeContext $context): void
|
||||
{
|
||||
// no-op step — count 가 1 이 되도록만 보장
|
||||
}
|
||||
}
|
||||
PHP);
|
||||
|
||||
$command = $this->makeCommandWithDummyIo();
|
||||
$method = new \ReflectionMethod(CoreUpdateCommand::class, 'spawnUpgradeStepsProcess');
|
||||
$method->setAccessible(true);
|
||||
|
||||
$logs = [];
|
||||
$log = function (string $msg) use (&$logs): void {
|
||||
$logs[] = $msg;
|
||||
};
|
||||
|
||||
$result = $method->invoke($command, '0.0.0', '0.0.1', true, $log);
|
||||
|
||||
$this->assertTrue($result, '정상 step 실행 시 spawn 성공');
|
||||
|
||||
$allLogs = implode("\n", $logs);
|
||||
$this->assertStringContainsString('실행된 step 수: 1', $allLogs, 'STEPS_EXECUTED 파싱 결과 로그');
|
||||
$this->assertStringContainsString('steps=1', $allLogs, '최종 spawn 완료 로그에 step 수 포함');
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function spawn_자식_비정상_종료_시_abort_모드는_throw_한다(): void
|
||||
{
|
||||
if (! function_exists('proc_open')) {
|
||||
$this->markTestSkipped('proc_open 미지원 환경');
|
||||
}
|
||||
|
||||
config(['app.update.spawn_failure_mode' => 'abort']);
|
||||
|
||||
File::put($this->failingStepPath, <<<'PHP'
|
||||
<?php
|
||||
|
||||
namespace App\Upgrades;
|
||||
|
||||
use App\Contracts\Extension\UpgradeStepInterface;
|
||||
use App\Extension\UpgradeContext;
|
||||
|
||||
class Upgrade_0_0_1_test_spawn_failure_fail implements UpgradeStepInterface
|
||||
{
|
||||
public function run(UpgradeContext $context): void
|
||||
{
|
||||
throw new \RuntimeException('자식 비정상 종료 테스트');
|
||||
}
|
||||
}
|
||||
PHP);
|
||||
|
||||
$command = $this->makeCommandWithDummyIo();
|
||||
$method = new \ReflectionMethod(CoreUpdateCommand::class, 'spawnUpgradeStepsProcess');
|
||||
$method->setAccessible(true);
|
||||
|
||||
try {
|
||||
$method->invoke($command, '0.0.0', '0.0.1', true, fn () => null);
|
||||
$this->fail('비정상 종료 시 mode=abort 에서 throw 되어야 한다');
|
||||
} catch (UpgradeHandoffException $e) {
|
||||
$this->assertStringContainsString('spawn 비정상 종료', $e->reason);
|
||||
$this->assertSame('0.0.0', $e->afterVersion);
|
||||
}
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function spawn_자식_비정상_종료_시_fallback_모드는_false_반환한다(): void
|
||||
{
|
||||
if (! function_exists('proc_open')) {
|
||||
$this->markTestSkipped('proc_open 미지원 환경');
|
||||
}
|
||||
|
||||
config(['app.update.spawn_failure_mode' => 'fallback']);
|
||||
|
||||
File::put($this->failingStepPath, <<<'PHP'
|
||||
<?php
|
||||
|
||||
namespace App\Upgrades;
|
||||
|
||||
use App\Contracts\Extension\UpgradeStepInterface;
|
||||
use App\Extension\UpgradeContext;
|
||||
|
||||
class Upgrade_0_0_1_test_spawn_failure_fail implements UpgradeStepInterface
|
||||
{
|
||||
public function run(UpgradeContext $context): void
|
||||
{
|
||||
throw new \RuntimeException('자식 비정상 종료 테스트');
|
||||
}
|
||||
}
|
||||
PHP);
|
||||
|
||||
$command = $this->makeCommandWithDummyIo();
|
||||
$method = new \ReflectionMethod(CoreUpdateCommand::class, 'spawnUpgradeStepsProcess');
|
||||
$method->setAccessible(true);
|
||||
|
||||
$result = $method->invoke($command, '0.0.0', '0.0.1', true, fn () => null);
|
||||
|
||||
$this->assertFalse($result, 'fallback 모드는 false 반환');
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function runUpgradeSteps_stale_메모리_감지_시_abort_throw_한다(): void
|
||||
{
|
||||
config(['app.version' => '7.0.0-beta.3']);
|
||||
config(['app.update.spawn_failure_mode' => 'abort']);
|
||||
|
||||
$service = app(CoreUpdateService::class);
|
||||
|
||||
try {
|
||||
$service->runUpgradeSteps('7.0.0-beta.3', '7.0.0-beta.5');
|
||||
$this->fail('stale 메모리 감지 시 UpgradeHandoffException 이 throw 되어야 한다');
|
||||
} catch (UpgradeHandoffException $e) {
|
||||
$this->assertSame('7.0.0-beta.3', $e->afterVersion);
|
||||
$this->assertStringContainsString('stale', $e->reason);
|
||||
$this->assertStringContainsString('memory=7.0.0-beta.3', $e->reason);
|
||||
$this->assertStringContainsString('target=7.0.0-beta.5', $e->reason);
|
||||
}
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function runUpgradeSteps_stale_메모리_감지_시_fallback_은_경고_후_진행한다(): void
|
||||
{
|
||||
config(['app.version' => '7.0.0-beta.3']);
|
||||
config(['app.update.spawn_failure_mode' => 'fallback']);
|
||||
|
||||
$service = app(CoreUpdateService::class);
|
||||
|
||||
// step 파일 없으면 stale 가드 통과 후 silent return — 예외 미발생 확인
|
||||
$service->runUpgradeSteps('7.0.0-beta.3', '7.0.0-beta.5');
|
||||
|
||||
// 예외 없이 도달하면 성공 — fallback 모드는 throw 하지 않고 step 실행으로 진입
|
||||
$this->assertTrue(true);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function runUpgradeSteps_memory_가_target_과_동일하면_가드_미발동(): void
|
||||
{
|
||||
config(['app.version' => '7.0.0-beta.5']);
|
||||
config(['app.update.spawn_failure_mode' => 'abort']);
|
||||
|
||||
$service = app(CoreUpdateService::class);
|
||||
|
||||
// spawn 자식 시나리오: 메모리 = target → 가드 무관 → step 파일 없으면 silent return
|
||||
$service->runUpgradeSteps('7.0.0-beta.3', '7.0.0-beta.5');
|
||||
|
||||
$this->assertTrue(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* CoreUpdateCommand 를 OutputStyle 주입 없이 리플렉션 호출 가능한 형태로 준비.
|
||||
*/
|
||||
private function makeCommandWithDummyIo(): CoreUpdateCommand
|
||||
{
|
||||
$command = app(CoreUpdateCommand::class);
|
||||
|
||||
$input = new \Symfony\Component\Console\Input\ArrayInput([]);
|
||||
$output = new \Symfony\Component\Console\Output\BufferedOutput;
|
||||
$style = new \Illuminate\Console\OutputStyle($input, $output);
|
||||
|
||||
$reflection = new \ReflectionClass($command);
|
||||
$property = $reflection->getProperty('output');
|
||||
$property->setAccessible(true);
|
||||
$property->setValue($command, $style);
|
||||
|
||||
if ($reflection->hasProperty('input')) {
|
||||
$inputProp = $reflection->getProperty('input');
|
||||
$inputProp->setAccessible(true);
|
||||
$inputProp->setValue($command, $input);
|
||||
}
|
||||
|
||||
return $command;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Identity;
|
||||
|
||||
use App\Contracts\Extension\IdentityVerificationInterface;
|
||||
use App\Enums\IdentityPolicySourceType;
|
||||
use App\Extension\IdentityVerification\DTO\VerificationChallenge;
|
||||
use App\Extension\IdentityVerification\DTO\VerificationResult;
|
||||
use App\Extension\IdentityVerification\IdentityVerificationManager;
|
||||
use App\Listeners\Identity\InitiateIdentityChallengeAfterRegister;
|
||||
use App\Models\IdentityPolicy;
|
||||
use App\Models\User;
|
||||
use App\Services\IdentityPolicyService;
|
||||
use App\Services\IdentityVerificationService;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* IDV provider 해석 우선순위 매트릭스 (refs #275).
|
||||
*
|
||||
* Mode A (Controller / Service::start providerId 명시) 와
|
||||
* Mode B (signup_after_create 정책 → Listener → Service::start) 양쪽에서
|
||||
* 호출자 명시 provider_id 가 settings/default 보다 우선되는지 검증.
|
||||
*
|
||||
* Manager 단위 우선순위는 Unit 테스트 (IdentityVerificationManagerTest) 가 커버하며,
|
||||
* 본 Feature 테스트는 Service / Listener / 정책을 거치는 통합 흐름을 검증한다.
|
||||
*
|
||||
* 시나리오 매니페스트: tests/scenarios/identity-provider-resolution.yaml
|
||||
*/
|
||||
class IdentityProviderResolutionTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 정책 흐름 통합 검증을 위한 fake provider 들.
|
||||
* 매 테스트마다 등록 후 tearDown 에서 정리.
|
||||
*/
|
||||
private IdentityVerificationInterface $mailProvider;
|
||||
|
||||
private IdentityVerificationInterface $externalProvider;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
// HookManager::resetAll() 호출 금지 — 코어 ServiceProvider 가 부트 시 등록한
|
||||
// listener (CoreActivityLogListener 등) 도 함께 날아가 다른 테스트에 누수된다.
|
||||
// provider 등록/해제만으로 본 매트릭스 격리는 충분하다.
|
||||
|
||||
$this->mailProvider = $this->makeFakeProvider('g7:core.mail');
|
||||
$this->externalProvider = $this->makeFakeProvider('plugin:fake_external');
|
||||
|
||||
/** @var IdentityVerificationManager $manager */
|
||||
$manager = $this->app->make(IdentityVerificationManager::class);
|
||||
$manager->register($this->mailProvider);
|
||||
$manager->register($this->externalProvider);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
/** @var IdentityVerificationManager $manager */
|
||||
$manager = $this->app->make(IdentityVerificationManager::class);
|
||||
$manager->unregister('g7:core.mail');
|
||||
$manager->unregister('plugin:fake_external');
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* Mode A: Service::start 에 명시한 providerId 가 Manager 해석에 그대로 반영.
|
||||
*/
|
||||
public function test_mode_a_explicit_provider_id_is_used_for_challenge(): void
|
||||
{
|
||||
/** @var IdentityVerificationService $service */
|
||||
$service = $this->app->make(IdentityVerificationService::class);
|
||||
|
||||
$challenge = $service->start(
|
||||
purpose: 'signup',
|
||||
target: ['email' => 'a@example.com'],
|
||||
context: ['ip_address' => '127.0.0.1'],
|
||||
providerId: 'plugin:fake_external',
|
||||
);
|
||||
|
||||
$this->assertSame('plugin:fake_external', $challenge->providerId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mode A: providerId = null 이면 Manager fallback (default = g7:core.mail).
|
||||
*/
|
||||
public function test_mode_a_null_provider_id_falls_back_to_default(): void
|
||||
{
|
||||
/** @var IdentityVerificationService $service */
|
||||
$service = $this->app->make(IdentityVerificationService::class);
|
||||
|
||||
$challenge = $service->start(
|
||||
purpose: 'signup',
|
||||
target: ['email' => 'a@example.com'],
|
||||
context: ['ip_address' => '127.0.0.1'],
|
||||
);
|
||||
|
||||
$this->assertSame('g7:core.mail', $challenge->providerId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mode A: 미등록 providerId 도 silent fallback (예외 throw 없음).
|
||||
*/
|
||||
public function test_mode_a_unregistered_provider_id_falls_back_silently(): void
|
||||
{
|
||||
/** @var IdentityVerificationService $service */
|
||||
$service = $this->app->make(IdentityVerificationService::class);
|
||||
|
||||
$challenge = $service->start(
|
||||
purpose: 'signup',
|
||||
target: ['email' => 'a@example.com'],
|
||||
context: ['ip_address' => '127.0.0.1'],
|
||||
providerId: 'plugin:nonexistent',
|
||||
);
|
||||
|
||||
$this->assertSame('g7:core.mail', $challenge->providerId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mode A: 등록되었지만 해당 purpose 미지원인 provider 도 silent fallback.
|
||||
*
|
||||
* 운영자가 정책/요청에 plugin:password_only 를 지정했지만 그 provider 가 signup 을 지원하지
|
||||
* 않는 경우, 예외 대신 mail (코어 기본) 로 fallback 되어야 한다.
|
||||
*/
|
||||
public function test_mode_a_provider_not_supporting_purpose_falls_back_silently(): void
|
||||
{
|
||||
// signup 은 지원하지 않고 password_reset 만 지원하는 가짜 provider 추가 등록.
|
||||
$passwordOnly = $this->makeFakeProvider('plugin:password_only', supportedPurposes: ['password_reset']);
|
||||
/** @var IdentityVerificationManager $manager */
|
||||
$manager = $this->app->make(IdentityVerificationManager::class);
|
||||
$manager->register($passwordOnly);
|
||||
|
||||
try {
|
||||
/** @var IdentityVerificationService $service */
|
||||
$service = $this->app->make(IdentityVerificationService::class);
|
||||
|
||||
$challenge = $service->start(
|
||||
purpose: 'signup',
|
||||
target: ['email' => 'a@example.com'],
|
||||
context: ['ip_address' => '127.0.0.1'],
|
||||
providerId: 'plugin:password_only',
|
||||
);
|
||||
|
||||
$this->assertSame(
|
||||
'g7:core.mail',
|
||||
$challenge->providerId,
|
||||
'signup 을 지원하지 않는 명시 provider 는 silent fallback 되어 mail 이 선택되어야 한다',
|
||||
);
|
||||
} finally {
|
||||
$manager->unregister('plugin:password_only');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mode B: signup_after_create 정책의 provider_id 가 Listener → Service::start → Manager 로 전파.
|
||||
*
|
||||
* AuthService 전체 가입 흐름 대신 Listener::handle 을 직접 호출하여
|
||||
* provider_id 전파만 검증한다 (가입 흐름 검증은 Auth 도메인 테스트 책임).
|
||||
*/
|
||||
public function test_mode_b_policy_provider_id_propagates_through_listener(): void
|
||||
{
|
||||
$policy = $this->createSignupAfterCreatePolicy('plugin:fake_external');
|
||||
$user = $this->createUser();
|
||||
|
||||
/** @var IdentityVerificationService $service */
|
||||
$service = $this->app->make(IdentityVerificationService::class);
|
||||
/** @var IdentityPolicyService $policyService */
|
||||
$policyService = $this->app->make(IdentityPolicyService::class);
|
||||
|
||||
$listener = new InitiateIdentityChallengeAfterRegister($service, $policyService);
|
||||
$listener->handle($user, [
|
||||
'signup_stage' => 'after_create',
|
||||
'ip_address' => '127.0.0.1',
|
||||
'user_agent' => 'phpunit',
|
||||
]);
|
||||
|
||||
$log = \App\Models\IdentityVerificationLog::query()
|
||||
->where('user_id', $user->id)
|
||||
->orderByDesc('id')
|
||||
->first();
|
||||
|
||||
$this->assertNotNull($log, '정책이 enabled 면 challenge log 가 생성되어야 함');
|
||||
$this->assertSame('plugin:fake_external', $log->provider_id);
|
||||
|
||||
unset($policy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mode B: 정책 provider_id = null 이면 Manager fallback (BC).
|
||||
*/
|
||||
public function test_mode_b_null_policy_provider_id_falls_back_to_default(): void
|
||||
{
|
||||
$this->createSignupAfterCreatePolicy(null);
|
||||
$user = $this->createUser();
|
||||
|
||||
/** @var IdentityVerificationService $service */
|
||||
$service = $this->app->make(IdentityVerificationService::class);
|
||||
/** @var IdentityPolicyService $policyService */
|
||||
$policyService = $this->app->make(IdentityPolicyService::class);
|
||||
|
||||
$listener = new InitiateIdentityChallengeAfterRegister($service, $policyService);
|
||||
$listener->handle($user, [
|
||||
'signup_stage' => 'after_create',
|
||||
'ip_address' => '127.0.0.1',
|
||||
'user_agent' => 'phpunit',
|
||||
]);
|
||||
|
||||
$log = \App\Models\IdentityVerificationLog::query()
|
||||
->where('user_id', $user->id)
|
||||
->orderByDesc('id')
|
||||
->first();
|
||||
|
||||
$this->assertNotNull($log);
|
||||
$this->assertSame('g7:core.mail', $log->provider_id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mode B: 정책 disabled 면 challenge 발행 자체 미수행 (BC 회귀 차단).
|
||||
*/
|
||||
public function test_mode_b_disabled_policy_skips_challenge(): void
|
||||
{
|
||||
$this->createSignupAfterCreatePolicy('plugin:fake_external', enabled: false);
|
||||
$user = $this->createUser();
|
||||
|
||||
/** @var IdentityVerificationService $service */
|
||||
$service = $this->app->make(IdentityVerificationService::class);
|
||||
/** @var IdentityPolicyService $policyService */
|
||||
$policyService = $this->app->make(IdentityPolicyService::class);
|
||||
|
||||
$listener = new InitiateIdentityChallengeAfterRegister($service, $policyService);
|
||||
$listener->handle($user, [
|
||||
'signup_stage' => 'after_create',
|
||||
'ip_address' => '127.0.0.1',
|
||||
'user_agent' => 'phpunit',
|
||||
]);
|
||||
|
||||
$count = \App\Models\IdentityVerificationLog::query()
|
||||
->where('user_id', $user->id)
|
||||
->count();
|
||||
|
||||
$this->assertSame(0, $count);
|
||||
}
|
||||
|
||||
/**
|
||||
* signup_after_create 정책을 DB 에 생성.
|
||||
*/
|
||||
private function createSignupAfterCreatePolicy(?string $providerId, bool $enabled = true): IdentityPolicy
|
||||
{
|
||||
return IdentityPolicy::query()->updateOrCreate(
|
||||
['key' => 'core.auth.signup_after_create'],
|
||||
[
|
||||
'scope' => 'hook',
|
||||
'target' => 'core.auth.after_register',
|
||||
'purpose' => 'signup',
|
||||
'provider_id' => $providerId,
|
||||
'enabled' => $enabled,
|
||||
'applies_to' => 'self',
|
||||
'fail_mode' => 'block',
|
||||
'grace_minutes' => 0,
|
||||
'priority' => 100,
|
||||
'conditions' => null,
|
||||
'source_type' => IdentityPolicySourceType::Core,
|
||||
'source_identifier' => 'core',
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트용 활성 사용자를 생성합니다.
|
||||
*/
|
||||
private function createUser(): User
|
||||
{
|
||||
return User::factory()->create([
|
||||
'email' => 'a@example.com',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 purpose (또는 일부 purpose) 를 지원하는 간단한 fake provider.
|
||||
*
|
||||
* @param string $id provider 식별자
|
||||
* @param array<int, string>|null $supportedPurposes null 이면 모든 purpose 지원, 배열이면 해당 항목만 지원
|
||||
*/
|
||||
private function makeFakeProvider(string $id, ?array $supportedPurposes = null): IdentityVerificationInterface
|
||||
{
|
||||
return new class($id, $supportedPurposes) implements IdentityVerificationInterface
|
||||
{
|
||||
/**
|
||||
* @param array<int, string>|null $supportedPurposes
|
||||
*/
|
||||
public function __construct(private string $id, private ?array $supportedPurposes = null) {}
|
||||
|
||||
public function getId(): string
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getChannels(): array
|
||||
{
|
||||
return ['email'];
|
||||
}
|
||||
|
||||
public function getRenderHint(): string
|
||||
{
|
||||
return 'text_code';
|
||||
}
|
||||
|
||||
public function supportsPurpose(string $purpose): bool
|
||||
{
|
||||
if ($this->supportedPurposes === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return in_array($purpose, $this->supportedPurposes, true);
|
||||
}
|
||||
|
||||
public function isAvailable(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function requestChallenge(User|array $target, array $context = []): VerificationChallenge
|
||||
{
|
||||
$targetHash = is_array($target) && ! empty($target['email'])
|
||||
? hash('sha256', mb_strtolower((string) $target['email']))
|
||||
: ($target instanceof User
|
||||
? hash('sha256', mb_strtolower((string) $target->email))
|
||||
: str_repeat('0', 64));
|
||||
|
||||
$userId = $target instanceof User ? $target->id : null;
|
||||
|
||||
$log = \App\Models\IdentityVerificationLog::query()->create([
|
||||
'provider_id' => $this->id,
|
||||
'purpose' => $context['purpose'] ?? 'signup',
|
||||
'channel' => 'email',
|
||||
'target_hash' => $targetHash,
|
||||
'user_id' => $userId,
|
||||
'status' => \App\Enums\IdentityVerificationStatus::Sent->value,
|
||||
'expires_at' => Carbon::now()->addMinutes(15),
|
||||
'origin_type' => $context['origin_type'] ?? null,
|
||||
'origin_identifier' => $context['origin_identifier'] ?? null,
|
||||
'origin_policy_key' => $context['origin_policy_key'] ?? null,
|
||||
'metadata' => [],
|
||||
'properties' => [],
|
||||
]);
|
||||
|
||||
return new VerificationChallenge(
|
||||
id: (string) $log->id,
|
||||
providerId: $this->id,
|
||||
purpose: $context['purpose'] ?? 'signup',
|
||||
channel: 'email',
|
||||
targetHash: $targetHash,
|
||||
expiresAt: $log->expires_at,
|
||||
renderHint: 'text_code',
|
||||
);
|
||||
}
|
||||
|
||||
public function verify(string $challengeId, array $input, array $context = []): VerificationResult
|
||||
{
|
||||
return VerificationResult::success(
|
||||
challengeId: $challengeId,
|
||||
providerId: $this->id,
|
||||
verifiedAt: Carbon::now(),
|
||||
);
|
||||
}
|
||||
|
||||
public function cancel(string $challengeId): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function getSettingsSchema(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function withConfig(array $config): static
|
||||
{
|
||||
return $this;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -115,7 +115,12 @@ class NamespaceMergeRegressionTest extends TestCase
|
||||
$this->assertInstanceOf(LanguagePackTranslator::class, $translator);
|
||||
|
||||
// 모듈 자체 src/lang 등록을 시뮬레이션 (TranslationServiceProvider 가 부팅 시 수행하는 작업)
|
||||
$translator->addNamespace('sirsoft-ecommerce', base_path('modules/sirsoft-ecommerce/src/lang'));
|
||||
// 활성 디렉토리 우선, 없으면 _bundled 로 폴백 (테스트 환경에서 ecommerce 미설치인 경우 대비)
|
||||
$ecommerceLangPath = base_path('modules/sirsoft-ecommerce/src/lang');
|
||||
if (! is_dir($ecommerceLangPath)) {
|
||||
$ecommerceLangPath = base_path('modules/_bundled/sirsoft-ecommerce/src/lang');
|
||||
}
|
||||
$translator->addNamespace('sirsoft-ecommerce', $ecommerceLangPath);
|
||||
|
||||
// 언어팩 fallback 등록 (LanguagePackServiceProvider::registerActivePack 가 수행)
|
||||
$translator->addNamespaceFallbackPath(
|
||||
|
||||
@@ -12,7 +12,7 @@ use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 언어팩 시스템 PO 8대 요구사항 정합성 검증 통합 테스트.
|
||||
* 언어팩 시스템 8대 요구사항 정합성 검증 통합 테스트.
|
||||
*
|
||||
* 본 테스트는 abstract-foraging-pony.md 계획서의 §1~§7 핵심 동작을
|
||||
* 한 파일로 통합 검증합니다. 도메인 매트릭스: Pure Logic + CRUD 혼합.
|
||||
@@ -22,7 +22,7 @@ class PolicyAlignmentTest extends TestCase
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* PO #1, #2: base locale 판정 헬퍼 동작 검증.
|
||||
* 요구사항 #1, #2: base locale 판정 헬퍼 동작 검증.
|
||||
*/
|
||||
public function test_base_locale_helper_recognizes_ko_en_only(): void
|
||||
{
|
||||
@@ -34,7 +34,7 @@ class PolicyAlignmentTest extends TestCase
|
||||
}
|
||||
|
||||
/**
|
||||
* PO #1: DB 비어있을 때 코어 lang/ko, lang/en 디렉토리에 대해 가상 보호 행이 합성된다.
|
||||
* 요구사항 #1: DB 비어있을 때 코어 lang/ko, lang/en 디렉토리에 대해 가상 보호 행이 합성된다.
|
||||
*/
|
||||
public function test_virtual_built_in_packs_synthesized_for_core_locales(): void
|
||||
{
|
||||
@@ -57,7 +57,7 @@ class PolicyAlignmentTest extends TestCase
|
||||
}
|
||||
|
||||
/**
|
||||
* PO #1, slot dedup: 같은 슬롯에 DB 행이 있으면 가상 행은 list 응답에서 스킵된다.
|
||||
* 요구사항 #1, slot dedup: 같은 슬롯에 DB 행이 있으면 가상 행은 list 응답에서 스킵된다.
|
||||
*/
|
||||
public function test_db_row_overrides_virtual_built_in_in_same_slot(): void
|
||||
{
|
||||
@@ -93,7 +93,7 @@ class PolicyAlignmentTest extends TestCase
|
||||
}
|
||||
|
||||
/**
|
||||
* PO #5: activate 시 의존성/버전 검사. 호스트 모듈이 없으면 실패해야 한다.
|
||||
* 요구사항 #5: activate 시 의존성/버전 검사. 호스트 모듈이 없으면 실패해야 한다.
|
||||
*/
|
||||
public function test_activate_fails_when_target_extension_does_not_exist(): void
|
||||
{
|
||||
@@ -125,13 +125,13 @@ class PolicyAlignmentTest extends TestCase
|
||||
}
|
||||
|
||||
/**
|
||||
* PO #3: install 흐름의 lang-packs/_bundled/ 패키지는 비보호로 등록되어야 한다.
|
||||
* 요구사항 #3: install 흐름의 lang-packs/_bundled/ 패키지는 비보호로 등록되어야 한다.
|
||||
*
|
||||
* 실제 install 은 ZIP 추출이 필요하므로 buildPackData 의 출력을 직접 검증.
|
||||
*/
|
||||
public function test_install_flow_produces_unprotected_packs(): void
|
||||
{
|
||||
// 가상 행도 비보호 (PO #3): 미설치 가상 행은 lang-packs/_bundled/ 의 ja 패키지 표현
|
||||
// 가상 행도 비보호 (요구사항 #3): 미설치 가상 행은 lang-packs/_bundled/ 의 ja 패키지 표현
|
||||
$repo = app(\App\Contracts\Repositories\LanguagePackRepositoryInterface::class);
|
||||
$manifest = [
|
||||
'identifier' => 'g7-module-test-ja',
|
||||
@@ -146,7 +146,7 @@ class PolicyAlignmentTest extends TestCase
|
||||
}
|
||||
|
||||
/**
|
||||
* PO #6: 호스트 확장 deactivate cascade 헬퍼 stash/get 라운드트립.
|
||||
* 요구사항 #6: 호스트 확장 deactivate cascade 헬퍼 stash/get 라운드트립.
|
||||
*/
|
||||
public function test_reactivation_stash_round_trip(): void
|
||||
{
|
||||
@@ -176,7 +176,7 @@ class PolicyAlignmentTest extends TestCase
|
||||
$this->assertSame($pack->id, $pending[0]['id']);
|
||||
$this->assertSame('日本語', $pending[0]['locale_native_name']);
|
||||
|
||||
// 두 번 호출하면 cache 가 비워져 빈 배열 반환 (PO #8: 모달 표시 안 함)
|
||||
// 두 번 호출하면 cache 가 비워져 빈 배열 반환 (요구사항 #8: 모달 표시 안 함)
|
||||
$second = $registrar->getPendingForReactivation('module', 'stash-module');
|
||||
$this->assertEmpty($second);
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ class RegistryPayloadLocalizationTest extends TestCase
|
||||
* ja 활성 + 활성 언어팩(g7-core-ja) 의 notification.channels 키가 보강된 시나리오.
|
||||
*
|
||||
* lang pack 빌드로 채워진 ja 라벨이 표시되는지 end-to-end 검증.
|
||||
* lang pack 미설치 환경에서는 skip — 회귀 본체(PO 보고)는 lang pack 활성화 후 발생.
|
||||
* lang pack 미설치 환경에서는 skip — 회귀 본체(현장 보고)는 lang pack 활성화 후 발생.
|
||||
*/
|
||||
public function test_notification_channels_resolve_to_japanese_when_lang_pack_active(): void
|
||||
{
|
||||
@@ -86,7 +86,7 @@ class RegistryPayloadLocalizationTest extends TestCase
|
||||
$koValue = __('notification.channels.mail.name', [], 'ko');
|
||||
|
||||
// ja 키가 lang pack 으로 로드되지 않은 환경(=ja 결과 = key 또는 ko fallback)에서는 skip.
|
||||
// PO 가 build-language-pack 실행 후 + 테스트 환경에서 LanguagePackServiceProvider 가
|
||||
// 운영자가 build-language-pack 실행 후 + 테스트 환경에서 LanguagePackServiceProvider 가
|
||||
// ja namespace 를 로드한 환경에서만 통합 시나리오 검증 가능.
|
||||
if ($jaValue === 'notification.channels.mail.name' || $jaValue === $koValue) {
|
||||
$this->markTestSkipped('g7-core-ja lang pack 의 notification.channels.* 키가 테스트 환경에 로드되지 않음');
|
||||
|
||||
@@ -120,4 +120,52 @@ class CoreActivityLogListenerIdentityTest extends TestCase
|
||||
'action' => 'identity.expired',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* IDV 4 액션 키의 라벨이 ko/en 모두 raw key 가 아닌 번역된 문자열로 해석되어야 한다.
|
||||
*
|
||||
* beta.4 출시 시점에 `identity.verify` / `identity.verify_failed` 의 마지막 세그먼트
|
||||
* 매핑이 누락되어 관리자 화면에 raw 액션 키가 노출되던 회귀를 차단한다.
|
||||
* `ActivityLog::getActionLabelAttribute` 5단계 fallback 중 마지막 단계(raw 문자열)에
|
||||
* 도달하면 안 된다.
|
||||
*
|
||||
* @return iterable<string, array{string}>
|
||||
*/
|
||||
public static function provideIdentityActionKeys(): iterable
|
||||
{
|
||||
return [
|
||||
'identity.request' => ['identity.request'],
|
||||
'identity.verify' => ['identity.verify'],
|
||||
'identity.verify_failed' => ['identity.verify_failed'],
|
||||
'identity.expired' => ['identity.expired'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider provideIdentityActionKeys
|
||||
*/
|
||||
public function test_identity_action_label_resolves_in_ko(string $action): void
|
||||
{
|
||||
app()->setLocale('ko');
|
||||
$log = new ActivityLog(['action' => $action]);
|
||||
|
||||
$label = $log->action_label;
|
||||
|
||||
$this->assertNotSame($action, $label, "ko 라벨이 raw 키 '{$action}' 로 노출됨 — lang/ko/activity_log.php action 배열 매핑 누락");
|
||||
$this->assertNotEmpty($label);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider provideIdentityActionKeys
|
||||
*/
|
||||
public function test_identity_action_label_resolves_in_en(string $action): void
|
||||
{
|
||||
app()->setLocale('en');
|
||||
$log = new ActivityLog(['action' => $action]);
|
||||
|
||||
$label = $log->action_label;
|
||||
|
||||
$this->assertNotSame($action, $label, "en 라벨이 raw 키 '{$action}' 로 노출됨 — lang/en/activity_log.php action 배열 매핑 누락");
|
||||
$this->assertNotEmpty($label);
|
||||
}
|
||||
}
|
||||
@@ -244,7 +244,7 @@ class ModuleMenuSyncTest extends TestCase
|
||||
/**
|
||||
* 제거 후 재설치 시 메뉴가 올바르게 유지·복원되는지 테스트
|
||||
*
|
||||
* PO 정책(#716eef99d, 2026-04-20): deleteData=false 시 메뉴/권한/역할은 보존된다.
|
||||
* 운영 정책(#716eef99d, 2026-04-20): deleteData=false 시 메뉴/권한/역할은 보존된다.
|
||||
* 따라서 uninstall 후에도 메뉴는 DB 에 남아있고, 재설치는 idempotent (user_overrides 비어있음 유지).
|
||||
*/
|
||||
public function test_reinstall_after_uninstall_creates_clean_menus(): void
|
||||
@@ -475,7 +475,7 @@ class ModuleMenuSyncTest extends TestCase
|
||||
/**
|
||||
* 모듈 제거 (deleteData=true) 시 동적 메뉴를 포함한 모든 메뉴가 삭제되는지 테스트
|
||||
*
|
||||
* PO 정책(#716eef99d, 2026-04-20): deleteData=true 경로에서만 메뉴/권한/역할 전수 삭제.
|
||||
* 운영 정책(#716eef99d, 2026-04-20): deleteData=true 경로에서만 메뉴/권한/역할 전수 삭제.
|
||||
* deleteData=false (기본) 경로는 메뉴 보존 → test_module_uninstall_preserves_menus_by_default 참조.
|
||||
*/
|
||||
public function test_module_uninstall_removes_all_menus_including_dynamic(): void
|
||||
|
||||
@@ -188,7 +188,7 @@ class ModuleRolePermissionTest extends TestCase
|
||||
/**
|
||||
* 모듈 제거 (deleteData=true) 시 권한이 role에서 분리되는지 테스트
|
||||
*
|
||||
* PO 정책(#716eef99d, 2026-04-20): deleteData=true 경로에서만 권한 detach + 삭제.
|
||||
* 운영 정책(#716eef99d, 2026-04-20): deleteData=true 경로에서만 권한 detach + 삭제.
|
||||
* deleteData=false 경로는 권한 보존 (재설치 시 사용자 역할 할당 복원 목적).
|
||||
*/
|
||||
public function test_module_uninstallation_detaches_permissions_from_roles(): void
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Upgrades;
|
||||
|
||||
use App\Contracts\Extension\ModuleInterface;
|
||||
use App\Contracts\Extension\PluginInterface;
|
||||
use App\Contracts\Extension\UpgradeStepInterface;
|
||||
use App\Extension\AbstractUpgradeStep;
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Extension\UpgradeContext;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 모듈/플러그인 측 AbstractUpgradeStep 의무 fatal 가드 회귀 검증.
|
||||
*
|
||||
* 코어 RunUpgradeStepsAbstractGuardTest 와 1:1 미러링 (확장 측 진입점).
|
||||
*
|
||||
* 6 케이스:
|
||||
* 1. 모듈 — g7_version=beta.5 이상, 미상속 → throw
|
||||
* 2. 모듈 — g7_version=beta.5 이상, 상속 → pass
|
||||
* 3. 모듈 — g7_version=beta.4 이하, 미상속 → legacy bypass (통과)
|
||||
* 4. 플러그인 — 동일 3종
|
||||
*/
|
||||
class ExtensionAbstractGuardTest extends TestCase
|
||||
{
|
||||
// ── 모듈 ────────────────────────────────────────────────────────────
|
||||
|
||||
public function test_module_throws_when_step_does_not_extend_abstract(): void
|
||||
{
|
||||
$step = $this->makeLegacyStep();
|
||||
$module = $this->mockModule(
|
||||
identifier: 'vendor-test-module-a',
|
||||
workingVersion: '1.0.0',
|
||||
g7Version: '>=7.0.0-beta.5',
|
||||
upgrades: ['1.0.0' => $step],
|
||||
);
|
||||
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$this->expectExceptionMessageMatches('/must extend App\\\\Extension\\\\AbstractUpgradeStep/');
|
||||
$this->expectExceptionMessageMatches('/vendor-test-module-a/');
|
||||
$this->expectExceptionMessageMatches('/module/');
|
||||
|
||||
$this->invokeRunUpgradeSteps(
|
||||
manager: app(ModuleManager::class),
|
||||
extension: $module,
|
||||
from: '0.9.0',
|
||||
to: '1.0.0',
|
||||
);
|
||||
}
|
||||
|
||||
public function test_module_passes_when_step_extends_abstract(): void
|
||||
{
|
||||
$step = $this->makeAbstractStep();
|
||||
$module = $this->mockModule(
|
||||
identifier: 'vendor-test-module-b',
|
||||
workingVersion: '1.0.0',
|
||||
g7Version: '>=7.0.0-beta.5',
|
||||
upgrades: ['1.0.0' => $step],
|
||||
);
|
||||
|
||||
$captured = [];
|
||||
$this->invokeRunUpgradeSteps(
|
||||
manager: app(ModuleManager::class),
|
||||
extension: $module,
|
||||
from: '0.9.0',
|
||||
to: '1.0.0',
|
||||
onStep: function (string $v) use (&$captured): void { $captured[] = $v; },
|
||||
);
|
||||
|
||||
$this->assertSame(['1.0.0'], $captured, '가드 통과 후 step 이 정상 실행되어야 함');
|
||||
}
|
||||
|
||||
public function test_module_legacy_g7_version_bypasses_guard(): void
|
||||
{
|
||||
$step = $this->makeLegacyStep();
|
||||
$module = $this->mockModule(
|
||||
identifier: 'vendor-test-module-c',
|
||||
workingVersion: '1.0.0',
|
||||
g7Version: '>=7.0.0-beta.4',
|
||||
upgrades: ['1.0.0' => $step],
|
||||
);
|
||||
|
||||
$captured = [];
|
||||
$this->invokeRunUpgradeSteps(
|
||||
manager: app(ModuleManager::class),
|
||||
extension: $module,
|
||||
from: '0.9.0',
|
||||
to: '1.0.0',
|
||||
onStep: function (string $v) use (&$captured): void { $captured[] = $v; },
|
||||
);
|
||||
|
||||
$this->assertSame(['1.0.0'], $captured, 'legacy g7_version 은 가드 미발동 (호환 보장)');
|
||||
}
|
||||
|
||||
public function test_module_callable_step_bypasses_guard(): void
|
||||
{
|
||||
// closure step 은 instanceof UpgradeStepInterface 미충족 → 가드 자체가 검사 안 함
|
||||
$called = false;
|
||||
$module = $this->mockModule(
|
||||
identifier: 'vendor-test-module-d',
|
||||
workingVersion: '1.0.0',
|
||||
g7Version: '>=7.0.0-beta.5',
|
||||
upgrades: ['1.0.0' => function () use (&$called): void { $called = true; }],
|
||||
);
|
||||
|
||||
$this->invokeRunUpgradeSteps(
|
||||
manager: app(ModuleManager::class),
|
||||
extension: $module,
|
||||
from: '0.9.0',
|
||||
to: '1.0.0',
|
||||
);
|
||||
|
||||
$this->assertTrue($called, 'callable step 은 가드를 우회하고 그대로 실행 (호환)');
|
||||
}
|
||||
|
||||
public function test_module_step_below_since_version_bypasses_guard(): void
|
||||
{
|
||||
// 확장 working version 이 5.0.0 이고 g7_version 이 beta.5 이상이면
|
||||
// sinceVersion = 5.0.0. 그러나 실행되는 step 이 4.x 이면 미발동.
|
||||
$legacyStep = $this->makeLegacyStep();
|
||||
$module = $this->mockModule(
|
||||
identifier: 'vendor-test-module-e',
|
||||
workingVersion: '5.0.0',
|
||||
g7Version: '>=7.0.0-beta.5',
|
||||
upgrades: ['4.5.0' => $legacyStep],
|
||||
);
|
||||
|
||||
$captured = [];
|
||||
$this->invokeRunUpgradeSteps(
|
||||
manager: app(ModuleManager::class),
|
||||
extension: $module,
|
||||
from: '4.4.0',
|
||||
to: '4.5.0',
|
||||
onStep: function (string $v) use (&$captured): void { $captured[] = $v; },
|
||||
);
|
||||
|
||||
$this->assertSame(['4.5.0'], $captured, '확장 working version 이전의 step 은 가드 미발동 (legacy step 호환)');
|
||||
}
|
||||
|
||||
// ── 플러그인 ─────────────────────────────────────────────────────────
|
||||
|
||||
public function test_plugin_throws_when_step_does_not_extend_abstract(): void
|
||||
{
|
||||
$step = $this->makeLegacyStep();
|
||||
$plugin = $this->mockPlugin(
|
||||
identifier: 'vendor-test-plugin-a',
|
||||
workingVersion: '1.0.0',
|
||||
g7Version: '>=7.0.0-beta.5',
|
||||
upgrades: ['1.0.0' => $step],
|
||||
);
|
||||
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$this->expectExceptionMessageMatches('/must extend App\\\\Extension\\\\AbstractUpgradeStep/');
|
||||
$this->expectExceptionMessageMatches('/vendor-test-plugin-a/');
|
||||
$this->expectExceptionMessageMatches('/plugin/');
|
||||
|
||||
$this->invokeRunUpgradeSteps(
|
||||
manager: app(PluginManager::class),
|
||||
extension: $plugin,
|
||||
from: '0.9.0',
|
||||
to: '1.0.0',
|
||||
);
|
||||
}
|
||||
|
||||
public function test_plugin_passes_when_step_extends_abstract(): void
|
||||
{
|
||||
$step = $this->makeAbstractStep();
|
||||
$plugin = $this->mockPlugin(
|
||||
identifier: 'vendor-test-plugin-b',
|
||||
workingVersion: '1.0.0',
|
||||
g7Version: '>=7.0.0-beta.5',
|
||||
upgrades: ['1.0.0' => $step],
|
||||
);
|
||||
|
||||
$captured = [];
|
||||
$this->invokeRunUpgradeSteps(
|
||||
manager: app(PluginManager::class),
|
||||
extension: $plugin,
|
||||
from: '0.9.0',
|
||||
to: '1.0.0',
|
||||
onStep: function (string $v) use (&$captured): void { $captured[] = $v; },
|
||||
);
|
||||
|
||||
$this->assertSame(['1.0.0'], $captured);
|
||||
}
|
||||
|
||||
public function test_plugin_legacy_g7_version_bypasses_guard(): void
|
||||
{
|
||||
$step = $this->makeLegacyStep();
|
||||
$plugin = $this->mockPlugin(
|
||||
identifier: 'vendor-test-plugin-c',
|
||||
workingVersion: '1.0.0',
|
||||
g7Version: '>=7.0.0-beta.4',
|
||||
upgrades: ['1.0.0' => $step],
|
||||
);
|
||||
|
||||
$captured = [];
|
||||
$this->invokeRunUpgradeSteps(
|
||||
manager: app(PluginManager::class),
|
||||
extension: $plugin,
|
||||
from: '0.9.0',
|
||||
to: '1.0.0',
|
||||
onStep: function (string $v) use (&$captured): void { $captured[] = $v; },
|
||||
);
|
||||
|
||||
$this->assertSame(['1.0.0'], $captured);
|
||||
}
|
||||
|
||||
public function test_plugin_null_g7_version_bypasses_guard(): void
|
||||
{
|
||||
// g7_version 미선언 (legacy 확장) → resolveSinceVersion=null → 가드 우회
|
||||
$step = $this->makeLegacyStep();
|
||||
$plugin = $this->mockPlugin(
|
||||
identifier: 'vendor-test-plugin-d',
|
||||
workingVersion: '1.0.0',
|
||||
g7Version: null,
|
||||
upgrades: ['1.0.0' => $step],
|
||||
);
|
||||
|
||||
$captured = [];
|
||||
$this->invokeRunUpgradeSteps(
|
||||
manager: app(PluginManager::class),
|
||||
extension: $plugin,
|
||||
from: '0.9.0',
|
||||
to: '1.0.0',
|
||||
onStep: function (string $v) use (&$captured): void { $captured[] = $v; },
|
||||
);
|
||||
|
||||
$this->assertSame(['1.0.0'], $captured);
|
||||
}
|
||||
|
||||
// ── 헬퍼 ────────────────────────────────────────────────────────────
|
||||
|
||||
private function mockModule(
|
||||
string $identifier,
|
||||
string $workingVersion,
|
||||
?string $g7Version,
|
||||
array $upgrades,
|
||||
): ModuleInterface {
|
||||
$module = Mockery::mock(ModuleInterface::class);
|
||||
$module->shouldReceive('getIdentifier')->andReturn($identifier);
|
||||
$module->shouldReceive('getVersion')->andReturn($workingVersion);
|
||||
$module->shouldReceive('getRequiredCoreVersion')->andReturn($g7Version);
|
||||
$module->shouldReceive('upgrades')->andReturn($upgrades);
|
||||
|
||||
return $module;
|
||||
}
|
||||
|
||||
private function mockPlugin(
|
||||
string $identifier,
|
||||
string $workingVersion,
|
||||
?string $g7Version,
|
||||
array $upgrades,
|
||||
): PluginInterface {
|
||||
$plugin = Mockery::mock(PluginInterface::class);
|
||||
$plugin->shouldReceive('getIdentifier')->andReturn($identifier);
|
||||
$plugin->shouldReceive('getVersion')->andReturn($workingVersion);
|
||||
$plugin->shouldReceive('getRequiredCoreVersion')->andReturn($g7Version);
|
||||
$plugin->shouldReceive('upgrades')->andReturn($upgrades);
|
||||
|
||||
return $plugin;
|
||||
}
|
||||
|
||||
private function makeLegacyStep(): UpgradeStepInterface
|
||||
{
|
||||
return new class implements UpgradeStepInterface
|
||||
{
|
||||
public function run(UpgradeContext $context): void {}
|
||||
};
|
||||
}
|
||||
|
||||
private function makeAbstractStep(): AbstractUpgradeStep
|
||||
{
|
||||
return new class extends AbstractUpgradeStep {};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ModuleManager|PluginManager $manager
|
||||
* @param ModuleInterface|PluginInterface $extension
|
||||
*/
|
||||
private function invokeRunUpgradeSteps(
|
||||
$manager,
|
||||
$extension,
|
||||
string $from,
|
||||
string $to,
|
||||
?\Closure $onStep = null,
|
||||
): void {
|
||||
$reflection = new \ReflectionClass($manager);
|
||||
$method = $reflection->getMethod('runUpgradeSteps');
|
||||
$method->setAccessible(true);
|
||||
$method->invoke($manager, $extension, $from, $to, false, $onStep);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Mockery::close();
|
||||
parent::tearDown();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,567 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Upgrades;
|
||||
|
||||
use App\Contracts\Extension\ModuleInterface;
|
||||
use App\Contracts\Extension\PluginInterface;
|
||||
use App\Extension\AbstractUpgradeStep;
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Extension\PluginManager;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* AbstractUpgradeStep 인프라가 *확장 위치* 에서도 코어와 동일하게 동작하는지 통합 검증.
|
||||
*
|
||||
* 본 테스트는 확장 측 dogfood step 이 아직 존재하지 않는 상황에서 회귀 안전망 역할:
|
||||
* - dataDir() 가 확장 디렉토리로 자동 분기되는가 (ReflectionClass 기반)
|
||||
* - Applier 가 확장의 delta JSON 을 읽어 호출되는가
|
||||
* - Migration 이 확장 디렉토리의 migrations/ 에서 glob+require_once 로 로드되는가
|
||||
* - postRun() 호출 순서가 보존되는가 (Applier → Migration → postRun)
|
||||
* - manifest 부재 시 graceful (no fatal)
|
||||
* - manifest 의 Applier 파일 미존재 시 명확한 RuntimeException
|
||||
* - 같은 버전 namespace 의 다른 파일이 두 번 require_once 될 때의 동작 (known limitation)
|
||||
*/
|
||||
class ExtensionAbstractUpgradeStepFullFlowTest extends TestCase
|
||||
{
|
||||
private array $tempDirs = [];
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$GLOBALS['__ext_full_flow_calls'] = [];
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
foreach ($this->tempDirs as $dir) {
|
||||
if (File::isDirectory($dir)) {
|
||||
File::deleteDirectory($dir);
|
||||
}
|
||||
}
|
||||
unset($GLOBALS['__ext_full_flow_calls']);
|
||||
Mockery::close();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
// ── 모듈 측 전체 흐름 ────────────────────────────────────────────────
|
||||
|
||||
public function test_module_full_flow_runs_applier_then_migration_then_post_run(): void
|
||||
{
|
||||
$version = '0.0.21-test.mod.flow';
|
||||
$extDir = $this->makeExtensionDir('module-flow');
|
||||
$stepClass = $this->writeStepFile($extDir, $version, postRunCall: 'PostRunM1');
|
||||
$this->writeManifest($extDir, $version, [
|
||||
['kind' => 'permissions', 'file' => 'permissions.delta.json'],
|
||||
]);
|
||||
$this->writeDelta($extDir, $version, 'permissions.delta.json', $this->permissionsDelta('PermApplierM1'));
|
||||
$this->writeApplier($extDir, $version, 'PermissionsApplier', 'PermApplierM1');
|
||||
$this->writeMigration($extDir, $version, '01_FirstStep.php', 'FirstStep', 'MigrationM1A');
|
||||
$this->writeMigration($extDir, $version, '02_SecondStep.php', 'SecondStep', 'MigrationM1B');
|
||||
|
||||
$stepInstance = new $stepClass;
|
||||
$module = $this->mockModule(
|
||||
identifier: 'vendor-module-flow',
|
||||
workingVersion: $version,
|
||||
g7Version: '>=7.0.0-beta.5',
|
||||
upgrades: [$version => $stepInstance],
|
||||
);
|
||||
|
||||
$this->invokeRunUpgradeSteps(
|
||||
manager: app(ModuleManager::class),
|
||||
extension: $module,
|
||||
from: '0.0.20',
|
||||
to: $version,
|
||||
);
|
||||
|
||||
$this->assertSame(
|
||||
['PermApplierM1', 'MigrationM1A', 'MigrationM1B', 'PostRunM1'],
|
||||
$GLOBALS['__ext_full_flow_calls'],
|
||||
'Applier 먼저, 다음 Migration 정렬 순서, 마지막 postRun',
|
||||
);
|
||||
}
|
||||
|
||||
public function test_module_data_dir_resolves_under_extension_path(): void
|
||||
{
|
||||
$version = '0.0.22-test.mod.datadir';
|
||||
$extDir = $this->makeExtensionDir('module-datadir');
|
||||
$stepClass = $this->writeStepFile($extDir, $version);
|
||||
$this->writeManifest($extDir, $version, [
|
||||
['kind' => 'permissions', 'file' => 'permissions.delta.json'],
|
||||
]);
|
||||
$this->writeDelta($extDir, $version, 'permissions.delta.json', $this->permissionsDelta('DataDirApplier'));
|
||||
$this->writeApplier($extDir, $version, 'PermissionsApplier', 'DataDirApplier');
|
||||
|
||||
$stepInstance = new $stepClass;
|
||||
|
||||
// dataDir() 는 protected — Reflection 으로 호출
|
||||
$reflection = new \ReflectionClass($stepInstance);
|
||||
$dataDirMethod = $reflection->getMethod('dataDir');
|
||||
$dataDirMethod->setAccessible(true);
|
||||
|
||||
$context = new \App\Extension\UpgradeContext(
|
||||
fromVersion: '0.0.21',
|
||||
toVersion: $version,
|
||||
currentStep: $version,
|
||||
);
|
||||
|
||||
$resolvedPath = $this->normalizePath($dataDirMethod->invoke($stepInstance, $context));
|
||||
$expected = $this->normalizePath($extDir.'/data/'.$version);
|
||||
|
||||
$this->assertStringStartsWith(
|
||||
$this->normalizePath($extDir),
|
||||
$resolvedPath,
|
||||
'dataDir() 는 확장 디렉토리 안에서 해석되어야 함 (ReflectionClass 기반 자동 분기)',
|
||||
);
|
||||
$this->assertSame(
|
||||
$expected,
|
||||
$resolvedPath,
|
||||
'dataDir() 는 확장 step 파일 옆 data/{ver}/ 를 가리켜야 함',
|
||||
);
|
||||
}
|
||||
|
||||
public function test_module_manifest_absent_does_not_fail(): void
|
||||
{
|
||||
// manifest.json 부재 → DataSnapshot::empty() 반환 → Applier 0개, fatal 없음
|
||||
$version = '0.0.23-test.mod.empty';
|
||||
$extDir = $this->makeExtensionDir('module-empty');
|
||||
$stepClass = $this->writeStepFile($extDir, $version, postRunCall: 'PostRunEmpty');
|
||||
// 의도적으로 data/{ver}/ 디렉토리 미생성
|
||||
|
||||
$stepInstance = new $stepClass;
|
||||
$module = $this->mockModule(
|
||||
identifier: 'vendor-module-empty',
|
||||
workingVersion: $version,
|
||||
g7Version: '>=7.0.0-beta.5',
|
||||
upgrades: [$version => $stepInstance],
|
||||
);
|
||||
|
||||
$this->invokeRunUpgradeSteps(
|
||||
manager: app(ModuleManager::class),
|
||||
extension: $module,
|
||||
from: '0.0.22',
|
||||
to: $version,
|
||||
);
|
||||
|
||||
$this->assertSame(
|
||||
['PostRunEmpty'],
|
||||
$GLOBALS['__ext_full_flow_calls'],
|
||||
'manifest 부재 시 Applier/Migration 0건, postRun 만 실행',
|
||||
);
|
||||
}
|
||||
|
||||
public function test_module_missing_applier_file_throws_runtime_exception(): void
|
||||
{
|
||||
$version = '0.0.24-test.mod.missing';
|
||||
$extDir = $this->makeExtensionDir('module-missing');
|
||||
$stepClass = $this->writeStepFile($extDir, $version);
|
||||
$this->writeManifest($extDir, $version, [
|
||||
['kind' => 'permissions', 'file' => 'permissions.delta.json'],
|
||||
]);
|
||||
$this->writeDelta($extDir, $version, 'permissions.delta.json', $this->permissionsDelta('NotUsed'));
|
||||
// 의도적으로 appliers/PermissionsApplier.php 생성 안 함
|
||||
|
||||
$stepInstance = new $stepClass;
|
||||
$module = $this->mockModule(
|
||||
identifier: 'vendor-module-missing',
|
||||
workingVersion: $version,
|
||||
g7Version: '>=7.0.0-beta.5',
|
||||
upgrades: [$version => $stepInstance],
|
||||
);
|
||||
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$this->expectExceptionMessageMatches('/Applier file not found/');
|
||||
|
||||
$this->invokeRunUpgradeSteps(
|
||||
manager: app(ModuleManager::class),
|
||||
extension: $module,
|
||||
from: '0.0.23',
|
||||
to: $version,
|
||||
);
|
||||
}
|
||||
|
||||
// ── 플러그인 측 전체 흐름 (모듈과 1:1 대응) ─────────────────────────
|
||||
|
||||
public function test_plugin_full_flow_runs_applier_then_migration_then_post_run(): void
|
||||
{
|
||||
$version = '0.0.31-test.plg.flow';
|
||||
$extDir = $this->makeExtensionDir('plugin-flow', 'plugin');
|
||||
$stepClass = $this->writeStepFile($extDir, $version, postRunCall: 'PostRunP1');
|
||||
$this->writeManifest($extDir, $version, [
|
||||
['kind' => 'permissions', 'file' => 'permissions.delta.json'],
|
||||
]);
|
||||
$this->writeDelta($extDir, $version, 'permissions.delta.json', $this->permissionsDelta('PermApplierP1'));
|
||||
$this->writeApplier($extDir, $version, 'PermissionsApplier', 'PermApplierP1');
|
||||
$this->writeMigration($extDir, $version, '01_FirstStep.php', 'FirstStep', 'MigrationP1A');
|
||||
|
||||
$stepInstance = new $stepClass;
|
||||
$plugin = $this->mockPlugin(
|
||||
identifier: 'vendor-plugin-flow',
|
||||
workingVersion: $version,
|
||||
g7Version: '>=7.0.0-beta.5',
|
||||
upgrades: [$version => $stepInstance],
|
||||
);
|
||||
|
||||
$this->invokeRunUpgradeSteps(
|
||||
manager: app(PluginManager::class),
|
||||
extension: $plugin,
|
||||
from: '0.0.30',
|
||||
to: $version,
|
||||
);
|
||||
|
||||
$this->assertSame(
|
||||
['PermApplierP1', 'MigrationP1A', 'PostRunP1'],
|
||||
$GLOBALS['__ext_full_flow_calls'],
|
||||
);
|
||||
}
|
||||
|
||||
public function test_plugin_data_dir_resolves_under_extension_path(): void
|
||||
{
|
||||
$version = '0.0.32-test.plg.datadir';
|
||||
$extDir = $this->makeExtensionDir('plugin-datadir', 'plugin');
|
||||
$stepClass = $this->writeStepFile($extDir, $version);
|
||||
|
||||
$stepInstance = new $stepClass;
|
||||
$reflection = new \ReflectionClass($stepInstance);
|
||||
$dataDirMethod = $reflection->getMethod('dataDir');
|
||||
$dataDirMethod->setAccessible(true);
|
||||
|
||||
$context = new \App\Extension\UpgradeContext(
|
||||
fromVersion: '0.0.31',
|
||||
toVersion: $version,
|
||||
currentStep: $version,
|
||||
);
|
||||
|
||||
$resolvedPath = $this->normalizePath($dataDirMethod->invoke($stepInstance, $context));
|
||||
$expected = $this->normalizePath($extDir.'/data/'.$version);
|
||||
|
||||
$this->assertSame($expected, $resolvedPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Windows / POSIX 경로 구분자 차이 흡수.
|
||||
*/
|
||||
private function normalizePath(string $path): string
|
||||
{
|
||||
return str_replace('\\', '/', $path);
|
||||
}
|
||||
|
||||
// ── namespace 격리 회귀 가드 (KNOWN LIMITATION 해결 검증) ────────────
|
||||
|
||||
/**
|
||||
* 두 다른 번들 모듈이 *같은 step 버전 + 같은 Migration 클래스명* 을 가져도
|
||||
* 각자 격리된 namespace 로 인해 PHP compile-time fatal 없이 양쪽 모두 실행됨을 검증.
|
||||
*
|
||||
* 격리 메커니즘:
|
||||
* - 모듈 A: `modules/_bundled/test-ext-collision-a-xxx/upgrades/data/{ver}/migrations/01_Shared.php`
|
||||
* → namespace `App\Upgrades\Data\Ext\Modules\TestExtCollisionA{xxx}\V{ver}\Migrations\Shared`
|
||||
* - 모듈 B: `modules/_bundled/test-ext-collision-b-yyy/upgrades/data/{ver}/migrations/01_Shared.php`
|
||||
* → namespace `App\Upgrades\Data\Ext\Modules\TestExtCollisionB{yyy}\V{ver}\Migrations\Shared`
|
||||
*
|
||||
* `require_once` 가 두 파일을 모두 로드하고, 각자 별개 FQCN 으로 선언되어 충돌 없음.
|
||||
*
|
||||
* 본 테스트는 KNOWN LIMITATION 의 해결 후 회귀 안전망 — 향후 namespace 패턴이 다시
|
||||
* 변경되어 두 확장이 같은 FQCN 을 갖게 되면 본 테스트가 fatal 로 실패한다.
|
||||
*/
|
||||
public function test_two_extensions_with_same_step_version_isolated_by_namespace(): void
|
||||
{
|
||||
$sharedVersion = '0.0.42-test.shared.ver';
|
||||
|
||||
// 모듈 A
|
||||
$extDirA = $this->makeExtensionDir('collision-a');
|
||||
$stepClassA = $this->writeStepFile($extDirA, $sharedVersion);
|
||||
$this->writeMigration($extDirA, $sharedVersion, '01_Shared.php', 'Shared', 'CollisionA');
|
||||
|
||||
// 모듈 B (다른 디렉토리, 다른 모듈 식별자, 같은 클래스명 + 같은 버전)
|
||||
$extDirB = $this->makeExtensionDir('collision-b');
|
||||
$stepClassB = $this->writeStepFile($extDirB, $sharedVersion);
|
||||
$this->writeMigration($extDirB, $sharedVersion, '01_Shared.php', 'Shared', 'CollisionB');
|
||||
|
||||
$stepA = new $stepClassA;
|
||||
$stepB = new $stepClassB;
|
||||
|
||||
$moduleA = $this->mockModule(
|
||||
identifier: 'vendor-collision-a',
|
||||
workingVersion: $sharedVersion,
|
||||
g7Version: '>=7.0.0-beta.5',
|
||||
upgrades: [$sharedVersion => $stepA],
|
||||
);
|
||||
$moduleB = $this->mockModule(
|
||||
identifier: 'vendor-collision-b',
|
||||
workingVersion: $sharedVersion,
|
||||
g7Version: '>=7.0.0-beta.5',
|
||||
upgrades: [$sharedVersion => $stepB],
|
||||
);
|
||||
|
||||
$manager = app(ModuleManager::class);
|
||||
|
||||
$this->invokeRunUpgradeSteps(
|
||||
manager: $manager,
|
||||
extension: $moduleA,
|
||||
from: '0.0.41',
|
||||
to: $sharedVersion,
|
||||
);
|
||||
$this->invokeRunUpgradeSteps(
|
||||
manager: $manager,
|
||||
extension: $moduleB,
|
||||
from: '0.0.41',
|
||||
to: $sharedVersion,
|
||||
);
|
||||
|
||||
// 두 확장 모두 자기 코드의 라벨로 호출되어야 함 — namespace 격리 성립
|
||||
$this->assertSame(
|
||||
['CollisionA', 'CollisionB'],
|
||||
$GLOBALS['__ext_full_flow_calls'],
|
||||
'두 확장이 같은 step 버전 + 같은 클래스명을 가져도 namespace 격리로 각자 실행됨',
|
||||
);
|
||||
}
|
||||
|
||||
public function test_versionedNamespace_uses_distinct_namespaces_for_different_extensions_same_version(): void
|
||||
{
|
||||
// namespace 격리의 *근원* 정적 검증 — DataSnapshot 단위에서 검증.
|
||||
$context = new \App\Extension\UpgradeContext(
|
||||
fromVersion: '0.0.0',
|
||||
toVersion: '1.0.0',
|
||||
currentStep: '1.0.0',
|
||||
);
|
||||
|
||||
$nsModuleA = \App\Extension\Upgrade\DataSnapshot::versionedNamespace(
|
||||
$context,
|
||||
'/var/www/modules/_bundled/vendor-foo/upgrades/data/1.0.0',
|
||||
);
|
||||
$nsModuleB = \App\Extension\Upgrade\DataSnapshot::versionedNamespace(
|
||||
$context,
|
||||
'/var/www/modules/_bundled/vendor-bar/upgrades/data/1.0.0',
|
||||
);
|
||||
$nsPlugin = \App\Extension\Upgrade\DataSnapshot::versionedNamespace(
|
||||
$context,
|
||||
'/var/www/plugins/_bundled/vendor-baz/upgrades/data/1.0.0',
|
||||
);
|
||||
$nsCore = \App\Extension\Upgrade\DataSnapshot::versionedNamespace(
|
||||
$context,
|
||||
'/var/www/upgrades/data/1.0.0',
|
||||
);
|
||||
|
||||
$this->assertNotSame($nsModuleA, $nsModuleB);
|
||||
$this->assertNotSame($nsModuleA, $nsPlugin);
|
||||
$this->assertNotSame($nsModuleA, $nsCore);
|
||||
$this->assertNotSame($nsModuleB, $nsCore);
|
||||
$this->assertNotSame($nsPlugin, $nsCore);
|
||||
|
||||
// 확장 식별자 segment 가 실제로 포함되어 있는지 확인
|
||||
$this->assertStringContainsString('VendorFoo', $nsModuleA);
|
||||
$this->assertStringContainsString('VendorBar', $nsModuleB);
|
||||
$this->assertStringContainsString('VendorBaz', $nsPlugin);
|
||||
|
||||
// 코어는 확장 segment 없음
|
||||
$this->assertStringNotContainsString('Ext\\Modules', $nsCore);
|
||||
$this->assertStringNotContainsString('Ext\\Plugins', $nsCore);
|
||||
}
|
||||
|
||||
// ── 헬퍼: 디렉토리/파일 fixture ─────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 확장 디렉토리 fixture 작성. 경로에 `modules/_bundled/{id}/upgrades/` 또는
|
||||
* `plugins/_bundled/{id}/upgrades/` 마커가 포함되어야 `DataSnapshot::versionedNamespace`
|
||||
* 가 확장 namespace 분기로 진입한다.
|
||||
*
|
||||
* type 이 'module' 이면 modules/_bundled, 'plugin' 이면 plugins/_bundled.
|
||||
*/
|
||||
private function makeExtensionDir(string $label, string $type = 'module'): string
|
||||
{
|
||||
$extType = $type === 'plugin' ? 'plugins' : 'modules';
|
||||
$identifier = 'test-ext-'.$label.'-'.bin2hex(random_bytes(4));
|
||||
// storage/.../testing/ 안의 합성 경로 — 마커 substring 만 매칭하면 namespace 분기 작동.
|
||||
$base = storage_path('framework/testing/'.$extType.'/_bundled/'.$identifier.'/upgrades');
|
||||
File::ensureDirectoryExists($base);
|
||||
// 정리 대상은 {id} 디렉토리 (storage/framework/testing/{type}/_bundled/{id})
|
||||
$this->tempDirs[] = dirname($base);
|
||||
|
||||
return $base;
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장의 step 파일을 작성 후 require_once + FQCN 반환.
|
||||
*
|
||||
* step 클래스명은 fixture 별 고유 — PHP 클래스 재선언 회피.
|
||||
*/
|
||||
private function writeStepFile(string $extDir, string $version, ?string $postRunCall = null): string
|
||||
{
|
||||
$unique = 'ExtStep_'.bin2hex(random_bytes(8));
|
||||
$stepFile = $extDir.'/'.$unique.'.php';
|
||||
|
||||
$postRunBody = $postRunCall !== null
|
||||
? "\$GLOBALS['__ext_full_flow_calls'][] = '{$postRunCall}';"
|
||||
: '';
|
||||
|
||||
$contents = <<<PHP
|
||||
<?php
|
||||
namespace App\\Upgrades\\Data\\TestFixtures;
|
||||
|
||||
use App\\Extension\\AbstractUpgradeStep;
|
||||
use App\\Extension\\UpgradeContext;
|
||||
|
||||
class {$unique} extends AbstractUpgradeStep
|
||||
{
|
||||
protected function postRun(UpgradeContext \$context): void
|
||||
{
|
||||
{$postRunBody}
|
||||
}
|
||||
}
|
||||
PHP;
|
||||
File::put($stepFile, $contents);
|
||||
require_once $stepFile;
|
||||
|
||||
return 'App\\Upgrades\\Data\\TestFixtures\\'.$unique;
|
||||
}
|
||||
|
||||
private function writeManifest(string $extDir, string $version, array $entries): void
|
||||
{
|
||||
$dir = $extDir.'/data/'.$version;
|
||||
File::ensureDirectoryExists($dir);
|
||||
File::put(
|
||||
$dir.'/manifest.json',
|
||||
json_encode(
|
||||
['version' => $version, 'files' => $entries],
|
||||
JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private function writeDelta(string $extDir, string $version, string $file, array $delta): void
|
||||
{
|
||||
$dir = $extDir.'/data/'.$version;
|
||||
File::ensureDirectoryExists($dir);
|
||||
File::put($dir.'/'.$file, json_encode($delta, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
|
||||
private function writeApplier(string $extDir, string $version, string $className, string $callLabel): void
|
||||
{
|
||||
$dir = $extDir.'/data/'.$version.'/appliers';
|
||||
File::ensureDirectoryExists($dir);
|
||||
$namespace = $this->namespaceForDataFile($dir, $version);
|
||||
$contents = <<<PHP
|
||||
<?php
|
||||
namespace {$namespace}\\Appliers;
|
||||
|
||||
use App\\Extension\\Upgrade\\SnapshotApplier;
|
||||
use App\\Extension\\UpgradeContext;
|
||||
|
||||
class {$className} implements SnapshotApplier
|
||||
{
|
||||
public function __construct(private readonly string \$jsonPath) {}
|
||||
|
||||
public function apply(UpgradeContext \$context): void
|
||||
{
|
||||
\$GLOBALS['__ext_full_flow_calls'][] = '{$callLabel}';
|
||||
}
|
||||
}
|
||||
PHP;
|
||||
File::put($dir.'/'.$className.'.php', $contents);
|
||||
}
|
||||
|
||||
private function writeMigration(
|
||||
string $extDir,
|
||||
string $version,
|
||||
string $fileName,
|
||||
string $className,
|
||||
string $callLabel,
|
||||
): void {
|
||||
$dir = $extDir.'/data/'.$version.'/migrations';
|
||||
File::ensureDirectoryExists($dir);
|
||||
$namespace = $this->namespaceForDataFile($dir, $version);
|
||||
$contents = <<<PHP
|
||||
<?php
|
||||
namespace {$namespace}\\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['__ext_full_flow_calls'][] = '{$callLabel}';
|
||||
}
|
||||
}
|
||||
PHP;
|
||||
File::put($dir.'/'.$fileName, $contents);
|
||||
}
|
||||
|
||||
/**
|
||||
* fixture 의 namespace prefix 계산.
|
||||
*
|
||||
* DataSnapshot::versionedNamespace 의 PHP 측 SSoT 를 그대로 호출하여 동기 보장.
|
||||
*/
|
||||
private function namespaceForDataFile(string $dir, string $version): string
|
||||
{
|
||||
$context = new \App\Extension\UpgradeContext(
|
||||
fromVersion: '0.0.0',
|
||||
toVersion: $version,
|
||||
currentStep: $version,
|
||||
);
|
||||
|
||||
return \App\Extension\Upgrade\DataSnapshot::versionedNamespace($context, $dir);
|
||||
}
|
||||
|
||||
private function permissionsDelta(string $unusedLabel): array
|
||||
{
|
||||
return [
|
||||
'added' => [],
|
||||
'removed' => [],
|
||||
'renamed' => [],
|
||||
];
|
||||
}
|
||||
|
||||
// ── 헬퍼: Manager 진입점 ─────────────────────────────────────────────
|
||||
|
||||
private function mockModule(
|
||||
string $identifier,
|
||||
string $workingVersion,
|
||||
?string $g7Version,
|
||||
array $upgrades,
|
||||
): ModuleInterface {
|
||||
$module = Mockery::mock(ModuleInterface::class);
|
||||
$module->shouldReceive('getIdentifier')->andReturn($identifier);
|
||||
$module->shouldReceive('getVersion')->andReturn($workingVersion);
|
||||
$module->shouldReceive('getRequiredCoreVersion')->andReturn($g7Version);
|
||||
$module->shouldReceive('upgrades')->andReturn($upgrades);
|
||||
|
||||
return $module;
|
||||
}
|
||||
|
||||
private function mockPlugin(
|
||||
string $identifier,
|
||||
string $workingVersion,
|
||||
?string $g7Version,
|
||||
array $upgrades,
|
||||
): PluginInterface {
|
||||
$plugin = Mockery::mock(PluginInterface::class);
|
||||
$plugin->shouldReceive('getIdentifier')->andReturn($identifier);
|
||||
$plugin->shouldReceive('getVersion')->andReturn($workingVersion);
|
||||
$plugin->shouldReceive('getRequiredCoreVersion')->andReturn($g7Version);
|
||||
$plugin->shouldReceive('upgrades')->andReturn($upgrades);
|
||||
|
||||
return $plugin;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ModuleManager|PluginManager $manager
|
||||
* @param ModuleInterface|PluginInterface $extension
|
||||
*/
|
||||
private function invokeRunUpgradeSteps(
|
||||
$manager,
|
||||
$extension,
|
||||
string $from,
|
||||
string $to,
|
||||
?\Closure $onStep = null,
|
||||
): void {
|
||||
$reflection = new \ReflectionClass($manager);
|
||||
$method = $reflection->getMethod('runUpgradeSteps');
|
||||
$method->setAccessible(true);
|
||||
$method->invoke($manager, $extension, $from, $to, false, $onStep);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Upgrades;
|
||||
|
||||
use App\Services\CoreUpdateService;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 다중 버전 업그레이드 경로 + partial migrate 멱등성 회귀 가드 (§8 + §10-B).
|
||||
*
|
||||
* 회귀 시나리오:
|
||||
* 1. 사용자가 beta.1 또는 beta.2 에서 beta.5 로 직접 점프하는 경우 — 본 테스트는 step 4건
|
||||
* (beta.2/3/4/5) 이 버전 순서대로 실행되는지 in-memory 시뮬레이션으로 검증한다.
|
||||
* (실제 fatal 가능성은 §9.6 잔존 결함으로 명시 — 본 테스트는 step 디스패치 순서 회귀 가드)
|
||||
*
|
||||
* 2. 마이그레이션이 부분 적용된 상태에서 `core:update --force` 재실행 시 동일 마이그레이션을
|
||||
* 재실행해도 SQL error 발생하지 않아야 한다 (Schema::hasColumn 가드 멱등성).
|
||||
*/
|
||||
class MultiVersionUpgradePathTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private string $stubStepDir;
|
||||
|
||||
private array $stubStepFiles = [];
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->stubStepDir = base_path('upgrades');
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
foreach ($this->stubStepFiles as $file) {
|
||||
if (File::exists($file)) {
|
||||
File::delete($file);
|
||||
}
|
||||
}
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function runUpgradeSteps_는_다중_버전_step_을_버전_순서대로_실행한다(): void
|
||||
{
|
||||
// memory 가 target 이상이어야 stale 가드 우회 (테스트 환경)
|
||||
config(['app.version' => '0.0.5']);
|
||||
|
||||
// beta.2 ~ beta.5 시뮬레이션을 0.0.2 ~ 0.0.5 로 대체 (실제 upgrades 디렉토리 오염 회피)
|
||||
foreach (['0_0_2', '0_0_3', '0_0_4', '0_0_5'] as $version) {
|
||||
$path = $this->stubStepDir.'/Upgrade_'.$version.'_test_multi_version.php';
|
||||
$this->stubStepFiles[] = $path;
|
||||
$className = 'Upgrade_'.$version.'_test_multi_version';
|
||||
File::put($path, <<<PHP
|
||||
<?php
|
||||
|
||||
namespace App\Upgrades;
|
||||
|
||||
use App\Contracts\Extension\UpgradeStepInterface;
|
||||
use App\Extension\UpgradeContext;
|
||||
|
||||
class {$className} implements UpgradeStepInterface
|
||||
{
|
||||
public function run(UpgradeContext \$context): void
|
||||
{
|
||||
// no-op
|
||||
}
|
||||
}
|
||||
PHP);
|
||||
}
|
||||
|
||||
$service = app(CoreUpdateService::class);
|
||||
|
||||
$executedOrder = [];
|
||||
$service->runUpgradeSteps(
|
||||
'0.0.1',
|
||||
'0.0.5',
|
||||
function (string $version) use (&$executedOrder): void {
|
||||
$executedOrder[] = $version;
|
||||
},
|
||||
);
|
||||
|
||||
// upgrade 파일명의 suffix (`_test_multi_version`) 는 prerelease 로 해석되어 버전에 추가됨
|
||||
$this->assertSame(
|
||||
[
|
||||
'0.0.2-test.multi.version',
|
||||
'0.0.3-test.multi.version',
|
||||
'0.0.4-test.multi.version',
|
||||
'0.0.5-test.multi.version',
|
||||
],
|
||||
$executedOrder,
|
||||
'step 은 버전 순서대로 실행되어야 한다',
|
||||
);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function hasColumn_가드된_마이그레이션은_두_번_적용해도_SQL_error_없다(): void
|
||||
{
|
||||
// 테스트 전용 테이블 준비
|
||||
Schema::create('partial_migrate_test', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('name');
|
||||
});
|
||||
|
||||
try {
|
||||
// 멱등 마이그레이션을 함수로 추출 — partial migrate 후 재실행 시뮬레이션
|
||||
$idempotentMigration = function (): void {
|
||||
Schema::table('partial_migrate_test', function (Blueprint $table): void {
|
||||
if (! Schema::hasColumn('partial_migrate_test', 'extra_col')) {
|
||||
$table->string('extra_col')->nullable();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// 1차 적용
|
||||
$idempotentMigration();
|
||||
$this->assertTrue(Schema::hasColumn('partial_migrate_test', 'extra_col'), '1차 적용 후 컬럼 존재');
|
||||
|
||||
// 2차 적용 — 가드 덕분에 silent skip, SQL error 없어야 함
|
||||
$idempotentMigration();
|
||||
$this->assertTrue(Schema::hasColumn('partial_migrate_test', 'extra_col'), '2차 적용 후에도 컬럼 존재 (silent skip)');
|
||||
} finally {
|
||||
Schema::dropIfExists('partial_migrate_test');
|
||||
}
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function hasColumn_가드없는_마이그레이션은_두_번_적용시_SQL_error_발생한다(): void
|
||||
{
|
||||
// 회귀 가드의 역명제 — 가드 없을 때 SQL error 가 발생함을 명시 확인
|
||||
Schema::create('partial_migrate_no_guard_test', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('name');
|
||||
});
|
||||
|
||||
try {
|
||||
$nonIdempotentMigration = function (): void {
|
||||
Schema::table('partial_migrate_no_guard_test', function (Blueprint $table): void {
|
||||
$table->string('extra_col')->nullable();
|
||||
});
|
||||
};
|
||||
|
||||
$nonIdempotentMigration();
|
||||
$this->assertTrue(Schema::hasColumn('partial_migrate_no_guard_test', 'extra_col'));
|
||||
|
||||
// 2차 적용 — SQL error 발생 기대
|
||||
$exceptionCaught = false;
|
||||
try {
|
||||
$nonIdempotentMigration();
|
||||
} catch (\Throwable $e) {
|
||||
$exceptionCaught = true;
|
||||
// SQLSTATE 또는 "Duplicate column"/"already exists" 메시지 확인
|
||||
$this->assertMatchesRegularExpression(
|
||||
'/(already exists|duplicate column|SQLSTATE)/i',
|
||||
$e->getMessage(),
|
||||
);
|
||||
}
|
||||
|
||||
$this->assertTrue(
|
||||
$exceptionCaught,
|
||||
'가드 없는 마이그레이션을 2번 적용하면 SQL error 발생해야 한다 (회귀 가드 의의 확인)',
|
||||
);
|
||||
} finally {
|
||||
Schema::dropIfExists('partial_migrate_no_guard_test');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Upgrades;
|
||||
|
||||
use App\Exceptions\CoreUpdateOperationException;
|
||||
use App\Services\CoreUpdateService;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* runUpgradeSteps 의 신규 fatal 가드 검증.
|
||||
*
|
||||
* 7.0.0-beta.5 부터 step 인스턴스가 AbstractUpgradeStep 미상속이면 즉시 throw.
|
||||
* legacy step (beta.4 이하) 은 가드 우회.
|
||||
*
|
||||
* 회귀 시나리오:
|
||||
* 1. AbstractUpgradeStep 미상속 step 을 beta.5 버전으로 머지 → runUpgradeSteps 가 즉시 차단
|
||||
* 2. legacy 버전 (alpha/beta.2~4) 은 미상속이어도 통과 (호환 보장)
|
||||
* 3. beta.5+ step 이 AbstractUpgradeStep 상속하면 정상 실행
|
||||
*/
|
||||
class RunUpgradeStepsAbstractGuardTest extends TestCase
|
||||
{
|
||||
private array $stubStepFiles = [];
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
foreach ($this->stubStepFiles as $file) {
|
||||
if (File::exists($file)) {
|
||||
File::delete($file);
|
||||
}
|
||||
}
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_throws_when_beta5_step_does_not_extend_abstract(): void
|
||||
{
|
||||
// stale 메모리 가드 우회를 위해 메모리 버전을 target 이상으로
|
||||
config(['app.version' => '7.9.9']);
|
||||
|
||||
// 7.9.9-test.guard.a 는 7.0.0-beta.5 보다 명확히 큼 (version_compare 의 pre-release
|
||||
// 해석에 영향 받지 않음). stub 은 AbstractUpgradeStep 미상속 → fatal 가드 발동.
|
||||
$version = '7_9_9_test_guard_a';
|
||||
$className = 'Upgrade_'.$version;
|
||||
$path = base_path('upgrades/'.$className.'.php');
|
||||
$this->stubStepFiles[] = $path;
|
||||
File::put($path, <<<PHP
|
||||
<?php
|
||||
|
||||
namespace App\Upgrades;
|
||||
|
||||
use App\Contracts\Extension\UpgradeStepInterface;
|
||||
use App\Extension\UpgradeContext;
|
||||
|
||||
class {$className} implements UpgradeStepInterface
|
||||
{
|
||||
public function run(UpgradeContext \$context): void {}
|
||||
}
|
||||
PHP);
|
||||
|
||||
$this->expectException(CoreUpdateOperationException::class);
|
||||
$this->expectExceptionMessageMatches('/must extend App\\\\Extension\\\\AbstractUpgradeStep/');
|
||||
|
||||
$service = app(CoreUpdateService::class);
|
||||
$service->runUpgradeSteps('7.0.0-beta.4', '7.9.9-test.guard.a');
|
||||
}
|
||||
|
||||
public function test_passes_when_beta5_step_extends_abstract(): void
|
||||
{
|
||||
config(['app.version' => '7.9.9']);
|
||||
|
||||
$version = '7_9_9_test_guard_b';
|
||||
$className = 'Upgrade_'.$version;
|
||||
$path = base_path('upgrades/'.$className.'.php');
|
||||
$this->stubStepFiles[] = $path;
|
||||
File::put($path, <<<PHP
|
||||
<?php
|
||||
|
||||
namespace App\Upgrades;
|
||||
|
||||
use App\Extension\AbstractUpgradeStep;
|
||||
|
||||
class {$className} extends AbstractUpgradeStep
|
||||
{
|
||||
}
|
||||
PHP);
|
||||
|
||||
$executed = [];
|
||||
$service = app(CoreUpdateService::class);
|
||||
$service->runUpgradeSteps(
|
||||
'7.0.0-beta.4',
|
||||
'7.9.9-test.guard.b',
|
||||
function (string $v) use (&$executed): void {
|
||||
$executed[] = $v;
|
||||
},
|
||||
);
|
||||
|
||||
$this->assertContains('7.9.9-test.guard.b', $executed);
|
||||
}
|
||||
|
||||
public function test_legacy_pre_beta5_step_bypasses_guard(): void
|
||||
{
|
||||
// legacy beta.4 이하 step 은 AbstractUpgradeStep 미상속이어도 통과 (호환)
|
||||
config(['app.version' => '7.0.0-beta.5']);
|
||||
|
||||
$version = '7_0_0_beta_4_test_guard_legacy';
|
||||
$className = 'Upgrade_'.$version;
|
||||
$path = base_path('upgrades/'.$className.'.php');
|
||||
$this->stubStepFiles[] = $path;
|
||||
File::put($path, <<<PHP
|
||||
<?php
|
||||
|
||||
namespace App\Upgrades;
|
||||
|
||||
use App\Contracts\Extension\UpgradeStepInterface;
|
||||
use App\Extension\UpgradeContext;
|
||||
|
||||
class {$className} implements UpgradeStepInterface
|
||||
{
|
||||
public function run(UpgradeContext \$context): void {}
|
||||
}
|
||||
PHP);
|
||||
|
||||
$executed = [];
|
||||
$service = app(CoreUpdateService::class);
|
||||
$service->runUpgradeSteps(
|
||||
'7.0.0-beta.3',
|
||||
'7.0.0-beta.4.test.guard.legacy',
|
||||
function (string $v) use (&$executed): void {
|
||||
$executed[] = $v;
|
||||
},
|
||||
);
|
||||
|
||||
$this->assertContains('7.0.0-beta.4.test.guard.legacy', $executed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Upgrades;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Enums\PermissionType;
|
||||
use App\Extension\UpgradeContext;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use Database\Seeders\RolePermissionSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* Upgrade_7_0_0_beta_5 의 본인인증 권한 키 마이그레이션 검증.
|
||||
*
|
||||
* 7.0.0-beta.5 도입 "버전별 데이터 스냅샷" 인프라로 재구성:
|
||||
* - 단순 rename (신 row 부재) → PermissionsApplier 가 in-place UPDATE
|
||||
* - 충돌 경로 (신 row 존재) → IdentityPermissionPivotMerge DataMigration
|
||||
*
|
||||
* 회귀 시나리오: beta.4 환경에서 운영자 커스텀 role 에 `core.admin.identity.manage` /
|
||||
* `core.admin.identity.policies.manage` 를 부여한 상태로 beta.5 로 업그레이드.
|
||||
*
|
||||
* 검증 핵심: `permissions.identifier` 컬럼만 UPDATE 하므로 `permission_id` 가 보존되어
|
||||
* `role_permissions` 피벗의 `granted_at` / `granted_by` / `scope_type` 도 자동 보존된다.
|
||||
*/
|
||||
class Upgrade_7_0_0_beta_5PermissionRenameTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private UpgradeContext $context;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->seed(RolePermissionSeeder::class);
|
||||
|
||||
$this->context = new UpgradeContext(
|
||||
fromVersion: '7.0.0-beta.4',
|
||||
toVersion: '7.0.0-beta.5',
|
||||
currentStep: '7.0.0-beta.5',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 본 PR 의 새 구조에서 IDV 권한 마이그레이션은 두 단계 — Applier 먼저, Migration 다음.
|
||||
*
|
||||
* AbstractUpgradeStep::run() 의 위임 순서 (dataSnapshot → dataMigrations) 와 동일.
|
||||
*/
|
||||
private function invokeMigrate(): void
|
||||
{
|
||||
$appliersDir = base_path('upgrades/data/7.0.0-beta.5/appliers');
|
||||
$migrationsDir = base_path('upgrades/data/7.0.0-beta.5/migrations');
|
||||
|
||||
require_once $appliersDir.'/PermissionsApplier.php';
|
||||
require_once $migrationsDir.'/04_IdentityPermissionPivotMerge.php';
|
||||
|
||||
$applierClass = 'App\\Upgrades\\Data\\V7_0_0_beta_5\\Appliers\\PermissionsApplier';
|
||||
$migrationClass = 'App\\Upgrades\\Data\\V7_0_0_beta_5\\Migrations\\IdentityPermissionPivotMerge';
|
||||
|
||||
$applier = new $applierClass(base_path('upgrades/data/7.0.0-beta.5/permissions.delta.json'));
|
||||
$applier->apply($this->context);
|
||||
|
||||
$migration = new $migrationClass;
|
||||
$migration->run($this->context);
|
||||
}
|
||||
|
||||
private function makeLegacyPermissionRow(string $identifier): Permission
|
||||
{
|
||||
return Permission::create([
|
||||
'identifier' => $identifier,
|
||||
'name' => ['ko' => 'legacy', 'en' => 'legacy'],
|
||||
'description' => ['ko' => '', 'en' => ''],
|
||||
'type' => PermissionType::Admin,
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'order' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 신권한 row 를 제거하여 경로 A (in-place rename) 환경 재현.
|
||||
*
|
||||
* RolePermissionSeeder 가 config/core.php 기반으로 신권한을 시드하므로,
|
||||
* 경로 A 검증을 위해 명시적으로 신권한 row 를 삭제.
|
||||
*/
|
||||
private function clearNewPermissionRows(): void
|
||||
{
|
||||
DB::table('permissions')
|
||||
->whereIn('identifier', [
|
||||
'core.admin.identity.providers.update',
|
||||
'core.admin.identity.policies.update',
|
||||
])
|
||||
->delete();
|
||||
}
|
||||
|
||||
public function test_path_a_inplace_rename_when_new_row_absent(): void
|
||||
{
|
||||
$this->clearNewPermissionRows();
|
||||
$legacy = $this->makeLegacyPermissionRow('core.admin.identity.manage');
|
||||
$legacyId = $legacy->id;
|
||||
|
||||
$this->invokeMigrate();
|
||||
|
||||
$this->assertDatabaseMissing('permissions', ['identifier' => 'core.admin.identity.manage']);
|
||||
$this->assertDatabaseHas('permissions', [
|
||||
'id' => $legacyId,
|
||||
'identifier' => 'core.admin.identity.providers.update',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_path_a_policies_manage_inplace_rename(): void
|
||||
{
|
||||
$this->clearNewPermissionRows();
|
||||
$legacy = $this->makeLegacyPermissionRow('core.admin.identity.policies.manage');
|
||||
$legacyId = $legacy->id;
|
||||
|
||||
$this->invokeMigrate();
|
||||
|
||||
$this->assertDatabaseMissing('permissions', ['identifier' => 'core.admin.identity.policies.manage']);
|
||||
$this->assertDatabaseHas('permissions', [
|
||||
'id' => $legacyId,
|
||||
'identifier' => 'core.admin.identity.policies.update',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_path_a_pivot_preserved_with_metadata(): void
|
||||
{
|
||||
$this->clearNewPermissionRows();
|
||||
$legacy = $this->makeLegacyPermissionRow('core.admin.identity.manage');
|
||||
|
||||
$role = Role::create([
|
||||
'identifier' => 'custom-idv-role-a',
|
||||
'name' => ['ko' => '커스텀 IDV', 'en' => 'Custom IDV'],
|
||||
'description' => ['ko' => '', 'en' => ''],
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
]);
|
||||
|
||||
$grantedAt = now()->subDays(7);
|
||||
$role->permissions()->attach($legacy->id, [
|
||||
'granted_at' => $grantedAt,
|
||||
'granted_by' => null,
|
||||
'scope_type' => 'role',
|
||||
]);
|
||||
|
||||
$this->invokeMigrate();
|
||||
|
||||
$pivot = DB::table('role_permissions')
|
||||
->where('role_id', $role->id)
|
||||
->where('permission_id', $legacy->id)
|
||||
->first();
|
||||
|
||||
$this->assertNotNull($pivot, '경로 A 에서 permission_id 가 보존되어 피벗 row 가 유지되어야 함');
|
||||
$this->assertSame('role', $pivot->scope_type);
|
||||
$this->assertEquals($grantedAt->toDateTimeString(), \Carbon\Carbon::parse($pivot->granted_at)->toDateTimeString());
|
||||
|
||||
$role->refresh();
|
||||
$identifiers = $role->permissions->pluck('identifier')->all();
|
||||
$this->assertContains('core.admin.identity.providers.update', $identifiers);
|
||||
$this->assertNotContains('core.admin.identity.manage', $identifiers);
|
||||
}
|
||||
|
||||
public function test_path_b_pivot_moved_when_new_row_already_exists(): void
|
||||
{
|
||||
// 신권한 row 는 RolePermissionSeeder 가 이미 생성한 상태 (경로 B 환경)
|
||||
$newRow = DB::table('permissions')
|
||||
->where('identifier', 'core.admin.identity.providers.update')
|
||||
->first();
|
||||
$this->assertNotNull($newRow, '경로 B 시나리오: 신권한 row 가 RolePermissionSeeder 에 의해 미리 존재');
|
||||
|
||||
$legacy = $this->makeLegacyPermissionRow('core.admin.identity.manage');
|
||||
|
||||
$role = Role::create([
|
||||
'identifier' => 'custom-idv-role-b',
|
||||
'name' => ['ko' => '커스텀 IDV B', 'en' => 'Custom IDV B'],
|
||||
'description' => ['ko' => '', 'en' => ''],
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
]);
|
||||
|
||||
$grantedAt = now()->subDays(3);
|
||||
$role->permissions()->attach($legacy->id, [
|
||||
'granted_at' => $grantedAt,
|
||||
'granted_by' => null,
|
||||
'scope_type' => 'self',
|
||||
]);
|
||||
|
||||
$this->invokeMigrate();
|
||||
|
||||
// 옛 row 는 삭제됨
|
||||
$this->assertDatabaseMissing('permissions', ['identifier' => 'core.admin.identity.manage']);
|
||||
// 신 row 는 그대로 유지 (id 변경 없음)
|
||||
$this->assertDatabaseHas('permissions', [
|
||||
'id' => $newRow->id,
|
||||
'identifier' => 'core.admin.identity.providers.update',
|
||||
]);
|
||||
|
||||
// role 은 신권한을 보유 (피벗이 신 permission_id 로 이동됨)
|
||||
$movedPivot = DB::table('role_permissions')
|
||||
->where('role_id', $role->id)
|
||||
->where('permission_id', $newRow->id)
|
||||
->first();
|
||||
$this->assertNotNull($movedPivot, '경로 B 에서 옛 피벗이 신권한 id 로 이동되어야 함');
|
||||
$this->assertSame('self', $movedPivot->scope_type);
|
||||
$this->assertEquals($grantedAt->toDateTimeString(), \Carbon\Carbon::parse($movedPivot->granted_at)->toDateTimeString());
|
||||
|
||||
// 옛 permission_id 참조 피벗은 없어야 함
|
||||
$this->assertDatabaseMissing('role_permissions', ['permission_id' => $legacy->id]);
|
||||
|
||||
$role->refresh();
|
||||
$identifiers = $role->permissions->pluck('identifier')->all();
|
||||
$this->assertContains('core.admin.identity.providers.update', $identifiers);
|
||||
}
|
||||
|
||||
public function test_path_b_duplicate_grant_old_pivot_dropped(): void
|
||||
{
|
||||
// 양쪽 모두 부여된 role 의 옛 피벗 row 는 단순 삭제 (신 피벗 보존)
|
||||
$newRow = DB::table('permissions')
|
||||
->where('identifier', 'core.admin.identity.providers.update')
|
||||
->first();
|
||||
$legacy = $this->makeLegacyPermissionRow('core.admin.identity.manage');
|
||||
|
||||
$role = Role::create([
|
||||
'identifier' => 'dual-grant-role',
|
||||
'name' => ['ko' => '듀얼', 'en' => 'Dual'],
|
||||
'description' => ['ko' => '', 'en' => ''],
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
]);
|
||||
|
||||
// 옛 + 신 권한 양쪽 부여
|
||||
$role->permissions()->attach($legacy->id, [
|
||||
'granted_at' => now()->subDays(10),
|
||||
'scope_type' => 'role',
|
||||
]);
|
||||
$role->permissions()->attach($newRow->id, [
|
||||
'granted_at' => now()->subDays(1),
|
||||
'scope_type' => 'self',
|
||||
]);
|
||||
|
||||
$this->invokeMigrate();
|
||||
|
||||
// role 은 단 1개 피벗만 보유 (신권한 측 — scope_type='self' 유지)
|
||||
$pivots = DB::table('role_permissions')
|
||||
->where('role_id', $role->id)
|
||||
->where('permission_id', $newRow->id)
|
||||
->get();
|
||||
$this->assertCount(1, $pivots);
|
||||
$this->assertSame('self', $pivots->first()->scope_type);
|
||||
|
||||
// 옛 row 와 옛 피벗 모두 사라짐
|
||||
$this->assertDatabaseMissing('permissions', ['id' => $legacy->id]);
|
||||
$this->assertDatabaseMissing('role_permissions', ['permission_id' => $legacy->id]);
|
||||
}
|
||||
|
||||
public function test_migration_idempotent_no_legacy_rows_silent_skip(): void
|
||||
{
|
||||
// 옛 키 row 가 없는 환경 (이미 마이그레이션 됨) → 안전 silent skip
|
||||
$this->invokeMigrate();
|
||||
$this->invokeMigrate();
|
||||
|
||||
$this->assertDatabaseMissing('permissions', ['identifier' => 'core.admin.identity.manage']);
|
||||
$this->assertDatabaseMissing('permissions', ['identifier' => 'core.admin.identity.policies.manage']);
|
||||
}
|
||||
|
||||
public function test_migration_handles_both_legacy_keys_simultaneously(): void
|
||||
{
|
||||
$this->clearNewPermissionRows();
|
||||
$legacyProviders = $this->makeLegacyPermissionRow('core.admin.identity.manage');
|
||||
$legacyPolicies = $this->makeLegacyPermissionRow('core.admin.identity.policies.manage');
|
||||
|
||||
$this->invokeMigrate();
|
||||
|
||||
$this->assertDatabaseHas('permissions', [
|
||||
'id' => $legacyProviders->id,
|
||||
'identifier' => 'core.admin.identity.providers.update',
|
||||
]);
|
||||
$this->assertDatabaseHas('permissions', [
|
||||
'id' => $legacyPolicies->id,
|
||||
'identifier' => 'core.admin.identity.policies.update',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,492 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Upgrades;
|
||||
|
||||
use App\Extension\UpgradeContext;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* Upgrade_7_0_0_beta_5 의 단발성 복구 인프라 검증.
|
||||
*
|
||||
* 7.0.0-beta.5 도입 "버전별 데이터 스냅샷" 인프라로 재구성:
|
||||
* - 핫픽스 4종이 upgrades/data/7.0.0-beta.5/migrations/ 안에 격리됨
|
||||
* - 본 테스트는 각 Migration 클래스의 run() 을 직접 호출하여 회귀 가드 유지
|
||||
*
|
||||
* 회귀 시나리오 (#347): beta.4 의 `applyDiscoveredTopLevelPaths` 결함으로 활성 확장
|
||||
* 디렉토리(`modules/{id}`, `plugins/{id}`, `templates/{id}`, `lang-packs/{id}`) 가
|
||||
* 손실된 환경에서, beta.5 step 이 DB active row 와 `_bundled/{id}` 를 매칭하여 자동 복원.
|
||||
*/
|
||||
class Upgrade_7_0_0_beta_5RecoveryTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private UpgradeContext $context;
|
||||
|
||||
/** @var array<int, string> 정리할 임시 디렉토리 */
|
||||
private array $tempDirs = [];
|
||||
|
||||
private ?string $originalBasePath = null;
|
||||
|
||||
private ?string $originalPendingPath = null;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$migrationsDir = base_path('upgrades/data/7.0.0-beta.5/migrations');
|
||||
require_once $migrationsDir.'/01_RecoverActiveExtensionDirs.php';
|
||||
require_once $migrationsDir.'/02_RecoverPendingStubFiles.php';
|
||||
require_once $migrationsDir.'/03_VerifyBundledLangPacksFallback.php';
|
||||
require_once $migrationsDir.'/05_RecoverPublicStorageSymlink.php';
|
||||
|
||||
$this->context = new UpgradeContext(
|
||||
fromVersion: '7.0.0-beta.4',
|
||||
toVersion: '7.0.0-beta.5',
|
||||
currentStep: '7.0.0-beta.5',
|
||||
);
|
||||
|
||||
$this->originalBasePath = base_path();
|
||||
$this->originalPendingPath = config('app.update.pending_path');
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
if ($this->originalBasePath !== null) {
|
||||
app()->setBasePath($this->originalBasePath);
|
||||
}
|
||||
if ($this->originalPendingPath !== null) {
|
||||
config(['app.update.pending_path' => $this->originalPendingPath]);
|
||||
}
|
||||
|
||||
foreach ($this->tempDirs as $dir) {
|
||||
if (File::isDirectory($dir)) {
|
||||
File::deleteDirectory($dir);
|
||||
}
|
||||
}
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 디렉토리 부재 + DB active + `_bundled` 존재 → 활성 디렉토리 자동 복원.
|
||||
*/
|
||||
public function test_recover_active_dir_when_bundled_exists(): void
|
||||
{
|
||||
$fakeBase = $this->arrangeFakeBase();
|
||||
|
||||
// DB: templates 테이블 active row 1건
|
||||
DB::table('templates')->insert([
|
||||
'identifier' => 'sirsoft-basic',
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => json_encode(['ko' => '테스트 템플릿', 'en' => 'Test Template']),
|
||||
'version' => '1.0.0',
|
||||
'status' => 'active',
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
// _bundled 만 존재, 활성 디렉토리 부재
|
||||
File::ensureDirectoryExists($fakeBase.'/templates/_bundled/sirsoft-basic');
|
||||
File::put($fakeBase.'/templates/_bundled/sirsoft-basic/manifest.json', '{"identifier":"sirsoft-basic"}');
|
||||
|
||||
$this->invokeRecover();
|
||||
|
||||
$this->assertFileExists(
|
||||
$fakeBase.'/templates/sirsoft-basic/manifest.json',
|
||||
'활성 templates/sirsoft-basic 이 _bundled 에서 자동 복원되어야 한다',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 디렉토리 정상 존재 시 silent skip (멱등).
|
||||
*/
|
||||
public function test_recover_skips_when_active_dir_present(): void
|
||||
{
|
||||
$fakeBase = $this->arrangeFakeBase();
|
||||
|
||||
DB::table('templates')->insert([
|
||||
'identifier' => 'sirsoft-basic',
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => json_encode(['ko' => '테스트 템플릿', 'en' => 'Test Template']),
|
||||
'version' => '1.0.0',
|
||||
'status' => 'active',
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
// 활성 디렉토리에 사용자 수정 콘텐츠
|
||||
File::ensureDirectoryExists($fakeBase.'/templates/sirsoft-basic');
|
||||
File::put($fakeBase.'/templates/sirsoft-basic/manifest.json', '{"installed":true,"user_modified":true}');
|
||||
|
||||
// _bundled 에 다른 내용
|
||||
File::ensureDirectoryExists($fakeBase.'/templates/_bundled/sirsoft-basic');
|
||||
File::put($fakeBase.'/templates/_bundled/sirsoft-basic/manifest.json', '{"identifier":"sirsoft-basic"}');
|
||||
|
||||
$this->invokeRecover();
|
||||
|
||||
// 활성 콘텐츠가 덮어쓰여지지 않아야 함
|
||||
$manifest = json_decode(File::get($fakeBase.'/templates/sirsoft-basic/manifest.json'), true);
|
||||
$this->assertTrue($manifest['user_modified'] ?? false, '정상 활성 디렉토리는 복구 대상에서 제외되어야 한다');
|
||||
}
|
||||
|
||||
/**
|
||||
* 외부 확장 (DB active + `_bundled` 부재) → DB row 단발성 비활성화.
|
||||
*/
|
||||
public function test_external_extension_marked_deactivated_when_bundled_missing(): void
|
||||
{
|
||||
$fakeBase = $this->arrangeFakeBase();
|
||||
|
||||
DB::table('modules')->insert([
|
||||
'identifier' => 'external-vendor-x',
|
||||
'vendor' => 'external-vendor',
|
||||
'name' => json_encode(['ko' => '외부 모듈', 'en' => 'External Module']),
|
||||
'version' => '1.0.0',
|
||||
'status' => 'active',
|
||||
'github_url' => 'https://github.com/external-vendor/x',
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
// _bundled 디렉토리는 만들지만 해당 식별자는 부재 (외부 확장)
|
||||
File::ensureDirectoryExists($fakeBase.'/modules/_bundled');
|
||||
|
||||
$this->invokeRecover();
|
||||
|
||||
$row = DB::table('modules')->where('identifier', 'external-vendor-x')->first();
|
||||
$this->assertSame('inactive', $row->status, '외부 확장 row 는 inactive 로 전환되어야 한다');
|
||||
$this->assertSame('extension_dir_lost_beta5', $row->deactivated_reason);
|
||||
$this->assertNotNull($row->deactivated_at);
|
||||
}
|
||||
|
||||
/**
|
||||
* `_pending/.gitignore` 와 `_pending/.gitkeep` 가 부재 시 stub 재생성.
|
||||
*/
|
||||
public function test_pending_stub_files_recreated_when_missing(): void
|
||||
{
|
||||
$fakeBase = $this->arrangeFakeBase();
|
||||
|
||||
// _pending 자체는 존재하나 stub 부재
|
||||
foreach (['modules', 'plugins', 'templates', 'lang-packs'] as $domain) {
|
||||
File::ensureDirectoryExists($fakeBase.'/'.$domain.'/_pending');
|
||||
}
|
||||
|
||||
$this->invokeRecoverPendingStubs();
|
||||
|
||||
foreach (['modules', 'plugins', 'templates', 'lang-packs'] as $domain) {
|
||||
$this->assertFileExists($fakeBase.'/'.$domain.'/_pending/.gitignore');
|
||||
$this->assertFileExists($fakeBase.'/'.$domain.'/_pending/.gitkeep');
|
||||
|
||||
$content = File::get($fakeBase.'/'.$domain.'/_pending/.gitignore');
|
||||
$this->assertStringContainsString('*', $content);
|
||||
$this->assertStringContainsString('!.gitkeep', $content);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `_pending/.gitignore` 가 이미 존재하면 덮어쓰지 않음 (멱등).
|
||||
*/
|
||||
public function test_pending_stub_files_preserved_when_present(): void
|
||||
{
|
||||
$fakeBase = $this->arrangeFakeBase();
|
||||
|
||||
File::ensureDirectoryExists($fakeBase.'/modules/_pending');
|
||||
File::put($fakeBase.'/modules/_pending/.gitignore', "# customized\n*\n!.gitignore\n!.gitkeep\n");
|
||||
File::put($fakeBase.'/modules/_pending/.gitkeep', '');
|
||||
|
||||
$this->invokeRecoverPendingStubs();
|
||||
|
||||
$content = File::get($fakeBase.'/modules/_pending/.gitignore');
|
||||
$this->assertStringContainsString('# customized', $content, '기존 stub 은 덮어쓰여지지 않아야 한다');
|
||||
}
|
||||
|
||||
/**
|
||||
* 4개 도메인 (modules/plugins/templates/language_packs) 일괄 복구.
|
||||
*/
|
||||
public function test_all_four_domains_recovered_in_one_pass(): void
|
||||
{
|
||||
$fakeBase = $this->arrangeFakeBase();
|
||||
|
||||
DB::table('modules')->insert([
|
||||
'identifier' => 'sirsoft-ecommerce',
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => json_encode(['ko' => '이커머스', 'en' => 'Ecommerce']),
|
||||
'version' => '1.0.0',
|
||||
'status' => 'active',
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
DB::table('plugins')->insert([
|
||||
'identifier' => 'sirsoft-payment',
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => json_encode(['ko' => '결제', 'en' => 'Payment']),
|
||||
'version' => '1.0.0',
|
||||
'status' => 'active',
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
DB::table('templates')->insert([
|
||||
'identifier' => 'sirsoft-basic',
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => json_encode(['ko' => '템플릿', 'en' => 'Template']),
|
||||
'version' => '1.0.0',
|
||||
'status' => 'active',
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
// language_packs 는 마이그레이션 이후 컬럼 구조가 다름 — 컬럼이 있을 때만 시드
|
||||
if (Schema::hasTable('language_packs') && Schema::hasColumn('language_packs', 'identifier')) {
|
||||
DB::table('language_packs')->insert([
|
||||
'identifier' => 'g7-core-ja',
|
||||
'vendor' => 'g7',
|
||||
'scope' => 'core',
|
||||
'target_identifier' => null,
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'Japanese',
|
||||
'locale_native_name' => '日本語',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => 'active',
|
||||
'manifest' => json_encode([]),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
File::ensureDirectoryExists($fakeBase.'/lang-packs/_bundled/g7-core-ja');
|
||||
File::put($fakeBase.'/lang-packs/_bundled/g7-core-ja/language-pack.json', '{"identifier":"g7-core-ja"}');
|
||||
}
|
||||
|
||||
File::ensureDirectoryExists($fakeBase.'/modules/_bundled/sirsoft-ecommerce');
|
||||
File::put($fakeBase.'/modules/_bundled/sirsoft-ecommerce/module.json', '{"identifier":"sirsoft-ecommerce"}');
|
||||
File::ensureDirectoryExists($fakeBase.'/plugins/_bundled/sirsoft-payment');
|
||||
File::put($fakeBase.'/plugins/_bundled/sirsoft-payment/plugin.json', '{"identifier":"sirsoft-payment"}');
|
||||
File::ensureDirectoryExists($fakeBase.'/templates/_bundled/sirsoft-basic');
|
||||
File::put($fakeBase.'/templates/_bundled/sirsoft-basic/manifest.json', '{"identifier":"sirsoft-basic"}');
|
||||
|
||||
$this->invokeRecover();
|
||||
|
||||
$this->assertFileExists($fakeBase.'/modules/sirsoft-ecommerce/module.json');
|
||||
$this->assertFileExists($fakeBase.'/plugins/sirsoft-payment/plugin.json');
|
||||
$this->assertFileExists($fakeBase.'/templates/sirsoft-basic/manifest.json');
|
||||
|
||||
if (Schema::hasTable('language_packs') && Schema::hasColumn('language_packs', 'identifier')) {
|
||||
$this->assertFileExists($fakeBase.'/lang-packs/g7-core-ja/language-pack.json');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 복원된 활성 디렉토리에 `.preserve-ownership` 마커가 작성되지 않아야 한다.
|
||||
*
|
||||
* Step 11 `restoreOwnership` 의 재귀 chown 이 마커가 있으면 skip 하므로, 본 step 이
|
||||
* 우발적으로 마커를 만들면 영구 권한 비대칭 위험. `_bundled` 에 마커가 없으면 활성도
|
||||
* 마커 없이 복원되어야 한다.
|
||||
*/
|
||||
public function test_recover_does_not_create_preserve_ownership_marker(): void
|
||||
{
|
||||
$fakeBase = $this->arrangeFakeBase();
|
||||
|
||||
DB::table('templates')->insert([
|
||||
'identifier' => 'sirsoft-basic',
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => json_encode(['ko' => '템플릿', 'en' => 'Template']),
|
||||
'version' => '1.0.0',
|
||||
'status' => 'active',
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
File::ensureDirectoryExists($fakeBase.'/templates/_bundled/sirsoft-basic');
|
||||
File::put($fakeBase.'/templates/_bundled/sirsoft-basic/manifest.json', '{"identifier":"sirsoft-basic"}');
|
||||
|
||||
$this->invokeRecover();
|
||||
|
||||
$this->assertFileDoesNotExist(
|
||||
$fakeBase.'/templates/sirsoft-basic/.preserve-ownership',
|
||||
'복원된 활성 디렉토리에 .preserve-ownership 마커가 우발적으로 작성되어서는 안 된다',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* lang-packs/_bundled 정상 존재 시 fallback skip (멱등 확인).
|
||||
*/
|
||||
public function test_lang_packs_fallback_skipped_when_already_present(): void
|
||||
{
|
||||
$fakeBase = $this->arrangeFakeBase();
|
||||
|
||||
File::ensureDirectoryExists($fakeBase.'/lang-packs/_bundled/g7-core-ja');
|
||||
File::put($fakeBase.'/lang-packs/_bundled/g7-core-ja/language-pack.json', '{"identifier":"g7-core-ja","preserve":true}');
|
||||
|
||||
$this->invokeLangPacksFallback();
|
||||
|
||||
$manifest = json_decode(File::get($fakeBase.'/lang-packs/_bundled/g7-core-ja/language-pack.json'), true);
|
||||
$this->assertTrue($manifest['preserve'] ?? false, '정상 데이터가 fallback 으로 덮어쓰여지면 안 된다');
|
||||
}
|
||||
|
||||
/**
|
||||
* lang-packs/_bundled 부재 + _pending 에 소스 존재 시 fallback 복원.
|
||||
*/
|
||||
public function test_lang_packs_fallback_recovers_from_deep_pending_source(): void
|
||||
{
|
||||
$fakeBase = $this->arrangeFakeBase();
|
||||
|
||||
$pending = config('app.update.pending_path');
|
||||
// 비표준 깊이(5단계) 의 소스 — beta.4 의 3단계 제약을 회피하는 경로
|
||||
$deepSource = $pending.'/core_20260511_120000/extracted/wrapper/extra-layer/lang-packs/_bundled';
|
||||
File::ensureDirectoryExists($deepSource.'/g7-core-ja');
|
||||
File::put($deepSource.'/g7-core-ja/language-pack.json', '{"identifier":"g7-core-ja","source":"deep"}');
|
||||
|
||||
$this->invokeLangPacksFallback();
|
||||
|
||||
$this->assertFileExists($fakeBase.'/lang-packs/_bundled/g7-core-ja/language-pack.json');
|
||||
$manifest = json_decode(File::get($fakeBase.'/lang-packs/_bundled/g7-core-ja/language-pack.json'), true);
|
||||
$this->assertSame('deep', $manifest['source'] ?? null);
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────
|
||||
// recoverPublicStorageSymlink (계획서 §5)
|
||||
// ──────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 정상 symlink 상태면 silent skip (멱등).
|
||||
*/
|
||||
public function test_recover_public_storage_symlink_skips_when_already_symlink(): void
|
||||
{
|
||||
$fakeBase = $this->arrangeFakeBase();
|
||||
File::ensureDirectoryExists($fakeBase.'/public');
|
||||
File::ensureDirectoryExists($fakeBase.'/storage/app/public');
|
||||
|
||||
if (! @symlink($fakeBase.'/storage/app/public', $fakeBase.'/public/storage')) {
|
||||
$this->markTestSkipped('symlink 생성 권한 부족 (Windows 일반 사용자)');
|
||||
}
|
||||
|
||||
$linkTargetBefore = readlink($fakeBase.'/public/storage');
|
||||
|
||||
$this->invokeRecoverPublicStorageSymlink();
|
||||
|
||||
$this->assertTrue(is_link($fakeBase.'/public/storage'), '정상 symlink 상태는 보존되어야 한다');
|
||||
$this->assertSame($linkTargetBefore, readlink($fakeBase.'/public/storage'), 'symlink target 미변경');
|
||||
}
|
||||
|
||||
/**
|
||||
* 일반 디렉토리 + Laravel storage:link source 존재 → rename 보존 + symlink 재생성.
|
||||
*/
|
||||
public function test_recover_public_storage_symlink_recovers_corrupted_directory(): void
|
||||
{
|
||||
$fakeBase = $this->arrangeFakeBase();
|
||||
File::ensureDirectoryExists($fakeBase.'/public/storage');
|
||||
File::ensureDirectoryExists($fakeBase.'/storage/app/public');
|
||||
|
||||
// 손상 상태 시뮬레이션 — public/storage 안에 dereferenced 복사 콘텐츠
|
||||
File::put($fakeBase.'/public/storage/uploaded.txt', 'dereferenced content');
|
||||
File::put($fakeBase.'/storage/app/public/uploaded.txt', 'original content');
|
||||
|
||||
if (! @symlink($fakeBase.'/storage/app/public', $fakeBase.'/test_symlink_capability')) {
|
||||
// 권한 없음 → recoverPublicStorageSymlink 가 rename 후 symlink 실패 → 원복 경로 검증으로 대체
|
||||
@unlink($fakeBase.'/test_symlink_capability');
|
||||
$this->markTestSkipped('symlink 생성 권한 부족 (Windows 일반 사용자)');
|
||||
}
|
||||
@unlink($fakeBase.'/test_symlink_capability');
|
||||
|
||||
$this->invokeRecoverPublicStorageSymlink();
|
||||
|
||||
// 1) public/storage 가 symlink 로 재생성
|
||||
$this->assertTrue(is_link($fakeBase.'/public/storage'), 'public/storage 가 symlink 로 재생성되어야 한다');
|
||||
$this->assertSame($fakeBase.'/storage/app/public', readlink($fakeBase.'/public/storage'));
|
||||
|
||||
// 2) .broken.{timestamp} 백업 디렉토리 존재 + dereferenced 콘텐츠 보존
|
||||
$backups = array_values(array_filter(
|
||||
scandir($fakeBase.'/public'),
|
||||
fn ($e) => str_starts_with($e, 'storage.broken.'),
|
||||
));
|
||||
$this->assertCount(1, $backups, '.broken.{timestamp} 백업 디렉토리 1개 존재');
|
||||
$this->assertFileExists($fakeBase.'/public/'.$backups[0].'/uploaded.txt');
|
||||
$this->assertSame('dereferenced content', File::get($fakeBase.'/public/'.$backups[0].'/uploaded.txt'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Laravel storage:link source (storage/app/public) 부재 → 운영자 의도적 구성으로 보고 skip.
|
||||
*/
|
||||
public function test_recover_public_storage_symlink_skips_when_source_absent(): void
|
||||
{
|
||||
$fakeBase = $this->arrangeFakeBase();
|
||||
File::ensureDirectoryExists($fakeBase.'/public/storage');
|
||||
File::put($fakeBase.'/public/storage/custom.txt', 'operator content');
|
||||
// storage/app/public 의도적 미생성 — Laravel 표준 미사용 운영자 시뮬
|
||||
|
||||
$this->invokeRecoverPublicStorageSymlink();
|
||||
|
||||
// public/storage 는 일반 디렉토리로 유지 + 콘텐츠 보존
|
||||
$this->assertFalse(is_link($fakeBase.'/public/storage'), 'source 부재 시 symlink 생성 안 함');
|
||||
$this->assertTrue(is_dir($fakeBase.'/public/storage'));
|
||||
$this->assertFileExists($fakeBase.'/public/storage/custom.txt');
|
||||
$this->assertSame('operator content', File::get($fakeBase.'/public/storage/custom.txt'));
|
||||
|
||||
// .broken.* 백업도 없어야 함 (rename 미실행)
|
||||
$entries = array_values(array_filter(
|
||||
scandir($fakeBase.'/public'),
|
||||
fn ($e) => str_starts_with($e, 'storage.broken.'),
|
||||
));
|
||||
$this->assertEmpty($entries, 'source 부재 시 rename 백업도 생성되지 않아야 한다');
|
||||
}
|
||||
|
||||
/**
|
||||
* public/storage 자체가 부재 (storage:link 미실행 환경) → skip.
|
||||
*/
|
||||
public function test_recover_public_storage_symlink_skips_when_public_storage_absent(): void
|
||||
{
|
||||
$fakeBase = $this->arrangeFakeBase();
|
||||
File::ensureDirectoryExists($fakeBase.'/public');
|
||||
File::ensureDirectoryExists($fakeBase.'/storage/app/public');
|
||||
// public/storage 의도적 미생성 — storage:link 가 한 번도 실행되지 않은 환경
|
||||
|
||||
$this->invokeRecoverPublicStorageSymlink();
|
||||
|
||||
$this->assertFalse(is_link($fakeBase.'/public/storage'), 'public/storage 부재 시 자동 생성 안 함');
|
||||
$this->assertFalse(file_exists($fakeBase.'/public/storage'), 'public/storage 자체가 생성되지 않아야 한다');
|
||||
}
|
||||
|
||||
/**
|
||||
* 격리된 base_path + pending_path 구성.
|
||||
*/
|
||||
private function arrangeFakeBase(): string
|
||||
{
|
||||
$fakeBase = storage_path('test_beta5_recovery_'.uniqid());
|
||||
File::ensureDirectoryExists($fakeBase);
|
||||
$this->tempDirs[] = $fakeBase;
|
||||
app()->setBasePath($fakeBase);
|
||||
|
||||
$fakePending = $fakeBase.'/storage/app/core_pending';
|
||||
File::ensureDirectoryExists($fakePending);
|
||||
config(['app.update.pending_path' => $fakePending]);
|
||||
|
||||
return $fakeBase;
|
||||
}
|
||||
|
||||
private function invokeRecover(): void
|
||||
{
|
||||
$class = 'App\\Upgrades\\Data\\V7_0_0_beta_5\\Migrations\\RecoverActiveExtensionDirs';
|
||||
(new $class)->run($this->context);
|
||||
}
|
||||
|
||||
private function invokeRecoverPendingStubs(): void
|
||||
{
|
||||
$class = 'App\\Upgrades\\Data\\V7_0_0_beta_5\\Migrations\\RecoverPendingStubFiles';
|
||||
(new $class)->run($this->context);
|
||||
}
|
||||
|
||||
private function invokeRecoverPublicStorageSymlink(): void
|
||||
{
|
||||
$class = 'App\\Upgrades\\Data\\V7_0_0_beta_5\\Migrations\\RecoverPublicStorageSymlink';
|
||||
(new $class)->run($this->context);
|
||||
}
|
||||
|
||||
private function invokeLangPacksFallback(): void
|
||||
{
|
||||
$class = 'App\\Upgrades\\Data\\V7_0_0_beta_5\\Migrations\\VerifyBundledLangPacksFallback';
|
||||
(new $class)->run($this->context);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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 도 함께 정리.
|
||||
*/
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# audit:allow test-scenario-coverage reason: 본 매니페스트는 #347 활성 디렉토리 보존 + 단발성 복구 인프라의 시나리오 매트릭스 SSoT. 핵심 회귀 가드는 test_files 의 통과 테스트로 커버.
|
||||
|
||||
feature: 코어 업데이트 활성 확장 디렉토리 보존 + beta.5 단발성 복구
|
||||
|
||||
description: |
|
||||
beta.4 의 `CoreUpdateService::applyDiscoveredTopLevelPaths` 가 `isCoveredByApplied`
|
||||
단방향 검사 결함으로 `applied=['templates/_bundled']` 일 때 source 의 `templates/`
|
||||
자체를 신규 항목으로 오인하여 `copyDirectory(removeOrphans:true)` 호출 → base 의
|
||||
활성 서브디렉토리(`templates/sirsoft-basic` 등) 가 orphan 으로 판정되어 삭제되던
|
||||
회귀 (#347) 의 차단 + beta.4 → beta.5 1회성 자동 복구 인프라.
|
||||
|
||||
근본 수정 (3건 trade-off 없는 구성):
|
||||
1. `isCoveredByApplied` 양방향 검사 — applied 가 path 의 자식일 때도 cover 판정.
|
||||
2. `applyDiscoveredTopLevelPaths` 의 `copyDirectory` 호출에서 `removeOrphans:false`
|
||||
— 자동 발견 폴백은 destination 의 orphan 정리 책임 없음.
|
||||
3. `update.protected_paths` 기본값에 `modules,plugins,templates,lang-packs` 추가
|
||||
— 부모 디렉토리 단위 자동 발견 자체를 방어 깊이로 차단.
|
||||
|
||||
단발성 복구 인프라 (`Upgrade_7_0_0_beta_5`):
|
||||
1. `recoverActiveExtensionDirs` — DB active row 식별자 + `_bundled/{id}` 매칭
|
||||
→ 활성 디렉토리 부재 시 `FilePermissionHelper::copyDirectory(removeOrphans:false)`
|
||||
복사. 4개 도메인 (modules/plugins/templates/language_packs) 동일 패턴.
|
||||
2. 외부 확장 (DB active + `_bundled` 부재): 자동 복구 불가 → stdout 안내 +
|
||||
DB row `status='inactive' + deactivated_reason='extension_dir_lost_beta5'`
|
||||
단발성 전환. `deactivated_*` 컬럼 부재 시 graceful skip.
|
||||
3. `recoverPendingStubFiles` — `{type}/_pending/{.gitignore,.gitkeep}` 부재 시
|
||||
재생성 (기존 stub 은 덮어쓰지 않음).
|
||||
4. `verifyBundledLangPacksFallback` — beta.4 의 `recoverLangPacksBundled` 와
|
||||
동등 fallback 을 무제한 깊이 재귀로 한 번 더 멱등 실행.
|
||||
|
||||
axes:
|
||||
source_structure: [bundled_only, bundled_plus_other, empty_top_level] # source 의 templates/ 디렉토리 구조
|
||||
applied_targets_set: [bundled_targets, no_targets, mixed_targets] # config('app.update.targets')
|
||||
active_subdir_state: [present, absent, empty] # base 의 활성 서브디렉토리 존재 여부
|
||||
protected_paths_set: [defaults_with_parent, defaults_without_parent] # protected_paths 에 부모 디렉토리 포함 여부
|
||||
domain: [modules, plugins, templates, language_packs]
|
||||
bundled_presence: [present, missing] # _bundled/{id} 존재 여부 (단발성 복구)
|
||||
source_url_column: [present_value, present_null, column_absent] # 외부 확장 안내 분기
|
||||
deactivated_columns: [present, absent] # 마이그레이션 적용 여부 (graceful skip)
|
||||
pending_stub_state: [both_present, gitignore_missing, gitkeep_missing, both_missing, dir_missing]
|
||||
lang_packs_pending_depth: [depth_2, depth_3, depth_5, depth_unbounded] # locatePendingLangPacksSourceDeep
|
||||
|
||||
exclusions:
|
||||
- { source_structure: empty_top_level, active_subdir_state: present, reason: "source 가 비었으면 자동 발견 폴백 자체가 트리거 안 됨 — 활성 서브디렉토리 보존 무조건 보장" }
|
||||
- { applied_targets_set: no_targets, source_structure: bundled_only, reason: "targets 가 비면 source 의 templates/ 자체가 자동 발견 대상이 됨 — protected_paths 분기로 차단되어야 정상" }
|
||||
- { domain: language_packs, deactivated_columns: absent, source_url_column: column_absent, reason: "마이그레이션 미적용 환경 — 단발성 마킹/안내 모두 graceful skip 외 다른 효과 없음" }
|
||||
|
||||
effects:
|
||||
- applyDiscoveredTopLevelPaths_does_not_remove_active_subdirs_when_source_only_has_bundled
|
||||
- applyDiscoveredTopLevelPaths_skips_parent_when_isCoveredByApplied_detects_child_in_applied
|
||||
- applyDiscoveredTopLevelPaths_skips_parent_when_protected_paths_lists_parent
|
||||
- applyDiscoveredTopLevelPaths_preserves_modules_plugins_templates_lang_packs_all_four_domains
|
||||
- applyUpdate_targets_branch_continues_to_remove_orphans_within_bundled_subtree # _bundled 내부 stale 파일 정리는 정상 동작
|
||||
- recoverActiveExtensionDirs_restores_from_bundled_when_active_missing
|
||||
- recoverActiveExtensionDirs_skips_when_active_present_and_nonempty
|
||||
- recoverActiveExtensionDirs_does_not_overwrite_user_modified_active_content
|
||||
- recoverActiveExtensionDirs_marks_external_extension_inactive_with_reason
|
||||
- recoverActiveExtensionDirs_skips_db_update_when_deactivated_columns_absent
|
||||
- recoverActiveExtensionDirs_emits_stdout_with_reinstall_command_when_source_url_present
|
||||
- recoverActiveExtensionDirs_emits_stdout_without_command_when_source_url_null
|
||||
- recoverActiveExtensionDirs_does_not_write_preserve_ownership_marker_to_restored_dir
|
||||
- recoverPendingStubFiles_creates_gitignore_and_gitkeep_when_absent
|
||||
- recoverPendingStubFiles_preserves_existing_stubs_idempotently
|
||||
- recoverPendingStubFiles_creates_pending_dir_when_missing
|
||||
- verifyBundledLangPacksFallback_skips_when_active_bundled_present
|
||||
- verifyBundledLangPacksFallback_recovers_from_deep_pending_source_unbounded_depth
|
||||
|
||||
test_files:
|
||||
- tests/Unit/Services/CoreUpdateServiceTest.php
|
||||
- tests/Feature/Upgrades/Upgrade_7_0_0_beta_5RecoveryTest.php
|
||||
|
||||
# 본 시나리오 매니페스트의 axes cross product 는 50+ 케이스이나, 실제 핵심 회귀 가드는
|
||||
# test_files 의 통과 테스트들이 SSoT — 매니페스트는 매트릭스 SSoT 역할.
|
||||
@@ -0,0 +1,93 @@
|
||||
# audit:allow test-scenario-coverage reason: 본 매니페스트는 코어 업데이트 spawn 실패 / silent skip / stale 메모리 가드 인프라의 시나리오 매트릭스 SSoT. 핵심 회귀 가드는 test_files 의 통과 테스트로 커버.
|
||||
|
||||
feature: 코어 업데이트 spawn 자식 실패 fail-fast + [STEPS_EXECUTED] silent skip 가드 + stale 메모리 가드
|
||||
|
||||
description: |
|
||||
공개 이슈 gnuboard/g7#28 (beta.3 → beta.4 업그레이드 도중 `Call to undefined method
|
||||
ensureWritableDirectories()` fatal) 의 발현 메커니즘은 spawn 자식 프로세스 실패 →
|
||||
부모 in-process fallback 진입 → 부모 메모리의 stale 클래스가 신규 메서드 호출 시
|
||||
fatal.
|
||||
|
||||
본 매니페스트는 spawn 자식 실패의 4가지 분기 (proc_open 비활성 / 자원 생성 실패 /
|
||||
자식 비정상 종료 / 자식 silent skip) 각각에 대해 spawn_failure_mode (abort/fallback)
|
||||
가 정상 동작하는지 + stale 메모리 가드가 in-process fallback 진입 시점에 abort/fallback
|
||||
분기를 일관 적용하는지의 cross product 회귀 가드.
|
||||
|
||||
구성 (정책 결정 2026-05-11):
|
||||
1. `spawn_failure_mode` 기본값 `abort` — 4분기 모두 UpgradeHandoffException throw.
|
||||
2. `[STEPS_EXECUTED]` stdout 라인 프로토콜 — 자식이 실행한 step 수 명시.
|
||||
부모가 신호 미수신 또는 step 0건 실행 (from<to) 감지 시 silent skip 으로 판정.
|
||||
3. `runUpgradeSteps` 진입 직후 stale 메모리 가드 — config('app.version') < toVersion
|
||||
이면 mode=abort 시 throw, mode=fallback 시 warning log.
|
||||
4. V-1 안전 작성 패턴 docs + audit rule `upgrade-step-vone-safety` (warning) —
|
||||
upgrade step 안의 `app(*Service|*Manager|*Repository::class)` 호출을 reviewer 에게 surface.
|
||||
|
||||
axes:
|
||||
spawn_branch: [proc_open_disabled, proc_open_resource_fail, child_abnormal_exit, child_silent_skip_no_signal, child_silent_skip_zero_steps]
|
||||
spawn_failure_mode: [abort, fallback]
|
||||
from_to_relation: [from_lt_to, from_eq_to_forced] # version_compare 분기
|
||||
parent_memory_version: [equal_to_to, less_than_to, greater_than_to] # stale 가드 트리거 조건
|
||||
steps_executed_signal: [present_positive, present_zero, absent] # 자식의 [STEPS_EXECUTED] 발행 상태
|
||||
child_process_origin: [beta_5_plus, beta_4_or_earlier] # 이전 버전 자식 (silent skip 시뮬레이션)
|
||||
upgrade_step_v_one_pattern: [app_service_call, app_manager_call, app_repository_call, local_only]
|
||||
audit_allow_inline: [present, absent] # 면제 주석 적용 여부
|
||||
symlink_target_state: [valid, broken, windows_no_privilege] # symlink 보존 분기 (§1 연동)
|
||||
|
||||
exclusions:
|
||||
- { spawn_branch: proc_open_disabled, parent_memory_version: equal_to_to, reason: "proc_open 비활성 시점에 부모는 항상 fromVersion 메모리 — equal 케이스 시뮬 불가" }
|
||||
- { from_to_relation: from_eq_to_forced, spawn_branch: child_silent_skip_zero_steps, reason: "from==to + force 케이스는 step 0건이 정상 동작이므로 silent skip 가드 미트리거" }
|
||||
- { child_process_origin: beta_4_or_earlier, steps_executed_signal: present_positive, reason: "beta.5 이전 자식은 [STEPS_EXECUTED] 신호 자체를 모름 — present_positive 시뮬 불가" }
|
||||
|
||||
effects:
|
||||
# §2 spawn_failure_mode + failSpawnWithMode
|
||||
- failSpawnWithMode_abort_throws_UpgradeHandoffException_with_resume_command
|
||||
- failSpawnWithMode_fallback_returns_false_with_warning_log
|
||||
- spawnUpgradeStepsProcess_proc_open_disabled_dispatches_to_failSpawnWithMode
|
||||
- spawnUpgradeStepsProcess_proc_open_resource_fail_dispatches_to_failSpawnWithMode
|
||||
- spawnUpgradeStepsProcess_child_abnormal_exit_dispatches_to_failSpawnWithMode
|
||||
# §2.1 [STEPS_EXECUTED] silent skip 가드
|
||||
- ExecuteUpgradeStepsCommand_emits_STEPS_EXECUTED_with_count_on_normal_completion
|
||||
- ExecuteUpgradeStepsCommand_does_not_emit_STEPS_EXECUTED_on_handoff_exit
|
||||
- spawnUpgradeStepsProcess_parses_STEPS_EXECUTED_with_positive_count_returns_true
|
||||
- spawnUpgradeStepsProcess_missing_STEPS_EXECUTED_dispatches_to_failSpawnWithMode
|
||||
- spawnUpgradeStepsProcess_zero_steps_with_from_lt_to_dispatches_to_failSpawnWithMode
|
||||
- spawnUpgradeStepsProcess_zero_steps_with_from_eq_to_forced_returns_true
|
||||
# §6 stale 메모리 가드
|
||||
- runUpgradeSteps_throws_UpgradeHandoffException_when_memory_lt_to_with_abort_mode
|
||||
- runUpgradeSteps_logs_warning_when_memory_lt_to_with_fallback_mode
|
||||
- runUpgradeSteps_proceeds_silently_when_memory_eq_or_gt_to
|
||||
- runUpgradeSteps_resume_command_format_matches_execute_upgrade_steps_signature
|
||||
# §1 symlink 보존 (CoreBackupHelper 위임 경로 포함)
|
||||
- copyDirectory_preserves_symlink_target_pointer_on_linux
|
||||
- copyDirectory_falls_back_to_directory_copy_on_symlink_failure
|
||||
- copyDirectory_replaces_existing_directory_with_symlink_when_source_is_symlink
|
||||
- removeOrphanItems_unlinks_orphan_symlinks_without_recursive_delete
|
||||
# §7 V-1 audit rule
|
||||
- upgrade_step_vone_safety_warns_on_app_service_call_in_upgrade_step
|
||||
- upgrade_step_vone_safety_warns_on_app_manager_call_in_upgrade_step
|
||||
- upgrade_step_vone_safety_warns_on_app_repository_call_in_upgrade_step
|
||||
- upgrade_step_vone_safety_skips_when_audit_allow_inline_present
|
||||
|
||||
test_files:
|
||||
- tests/Feature/Console/CoreUpdateCommandSpawnFailureTest.php
|
||||
- tests/Feature/Console/CoreUpdateCommandHandoffTest.php
|
||||
- tests/Feature/Upgrades/MultiVersionUpgradePathTest.php
|
||||
- tests/Unit/Extension/Helpers/FilePermissionHelperSymlinkTest.php
|
||||
|
||||
# 본 매니페스트의 axes cross product 는 800+ 케이스이나, 실제 회귀 가드는 test_files 의
|
||||
# 통과 테스트들이 SSoT — 매니페스트는 매트릭스 SSoT 역할.
|
||||
#
|
||||
# 잔존 결함 (계획서 §9 명시, 본 매트릭스에서 제외):
|
||||
# 9.1: proc_open 비활성 + spawn_failure_mode=fallback 사용자의 V-1 fatal
|
||||
# → mode=fallback 자체가 호환 옵션이며, V-1 위험 잔존은 fallback 의 본질.
|
||||
# 매트릭스 검증 대상 아님.
|
||||
# 9.2: Windows 환경의 public/storage symlink 보존
|
||||
# → axes.symlink_target_state=windows_no_privilege 케이스로 표현되며,
|
||||
# symlink 생성 자체가 PHP 권한 부족으로 실패 → 일반 디렉토리 폴백.
|
||||
# 회귀 테스트가 markTestSkipped 로 표시.
|
||||
# 9.3: OPCache file_cache 활성 환경의 stale 자식 디스크 캐시
|
||||
# → 본 매니페스트 범위 밖 (인프라 설정).
|
||||
# 9.6: beta.1/2 사용자의 beta.5 직접 점프 fatal
|
||||
# → axes.parent_memory_version=less_than_to 케이스 일부 시뮬레이션 가능하나,
|
||||
# 실 fatal 은 이전 버전 디스크의 CoreUpdateCommand 가 호출되는 시점이라
|
||||
# 본 브랜치 코드의 영향력 범위 밖. 단계적 업그레이드 가이드 (CHANGELOG Upgrade Notice).
|
||||
@@ -0,0 +1,83 @@
|
||||
# audit:allow test-scenario-coverage reason: 본 매니페스트는 본인인증 권한 분리 SSoT. 핵심 회귀 가드는 test_files 의 통과 테스트가 cover.
|
||||
|
||||
feature: 본인인증(IDV) 관리자 권한 — read / update 분리
|
||||
|
||||
description: |
|
||||
메시지 템플릿 카테고리(`messages.read` / `messages.update`)와 일관되도록
|
||||
프로바이더/정책 카테고리도 `read` / `update` 로 분리.
|
||||
|
||||
핵심 변경:
|
||||
- 권한 키 rename: `core.admin.identity.manage` → `.providers.update`
|
||||
- 권한 키 rename: `core.admin.identity.policies.manage` → `.policies.update`
|
||||
- 신설: `core.admin.identity.providers.read` (프로바이더 설정 조회)
|
||||
- 신설: `core.admin.identity.policies.read` (정책 조회)
|
||||
- 라우트 미들웨어 분리: GET → `.read`, POST/PATCH/DELETE → `.update`
|
||||
- Upgrade_7_0_0_beta_5 step 이 in-place identifier UPDATE 로 마이그레이션 →
|
||||
role_permissions 피벗(scope_type/granted_at/granted_by) 자동 보존
|
||||
- PolicyResource / PolicyCollection / ProviderResource abilityMap 갱신
|
||||
- 코어 admin + 이커머스 + 게시판 본인인증 정책 탭에 abilityMap 기반 disabled 적용
|
||||
|
||||
axes:
|
||||
permission_set: [none, providers_read_only, providers_update_only, providers_both, policies_read_only, policies_update_only, policies_both, all_four]
|
||||
api_method: [GET_providers, POST_providers, GET_policies, POST_policies, PATCH_policies, DELETE_policies]
|
||||
user_type: [super_admin, regular_with_role, guest]
|
||||
upgrade_state: [pre_beta5_legacy_keys, post_beta5_migrated, post_beta5_fresh_install]
|
||||
|
||||
exclusions:
|
||||
- { user_type: guest, api_method: GET_providers, reason: "guest 는 admin 라우트 접근 불가 (401)" }
|
||||
- { user_type: guest, api_method: POST_providers, reason: "동일" }
|
||||
- { user_type: guest, api_method: GET_policies, reason: "동일" }
|
||||
- { user_type: guest, api_method: POST_policies, reason: "동일" }
|
||||
- { user_type: guest, api_method: PATCH_policies, reason: "동일" }
|
||||
- { user_type: guest, api_method: DELETE_policies, reason: "동일" }
|
||||
- { permission_set: providers_read_only, api_method: GET_policies, reason: "정책 API 는 policies.* 권한이 결정 — providers.read 무관" }
|
||||
- { permission_set: providers_update_only, api_method: GET_policies, reason: "동일" }
|
||||
- { permission_set: policies_read_only, api_method: GET_providers, reason: "프로바이더 API 는 providers.* 권한이 결정 — policies.read 무관" }
|
||||
- { permission_set: policies_update_only, api_method: GET_providers, reason: "동일" }
|
||||
- { upgrade_state: post_beta5_fresh_install, api_method: GET_providers, reason: "신규 설치는 legacy 키 자체가 없으므로 마이그레이션 대상 외" }
|
||||
|
||||
effects:
|
||||
# 조회 권한 분리
|
||||
- providers_read_grants_get_access_without_update
|
||||
- providers_update_alone_does_not_grant_get_access
|
||||
- policies_read_grants_get_access_without_update
|
||||
- policies_update_alone_does_not_grant_get_access
|
||||
|
||||
# 수정 권한 분리
|
||||
- providers_update_required_for_post_endpoints
|
||||
- policies_update_required_for_store_update_destroy
|
||||
- read_only_user_blocked_on_mutation_endpoints
|
||||
|
||||
# 권한 격리
|
||||
- no_permission_blocked_on_all_endpoints_with_403
|
||||
- all_four_permission_user_has_full_access
|
||||
|
||||
# 마이그레이션 보존
|
||||
- legacy_manage_permission_id_preserved_during_rename
|
||||
- role_permissions_pivot_metadata_preserved_after_rename
|
||||
- role_membership_with_legacy_permission_continues_after_migration
|
||||
- migration_is_idempotent_silent_skip_when_no_legacy_rows
|
||||
- fresh_install_creates_four_permissions_without_migration
|
||||
|
||||
# 새 권한 카탈로그 가시성
|
||||
- permission_catalog_lists_eight_identity_permissions_after_migration
|
||||
- permission_labels_localized_in_ko_en_ja
|
||||
|
||||
# abilityMap UI 가드
|
||||
- policy_resource_can_update_reflects_policies_update_permission
|
||||
- policy_resource_can_delete_reflects_policies_update_permission
|
||||
- policy_collection_can_create_reflects_policies_update_permission
|
||||
- provider_resource_can_update_reflects_providers_update_permission
|
||||
|
||||
# 레이아웃 disabled 가드 (코어/이커머스/게시판)
|
||||
- core_admin_policies_tab_add_button_disabled_when_can_create_false
|
||||
- core_admin_policies_tab_edit_button_hidden_when_can_update_false
|
||||
- core_admin_policies_tab_delete_button_hidden_when_can_delete_false
|
||||
- core_admin_providers_tab_save_button_disabled_when_can_update_false
|
||||
- ecommerce_policies_tab_add_button_disabled_when_can_create_false
|
||||
- board_policies_tab_add_button_disabled_when_can_create_false
|
||||
|
||||
test_files:
|
||||
- tests/Feature/Api/Admin/Identity/AdminIdentityProviderPermissionTest.php
|
||||
- tests/Feature/Api/Admin/Identity/AdminIdentityPolicyPermissionTest.php
|
||||
- tests/Feature/Upgrades/Upgrade_7_0_0_beta_5PermissionRenameTest.php
|
||||
@@ -0,0 +1,61 @@
|
||||
# audit:allow test-scenario-coverage reason: 본 매니페스트는 IDV provider 해석 우선순위 매트릭스 SSoT. 회귀 가드는 test_files 의 Unit/Feature 테스트로 커버.
|
||||
|
||||
feature: IDV provider 해석 우선순위 — `provider_id` 명시 전달 (refs #275)
|
||||
|
||||
description: |
|
||||
본인인증 challenge 발행 시 어떤 IdentityVerification provider 가 선택되는지를 결정하는
|
||||
우선순위 매트릭스. 다음 2가지 진입점에서 호출자가 명시한 `provider_id` 가 우선되어야 한다:
|
||||
|
||||
1. Mode A (API 직접 호출):
|
||||
POST /api/identity/challenges { provider_id: 'plugin:external' }
|
||||
→ Controller → Service::start(providerId) → Manager::resolveForPurpose($purpose, $providerId)
|
||||
|
||||
2. Mode B (정책 기반 자동 발행):
|
||||
core.auth.after_register 훅 → InitiateIdentityChallengeAfterRegister::handle
|
||||
→ 정책 resolve 후 $policy->provider_id 를 Service::start 에 전달
|
||||
→ Manager::resolveForPurpose($purpose, $policy->provider_id)
|
||||
|
||||
결함 배경 (이슈 #275):
|
||||
- 코어 Controller / Service / Manager 가 `provider_id` 를 전달할 통로 자체가 없었음
|
||||
- signup_after_create 정책에 inicis 매핑해도 항상 mail fallback 발생
|
||||
- 결과: 프론트 모달은 KG이니시스 UI 인데 백엔드는 mail challenge 를 만들어 검증 불일치
|
||||
|
||||
fallback 보장:
|
||||
- 명시 provider 가 미등록 / purpose 미지원 시 silent fallback (예외 throw X)
|
||||
- 운영자가 정책에 plugin provider 를 지정했지만 plugin 이 비활성화된 상태에서도 가입 흐름이 막히면 안 됨
|
||||
|
||||
axes:
|
||||
call_mode: [mode_a_explicit, mode_b_policy]
|
||||
provider_id_state: [null_unspecified, valid_registered_supported, registered_not_supporting_purpose, unregistered]
|
||||
purpose: [signup, password_reset, sensitive_action]
|
||||
|
||||
exclusions:
|
||||
- { call_mode: mode_b_policy, purpose: password_reset, reason: "after_register 훅은 signup 전용. password_reset 은 별도 진입점." }
|
||||
- { call_mode: mode_b_policy, purpose: sensitive_action, reason: "동일 사유 — Mode B 는 signup 정책에만 매칭" }
|
||||
|
||||
effects:
|
||||
- explicit_provider_id_takes_precedence_over_settings_purpose_providers
|
||||
- explicit_provider_id_takes_precedence_over_default_provider
|
||||
- unregistered_provider_id_silently_falls_back_to_legacy_priority
|
||||
- registered_provider_id_not_supporting_purpose_silently_falls_back
|
||||
- null_provider_id_preserves_legacy_priority_chain
|
||||
- policy_provider_id_propagates_through_listener_to_manager
|
||||
- log_provider_id_matches_explicit_provider_when_resolution_succeeds
|
||||
- log_provider_id_falls_back_to_legacy_when_explicit_unavailable
|
||||
- policy_render_hint_fallback_passes_provider_id_to_manager
|
||||
- policy_render_hint_first_branch_short_circuits_when_provider_registered
|
||||
|
||||
test_files:
|
||||
- tests/Unit/Extension/IdentityVerification/IdentityVerificationManagerTest.php
|
||||
- tests/Unit/Services/IdentityPolicyServiceResolveRenderHintTest.php
|
||||
- tests/Feature/Identity/IdentityProviderResolutionTest.php
|
||||
|
||||
rules_layer_coverage:
|
||||
- rule: service-direct-data-access
|
||||
coverage: |
|
||||
IdentityVerificationService 는 Manager 위임 + Repository 통한 사용자 갱신만 (직접 모델 mutation 없음).
|
||||
IdentityPolicyService::resetFieldOverride 는 Repository::save 경유 (직접 $policy->save() 호출 금지).
|
||||
- rule: listener-must-implement-hooklistenerinterface
|
||||
coverage: InitiateIdentityChallengeAfterRegister 는 HookListenerInterface 구현 + getSubscribedHooks() 보유
|
||||
- rule: listener-direct-db-facade
|
||||
coverage: Listener 는 Service 와 PolicyService 만 호출 (DB facade / Model::query 미사용)
|
||||
@@ -3,7 +3,7 @@
|
||||
feature: 코어 업그레이드 권한 복원 정합화 (storage/app 사용자 데이터 보존)
|
||||
|
||||
description: |
|
||||
PO 운영 환경(7.0.0-beta.3 → 7.0.0-beta.4 업그레이드 후) 에서 모든 상품 이미지가
|
||||
운영 환경(7.0.0-beta.3 → 7.0.0-beta.4 업그레이드 후) 에서 모든 상품 이미지가
|
||||
표시되지 않던 회귀의 근본 차단 + 업그레이드 전후 권한 100% 동일 복구 인프라.
|
||||
|
||||
배경:
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
# audit:allow test-scenario-coverage reason: 본 매니페스트는 7.0.0-beta.5 도입 "버전별 데이터 스냅샷" 인프라의 시나리오 매트릭스 SSoT. 핵심 회귀 가드는 test_files 의 통과 테스트로 커버.
|
||||
|
||||
feature: 버전별 데이터 스냅샷 (AbstractUpgradeStep + data/{version}/ 격리)
|
||||
|
||||
description: |
|
||||
spawn 자식 (경로 B) 의 fresh-load 가 멀티 버전 점프 시 각 step 의 시더·Manager·헬퍼를
|
||||
모두 *최종 버전 메모리* 로 동작하게 만드는 비대칭 회귀를 차단한다.
|
||||
|
||||
본 인프라는:
|
||||
1. AbstractUpgradeStep — 카탈로그/변환/핫픽스 위임 규약
|
||||
2. upgrades/data/{version}/ — manifest + delta JSON + appliers/ + migrations/ 격리
|
||||
3. 버전 namespace (App\Upgrades\Data\V{ver}\Appliers|Migrations) — 다른 버전 클래스명 충돌 회피
|
||||
4. CoreUpdateService::runUpgradeSteps 의 fatal 가드 — beta.5+ 미상속 step 즉시 throw
|
||||
5. audit rule upgrade-step-data-snapshot (severity: error) — PR 시점 차단
|
||||
6. dogfood — Upgrade_7_0_0_beta_5 의 모든 핫픽스 5종 + IDV 권한 rename 을 새 구조로 보존
|
||||
|
||||
axes:
|
||||
extension_type: [core, bundled_module, bundled_plugin, external_module, external_plugin, bundled_template_na, bundled_langpack_na] # 적용 범위 (NA = upgrade step 시스템 부재)
|
||||
extension_g7_version_constraint: [ge_beta_5, ge_beta_4_legacy, null_constraint, malformed] # ExtensionUpgradeGuardHelper since-version 분기
|
||||
step_version: [pre_beta_5_legacy, beta_5, post_beta_5, ext_below_since, ext_at_since, ext_above_since] # 버전 가드 트리거 조건 (코어 + 확장 working-version 기준 양쪽)
|
||||
step_class_inheritance: [extends_abstract, implements_only, no_implements, callable_closure]
|
||||
data_dir_state: [absent, present_manifest_only, present_full]
|
||||
manifest_kind: [permissions, role_permissions, notification_definitions, identity_policies, unknown]
|
||||
applier_namespace: [matching_version, mismatched_version, missing_class]
|
||||
migration_filename_prefix: [no_prefix, two_digit_prefix, three_digit_prefix, alphabetic_only]
|
||||
migration_order: [01_02_03_alphabetical, 03_01_02_explicit_via_prefix]
|
||||
delta_operation: [added_only, removed_only, renamed_only, mixed, empty_delta]
|
||||
rename_collision: [new_row_absent, new_row_exists, both_absent] # IDV 권한 마이그레이션 분기
|
||||
pivot_state: [no_grant, single_role, dual_grant_on_both, multi_role]
|
||||
v_one_violation_in_applier: [seeders_use, app_service_call, app_manager_call, app_repository_call, none]
|
||||
v_one_violation_in_migration: [seeders_use, app_service_call, app_manager_call, app_repository_call, none]
|
||||
cross_version_reference: [self_only, other_version_in_applier, other_version_in_migration]
|
||||
audit_allow_inline: [present, absent] # 면제 주석 적용 여부
|
||||
hotfix_filesystem_state: [healthy, broken_active_dir, broken_pending_stub, broken_langpacks_bundled, broken_storage_symlink]
|
||||
cross_extension_namespace_collision: [single, two_extensions_same_step_version_class] # known limitation 검증
|
||||
|
||||
exclusions:
|
||||
- { step_version: pre_beta_5_legacy, step_class_inheritance: extends_abstract, reason: "legacy step 은 AbstractUpgradeStep 도입 전 코드 — 상속 불가" }
|
||||
- { step_version: pre_beta_5_legacy, data_dir_state: present_full, reason: "legacy step 은 data/ 디렉토리 미사용" }
|
||||
- { applier_namespace: missing_class, manifest_kind: unknown, reason: "kind 자체가 모르는 값이면 applier 클래스 매핑 단계 진입 안 함" }
|
||||
- { manifest_kind: unknown, delta_operation: mixed, reason: "unknown kind 는 manifest 단계에서 차단 — delta 미접근" }
|
||||
- { rename_collision: both_absent, pivot_state: dual_grant_on_both, reason: "양쪽 row 부재 시 피벗 상태와 무관 (silent skip)" }
|
||||
- { cross_version_reference: other_version_in_applier, v_one_violation_in_applier: app_service_call, reason: "두 위반 동시 케이스는 단일 axis 분석 의미 흐림" }
|
||||
- { extension_type: bundled_template_na, reason: "템플릿은 upgrade step 시스템 부재 — 본 가드 대상 외 (미래 도입 시 자동 상속)" }
|
||||
- { extension_type: bundled_langpack_na, reason: "언어팩은 upgrade step 시스템 부재 — 본 가드 대상 외" }
|
||||
- { extension_type: external_module, extension_g7_version_constraint: ge_beta_5, audit_allow_inline: absent, reason: "외부 확장은 활성 디렉토리 — audit 미적용 (런타임 가드만 발화)" }
|
||||
- { extension_type: external_plugin, extension_g7_version_constraint: ge_beta_5, audit_allow_inline: absent, reason: "외부 확장은 활성 디렉토리 — audit 미적용 (런타임 가드만 발화)" }
|
||||
- { extension_g7_version_constraint: ge_beta_4_legacy, step_class_inheritance: no_implements, reason: "legacy g7_version 확장은 가드 미발동 (호환 유지)" }
|
||||
- { extension_g7_version_constraint: null_constraint, step_class_inheritance: no_implements, reason: "g7_version 미선언 = legacy 로 판정 (호환)" }
|
||||
- { extension_g7_version_constraint: malformed, step_class_inheritance: no_implements, reason: "파싱 실패 시 보수적으로 legacy 처리 (가드 미발동)" }
|
||||
# cross_extension_namespace_collision 의 두 케이스 모두 회귀 가드 보유:
|
||||
# - single: 기본 케이스 (다른 step 버전이면 자명 격리)
|
||||
# - two_extensions_same_step_version_class: namespace 에 확장 식별자 segment 가
|
||||
# 포함되어 PHP compile-time fatal 회피. 정적 검증(DataSnapshotTest) + 실행 검증
|
||||
# (ExtensionAbstractUpgradeStepFullFlowTest::test_two_extensions_..._isolated_by_namespace)
|
||||
|
||||
test_files:
|
||||
unit:
|
||||
- path: tests/Unit/Extension/Upgrade/DataSnapshotTest.php
|
||||
covers:
|
||||
- empty / fromManifest 미존재 시 빈 스냅샷
|
||||
- versionedNamespace 의 점/하이픈 → underscore 변환
|
||||
- versionedNamespace 의 코어/번들 모듈/번들 플러그인/외부 확장 경로 분기
|
||||
- 같은 step 버전이라도 다른 확장은 서로 다른 namespace 부여 (격리 회귀 가드)
|
||||
- manifest → Applier 동적 로드 + 클래스 인스턴스화
|
||||
- Applier 파일 부재 / namespace 불일치 시 RuntimeException
|
||||
- path: tests/Unit/Extension/AbstractUpgradeStepTest.php
|
||||
covers:
|
||||
- run() 의 위임 흐름 (dataSnapshot → dataMigrations → postRun)
|
||||
- migrations 파일명 정렬 순서 실행
|
||||
- 두 자리 prefix 자동 제거 후 클래스명 매핑
|
||||
- data/{version}/ 디렉토리 부재 시 silent skip
|
||||
feature:
|
||||
- path: tests/Feature/Upgrades/RunUpgradeStepsAbstractGuardTest.php
|
||||
covers:
|
||||
- beta.5+ AbstractUpgradeStep 미상속 시 CoreUpdateOperationException
|
||||
- beta.5+ 상속 시 정상 실행
|
||||
- legacy beta.4 이하는 미상속이어도 통과
|
||||
- path: tests/Feature/Upgrades/Upgrade_7_0_0_beta_5PermissionRenameTest.php
|
||||
covers:
|
||||
- PermissionsApplier 의 in-place rename (신 row 부재 경로)
|
||||
- IdentityPermissionPivotMerge 의 충돌 경로 피벗 병합
|
||||
- 양쪽 부여된 role 의 옛 피벗 삭제 + 신 피벗 보존
|
||||
- 멱등성 (두 번 실행 안전)
|
||||
- path: tests/Feature/Upgrades/Upgrade_7_0_0_beta_5RecoveryTest.php
|
||||
covers:
|
||||
- 4개 도메인 활성 디렉토리 복구 (modules / plugins / templates / language_packs)
|
||||
- 외부 확장 손실 시 단발성 비활성화 + 안내
|
||||
- _pending stub 재생성
|
||||
- lang-packs/_bundled fallback
|
||||
- public/storage symlink 복구
|
||||
- path: tests/Feature/Upgrades/ExtensionAbstractGuardTest.php
|
||||
covers:
|
||||
- 번들 모듈 — g7_version >= beta.5, 미상속 step → RuntimeException
|
||||
- 번들 모듈 — 상속 step → 정상 실행
|
||||
- 번들 모듈 — legacy g7_version → 가드 우회
|
||||
- 번들 모듈 — callable closure → 가드 우회 (호환)
|
||||
- 번들 모듈 — step 버전 < 확장 since-version → 가드 우회 (legacy step 호환)
|
||||
- 번들 플러그인 — 미상속/상속/legacy/null g7_version 4종 동등 미러링
|
||||
- path: tests/Feature/Upgrades/ExtensionAbstractUpgradeStepFullFlowTest.php
|
||||
covers:
|
||||
- 모듈 측 전체 흐름 — Applier → Migration → postRun 순서 보존
|
||||
- 플러그인 측 전체 흐름 (동일)
|
||||
- dataDir() 가 확장 디렉토리로 자동 분기 (ReflectionClass 기반)
|
||||
- manifest.json 부재 시 graceful silent (no fatal)
|
||||
- manifest 의 Applier 파일 미존재 시 명확한 RuntimeException
|
||||
- 두 다른 모듈이 같은 step 버전 + 같은 Migration 클래스명 → namespace 격리로 양쪽 모두 자기 코드 실행
|
||||
- DataSnapshot::versionedNamespace 가 코어/확장간 서로 다른 namespace 부여
|
||||
unit_helpers:
|
||||
- path: tests/Unit/Extension/Helpers/ExtensionUpgradeGuardHelperTest.php
|
||||
covers:
|
||||
- resolveSinceVersion 분기 (null / 빈 / legacy / beta.5+ / OR / 파싱 실패)
|
||||
- assertAbstractInheritance 분기 (stepVersion < / = / > sinceVersion × 상속/미상속)
|
||||
- 예외 메시지 포맷 (확장 타입 / 식별자 / step 버전 / 도입 코어 버전 포함)
|
||||
|
||||
manual_verification:
|
||||
- "실제 beta.4 환경에서 IDV 권한 옛 키 시드 후 php artisan core:update 로 beta.5 점프 → permissions / role_permissions 의 신 키 식별자 + 피벗 보존 확인"
|
||||
- "fresh-load invariant 확인: data/7.0.0-beta.5/ 안의 클래스에서 Database\\Seeders 또는 app(*Service|*Manager|*Repository::class) 호출 시 audit error 발화"
|
||||
- "공용 디렉토리 app/Extension/Upgrade/Appliers/ 또는 app/Extension/Upgrade/Migrations/ 생성 시 audit error 발화"
|
||||
- "더미 _bundled 모듈에 g7_version=>=7.0.0-beta.5 + AbstractUpgradeStep 미상속 step 작성 → php artisan module:update 실행 시 RuntimeException 확인 (메시지에 must extend App\\Extension\\AbstractUpgradeStep 포함)"
|
||||
- "동일 모듈에 step 을 extends AbstractUpgradeStep 으로 변경 + upgrades/data/{version}/manifest.json 추가 → 재실행 시 정상 통과"
|
||||
- "g7_version=>=7.0.0-beta.4 인 더미 모듈에 미상속 step 작성 → 가드 우회 확인 (legacy 호환)"
|
||||
- "동일 시나리오를 플러그인으로 반복"
|
||||
|
||||
upstream_dependencies:
|
||||
- "CoreUpdateService::runUpgradeSteps (line 1593+ fatal 가드 — 코어)"
|
||||
- "ModuleManager::runUpgradeSteps (line 4046+ fatal 가드 — 번들 모듈)"
|
||||
- "PluginManager::runUpgradeSteps (line 4228+ fatal 가드 — 번들 플러그인)"
|
||||
- "ExtensionUpgradeGuardHelper (확장 since-version 판정 SSoT)"
|
||||
- "AbstractUpgradeStep::run (final 메서드, 위임 순서 강제 — 코어/확장 공용)"
|
||||
- "정적 audit 룰 (PR 시점 차단 — 코어/번들 확장 동시)"
|
||||
- "docs/extension/upgrade-step-guide.md §13 (규약 문서)"
|
||||
- "docs/extension/module-basics.md / plugin-development.md (확장 작성자 진입점)"
|
||||
Reference in new issue
Block a user