chore(payment): NHN KCP와 NICE 결제 플러그인 개발 브랜치 분리

정식 develop에서는 기본 번들 정책에 따라 제거된 결제 플러그인을 별도 개발 브랜치에서 계속 유지보수할 수 있도록 복원한다.
This commit is contained in:
thisgun committed 2026-07-02 20:03:22 +09:00
1 parent 49b21e788c
commit 657f546efc
651 files changed
+49118 -20476

No files matched your search

@@ -3,14 +3,12 @@
namespace Tests\Feature\Api\Admin;
use App\Contracts\Extension\CacheInterface;
use App\Contracts\Repositories\AttachmentRepositoryInterface;
use App\Contracts\Repositories\ConfigRepositoryInterface;
use App\Enums\ExtensionOwnerType;
use App\Models\Attachment;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use App\Services\SettingsService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
@@ -734,10 +732,6 @@ class SettingsControllerTest extends TestCase
/**
* 시스템 정보 응답 구조 검증
*
* @scenario probe_item=cpu_info,probe_outcome=success,auth_state=authenticated_with_permission
*
* @effects all_probes_success_returns_full_payload
*/
public function test_system_info_returns_correct_structure(): void
{
@@ -1371,210 +1365,4 @@ class SettingsControllerTest extends TestCase
$response->assertStatus(200)
->assertJson(['success' => true]);
}
// ========================================================================
// 시스템 정보 probe 실패 격리 테스트 — gnuboard/g7#59
// (구조/캐시/정상값은 위 systemInfo 테스트가 이미 커버. 여기서는 호스팅
// disable_functions/open_basedir 로 probe 가 실패해도 전체 200 을 유지하는지 검증)
// ========================================================================
/**
* 인증 없이 시스템 정보 조회 시 401 반환 (probe 실행 전 인증 가드 차단)
*
* @scenario probe_item=cpu_info,probe_outcome=success,auth_state=unauthenticated
*
* @effects unauthenticated_returns_401
*/
public function test_system_info_returns_401_without_authentication(): void
{
$response = $this->getJson('/api/admin/settings/system-info');
$response->assertStatus(401);
}
/**
* read 권한 없이 시스템 정보 조회 시 403 반환 (probe 실행 전 권한 가드 차단)
*
* @scenario probe_item=cpu_info,probe_outcome=success,auth_state=authenticated_without_permission
*
* @effects without_permission_returns_403
*/
public function test_system_info_returns_403_without_permission(): void
{
$user = User::factory()->create();
$adminRole = Role::firstOrCreate(
['identifier' => 'admin'],
[
'name' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
'description' => json_encode(['ko' => '시스템 관리자', 'en' => 'System Administrator']),
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'is_active' => true,
]
);
$readPermission = Permission::where('identifier', 'core.settings.read')->first();
if ($adminRole && $readPermission) {
$adminRole->permissions()->detach($readPermission->id);
}
$user->roles()->attach($adminRole->id, [
'assigned_at' => now(),
'assigned_by' => null,
]);
$token = $user->createToken('test-token')->plainTextToken;
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$token,
'Accept' => 'application/json',
])->getJson('/api/admin/settings/system-info');
$response->assertStatus(403);
}
/**
* probe 실패 격리(핵심 회귀 #59): 개별 항목 수집이 예외/Error 를 던져도
* API 전체는 500 이 아니라 200 을 반환하고, 실패 항목만 'unknown' 폴백으로 채운다.
*
* disable_functions/open_basedir 호스팅에서 php_uname·shell_exec·disk_*_space 가
* Error 를 던지는 상황을 getCpuInfo() 로 시뮬레이션한다. safeSystemProbe 가 이를
* 격리하지 못하면 buildSystemInfo → getSystemInfo → 컨트롤러로 전파되어 500 이 난다.
*
* @scenario probe_item=cpu_info,probe_outcome=throws_error,auth_state=authenticated_with_permission
*
* @effects failing_probe_isolated_and_api_returns_200
* @effects failed_item_filled_with_unknown_fallback
*/
public function test_system_info_isolates_failing_probe_and_returns_200(): void
{
// 캐시된 정상 페이로드가 있으면 buildSystemInfo 가 재실행되지 않으므로 먼저 비운다.
$cache = $this->app->make(CacheInterface::class);
$cache->forget('settings.system_info.'.app()->getLocale());
$service = new class($this->app) extends SettingsService
{
public function __construct($app)
{
parent::__construct(
$app->make(ConfigRepositoryInterface::class),
$app->make(AttachmentRepositoryInterface::class),
$app->make(CacheInterface::class),
);
}
protected function getCpuInfo(): string
{
throw new \Error('Call to undefined function shell_exec() (disable_functions)');
}
};
$this->app->instance(SettingsService::class, $service);
$response = $this->authRequest()->getJson('/api/admin/settings/system-info');
// 실패한 cpu_info 만 unknown 폴백, 나머지 항목은 정상 수집되어 전체 200 유지.
$response->assertStatus(200)
->assertJson([
'success' => true,
'data' => [
'cpu_info' => __('common.unknown'),
],
])
->assertJsonStructure([
'data' => [
'memory_usage' => ['total', 'used', 'free', 'percentage'],
'disk_usage' => ['total', 'used', 'free', 'percentage'],
'php_extensions' => ['required', 'optional'],
'server_time',
],
]);
}
/**
* 사용량 조회 실패 시 폴백 배열 구조 검증: unknownUsage 는 total/used/free 를
* 'unknown' 으로, percentage 를 0 으로 채워 memory_usage·disk_usage 형식을 유지한다.
*
* @scenario probe_item=memory_usage,probe_outcome=throws_error,auth_state=authenticated_with_permission
*
* @effects usage_array_fallback_keeps_total_used_free_unknown_and_percentage_zero
*/
public function test_unknown_usage_fallback_keeps_usage_array_shape(): void
{
$service = $this->app->make(SettingsService::class);
$ref = new \ReflectionMethod($service, 'unknownUsage');
$ref->setAccessible(true);
$fallback = $ref->invoke($service);
$this->assertSame(
['total', 'used', 'free', 'percentage'],
array_keys($fallback)
);
$this->assertSame(__('common.unknown'), $fallback['total']);
$this->assertSame(__('common.unknown'), $fallback['used']);
$this->assertSame(__('common.unknown'), $fallback['free']);
$this->assertSame(0, $fallback['percentage']);
}
/**
* safeSystemProbe 단위 검증: 콜백이 \Error 를 던지면 전파하지 않고 폴백을 반환한다.
*/
public function test_safe_system_probe_returns_fallback_on_error(): void
{
$service = $this->app->make(SettingsService::class);
$ref = new \ReflectionMethod($service, 'safeSystemProbe');
$ref->setAccessible(true);
$result = $ref->invoke($service, 'cpu_info', function () {
throw new \Error('disable_functions');
}, 'FALLBACK');
$this->assertSame('FALLBACK', $result);
}
// ========================================================================
// 설정 복원 (restore) 검증 — RestoreSettingsRequest 이전 회귀
// ========================================================================
/**
* 인증 없이 설정 복원 요청 시 401 반환
*/
public function test_restore_returns_401_without_authentication(): void
{
$response = $this->postJson('/api/admin/settings/restore', ['backup_path' => 'foo']);
$response->assertStatus(401);
}
/**
* update 권한 없이 설정 복원 요청 시 403 반환
*/
public function test_restore_returns_403_without_update_permission(): void
{
$user = $this->createAdminUser(['core.settings.read']);
$token = $user->createToken('test-token')->plainTextToken;
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$token,
'Accept' => 'application/json',
])->postJson('/api/admin/settings/restore', ['backup_path' => 'foo']);
$response->assertStatus(403);
}
/**
* backup_path 누락 시 FormRequest 검증으로 422 반환
*
* 회귀: 검증을 컨트롤러 내 empty() 체크에서 RestoreSettingsRequest 로 이전한 뒤에도
* 백업 경로 미입력이 422 로 차단되는지 확인한다.
*/
public function test_restore_returns_422_when_backup_path_missing(): void
{
$response = $this->authRequest()->postJson('/api/admin/settings/restore', []);
$response->assertStatus(422)
->assertJsonValidationErrors(['backup_path']);
}
}
@@ -1,119 +0,0 @@
<?php
namespace Tests\Feature\Api\Public;
use App\Services\ExtensionBundleService;
use Illuminate\Support\Facades\File;
use Mockery;
use Tests\TestCase;
/**
* 확장 프론트엔드 병합 번들 서빙 엔드포인트 Feature 테스트
*
* /api/{modules,plugins}/bundle.{js,css} 의 응답 계약(Content-Type, ETag,
* 304 Not Modified, 빈 번들 처리)을 검증한다. ExtensionBundleService 를
* 컨테이너에 mock 바인딩해 활성 확장 조합에 의존하지 않고 컨트롤러 결선을 검증한다.
*/
class ExtensionBundleServingTest extends TestCase
{
private string $fixtureDir;
protected function setUp(): void
{
parent::setUp();
$this->fixtureDir = storage_path('framework/testing/ext-bundle-serving');
File::ensureDirectoryExists($this->fixtureDir);
}
protected function tearDown(): void
{
if (is_dir($this->fixtureDir)) {
foreach (glob($this->fixtureDir.'/*') as $f) {
@unlink($f);
}
@rmdir($this->fixtureDir);
}
Mockery::close();
parent::tearDown();
}
/**
* ExtensionBundleService 를 지정 경로를 반환하도록 mock 바인딩한다.
*/
private function bindBundleService(string $returnPath): void
{
$mock = Mockery::mock(ExtensionBundleService::class);
$mock->shouldReceive('getCurrentVersion')->andReturn(777);
$mock->shouldReceive('getBundleFilePath')->andReturn($returnPath);
$this->app->instance(ExtensionBundleService::class, $mock);
}
public function test_module_bundle_js_serves_merged_file_with_etag(): void
{
$path = $this->fixtureDir.'/module.777.js';
File::put($path, "(function(){window.A=1})()\n;\n(function(){window.B=2})()");
$this->bindBundleService($path);
$response = $this->get('/api/modules/bundle.js?v=777');
$response->assertOk();
$this->assertStringStartsWith('text/javascript', $response->headers->get('Content-Type'));
$response->assertHeader('ETag');
$this->assertStringContainsString('window.A=1', $response->streamedContent() ?? $response->getContent());
$this->assertStringContainsString("\n;\n", $response->streamedContent() ?? $response->getContent());
}
public function test_bundle_returns_304_on_matching_etag(): void
{
$path = $this->fixtureDir.'/plugin.777.js';
File::put($path, '(function(){})()');
$this->bindBundleService($path);
$first = $this->get('/api/plugins/bundle.js?v=777');
$first->assertOk();
$etag = $first->headers->get('ETag');
$this->assertNotNull($etag);
$second = $this->get('/api/plugins/bundle.js?v=777', ['If-None-Match' => $etag]);
$second->assertStatus(304);
}
public function test_empty_bundle_returns_empty_ok_response(): void
{
// 활성 global 에셋이 없으면 서비스가 빈 경로 반환 → 컨트롤러 빈 200
$this->bindBundleService('');
$response = $this->get('/api/modules/bundle.js?v=777');
$response->assertOk();
$this->assertStringStartsWith('text/javascript', $response->headers->get('Content-Type'));
// 빈 번들은 일반 Response(스트림 아님) — getContent 로 빈 본문 확인
$this->assertSame('', $response->getContent());
}
public function test_module_bundle_css_serves_with_css_content_type(): void
{
$path = $this->fixtureDir.'/module.777.css';
File::put($path, '.a{color:red}');
$this->bindBundleService($path);
$response = $this->get('/api/modules/bundle.css?v=777');
$response->assertOk();
$this->assertStringStartsWith('text/css', $response->headers->get('Content-Type'));
}
public function test_bundle_routes_do_not_collide_with_asset_route(): void
{
// bundle.js 는 assets/{identifier}/{path} 로 매칭되면 안 됨 (정적 세그먼트 우선)
$path = $this->fixtureDir.'/module.777.js';
File::put($path, '(function(){window.BUNDLE=1})()');
$this->bindBundleService($path);
$response = $this->get('/api/modules/bundle.js?v=777');
$response->assertOk();
// 개별 에셋 서빙(serveAsset)이 아니라 번들 서빙(serveBundleJs)이 응답
$this->assertStringContainsString('window.BUNDLE=1', $response->streamedContent() ?? $response->getContent());
}
}
@@ -787,123 +787,4 @@ class LayoutServingTest extends TestCase
// Assert: 압축 후 크기가 50% 이상 감소
$this->assertLessThan($originalSize * 0.5, $compressedSize);
}
/**
* 공개 서빙 응답에서 개발자용 comment / _comment 필드가 제거되어야 합니다.
*
* 레이아웃 JSON 의 comment/_comment 는 편집기·개발자용 주석으로 런타임 렌더러가
* 사용하지 않으며, 공개 응답 크기를 키우므로 서빙 시 재귀적으로 제거된다.
*/
public function test_strips_developer_comments_from_public_serving(): void
{
$template = Template::create([
'identifier' => 'sirsoft-admin_basic',
'vendor' => 'sirsoft',
'name' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
'version' => '1.0.0',
'type' => 'admin',
'status' => ExtensionStatus::Active->value,
'description' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
]);
$layout = TemplateLayout::create([
'template_id' => $template->id,
'name' => 'commented',
'content' => [
'comment' => '레이아웃 최상단 개발자 주석',
'meta' => ['title' => 'Commented Layout'],
'data_sources' => [
[
'_comment' => '데이터소스 설명 주석',
'id' => 'stats',
'type' => 'api',
'endpoint' => '/api/stats',
],
],
'components' => [
[
'comment' => '컴포넌트 설명 주석',
'type' => 'div',
'props' => ['class' => 'container'],
'children' => [
[
'_comment' => '중첩 자식 주석',
'type' => 'span',
'props' => [],
'children' => ['Hello'],
],
],
],
],
],
]);
$response = $this->getJson("/api/layouts/{$template->identifier}/{$layout->name}.json");
$response->assertStatus(200);
// 응답 본문 어디에도 comment / _comment 키가 없어야 함
$body = $response->getContent();
$this->assertStringNotContainsString('"comment"', $body);
$this->assertStringNotContainsString('"_comment"', $body);
// 실제 콘텐츠(컴포넌트 구조)는 보존
$data = $response->json('data');
$this->assertArrayNotHasKey('comment', $data);
$this->assertSame('div', $data['components'][0]['type']);
$this->assertArrayNotHasKey('comment', $data['components'][0]);
$this->assertArrayNotHasKey('_comment', $data['components'][0]['children'][0]);
$this->assertArrayNotHasKey('_comment', $data['data_sources'][0]);
}
/**
* 한글이 포함된 응답이 \uXXXX 이스케이프 없이 raw UTF-8 로 직렬화되어야 합니다.
*
* JSON_UNESCAPED_UNICODE 적용으로 멀티바이트 문자의 전송 크기를 줄인다.
*/
public function test_serves_korean_as_unescaped_utf8(): void
{
$template = Template::create([
'identifier' => 'sirsoft-admin_basic',
'vendor' => 'sirsoft',
'name' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
'version' => '1.0.0',
'type' => 'admin',
'status' => ExtensionStatus::Active->value,
'description' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
]);
$layout = TemplateLayout::create([
'template_id' => $template->id,
'name' => 'korean',
'content' => [
'meta' => ['title' => '한글 제목'],
'data_sources' => [],
'components' => [
[
'type' => 'span',
'props' => [],
'children' => ['안녕하세요'],
],
],
],
]);
// 압축 없이 raw 본문 검사 (Accept-Encoding 미지정)
$response = $this->getJson("/api/layouts/{$template->identifier}/{$layout->name}.json");
$response->assertStatus(200);
$body = $response->getContent();
// raw UTF-8 한글이 그대로 실려야 함
$this->assertStringContainsString('한글 제목', $body);
$this->assertStringContainsString('안녕하세요', $body);
// \uXXXX 이스케이프 형태가 아니어야 함 (예: '한' = 한)
$this->assertStringNotContainsString('\\ud55c', $body);
// 메시지도 raw UTF-8 (레이아웃 제공 성공 메시지)
$this->assertMatchesRegularExpression('/[가-힣]/u', $body);
}
}
@@ -391,90 +391,6 @@ class LayoutSourceMetaServingTest extends TestCase
}
}
/**
* comment / _comment 필드를 가진 레이아웃을 생성합니다.
*
* @param Template $template 대상 템플릿
* @return TemplateLayout 생성된 레이아웃
*/
private function createCommentedLayout(Template $template): TemplateLayout
{
return TemplateLayout::create([
'template_id' => $template->id,
'name' => 'commented',
'content' => [
'comment' => '레이아웃 최상단 개발자 주석',
'meta' => ['title' => 'Commented'],
'components' => [
[
'comment' => '컴포넌트 설명 주석',
'type' => 'basic',
'name' => 'Div',
'props' => ['className' => 'container'],
'children' => [
[
'_comment' => '중첩 자식 주석',
'type' => 'basic',
'name' => 'Span',
'text' => 'Hello',
],
],
],
],
],
]);
}
/**
* 편집 모드(with_source_meta) 서빙에서는 comment 필드가 보존되어야 합니다.
*
* 편집기는 comment 를 편집 가능한 속성으로 노출하므로 편집 경로에서는 제거하지 않는다.
* 공개 서빙과 별도 캐시 키로 분리되어 조건부 제거가 안전함을 함께 검증한다.
*/
#[Test]
public function serve_with_source_meta_preserves_developer_comments(): void
{
$template = $this->createActiveTemplate();
$this->createCommentedLayout($template);
$admin = $this->makeEditor();
Sanctum::actingAs($admin, ['*'], 'sanctum');
$response = $this->getJson("/api/layouts/{$template->identifier}/commented.json?with_source_meta=1");
$response->assertStatus(200);
// 편집 모드에서는 comment / _comment 가 보존됨
$data = $response->json('data');
$this->assertSame('레이아웃 최상단 개발자 주석', $data['comment'] ?? null);
$this->assertSame('컴포넌트 설명 주석', $data['components'][0]['comment'] ?? null);
$this->assertSame('중첩 자식 주석', $data['components'][0]['children'][0]['_comment'] ?? null);
}
/**
* 공개 서빙(옵션 미전달)에서는 comment 필드가 제거되어야 합니다.
*
* 편집 경로와 동일 레이아웃 소스를 사용해 공개/편집 캐시 키 분리를 함께 검증한다.
*/
#[Test]
public function serve_without_source_meta_strips_developer_comments(): void
{
$template = $this->createActiveTemplate();
$this->createCommentedLayout($template);
$response = $this->getJson("/api/layouts/{$template->identifier}/commented.json");
$response->assertStatus(200);
$body = $response->getContent();
$this->assertStringNotContainsString('"comment"', $body);
$this->assertStringNotContainsString('"_comment"', $body);
// 실제 콘텐츠는 보존
$data = $response->json('data');
$this->assertSame('Div', $data['components'][0]['name']);
}
/**
* 컴포넌트 트리에서 특정 키가 존재하는지 재귀 탐색
*/
@@ -12,7 +12,7 @@ use Tests\TestCase;
/**
* `spawn_failure_mode` + `[STEPS_EXECUTED]` 신호 + stale 메모리 가드 회귀 테스트 (§2/§2.1/§6).
*
* 회귀 시나리오 (gnuboard/g7#28):
* 회귀 시나리오 (이슈 #28):
* - spawn 자식 실패 → in-process fallback 진입 → 부모 메모리 stale → upgrade step
* 안에서 신규 메서드 호출 fatal (예: `Call to undefined method ensureWritableDirectories()`)
*
@@ -96,107 +96,31 @@ class CoreUpdateCommandSpawnFailureTest extends TestCase
}
#[Test]
public function spawn_자식_범위내_스텝_파일이_없어_0건이면_정상_통과한다(): void
public function spawn_자식_silent_skip_시_abort_모드는_throw_한다(): void
{
if (! function_exists('proc_open')) {
$this->markTestSkipped('proc_open 미지원 환경');
}
// upgrade 파일 없이 호출 → 자식은 [STEPS_EXECUTED] executed=0, discovered=0 발행 + exit=0
// "범위 내 스텝 파일 자체가 없음" 은 정상 상황 (예: 스텝 불필요 릴리즈).
// discovered=0 이면 fail-fast 를 발동하지 않고 정상 통과해야 한다 (케이스 B).
// 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);
$logs = [];
$log = function (string $msg) use (&$logs): void {
$logs[] = $msg;
};
// 실 스텝 파일이 존재하지 않는 버전 범위 (9.9.8 → 9.9.9)
$result = $method->invoke($command, '9.9.8', '9.9.9', true, $log);
$this->assertTrue($result, '범위 내 스텝 파일이 없어 0건이면 정상 통과(true)여야 한다');
$allLogs = implode("\n", $logs);
$this->assertStringContainsString('실행할 스텝 없음', $allLogs, '스텝 부재 정상 통과 로그');
}
#[Test]
public function spawn_자식_범위내_스텝이_있는데_0건_실행이면_abort_throw_한다(): void
{
// 범위 내에 스텝 파일이 실제로 존재(discovered>0)하는데 executed=0 인 경우 —
// 이전 버전 자식이 신규 스텝을 놓치고 silent skip 한 gnuboard/g7#28 케이스 (케이스 A).
// 이 경우에만 fail-fast 를 발동해야 한다.
//
// 재현: 스텝 파일은 존재하나 자식의 runUpgradeSteps 가 executed 를 0 으로 보고하도록,
// discovered 는 세되 onStep 은 호출하지 않는 상황을 자식 프로세스 안에서 만들 수 없으므로,
// 부모 가드 로직(handleSpawnExit)을 직접 호출해 discovered>0 && executed=0 분기를 검증한다.
config(['app.update.spawn_failure_mode' => 'abort']);
$command = $this->makeCommandWithDummyIo();
$method = new \ReflectionMethod(CoreUpdateCommand::class, 'handleSpawnExit');
$method->setAccessible(true);
try {
// exitCode=0, handoffPayload=null, stepsExecuted=0, stepsDiscovered=5
$method->invoke($command, 0, null, 0, 5, '9.9.8', '9.9.9', fn () => null);
$this->fail('discovered>0 && executed=0 이면 mode=abort 에서 throw 되어야 한다');
$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->assertStringContainsString('발견 5건', $e->reason);
$this->assertSame('9.9.8', $e->afterVersion);
}
}
#[Test]
public function handleSpawnExit_executed_0_discovered_0_이면_from_lt_to_여도_정상_통과한다(): void
{
// 케이스 B — 범위 내 스텝 파일 부재. from<to 여도 실패 아님 (스텝 불필요 릴리즈).
// proc_open 불필요한 순수 판정 로직 단위 검증.
config(['app.update.spawn_failure_mode' => 'abort']);
$command = $this->makeCommandWithDummyIo();
$method = new \ReflectionMethod(CoreUpdateCommand::class, 'handleSpawnExit');
$method->setAccessible(true);
$logs = [];
$log = function (string $msg) use (&$logs): void {
$logs[] = $msg;
};
// exitCode=0, handoffPayload=null, stepsExecuted=0, stepsDiscovered=0
$result = $method->invoke($command, 0, null, 0, 0, '7.0.0', '7.0.1', $log);
$this->assertTrue($result, 'discovered=0 이면 abort 모드에서도 정상 통과(true)');
$this->assertStringContainsString('실행할 스텝 없음', implode("\n", $logs));
}
#[Test]
public function handleSpawnExit_구버전_자식_discovered_null_은_레거시_fail_fast_판정을_유지한다(): void
{
// discovered 필드를 모르는 구버전 자식 — executed=0 + discovered=null + from<to.
// 신버전 부모는 이 케이스를 기존(레거시) fail-fast 로 판정해야 한다 (안전 우선).
config(['app.update.spawn_failure_mode' => 'abort']);
$command = $this->makeCommandWithDummyIo();
$method = new \ReflectionMethod(CoreUpdateCommand::class, 'handleSpawnExit');
$method->setAccessible(true);
try {
// stepsExecuted=0, stepsDiscovered=null (구버전 자식)
$method->invoke($command, 0, null, 0, null, '7.0.0', '7.0.1', fn () => null);
$this->fail('discovered=null + executed=0 + from<to 는 레거시 fail-fast 여야 한다');
} catch (UpgradeHandoffException $e) {
$this->assertStringContainsString('step 0건 실행', $e->reason);
$this->assertStringNotContainsString('발견', $e->reason, 'discovered 미상이므로 발견 건수 표기 없음');
}
}
#[Test]
public function spawn_자식_범위내_스텝_파일이_없어_0건이면_fallback_모드도_정상_통과한다(): void
public function spawn_자식_silent_skip_시_fallback_모드는_false_반환한다(): void
{
if (! function_exists('proc_open')) {
$this->markTestSkipped('proc_open 미지원 환경');
@@ -210,7 +134,7 @@ class CoreUpdateCommandSpawnFailureTest extends TestCase
$result = $method->invoke($command, '9.9.8', '9.9.9', true, fn () => null);
$this->assertTrue($result, '스텝 파일 부재(discovered=0)는 fallback 모드에서도 정상 통과(true)');
$this->assertFalse($result, 'mode=fallback 에서 step 0건 실행은 false 반환');
}
#[Test]
@@ -1,107 +0,0 @@
<?php
namespace Tests\Feature\Console;
use App\Console\Commands\Core\CoreUpdateCommand;
use Illuminate\Console\OutputStyle;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Tests\TestCase;
/**
* CoreUpdateCommand 의 업그레이드 스텝 재실행 권한 안내 (renderResumeGuidance) 계약 테스트.
*
* 배경: sudo(root) 로 `core:update` 를 실행하면 업그레이드 스텝 spawn 자식이 root 로
* 돌아가고, 그 자식이 실패하면 스텝이 미실행 상태로 남아 운영자에게 재실행을 안내한다.
* 이때 실행 사용자 권한에 따라 4가지 경우로 분기해 안내해야 한다:
*
* 1. non_root — 일반 SSH 사용자 / 공유 호스팅(웹서버=PHP=실행 유저) / posix 미지원
* → 명령만 그대로. sudo -u 접두사·경고 없음.
* 2. root_web_known — root 실행 + 웹서버 계정 식별 가능
* → `sudo -u {webUser}` + 계정명 명시 경고.
* 3. root_web_symmetric — root 실행 + 웹서버 계정이 root 로 추정 (root 서비스 구성)
* → 명령만 그대로.
* 4. root_web_unknown — root 실행 + 웹서버 계정 식별 불가
* → `sudo -u <웹서버계정>` placeholder + 계정명 미상 경고.
*
* `classifyResumeExecutionContext()` 는 posix/파일시스템 상태에 의존하므로, 판정 결과를
* 입력으로 받아 출력만 담당하는 `renderResumeGuidance()` 를 리플렉션으로 직접 검증한다.
*/
class CoreUpdateResumeGuidanceTest extends TestCase
{
private const RESUME = 'php artisan core:execute-upgrade-steps --from=7.0.0 --to=7.0.1 --force';
/**
* 모드/유저를 입력해 renderResumeGuidance 를 실행하고 콘솔 출력 문자열을 반환한다.
*/
private function render(string $mode, ?string $webUser): string
{
$command = app(CoreUpdateCommand::class);
$input = new ArrayInput([]);
$output = new BufferedOutput;
$style = new OutputStyle($input, $output);
$reflection = new \ReflectionClass($command);
$property = $reflection->getProperty('output');
$property->setAccessible(true);
$property->setValue($command, $style);
$method = new \ReflectionMethod(CoreUpdateCommand::class, 'renderResumeGuidance');
$method->setAccessible(true);
$method->invoke($command, self::RESUME, $mode, $webUser);
return $output->fetch();
}
/**
* 케이스 1: non_root — 명령만 그대로. sudo -u 접두사·경고 없음.
*/
public function test_non_root_prints_command_verbatim_without_permission_warning(): void
{
$out = $this->render('non_root', null);
$this->assertStringContainsString(self::RESUME, $out);
$this->assertStringNotContainsString('sudo -u', $out);
$this->assertStringNotContainsString('root', $out);
}
/**
* 케이스 2: root_web_known — sudo -u {webUser} 접두사 + 계정명 명시 경고.
*/
public function test_root_web_known_prefixes_sudo_and_warns_with_account_name(): void
{
$out = $this->render('root_web_known', 'www-data');
$this->assertStringContainsString('sudo -u www-data '.self::RESUME, $out);
// 계정명이 경고 문구에 노출되어야 한다
$this->assertStringContainsString('www-data', $out);
$this->assertStringContainsString('root', $out);
// placeholder 는 나오면 안 된다 (계정 식별 성공 경로)
$this->assertStringNotContainsString('<웹서버계정>', $out);
}
/**
* 케이스 3: root_web_symmetric — root 서비스 구성 → 명령만 그대로.
*/
public function test_root_web_symmetric_prints_command_verbatim(): void
{
$out = $this->render('root_web_symmetric', null);
$this->assertStringContainsString(self::RESUME, $out);
$this->assertStringNotContainsString('sudo -u', $out);
}
/**
* 케이스 4: root_web_unknown — placeholder + 계정명 미상 경고.
*/
public function test_root_web_unknown_uses_placeholder_and_generic_warning(): void
{
$out = $this->render('root_web_unknown', null);
$this->assertStringContainsString('sudo -u <웹서버계정> '.self::RESUME, $out);
$this->assertStringContainsString('식별하지 못했습니다', $out);
// 대표 웹서버 계정 예시를 안내에 포함해 운영자가 직접 확인하도록 유도
$this->assertStringContainsString('www-data', $out);
}
}
@@ -120,17 +120,4 @@ class CoreUpdateWithBundleTest extends TestCase
->expectsOutputToContain('--vendor-mode')
->assertExitCode(0);
}
/**
* `--prune` 옵션이 등록되어 있는지 검증합니다 (공개 #64).
*
* 실제 파일 적용 로직(증분/prune)은 CoreUpdateServiceTest 의 applyUpdate 단위
* 테스트가 커버하며, 여기서는 커맨드 표면에 옵션이 노출되는지만 확인한다.
*/
public function test_core_update_command_accepts_prune_option(): void
{
$this->artisan('core:update', ['--help' => true])
->expectsOutputToContain('--prune')
->assertExitCode(0);
}
}
@@ -1,132 +0,0 @@
<?php
namespace Tests\Feature\Console;
use App\Extension\ExtensionManager;
use App\Extension\HookCacheManager;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\File;
use Mockery;
use Tests\TestCase;
/**
* hooks:cache / hooks:clear Artisan 커맨드 Feature 테스트.
*
* 정적 훅 매핑 캐시 생성/삭제 명령이 캐시 파일을 실제로 생성·삭제하는지 검증한다.
*/
class HooksCacheCommandTest extends TestCase
{
use RefreshDatabase;
private string $tmpCachePath;
protected function setUp(): void
{
parent::setUp();
$this->tmpCachePath = storage_path('framework/testing/hooks_cmd_'.uniqid().'.php');
// 실제 bootstrap/cache/hooks.php 를 건드리지 않도록 임시 경로 매니저를 컨테이너에 바인딩
$this->app->instance(HookCacheManager::class, new class($this->tmpCachePath) extends HookCacheManager
{
public function __construct(string $path)
{
$this->cacheFilePath = $path;
}
});
}
protected function tearDown(): void
{
if (File::exists($this->tmpCachePath)) {
File::delete($this->tmpCachePath);
}
parent::tearDown();
}
/**
* @scenario cache_state=absent, listener_type=action_sync, regeneration_trigger=hooks_cache_command, registration_source=module
*
* @effects hooks_cache_command_generates_cache_file, removed_core_listener_dropped_from_cache_after_regeneration
*/
public function test_hooks_cache_command_generates_cache_file(): void
{
$this->assertFalse(File::exists($this->tmpCachePath));
$this->artisan('hooks:cache')
->assertSuccessful();
$this->assertTrue(File::exists($this->tmpCachePath), 'hooks:cache 는 캐시 파일을 생성해야 합니다');
$cache = require $this->tmpCachePath;
$this->assertArrayHasKey('core', $cache);
$this->assertArrayHasKey('modules', $cache);
$this->assertArrayHasKey('plugins', $cache);
$this->assertGreaterThan(0, count($cache['core']));
}
/**
* @scenario cache_state=present_valid, listener_type=action_queued, regeneration_trigger=hooks_clear_command, registration_source=plugin
*
* @effects hooks_clear_command_removes_cache_file
*/
public function test_hooks_clear_command_removes_cache_file(): void
{
// 먼저 생성
$this->artisan('hooks:cache')->assertSuccessful();
$this->assertTrue(File::exists($this->tmpCachePath));
// 삭제
$this->artisan('hooks:clear')->assertSuccessful();
$this->assertFalse(File::exists($this->tmpCachePath), 'hooks:clear 는 캐시 파일을 삭제해야 합니다');
}
/**
* @scenario cache_state=present_but_testing_env, listener_type=action_queued, regeneration_trigger=hooks_cache_command, registration_source=module
*
* @effects hooks_clear_is_safe_when_cache_absent
*/
public function test_hooks_clear_command_is_safe_when_cache_absent(): void
{
$this->assertFalse(File::exists($this->tmpCachePath));
// 캐시 부재 상태에서도 성공 종료 (route:clear 동형)
$this->artisan('hooks:clear')->assertSuccessful();
}
/**
* extension:update-autoload 가 오토로드 캐시와 함께 정적 훅 매핑 캐시를 재생성하는지 검증합니다.
*
* 코어 업데이트(CoreUpdateService::clearAllCaches → extension:update-autoload)의
* 훅 캐시 재생성 choke point. 코어 리스너 추가/변경/삭제가 이 경로로 캐시에 반영된다.
*
* 격리: ExtensionManager::generateAutoloadFile() 은 mock 으로 no-op 처리한다.
* 실제 커맨드를 그대로 실행하면 testing DB(활성 확장 0건) 기준으로 실 경로
* `bootstrap/cache/autoload-extensions.php` 를 빈 배열로 덮어써 dev 환경을 오염시킨다
* (feedback_test_must_protect_dev_directories). 훅 캐시는 setUp 의 임시 경로 매니저로 격리.
*
* @scenario cache_state=corrupted_broken_structure, listener_type=action_queued, regeneration_trigger=core_update, registration_source=plugin
*
* @effects core_update_regenerates_hook_cache_via_clearAllCaches_extension_update_autoload, extension_update_regenerates_hook_cache_via_updateComposerAutoload
*/
public function test_extension_update_autoload_regenerates_hook_cache(): void
{
// 실 오토로드 캐시 파일을 건드리지 않도록 generateAutoloadFile 을 no-op 으로 대체
$extensionManager = Mockery::mock(ExtensionManager::class)->makePartial();
$extensionManager->shouldReceive('generateAutoloadFile')->once();
$this->app->instance(ExtensionManager::class, $extensionManager);
$this->assertFalse(File::exists($this->tmpCachePath));
$this->artisan('extension:update-autoload')->assertSuccessful();
$this->assertTrue(
File::exists($this->tmpCachePath),
'extension:update-autoload 는 훅 매핑 캐시를 함께 재생성해야 합니다 (코어 업데이트 choke point)'
);
$cache = require $this->tmpCachePath;
$this->assertArrayHasKey('core', $cache);
$this->assertGreaterThan(0, count($cache['core']));
}
}
@@ -251,131 +251,4 @@ class GzipEncodeResponseTest extends TestCase
// 압축 후 크기가 50% 이상 감소해야 함
$this->assertLessThan($originalSize * 0.5, $compressedSize);
}
/**
* 임시 파일을 생성하고 테스트 종료 시 정리되도록 등록합니다.
*
* @param string $content 파일 내용
* @return string 생성된 임시 파일 경로
*/
private function makeTempFile(string $content): string
{
$path = tempnam(sys_get_temp_dir(), 'gzip_test_');
file_put_contents($path, $content);
$this->beforeApplicationDestroyed(function () use ($path) {
@unlink($path);
});
return $path;
}
/**
* BinaryFileResponse(번들 JS/CSS 서빙)도 gzip 압축되어야 합니다.
*
* 기존에는 BinaryFileResponse.getContent() 가 false 를 반환해 미들웨어가
* 압축 없이 통과시켜 번들이 비압축 전송되던 사각지대를 해소한 회귀 테스트입니다.
*/
public function test_compresses_binary_file_response(): void
{
// 1KB 이상의 JS 번들 파일 (압축 대상 크기 충족)
$jsContent = str_repeat("console.log('bundle chunk');\n", 200);
$path = $this->makeTempFile($jsContent);
$middleware = new GzipEncodeResponse;
$request = Request::create('/api/modules/bundle.js', 'GET');
$request->headers->set('Accept-Encoding', 'gzip');
$response = $middleware->handle($request, function () use ($path) {
return response()->file($path, ['Content-Type' => 'text/javascript']);
});
// 압축 적용 확인
$this->assertEquals('gzip', $response->headers->get('Content-Encoding'));
// 압축 해제 시 원본 파일 내용 복원
$decompressed = gzdecode($response->getContent());
$this->assertNotFalse($decompressed);
$this->assertEquals($jsContent, $decompressed);
// Content-Length 는 압축된 크기와 일치
$this->assertEquals(
strlen($response->getContent()),
(int) $response->headers->get('Content-Length')
);
// Vary: Accept-Encoding 헤더 설정
$this->assertStringContainsString(
'Accept-Encoding',
$response->headers->get('Vary', '')
);
}
/**
* BinaryFileResponse 압축 시 원본 응답의 캐싱 헤더가 승계되어야 합니다.
*/
public function test_binary_file_response_preserves_headers(): void
{
$cssContent = str_repeat('.selector{color:red}', 100);
$path = $this->makeTempFile($cssContent);
$middleware = new GzipEncodeResponse;
$request = Request::create('/api/plugins/bundle.css', 'GET');
$request->headers->set('Accept-Encoding', 'gzip');
$response = $middleware->handle($request, function () use ($path) {
$fileResponse = response()->file($path, [
'Content-Type' => 'text/css',
'ETag' => '"test-etag"',
]);
$fileResponse->headers->set('Cache-Control', 'public, max-age=31536000, immutable');
return $fileResponse;
});
$this->assertEquals('gzip', $response->headers->get('Content-Encoding'));
$this->assertEquals('"test-etag"', $response->headers->get('ETag'));
$this->assertStringContainsString('immutable', $response->headers->get('Cache-Control', ''));
}
/**
* 작은 BinaryFileResponse(1KB 미만)는 압축하지 않아야 합니다.
*/
public function test_does_not_compress_small_binary_file_response(): void
{
$path = $this->makeTempFile('small');
$middleware = new GzipEncodeResponse;
$request = Request::create('/api/modules/bundle.js', 'GET');
$request->headers->set('Accept-Encoding', 'gzip');
$response = $middleware->handle($request, function () use ($path) {
return response()->file($path, ['Content-Type' => 'text/javascript']);
});
// 1KB 미만은 압축 생략 — 원본 BinaryFileResponse 그대로 통과
$this->assertNull($response->headers->get('Content-Encoding'));
}
/**
* gzip 미지원 클라이언트에는 BinaryFileResponse 를 압축하지 않아야 합니다.
*/
public function test_does_not_compress_binary_file_response_without_gzip_support(): void
{
$jsContent = str_repeat("console.log('x');\n", 200);
$path = $this->makeTempFile($jsContent);
$middleware = new GzipEncodeResponse;
// Accept-Encoding 헤더 없음
$request = Request::create('/api/modules/bundle.js', 'GET');
$response = $middleware->handle($request, function () use ($path) {
return response()->file($path, ['Content-Type' => 'text/javascript']);
});
$this->assertNull($response->headers->get('Content-Encoding'));
}
}
+4 -4
View File
@@ -5,7 +5,7 @@ G7 코어의 Playwright (TypeScript) 기반 결정론적 E2E 인프라.
## 빠른 시작
```powershell
# PowerShell (개발 환경)
# PowerShell (PO 환경)
$env:PLAYWRIGHT_BASE_URL='https://g7.dev'
npm run test:e2e # 전체 spec
npm run test:e2e:smoke # @smoke 태그 (homepage / login / admin-dashboard 3건)
@@ -24,9 +24,9 @@ PLAYWRIGHT_BASE_URL=https://g7.dev npx playwright test
1. **`PLAYWRIGHT_BASE_URL` 환경변수** — CI / 명시적 오버라이드 (최우선)
2. **`.env` 의 `APP_URL`** — 단 `http://localhost` 류는 fallback 부적합 (Apache vhost 미경유)
3. **그 외** — 명시 에러 (의도적으로 base URL 을 지정하지 않으면 spec 미실행)
3. **그 외** — 명시 에러 (PO 가 의도적으로 base URL 을 지정하지 않으면 spec 미실행)
도메인이 가변(개발자/CI/운영 환경별 다름)이므로 fallback 하드코딩 금지.
도메인이 가변(개발자/CI/PO 환경별 다름)이므로 fallback 하드코딩 금지.
## 디렉토리 구조
@@ -141,7 +141,7 @@ await page.route('https://api.tosspayments.com/v1/payments/confirm', route => ro
```
분기별(성공/실패/취소/금액 불일치/중복) 가맹점 측 처리(주문 상태 전환, 재고 차감, 알림 발송) 정확성 검증.
실 카드 결제 자동화는 권장하지 않음 — 수동 검증.
실 카드 결제 자동화는 권장하지 않음 — PO 수동 검증.
## 회귀 / Flaky 처리
@@ -1,116 +0,0 @@
/**
* E2E: 관리자 ↔ 유저 화면 상호 이동 링크 + 모바일 사이드바 드로어 상단 잘림 수정 (#450)
*
* @scenario admin_sidebar_view_site, admin_board_view_user_page, mobile_drawer_not_clipped
* @effects new_tab_navigation, drawer_starts_below_header
*
* 검증:
* 1. 관리자 사이드바 하단 "사이트 보기" 링크가 A[href="/"][target="_blank"] 로 마운트
* 2. 관리자 게시물 조회 화면에 "유저 화면 보기" 링크가 새 탭으로 마운트
* 3. 모바일 뷰포트에서 드로어를 열면 드로어 상단이 헤더(약 64px) 아래에서 시작 —
* 첫 메뉴 항목이 헤더에 가려 잘리지 않는다 (버그 회귀 가드)
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
/** admin 진입 공통 대기 */
async function gotoAdmin(page: import('@playwright/test').Page, path: string): Promise<void> {
await page.goto(path);
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
await page.waitForFunction(
() => !window.location.pathname.includes('/admin/login') || document.readyState === 'complete',
{ timeout: 15_000 },
);
}
// @scenario link=admin_sidebar_to_user_site, permitted=na
// @effects new_tab_navigation
test('@smoke #450 - 관리자 사이드바 "사이트 보기" 링크가 새 탭 A 로 마운트된다', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
await gotoAdmin(page, '/admin/dashboard');
expect(page.url()).not.toMatch(/\/admin\/login/);
const link = page.locator('#sidebar_view_site_link');
await expect(link).toBeAttached({ timeout: 10_000 });
await expect(link).toHaveAttribute('href', '/');
await expect(link).toHaveAttribute('target', '_blank');
await expect(link).toHaveAttribute('rel', 'noopener noreferrer');
// 사이드바 footer 는 스크롤 메뉴 밖의 형제이므로, 메뉴 영역과 별도로 마운트된다.
await expect(page.locator('#sidebar_footer')).toBeAttached();
});
// @scenario link=admin_board_to_user_board, permitted=na
// @effects new_tab_navigation, board_admin_routes_by_slug
test('@smoke #450 - 관리자 게시물 조회 화면에 "유저 화면 보기" 새 탭 링크가 마운트된다', async ({ page }) => {
// 게시판 관리 권한으로 관리자 게시물 목록 진입
const token = issueToken('sirsoft-board.notice.admin.posts.read', 'sirsoft-board.notice.admin.manage');
await authenticatePage(page, token);
await gotoAdmin(page, '/admin/board/notice');
expect(page.url()).not.toMatch(/\/admin\/login/);
const link = page.locator('#view_user_page_link').first();
// 게시판이 없거나 접근 불가 환경에서는 스킵 (권한/데이터 의존)
if ((await link.count()) === 0) {
test.skip(true, '게시판(notice) 미존재 또는 접근 불가 — 데이터 의존 스킵');
}
await expect(link).toHaveAttribute('target', '_blank');
await expect(link).toHaveAttribute('href', /\/board\/notice/);
});
// @scenario link=admin_product_to_user_detail, permitted=na
// @effects new_tab_navigation, product_detail_routes_by_code
test('@smoke #450 - 관리자 상품 수정 화면에 "유저 화면 보기" 새 탭 링크가 마운트된다', async ({ page }) => {
const token = issueToken('sirsoft-ecommerce.product.read', 'sirsoft-ecommerce.product.update');
await authenticatePage(page, token);
// 임의 상품 편집 경로 진입 (상품 미존재 시 링크 미노출 → 데이터 의존 스킵)
await gotoAdmin(page, '/admin/ecommerce/products/1/edit');
expect(page.url()).not.toMatch(/\/admin\/login/);
const link = page.locator('#view_user_page_link').first();
if ((await link.count()) === 0) {
test.skip(true, '상품(id=1) 미존재 또는 접근 불가 — 데이터 의존 스킵');
}
await expect(link).toHaveAttribute('target', '_blank');
await expect(link).toHaveAttribute('href', /\/products\/1$/);
});
// @scenario link=admin_sidebar_to_user_site, permitted=na
// @effects drawer_starts_below_header
test('@smoke #450 - 모바일 드로어가 헤더 아래에서 시작해 첫 메뉴가 잘리지 않는다', async ({ page }) => {
const token = issueToken('core.templates.layouts.edit');
await authenticatePage(page, token);
// 모바일 뷰포트 (portable breakpoint 진입)
await page.setViewportSize({ width: 390, height: 780 });
await gotoAdmin(page, '/admin/dashboard');
expect(page.url()).not.toMatch(/\/admin\/login/);
// 햄버거로 드로어 열기 (모바일 헤더의 토글). 토글 id 는 menu_toggle_btn 계열.
const toggle = page.locator('#menu_toggle_btn, [data-testid="menu_toggle_btn"], .menu_toggle_btn').first();
if ((await toggle.count()) > 0) {
await toggle.click();
}
const drawer = page.locator('#left_sidebar_area');
await expect(drawer).toBeAttached({ timeout: 10_000 });
// 드로어의 상단 y 좌표가 헤더 높이(약 64px = h-16) 이상이어야 한다.
// inset-y-0(top:0) 회귀 시 이 값이 0 이 되어 첫 메뉴가 헤더에 가려진다.
const box = await drawer.boundingBox();
if (box) {
expect(box.y, '드로어가 top:0 으로 헤더를 덮음 (#450 회귀)').toBeGreaterThanOrEqual(48);
}
// 첫 메뉴 항목의 top 이 헤더 하단(약 56~64px)보다 아래에 있어야 한다.
const firstItem = page.locator('#admin_sidebar_menu .admin-sidebar-item').first();
if ((await firstItem.count()) > 0) {
const itemBox = await firstItem.boundingBox();
if (itemBox) {
expect(itemBox.y, '첫 메뉴 항목이 헤더에 가려 잘림 (#450 회귀)').toBeGreaterThanOrEqual(48);
}
}
});
@@ -20,7 +20,7 @@
* 라운드트립으로 런타임 동작 검증.
* - 백엔드(OrderResponsePaymentHandlerTest.php, 6건 green): provider→응답
* pg_payment_handler 매핑, 미선언 시 키 부재.
* 브라우저 실측은 PG 샌드박스가 구성된 환경에서 직접 수행한다.
* 브라우저 실측은 PG 샌드박스가 구성된 환경에서 PO 가 직접 수행한다.
*
* 활성화 전 사전 작업:
* 1. checkout 결제하기 버튼에 data-testid="checkout-submit-order"
@@ -1,78 +0,0 @@
/**
* E2E: 확장 프론트엔드 병합 번들 로딩 회귀 검증
*
* @scenario extension-bundle-loading
* @effects bundle_js_requested_once_per_type, individual_iife_requests_absent,
* gdpr_interceptor_still_active, extension_handlers_registered
*
* 배경: 활성 모듈/플러그인 IIFE 를 서버측에서 종류별 1개 번들로 병합 서빙한다.
* 실제 페이지 로드 시 (1) 개별 `*.iife.js` 요청이 사라지고 `bundle.js` 로 대체되는지,
* (2) gdpr preblocker 가 여전히 유효한지(병합 후 race 회귀 없음), (3) 확장 자가등록
* (핸들러/레지스트리)이 정상 동작하는지 실측한다.
*/
import { test, expect } from '@playwright/test';
test.describe('확장 병합 번들 로딩', () => {
test('@smoke 홈페이지 로드 시 개별 iife 대신 병합 번들이 요청된다', async ({ page }) => {
const requestedUrls: string[] = [];
page.on('request', (req) => {
requestedUrls.push(req.url());
});
await page.goto('/');
await page.waitForLoadState('networkidle', { timeout: 30_000 });
const moduleBundle = requestedUrls.filter((u) => /\/api\/modules\/bundle\.js/.test(u));
const pluginBundle = requestedUrls.filter((u) => /\/api\/plugins\/bundle\.js/.test(u));
// 활성 확장이 있으면 번들이 요청되고, 종류별로 1건씩만 나가야 한다
const individualIife = requestedUrls.filter((u) => /\/api\/(modules|plugins)\/assets\/.*\.iife\.js/.test(u));
// 개별 iife 직접 요청은 0건 (번들로 대체)
expect(individualIife, `개별 iife 요청이 남아있음: ${individualIife.join(', ')}`).toHaveLength(0);
// 번들이 요청됐다면 종류별 최대 1건 (중복 가드)
expect(moduleBundle.length, '모듈 번들 중복 요청').toBeLessThanOrEqual(1);
expect(pluginBundle.length, '플러그인 번들 중복 요청').toBeLessThanOrEqual(1);
});
test('@smoke 병합 번들 응답이 정상(200/304)이고 same-origin 이다', async ({ page }) => {
const bundleResponses: { url: string; status: number }[] = [];
page.on('response', (res) => {
if (/\/api\/(modules|plugins)\/bundle\.(js|css)/.test(res.url())) {
bundleResponses.push({ url: res.url(), status: res.status() });
}
});
await page.goto('/');
await page.waitForLoadState('networkidle', { timeout: 30_000 });
for (const r of bundleResponses) {
expect([200, 304], `번들 응답 비정상: ${r.url} → ${r.status}`).toContain(r.status);
// same-origin (/api/...) — CDN/외부 origin 금지 (gdpr preblocker 자기차단 방지)
const origin = new URL(page.url()).origin;
expect(r.url.startsWith(origin), `번들 URL 이 same-origin 아님: ${r.url}`).toBe(true);
}
});
test('@smoke 확장 병합 로드 후 페이지가 정상 렌더된다 (자가등록 계약)', async ({ page }) => {
const consoleErrors: string[] = [];
page.on('console', (msg) => {
if (msg.type() === 'error') {
consoleErrors.push(msg.text());
}
});
await page.goto('/');
await page.waitForLoadState('networkidle', { timeout: 30_000 });
// 홈 네비게이션이 렌더되면 템플릿 엔진 + 확장 자가등록이 정상 작동한 것
await expect(page.getByTestId('nav-home')).toBeVisible({ timeout: 15_000 });
// 번들 파싱 에러(ASI 경계 붕괴)가 있으면 "Unexpected token" 등 콘솔 에러가 뜬다
const parseErrors = consoleErrors.filter((e) =>
/Unexpected token|SyntaxError|is not defined|Unknown action handler/i.test(e),
);
expect(parseErrors, `번들 실행 관련 콘솔 에러: ${parseErrors.join(' | ')}`).toHaveLength(0);
});
});
@@ -19,7 +19,7 @@
* 2. core.users.read 권한 토큰 fixture (issueToken).
* 3. test.describe.skip → test.describe (data-testid 추가 없이 #search_input id 로 접근 가능).
*
* 단위 테스트가 가드 로직을 잠그고 있어, 본 라이브 spec 은 실환경에서의 최종 확증용이다.
* 단위 테스트가 가드 로직을 잠그고 있어, 본 라이브 spec 은 PO 환경에서의 최종 확증용이다.
*/
import { test, expect, issueToken, authenticatePage } from '../fixtures/auth';
@@ -1,5 +1,5 @@
/**
* DevTools — 번들 분리 (lazy/debug 로드) 검증. (engine-v1.51.0)
* DevTools — 번들 분리 (lazy/debug 로드) 검증. (engine-v1.52.0)
*
* 개발자 진단도구(DevTools)는 디버그 모드에서만 쓰이므로 코어 번들에서 분리해 별도
* devtools.min.js 로 빌드하고, `initDevToolsAPI()` 가 `isEnabled()` 참일 때만 런타임
@@ -6,7 +6,7 @@
* reconciliation 이 행을 합쳐 렌더 누락. 슬롯에 주입된 컴포넌트(헤더 통화 셀렉터)도 데스크톱/
* 모바일 SlotContainer 양쪽 마운트 시 정적 root id 중복.
*
* 수정(engine-v1.50.0):
* 수정(engine-v1.52.4):
* - DynamicRenderer 가 id 표현식을 iteration 컨텍스트로 보간(resolvedComponentId).
* - SlotContainer 가 주입 컴포넌트 root id 를 컨테이너 id 로 스코프.
* - 대시보드 반복 목록·게시판/이커머스 위젯 id 동적화.
@@ -13,7 +13,7 @@
* 헤드리스에서 안정 검증 가능. 따라서 본 spec 은 **분기 안에 드롭 슬롯이 생성되는지**
* (결함① 의 직접 회귀 가드)를 렌더 계층에서 검증한다.
* - 드롭 commit(moveNode) + undo 는 헤드리스 합성 입력에서 collision 미해소로 no-op —
* 단위(`responsiveBranchPath.test.ts` moveNode 분기 정렬)와 실브라우저(Chrome MCP
* 단위(`responsiveBranchPath.test.ts` moveNode 분기 정렬)와 실브라우저(Chrome MCP PO
* 검수)로 검증한다(feedback_chrome_mcp_dnd_kit_incompatible).
*
* @scenario responsive_branch_edit drag_drop
@@ -356,7 +356,7 @@ test('@smoke #399 Phase 1.16 - footer_buttons 의 cancel/save 가 .btn-secondary
// 행 간격은 부모 .stack 의 gap-4 가 처리하므로 자식의 py-*/pt-*/pb-*/my-*/mt-*/mb-*
// 는 이중 간격을 만든다. 박스 스타일(bg-/border/rounded/shadow/ring)을 동반한
// 자식의 전방위 p-*/m-* 는 박스 내부 padding 이므로 보존.
// 본 spec 의 보안 탭 #field_login_lockout_time 은 검수자가 직접 지목한 사례 — 수직
// 본 spec 의 보안 탭 #field_login_lockout_time 은 PO 가 직접 지목한 사례 — 수직
// 패딩 토큰이 모두 제거되어 있어야 한다.
const lockoutField = page.locator('#field_login_lockout_time').first();
if (await lockoutField.count() > 0) {
@@ -40,7 +40,7 @@ class DatabaseConfigDeprecationTest extends TestCase
$this->assertEmpty(
$deprecations,
'config/database.php emitted PHP deprecation: '
.json_encode($deprecations, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)
. json_encode($deprecations, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)
);
}
@@ -57,94 +57,15 @@ class DatabaseConfigDeprecationTest extends TestCase
if ($directReferences > 0 && ! $hasGuard) {
$this->fail(
'config/database.php references PDO::MYSQL_ATTR_SSL_CA without a '
.'PHP_VERSION_ID >= 80500 ternary guard. This causes E_DEPRECATED '
.'on PHP 8.5+. Use \\Pdo\\Mysql::ATTR_SSL_CA when PHP_VERSION_ID >= 80500.'
"config/database.php references PDO::MYSQL_ATTR_SSL_CA without a "
. "PHP_VERSION_ID >= 80500 ternary guard. This causes E_DEPRECATED "
. "on PHP 8.5+. Use \\Pdo\\Mysql::ATTR_SSL_CA when PHP_VERSION_ID >= 80500."
);
}
$this->assertTrue(true);
}
/**
* 이슈 #63 회귀 — Read 커넥션은 DB_READ_* 가 비어 있으면 DB_WRITE_* 로 fallback 한다.
*
* 미설정(null) / 빈 문자열('') / 명시값 세 케이스를 모두 검증한다. 특히 빈 문자열
* 케이스는 config 가 `env('DB_READ_HOST', default)` (중첩 env) 로 되돌아가면
* fallback 이 무력화되므로(env() 가 ''를 반환) 이 테스트가 그 회귀를 차단한다.
*
* @dataProvider readFallbackProvider
*/
public function test_read_connection_falls_back_to_write_when_read_env_empty(
?string $readHost,
string $expectedHost
): void {
$original = [
'DB_WRITE_HOST' => $_ENV['DB_WRITE_HOST'] ?? null,
'DB_READ_HOST' => $_ENV['DB_READ_HOST'] ?? null,
];
$this->setEnvVar('DB_WRITE_HOST', 'write-host.test');
$this->setEnvVar('DB_READ_HOST', $readHost);
try {
// config 파일을 직접 require — 내부 env() 가 현재 $_ENV/putenv 값을 평가한다.
$config = require config_path('database.php');
$resolvedHost = $config['connections']['mysql']['read']['host'][0] ?? null;
$this->assertSame($expectedHost, $resolvedHost);
} finally {
$this->setEnvVar('DB_WRITE_HOST', $original['DB_WRITE_HOST']);
$this->setEnvVar('DB_READ_HOST', $original['DB_READ_HOST']);
}
}
/**
* @return array<string, array{0: ?string, 1: string}>
*/
public static function readFallbackProvider(): array
{
return [
'read 미설정 → write' => [null, 'write-host.test'],
'read 빈 문자열 → write' => ['', 'write-host.test'],
'read 명시 → read replica 존중' => ['read-replica.test', 'read-replica.test'],
];
}
/**
* 정적 검사 — config 가 read fallback 에 Elvis(?:) 패턴을 사용하는지 확인.
* 중첩 env(A, env(B)) 로 회귀하면(빈 문자열 fallback 실패) 이 테스트가 차단한다.
*/
public function test_config_uses_elvis_fallback_for_read_connection(): void
{
$file = file_get_contents(config_path('database.php'));
$this->assertMatchesRegularExpression(
"/env\('DB_READ_HOST'\)\s*\?:\s*env\('DB_WRITE_HOST'/",
$file,
'config/database.php 의 read.host 가 Elvis(?:) write fallback 을 사용해야 한다 '
.'(이슈 #63 — 빈 문자열 DB_READ_HOST 시 write 로 fallback).'
);
}
/**
* process env 를 임시로 설정/해제한다 (putenv + $_ENV + $_SERVER 동기).
*
* @param string $key 환경변수 키
* @param string|null $value 값 (null 이면 제거)
*/
private function setEnvVar(string $key, ?string $value): void
{
if ($value === null) {
putenv($key);
unset($_ENV[$key], $_SERVER[$key]);
} else {
putenv("{$key}={$value}");
$_ENV[$key] = $value;
$_SERVER[$key] = $value;
}
}
/**
* @param callable $fn 실행 중 발생한 deprecation 을 수집할 콜백
* @return array<int, array{message: string, file: string, line: int}>
@@ -159,7 +80,6 @@ class DatabaseConfigDeprecationTest extends TestCase
$deprecations[] = compact('message', 'file', 'line');
}
}
return true;
}, E_DEPRECATED | E_USER_DEPRECATED);
@@ -1,350 +0,0 @@
<?php
namespace Tests\Unit\Extension;
use App\Extension\Helpers\CoreBackupHelper;
use Illuminate\Support\Facades\File;
use Tests\TestCase;
/**
* CoreBackupHelper::computeApplyList() 단위 테스트 (공개 #64)
*
* `core:update` 기본(증분) 모드의 3-way 판정을 검증합니다:
* - base == theirs (코어 미변경) → 적용 목록 제외 (사용자 상태 보존)
* - base 없음 (신규) → added 로 목록 포함
* - size 다름 / md5 다름 (변경) → changed 로 목록 포함
* - symlink / excludes / protected → 목록 제외
*/
class CoreBackupHelperApplyListTest extends TestCase
{
private string $basePath; // 백업 스냅샷 (base = 구버전 원본)
private string $theirsPath; // _pending (theirs = 신 버전)
protected function setUp(): void
{
parent::setUp();
$root = storage_path('app/test_apply_list_'.uniqid());
$this->basePath = $root.DIRECTORY_SEPARATOR.'base';
$this->theirsPath = $root.DIRECTORY_SEPARATOR.'theirs';
File::ensureDirectoryExists($this->basePath);
File::ensureDirectoryExists($this->theirsPath);
}
protected function tearDown(): void
{
$root = dirname($this->basePath);
if (File::isDirectory($root)) {
File::deleteDirectory($root);
}
parent::tearDown();
}
/**
* base == theirs 인 파일은 적용 목록에서 제외됩니다 (코어 미변경 → 보존).
*/
public function test_unchanged_file_is_excluded_from_apply_list(): void
{
$this->writeBoth('app/Same.php', '<?php // identical', '<?php // identical');
$result = CoreBackupHelper::computeApplyList(
$this->basePath,
$this->theirsPath,
['app'],
[],
[],
);
$this->assertNotContains('app/Same.php', $result['apply']);
$this->assertSame(0, $result['added_count']);
$this->assertSame(0, $result['changed_count']);
}
/**
* base 에 없고 theirs 에만 있는 파일은 added 로 포함됩니다 (신규).
*/
public function test_new_file_is_added_to_apply_list(): void
{
File::ensureDirectoryExists($this->theirsPath.DIRECTORY_SEPARATOR.'app');
File::put($this->theirsPath.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'New.php', '<?php // new');
$result = CoreBackupHelper::computeApplyList(
$this->basePath,
$this->theirsPath,
['app'],
[],
[],
);
$this->assertContains('app/New.php', $result['apply']);
$this->assertSame(1, $result['added_count']);
$this->assertSame(0, $result['changed_count']);
}
/**
* size 가 다른 파일은 md5 계산 없이 changed 로 포함됩니다.
*/
public function test_size_differing_file_is_changed(): void
{
$this->writeBoth('app/Grown.php', '<?php // small', '<?php // this content is clearly longer than base');
$result = CoreBackupHelper::computeApplyList(
$this->basePath,
$this->theirsPath,
['app'],
[],
[],
);
$this->assertContains('app/Grown.php', $result['apply']);
$this->assertSame(1, $result['changed_count']);
$this->assertSame(0, $result['added_count']);
}
/**
* size 는 같지만 내용(md5)이 다른 파일은 changed 로 포함됩니다.
*/
public function test_same_size_different_content_file_is_changed(): void
{
// 동일 길이(12), 내용만 다름
$this->writeBoth('app/Edited.php', 'AAAAAAAAAAAA', 'BBBBBBBBBBBB');
$result = CoreBackupHelper::computeApplyList(
$this->basePath,
$this->theirsPath,
['app'],
[],
[],
);
$this->assertContains('app/Edited.php', $result['apply']);
$this->assertSame(1, $result['changed_count']);
}
/**
* excludes 패턴에 매칭되는 파일은 목록에서 제외됩니다.
*/
public function test_excluded_file_is_not_in_apply_list(): void
{
// theirs 에만 존재하지만 node_modules 하위 → 제외
File::ensureDirectoryExists($this->theirsPath.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'node_modules');
File::put($this->theirsPath.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'node_modules'.DIRECTORY_SEPARATOR.'x.js', 'x');
$result = CoreBackupHelper::computeApplyList(
$this->basePath,
$this->theirsPath,
['app'],
[],
['node_modules'],
);
$this->assertSame([], $result['apply']);
}
/**
* protected_paths 하위 항목은 목록에서 제외됩니다.
*/
public function test_protected_path_file_is_not_in_apply_list(): void
{
File::ensureDirectoryExists($this->theirsPath.DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.'app');
File::put($this->theirsPath.DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'runtime.txt', 'data');
$result = CoreBackupHelper::computeApplyList(
$this->basePath,
$this->theirsPath,
['storage'],
['storage'],
[],
);
$this->assertSame([], $result['apply']);
}
/**
* targets 에 명시된 `{domain}/_bundled` 경로는 상위 protected(`{domain}`)보다
* 우선하여 apply 목록에 포함됩니다 (공개 #64 / 내부 #452 회귀).
*
* 배경: `config/app.php` 의 update.targets 에는 `modules/_bundled`,
* `plugins/_bundled`, `templates/_bundled`, `lang-packs/_bundled` 가 있고,
* protected_paths 에는 부모 `modules`, `plugins`, `templates`, `lang-packs` 가
* 있다. protected 는 자동 발견 폴백이 활성 서브디렉토리(`modules/sirsoft-*`)를
* 통째로 삭제하는 회귀(#347)를 막기 위한 것인데, 정상 증분 흐름의 apply 산출에서
* `{domain}/_bundled/...` 파일이 `{domain}/` 접두사에 걸려 통째로 제외되면
* 코어 업데이트 시 번들 확장의 새 파일(composer.json·vendor-bundle.*)이
* 반영되지 않는다. targets 에 더 구체적으로 명시된 경로는 상위 protected 를
* 오버라이드해야 한다. 4종 확장(모듈/플러그인/템플릿/언어팩) 전수 검증.
*
* @dataProvider bundledDomainProvider
*/
public function test_bundled_target_overrides_parent_protected_path(string $domain): void
{
$bundledTarget = "{$domain}/_bundled";
// theirs 에만 존재하는 신규 번들 파일 (added)
$newRel = "{$bundledTarget}/vendor-ext/composer.json";
$newAbs = $this->theirsPath.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $newRel);
File::ensureDirectoryExists(dirname($newAbs));
File::put($newAbs, '{"version":"1.0.1"}');
// base·theirs 양쪽에 있지만 내용이 다른 번들 파일 (changed)
$this->writeBoth(
"{$bundledTarget}/vendor-ext/vendor-bundle.json",
'{"composer_json_sha256":"old"}',
'{"composer_json_sha256":"new-value-differs"}',
);
// 활성 서브디렉토리(=targets 밖, protected 로 보존되어야 함)
$activeRel = "{$domain}/vendor-ext-active";
File::ensureDirectoryExists($this->theirsPath.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $activeRel));
File::put(
$this->theirsPath.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, "{$activeRel}/active.php"),
'active',
);
$result = CoreBackupHelper::computeApplyList(
$this->basePath,
$this->theirsPath,
[$bundledTarget], // targets: _bundled 만 명시
[$domain, 'storage', 'vendor'], // protected: 부모 도메인 포함 (실제 config 반영)
['node_modules', '.git'],
);
// _bundled 하위 신규/변경 파일은 apply 목록에 포함되어야 한다
$this->assertContains("{$bundledTarget}/vendor-ext/composer.json", $result['apply']);
$this->assertContains("{$bundledTarget}/vendor-ext/vendor-bundle.json", $result['apply']);
$this->assertSame(1, $result['added_count']);
$this->assertSame(1, $result['changed_count']);
// 활성 서브디렉토리(targets 밖)는 순회 대상이 아니므로 목록에 없어야 한다
$this->assertNotContains("{$activeRel}/active.php", $result['apply']);
}
/**
* 4종 번들 확장 도메인 (config/app.php 의 targets/protected_paths 실제 조합).
*
* @return array<string, array{string}>
*/
public static function bundledDomainProvider(): array
{
return [
'modules' => ['modules'],
'plugins' => ['plugins'],
'templates' => ['templates'],
'lang-packs' => ['lang-packs'],
];
}
/**
* target 과 protected 가 정확히 동일한 경로면 여전히 제외됩니다 (기존 방어 유지).
*
* `_bundled` 오버라이드는 "targets 가 protected 보다 더 구체적(하위)일 때"만
* 적용된다. target == protected (예: storage) 는 제외가 정상.
*/
public function test_target_equal_to_protected_is_still_excluded(): void
{
File::ensureDirectoryExists($this->theirsPath.DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.'app');
File::put($this->theirsPath.DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'runtime.txt', 'data');
$result = CoreBackupHelper::computeApplyList(
$this->basePath,
$this->theirsPath,
['storage'],
['storage'],
[],
);
$this->assertSame([], $result['apply']);
}
/**
* added 와 changed 가 섞여 있을 때 apply 목록이 정렬되어 둘 다 포함합니다.
*/
public function test_apply_list_merges_added_and_changed_sorted(): void
{
$this->writeBoth('app/Zeta.php', 'old', 'new-different'); // changed
File::put($this->theirsPath.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'Alpha.php', 'brand-new'); // added
$this->writeBoth('app/Keep.php', 'same', 'same'); // unchanged → 제외
$result = CoreBackupHelper::computeApplyList(
$this->basePath,
$this->theirsPath,
['app'],
[],
[],
);
$this->assertSame(['app/Alpha.php', 'app/Zeta.php'], $result['apply']);
$this->assertSame(1, $result['added_count']);
$this->assertSame(1, $result['changed_count']);
}
/**
* 단일 파일 target 도 3-way 판정을 받습니다 (변경 시 changed).
*/
public function test_single_file_target_is_classified(): void
{
File::put($this->basePath.DIRECTORY_SEPARATOR.'artisan', 'v1');
File::put($this->theirsPath.DIRECTORY_SEPARATOR.'artisan', 'v2-changed');
$result = CoreBackupHelper::computeApplyList(
$this->basePath,
$this->theirsPath,
['artisan'],
[],
[],
);
$this->assertContains('artisan', $result['apply']);
$this->assertSame(1, $result['changed_count']);
}
/**
* theirs 의 symlink 는 적용 목록에서 제외되고 has_symlink 플래그가 켜집니다.
* (링크 자체는 copyDirectory 의 별도 링크 처리 경로가 담당 — 목록 산출 대상 아님)
*/
public function test_symlink_is_excluded_and_flagged(): void
{
// theirs/app/real.php + theirs/app/link.php(→ real.php) 구성
File::ensureDirectoryExists($this->theirsPath.DIRECTORY_SEPARATOR.'app');
$realTarget = $this->theirsPath.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'real.php';
File::put($realTarget, '<?php // real');
$linkPath = $this->theirsPath.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'link.php';
if (! @symlink($realTarget, $linkPath) || ! is_link($linkPath)) {
// Windows SeCreateSymbolicLink 권한 부족 등 — 링크 생성 불가 환경은 skip
$this->markTestSkipped('symlink 생성 불가 환경 (권한 부족)');
}
$result = CoreBackupHelper::computeApplyList(
$this->basePath,
$this->theirsPath,
['app'],
[],
[],
);
// real.php 는 added 로 포함되지만 link.php 는 목록에서 제외
$this->assertContains('app/real.php', $result['apply']);
$this->assertNotContains('app/link.php', $result['apply']);
$this->assertTrue($result['has_symlink'], 'symlink 발견 시 has_symlink 플래그가 켜져야 한다');
}
/**
* base·theirs 양쪽에 동일 파일을 씁니다.
*/
private function writeBoth(string $relative, string $baseContent, string $theirsContent): void
{
$rel = str_replace('/', DIRECTORY_SEPARATOR, $relative);
$baseFile = $this->basePath.DIRECTORY_SEPARATOR.$rel;
File::ensureDirectoryExists(dirname($baseFile));
File::put($baseFile, $baseContent);
$theirsFile = $this->theirsPath.DIRECTORY_SEPARATOR.$rel;
File::ensureDirectoryExists(dirname($theirsFile));
File::put($theirsFile, $theirsContent);
}
}
@@ -1,268 +0,0 @@
<?php
namespace Tests\Unit\Extension;
use App\Contracts\Repositories\ModuleRepositoryInterface;
use App\Contracts\Repositories\PluginRepositoryInterface;
use App\Extension\ExtensionManager;
use Illuminate\Support\Facades\File;
use Tests\TestCase;
/**
* 확장 소스 classmap(B2) 생성 무결성 테스트.
*
* 서빙 API 부팅 비용 최적화: 확장 소스 클래스를 classmap 에 편입하여 findFile 의
* 파일시스템 스캔(PSR-4 폴백 stat)을 제거한다. 안전 게이트:
* - FQCN 추출 정확성 (namespace + class/interface/trait/enum)
* - 소스 클래스만 대상 (서드파티 vendor 미포함 — 격리 불변조건 보존)
* - 매핑 경로 유효성
*
* @see ExtensionManager::buildSourceClassmap()
*/
class ExtensionSourceClassmapTest extends TestCase
{
private string $fixtureDir;
private ExposedExtensionManager $manager;
protected function setUp(): void
{
parent::setUp();
$this->manager = new ExposedExtensionManager(
app(ModuleRepositoryInterface::class),
app(PluginRepositoryInterface::class),
);
// base_path 하위 임시 픽스처 (buildSourceClassmap 이 base_path 상대경로를 산출하므로)
$this->fixtureDir = base_path('storage/framework/testing/classmap_fx_'.uniqid());
File::ensureDirectoryExists($this->fixtureDir.'/src');
}
protected function tearDown(): void
{
if (File::isDirectory($this->fixtureDir)) {
File::deleteDirectory($this->fixtureDir);
}
parent::tearDown();
}
private function relative(string $absolute): string
{
return str_replace('\\', '/', substr($absolute, strlen(base_path()) + 1));
}
/**
* @effects extracts_fqcn_for_class_declaration, extracts_fqcn_for_interface_declaration, extracts_fqcn_for_trait_declaration, extracts_fqcn_for_enum_declaration
*/
public function test_extracts_fqcn_for_class_interface_trait_enum(): void
{
$cases = [
'FooClass.php' => "<?php\nnamespace Vendor\\Ext\\Sub;\nclass FooClass {}\n",
'BarInterface.php' => "<?php\nnamespace Vendor\\Ext;\ninterface BarInterface {}\n",
'BazTrait.php' => "<?php\nnamespace Vendor\\Ext;\ntrait BazTrait {}\n",
'QuxEnum.php' => "<?php\nnamespace Vendor\\Ext;\nenum QuxEnum: string { case A = 'a'; }\n",
];
foreach ($cases as $file => $code) {
File::put($this->fixtureDir.'/src/'.$file, $code);
}
$psr4 = ['Vendor\\Ext\\' => $this->relative($this->fixtureDir.'/src')];
$classmap = $this->manager->exposedBuildSourceClassmap($psr4);
$this->assertArrayHasKey('Vendor\\Ext\\Sub\\FooClass', $classmap);
$this->assertArrayHasKey('Vendor\\Ext\\BarInterface', $classmap);
$this->assertArrayHasKey('Vendor\\Ext\\BazTrait', $classmap);
$this->assertArrayHasKey('Vendor\\Ext\\QuxEnum', $classmap);
}
/**
* @effects maps_fqcn_to_correct_relative_path
*/
public function test_maps_fqcn_to_correct_relative_path(): void
{
File::ensureDirectoryExists($this->fixtureDir.'/src/Services');
File::put($this->fixtureDir.'/src/Services/OrderService.php',
"<?php\nnamespace Vendor\\Ext\\Services;\nclass OrderService {}\n");
$psr4 = ['Vendor\\Ext\\' => $this->relative($this->fixtureDir.'/src')];
$classmap = $this->manager->exposedBuildSourceClassmap($psr4);
$this->assertArrayHasKey('Vendor\\Ext\\Services\\OrderService', $classmap);
$expected = $this->relative($this->fixtureDir.'/src/Services/OrderService.php');
$this->assertSame($expected, $classmap['Vendor\\Ext\\Services\\OrderService']);
}
/**
* @effects ignores_files_outside_declared_namespace
*/
public function test_ignores_files_outside_declared_namespace(): void
{
// PSR-4 네임스페이스와 다른 네임스페이스의 파일은 제외 (다른 PSR-4 항목이 담당)
File::put($this->fixtureDir.'/src/Foreign.php',
"<?php\nnamespace Other\\Package;\nclass Foreign {}\n");
$psr4 = ['Vendor\\Ext\\' => $this->relative($this->fixtureDir.'/src')];
$classmap = $this->manager->exposedBuildSourceClassmap($psr4);
$this->assertArrayNotHasKey('Other\\Package\\Foreign', $classmap);
}
/**
* @effects skips_files_without_top_level_declaration
*/
public function test_skips_files_without_top_level_declaration(): void
{
File::put($this->fixtureDir.'/src/helpers.php',
"<?php\nfunction ext_helper() { return 1; }\n");
$psr4 = ['Vendor\\Ext\\' => $this->relative($this->fixtureDir.'/src')];
$classmap = $this->manager->exposedBuildSourceClassmap($psr4);
$this->assertEmpty($classmap);
}
/**
* @effects missing_directory_returns_empty
*/
public function test_missing_directory_returns_empty(): void
{
$psr4 = ['Vendor\\Ext\\' => 'nonexistent/path/xyz'];
$classmap = $this->manager->exposedBuildSourceClassmap($psr4);
$this->assertSame([], $classmap);
}
/**
* 실제 생성된 autoload-extensions.php 의 src_classmap 이 소스 클래스만 담고
* 서드파티 vendor 경로를 포함하지 않는지 검증 (vendor 격리 불변조건).
*
* 로컬에 파일이 없으면(테스트 환경 미생성) 스킵.
*
* @effects generated_src_classmap_excludes_vendor_paths, generated_src_classmap_only_extension_namespaces
*/
public function test_generated_src_classmap_excludes_vendor_paths(): void
{
$autoloadFile = base_path('bootstrap/cache/autoload-extensions.php');
if (! file_exists($autoloadFile)) {
$this->markTestSkipped('autoload-extensions.php 미생성 (extension:update-autoload 필요)');
}
$data = require $autoloadFile;
if (empty($data['src_classmap'])) {
$this->markTestSkipped('src_classmap 비어있음 (활성 확장 없음)');
}
foreach ($data['src_classmap'] as $fqcn => $path) {
// 서드파티 vendor 디렉토리를 가리키면 안 됨 (확장별 독립 vendor 는 자체 autoload 담당)
$this->assertStringNotContainsString('/vendor/', $path,
"src_classmap 이 vendor 경로를 포함하면 안 됩니다: {$fqcn} => {$path}");
// 확장 소스 네임스페이스여야 함
$this->assertTrue(
str_starts_with($fqcn, 'Modules\\') || str_starts_with($fqcn, 'Plugins\\'),
"src_classmap 은 확장 소스 네임스페이스만 포함해야 합니다: {$fqcn}"
);
}
}
/**
* addClassMap 등록 시 findFile 이 classMap 에서 즉시 해석(파일시스템 스캔 없이)하고,
* classmap 미등록 클래스는 PSR-4 폴백으로 해석되는지 검증한다.
*
* findFile 이 classMap 을 최우선 조회하므로(vendor/composer/ClassLoader.php),
* 등록된 확장 클래스는 파일시스템 접근 없이 경로를 반환한다. 미등록 클래스는
* addPsr4 폴백으로 안전하게 해석된다(안전망).
*
* @effects classmap_present_findFile_hits_without_filesystem_stat, classmap_absent_findFile_falls_back_to_psr4, class_loading_remains_lazy_include_on_use
*/
public function test_add_class_map_find_file_hit_and_psr4_fallback(): void
{
// 두 클래스 준비: 하나는 classmap 등록, 하나는 미등록(PSR-4 폴백 대상)
File::ensureDirectoryExists($this->fixtureDir.'/src');
File::put($this->fixtureDir.'/src/Mapped.php',
"<?php\nnamespace Vendor\\CmTest;\nclass Mapped {}\n");
File::put($this->fixtureDir.'/src/Unmapped.php',
"<?php\nnamespace Vendor\\CmTest;\nclass Unmapped {}\n");
$loader = require base_path('vendor/autoload.php');
// PSR-4 등록 (폴백 경로)
$loader->addPsr4('Vendor\\CmTest\\', $this->fixtureDir.'/src');
// classmap 에는 Mapped 만 등록
$mappedPath = $this->fixtureDir.'/src/Mapped.php';
$loader->addClassMap(['Vendor\\CmTest\\Mapped' => $mappedPath]);
// classmap hit: 등록 경로 그대로 반환 (파일시스템 스캔 없이)
$this->assertSame($mappedPath, $loader->findFile('Vendor\\CmTest\\Mapped'));
// classmap miss: PSR-4 폴백으로 해석 (경로가 정상 반환)
$fallback = $loader->findFile('Vendor\\CmTest\\Unmapped');
$this->assertNotFalse($fallback);
$this->assertStringEndsWith('Unmapped.php', str_replace('\\', '/', $fallback));
// 지연 로드: findFile 은 경로만 반환하며 클래스를 include 하지 않는다
$this->assertFalse(class_exists('Vendor\\CmTest\\Mapped', false),
'findFile 은 경로만 반환하고 include 하지 않아야 합니다 (lazy)');
// 정리: 이 프로세스 loader 에 남은 테스트 PSR-4/classmap 은 테스트 클래스라 무해
}
/**
* 재생성 시 addClassMap 이 동일 FQCN 의 경로를 새 값으로 덮어쓰는지 검증한다.
*
* 확장 업데이트로 클래스 파일 위치가 바뀌면(같은 FQCN, 새 경로) updateComposerAutoload 이
* 재생성 후 런타임 addClassMap 을 호출한다. array_merge 로 새 경로가 옛 경로를 이긴다
* (stale 경로 shadow 방지).
*
* @effects install_regenerates_src_classmap_via_updateComposerAutoload
*/
public function test_reregistration_overwrites_stale_path_for_same_fqcn(): void
{
$loader = require base_path('vendor/autoload.php');
$oldPath = base_path('storage/framework/testing/old_'.uniqid().'.php');
$newPath = base_path('storage/framework/testing/new_'.uniqid().'.php');
// 옛 경로 등록 (요청 부팅 시점 상태 시뮬)
$loader->addClassMap(['Vendor\\Regen\\Moved' => $oldPath]);
$this->assertSame($oldPath, $loader->findFile('Vendor\\Regen\\Moved'));
// 재생성 후 새 경로 등록 (updateComposerAutoload → addClassMap 시뮬)
$loader->addClassMap(['Vendor\\Regen\\Moved' => $newPath]);
// 새 경로가 옛 경로를 덮어써야 함 (stale shadow 방지)
$this->assertSame($newPath, $loader->findFile('Vendor\\Regen\\Moved'),
'재등록 시 동일 FQCN 은 새 경로로 덮어써져야 합니다');
}
/**
* src_classmap 키가 없는 구버전 autoload-extensions.php 도 안전하게 동작하는지 검증한다.
*
* B2 이전 버전에서 업데이트한 사이트는 재생성 전까지 src_classmap 키가 없는 파일을 갖는다.
* 진입점 소비자는 `! empty(...)` 가드로 키 부재를 안전하게 건너뛰어야 한다(하위호환).
*
* @effects classmap_absent_findFile_falls_back_to_psr4
*/
public function test_missing_src_classmap_key_is_backward_compatible(): void
{
// 구버전 포맷 (src_classmap 키 없음)
$legacy = ['psr4' => [], 'classmap' => [], 'files' => [], 'vendor_autoloads' => []];
// 소비자 가드 패턴 재현: 키 부재 시 addClassMap 미호출 (예외 없음)
$this->assertTrue(empty($legacy['src_classmap']),
'구버전 파일은 src_classmap 키가 없어야 하고, 소비자는 이를 안전하게 스킵해야 합니다');
}
}
/**
* protected buildSourceClassmap 를 테스트에서 호출하기 위한 서브클래스.
*/
class ExposedExtensionManager extends ExtensionManager
{
public function exposedBuildSourceClassmap(array $psr4): array
{
return $this->buildSourceClassmap($psr4);
}
}
@@ -10,7 +10,7 @@ use Tests\TestCase;
/**
* `FilePermissionHelper::copyDirectory` / `removeOrphanItems` 의 symlink 보존 동작 회귀 가드.
*
* 회귀 시나리오 (gnuboard/g7#28):
* 회귀 시나리오 (이슈 #28 + 본 계획 §1):
* - 코어 자동 롤백 시 `public/storage` symlink 가 target 디렉토리 내용으로 추적 복사되어
* symlink 가 일반 디렉토리로 변질 → 운영자가 `storage:link` 재실행 필요
* - `removeOrphanItems` 가 source 부재 symlink 를 디렉토리로 인식하여 target 의 모든 파일을
@@ -134,78 +134,4 @@ class FilePermissionHelperSymlinkTest extends TestCase
$this->assertSame('hi', File::get($dest.'/file.txt'));
$this->assertSame('world', File::get($dest.'/sub/nested.txt'));
}
/**
* Windows JUNCTION (`mklink /J`) 는 PHP 의 `SplFileInfo::isLink()` / `isDir()` 이
* 모두 false 를 반환하는 reparse point 다. `php artisan storage:link` 가 Windows 에서
* 생성하는 `public/storage` 가 이 형태이며, 이를 파일로 오판하면 `copyFile` 이
* 디렉토리를 `copy()` 에 넘겨 `copy(): The first argument ... cannot be a directory` 로
* 코어 업데이트가 실패한다 (회귀 가드).
*
* junction 은 Windows 전용이므로 비-Windows 환경에서는 skip.
*/
#[Test]
public function copyDirectory_는_windows_junction_을_파일로_오판하지_않고_보존합니다(): void
{
if (PHP_OS_FAMILY !== 'Windows') {
$this->markTestSkipped('junction 은 Windows 전용 (mklink /J)');
}
$source = $this->tempRoot.'/src';
$dest = $this->tempRoot.'/dst';
$linkTarget = $this->tempRoot.'/link_target';
File::ensureDirectoryExists($source);
File::ensureDirectoryExists($linkTarget);
File::put($linkTarget.'/inside.txt', 'junction 대상 안 파일');
$junctionPath = $source.'/storage';
// mklink /J 는 관리자 권한 없이 생성 가능 (심볼릭 링크와 달리 SeCreateSymbolicLink 불필요)
exec('cmd /c mklink /J '.escapeshellarg($junctionPath).' '.escapeshellarg($linkTarget).' 2>&1', $out, $code);
if ($code !== 0 || ! is_dir($junctionPath)) {
$this->markTestSkipped('junction 생성 실패: '.implode("\n", $out));
}
// 사전 조건: PHP 가 junction 을 link/dir 어느 쪽으로도 인식하지 못함을 확인
$this->assertFalse(is_link($junctionPath), 'junction 은 is_link() 가 false (전제)');
// copyFile 이 디렉토리를 받아 던지던 예외 없이 완료되어야 한다
FilePermissionHelper::copyDirectory($source, $dest);
// junction 은 dest 에도 junction 으로 보존되어 target 내용에 접근 가능해야 한다
$this->assertTrue(is_dir($dest.'/storage'), 'dest 의 storage 는 디렉토리(junction)로 접근 가능해야 한다');
$this->assertFileExists($dest.'/storage/inside.txt', 'junction 통과 시 target 파일 접근 가능');
}
/**
* removeOrphanItems 가 source 부재 junction 을 재귀 삭제(target 내용 삭제)하지 않고
* 링크 자체만 제거하는지 검증 (junction 은 isDir() 이 false 라 별도 rmdir 경로 필요).
*/
#[Test]
public function removeOrphanItems_는_source_부재_junction_을_target_추적_없이_링크만_제거합니다(): void
{
if (PHP_OS_FAMILY !== 'Windows') {
$this->markTestSkipped('junction 은 Windows 전용 (mklink /J)');
}
$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 에만 존재하는 junction (source 에는 없음)
exec('cmd /c mklink /J '.escapeshellarg($dest.'/orphan_link').' '.escapeshellarg($linkTarget).' 2>&1', $out, $code);
if ($code !== 0 || ! is_dir($dest.'/orphan_link')) {
$this->markTestSkipped('junction 생성 실패: '.implode("\n", $out));
}
FilePermissionHelper::copyDirectory($source, $dest, null, [], '', true);
$this->assertDirectoryDoesNotExist($dest.'/orphan_link', 'orphan junction 은 제거되어야 한다');
$this->assertFileExists($linkTarget.'/precious.txt', 'junction target 의 파일은 보존되어야 한다 (재귀 삭제 사고 차단)');
}
}
@@ -1,414 +0,0 @@
<?php
namespace Tests\Unit\Extension;
use App\Contracts\Extension\HookListenerInterface;
use App\Extension\HookCacheManager;
use App\Extension\HookListenerRegistrar;
use App\Extension\HookManager;
use App\Extension\ModuleManager;
use App\Extension\PluginManager;
use App\Jobs\DispatchHookListenerJob;
use App\Listeners\NotificationHookListener;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;
/**
* 정적 훅 매핑 캐시 무결성 테스트.
*
* 성능 개선(서빙 API 부팅 비용)의 안전 게이트: 캐시 경로 등록이 스캔 경로 등록과
* 바이트 동일해야 하며(훅 발화 누락 0), 캐시 미스는 안전 폴백해야 한다.
*
* @see HookCacheManager
* @see HookListenerRegistrar::registerFromCache()
*/
class HookCacheManagerTest extends TestCase
{
use RefreshDatabase;
private string $tmpCachePath;
protected function setUp(): void
{
parent::setUp();
HookManager::resetAll();
HookListenerRegistrar::clear();
// request-scoped static memo 를 테스트 간 리셋 (누출 방지).
// 한 프로세스에서 여러 테스트가 도는 PHPUnit 특성상 read() 가 채운 static
// memo 가 다음 테스트로 누출되면 격리가 깨진다 — clear() 가 memo 를 null 로 되돌린다.
(new HookCacheManager)->clear();
// 실제 bootstrap/cache/hooks.php 를 건드리지 않도록 임시 경로 사용
$this->tmpCachePath = storage_path('framework/testing/hooks_test_'.uniqid().'.php');
}
protected function tearDown(): void
{
if (File::exists($this->tmpCachePath)) {
File::delete($this->tmpCachePath);
}
HookManager::resetAll();
HookListenerRegistrar::clear();
parent::tearDown();
}
/**
* getHooks/getFilters 를 [name => [priority => callbackCount]] 지문으로 변환합니다.
*
* 클로저는 직접 비교할 수 없으므로 구조(훅명·우선순위·콜백 수)만 비교한다.
*
* @return array{actions: array, filters: array}
*/
private function fingerprint(): array
{
$reduce = function (array $registry): array {
$out = [];
foreach ($registry as $name => $byPriority) {
foreach ($byPriority as $priority => $callbacks) {
$out[$name][$priority] = count($callbacks);
}
}
ksort($out);
return $out;
};
return [
'actions' => $reduce(HookManager::getHooks()),
'filters' => $reduce(HookManager::getFilters()),
];
}
/**
* 캐시 경로 등록 결과가 스캔(register) 경로와 바이트 동일한지 검증합니다.
*
* 스텁 리스너 3종(action/filter/sync)을 register() 로 등록한 지문과,
* 동일 리스너의 getSubscribedHooks() 를 캐시로 저장 후 registerFromCache() 로
* 등록한 지문이 완전히 일치해야 한다 (훅 발화 누락 0 게이트).
*
* @scenario cache_state=present_valid, listener_type=filter, regeneration_trigger=extension_update, registration_source=core
*
* @effects cache_path_registration_byte_identical_to_scan_path, cache_registered_filter_executes_synchronously_and_returns_value
*/
public function test_cache_path_registration_is_identical_to_scan_path(): void
{
Queue::fake();
$listeners = [
HookCacheStubAction::class,
HookCacheStubFilter::class,
HookCacheStubSync::class,
];
// --- 스캔 경로 (register → getSubscribedHooks 호출) ---
HookManager::resetAll();
HookListenerRegistrar::clear();
foreach ($listeners as $listener) {
HookListenerRegistrar::register($listener, 'stub-source');
}
$scanFingerprint = $this->fingerprint();
// --- 캐시 경로 (사전 계산된 getSubscribedHooks 를 registerFromCache) ---
HookManager::resetAll();
HookListenerRegistrar::clear();
foreach ($listeners as $listener) {
$hooks = $listener::getSubscribedHooks();
HookListenerRegistrar::registerFromCache($listener, $hooks, 'stub-source');
}
$cacheFingerprint = $this->fingerprint();
$this->assertSame(
$scanFingerprint,
$cacheFingerprint,
'캐시 경로 등록은 스캔 경로와 훅 매핑이 바이트 동일해야 합니다 (발화 누락 0)'
);
// 지문이 비어있지 않은지(실제로 등록됐는지) 확인
$this->assertNotEmpty($scanFingerprint['actions']);
$this->assertNotEmpty($scanFingerprint['filters']);
}
/**
* registerFromCache 로 등록한 action 리스너가 큐 디스패치되는지 검증합니다.
*
* 캐시 경로도 register 와 동일한 큐 정책(DispatchHookListenerJob)을 따라야 한다.
*
* @scenario cache_state=present_valid, listener_type=action_queued, regeneration_trigger=hooks_clear_command, registration_source=plugin
*
* @effects cache_registered_action_dispatches_queue_job, listener_class_not_autoloaded_at_boot_when_registered_from_cache
*/
public function test_cache_registered_action_dispatches_job(): void
{
Queue::fake();
$hooks = HookCacheStubAction::class::getSubscribedHooks();
HookListenerRegistrar::registerFromCache(HookCacheStubAction::class, $hooks, 'stub-source');
HookManager::doAction('test.hookcache.action', 'payload');
Queue::assertPushed(DispatchHookListenerJob::class, function ($job) {
return $job->listenerClass === HookCacheStubAction::class;
});
}
/**
* registerFromCache 로 등록한 filter 리스너가 동기 실행되고 반환값이 전달되는지 검증합니다.
*
* @scenario cache_state=corrupted_broken_structure, listener_type=filter, regeneration_trigger=hooks_cache_command, registration_source=plugin
*
* @effects cache_registered_sync_action_executes_immediately
*/
public function test_cache_registered_filter_executes_synchronously(): void
{
Queue::fake();
$hooks = HookCacheStubFilter::class::getSubscribedHooks();
HookListenerRegistrar::registerFromCache(HookCacheStubFilter::class, $hooks, 'stub-source');
$result = HookManager::applyFilters('test.hookcache.filter', 'original');
$this->assertSame('original_cached', $result);
}
/**
* 캐시 파일 부재 시 read() 가 null 을 반환(스캔 폴백)하는지 검증합니다.
*
* @scenario cache_state=absent, listener_type=action_queued, regeneration_trigger=extension_update, registration_source=core
*
* @effects absent_cache_falls_back_to_scan_registration
*/
public function test_read_returns_null_when_cache_absent(): void
{
$manager = new HookCacheManagerWithPath($this->tmpCachePath);
$this->assertFalse($manager->isCached());
$this->assertNull($manager->read());
}
/**
* 손상된 캐시 파일은 read() 가 null 을 반환(안전 폴백)하는지 검증합니다.
*
* @scenario cache_state=corrupted_broken_structure, listener_type=action_sync, regeneration_trigger=hooks_clear_command, registration_source=core
*
* @effects corrupted_cache_returns_null_and_falls_back_to_scan, hooks_clear_is_safe_when_cache_absent
*/
public function test_read_returns_null_when_cache_corrupted(): void
{
File::ensureDirectoryExists(dirname($this->tmpCachePath));
File::put($this->tmpCachePath, "<?php return ['broken' => true];");
$manager = new HookCacheManagerWithPath($this->tmpCachePath);
$this->assertTrue($manager->isCached());
$this->assertNull($manager->read(), '구조가 올바르지 않은 캐시는 null 폴백해야 합니다');
}
/**
* generate() 가 core/modules/plugins 3-버킷 구조를 생성하고 read() 로 되읽히는지 검증합니다.
*
* 실제 활성 모듈/플러그인 인스턴스로 생성하여 코어 리스너가 다수 수집됨을 확인한다.
*
* @scenario cache_state=present_valid, listener_type=action_sync, regeneration_trigger=core_update, registration_source=module
*
* @effects generate_produces_three_bucket_cache_core_modules_plugins, each_cache_entry_has_listener_hooks_and_dynamic_keys
*/
public function test_generate_produces_readable_three_bucket_cache(): void
{
$manager = new HookCacheManagerWithPath($this->tmpCachePath);
$moduleManager = app(ModuleManager::class);
$moduleManager->loadModules();
$pluginManager = app(PluginManager::class);
$pluginManager->loadPlugins();
$counts = $manager->generate($moduleManager, $pluginManager);
$this->assertTrue($manager->isCached());
$cache = $manager->read();
$this->assertIsArray($cache);
$this->assertArrayHasKey('core', $cache);
$this->assertArrayHasKey('modules', $cache);
$this->assertArrayHasKey('plugins', $cache);
// 코어 리스너는 app/Listeners 에 다수 존재
$this->assertGreaterThan(0, $counts['core']);
$this->assertGreaterThan(0, count($cache['core']));
// 각 코어 항목은 listener/hooks/dynamic 키를 가진다
foreach ($cache['core'] as $entry) {
$this->assertArrayHasKey('listener', $entry);
$this->assertArrayHasKey('hooks', $entry);
$this->assertArrayHasKey('dynamic', $entry);
$this->assertIsBool($entry['dynamic']);
}
}
/**
* 동적 훅 리스너(NotificationHookListener)가 dynamic=true 로 표시되는지 검증합니다.
*
* 코어 캐시에서 registerDynamicHooks 보유 리스너는 boot 후반부 지연 실행 대상이므로
* dynamic 플래그가 정확해야 한다.
*
* @scenario cache_state=present_valid, listener_type=dynamic, regeneration_trigger=hooks_cache_command, registration_source=core
*
* @effects dynamic_listener_flagged_in_core_cache, dynamic_flagged_listener_deferred_to_boot_tail_like_scan_path
*/
public function test_dynamic_listener_is_flagged_in_cache(): void
{
$manager = new HookCacheManagerWithPath($this->tmpCachePath);
$moduleManager = app(ModuleManager::class);
$moduleManager->loadModules();
$pluginManager = app(PluginManager::class);
$pluginManager->loadPlugins();
$manager->generate($moduleManager, $pluginManager);
$cache = $manager->read();
$notificationEntry = collect($cache['core'])
->firstWhere('listener', NotificationHookListener::class);
$this->assertNotNull($notificationEntry, 'NotificationHookListener 가 코어 캐시에 있어야 합니다');
$this->assertTrue($notificationEntry['dynamic'], 'registerDynamicHooks 보유 리스너는 dynamic=true');
}
/**
* clear() 가 캐시 파일을 삭제하는지 검증합니다.
*
* @scenario cache_state=present_but_testing_env, listener_type=action_sync, regeneration_trigger=extension_update, registration_source=plugin
*
* @effects testing_env_always_scans_ignoring_cache_file
*/
public function test_clear_removes_cache_file(): void
{
File::ensureDirectoryExists(dirname($this->tmpCachePath));
File::put($this->tmpCachePath, "<?php return ['core'=>[],'modules'=>[],'plugins'=>[]];");
$manager = new HookCacheManagerWithPath($this->tmpCachePath);
$this->assertTrue($manager->isCached());
$this->assertTrue($manager->clear());
$this->assertFalse($manager->isCached());
}
/**
* read() 는 request-scoped static 메모리 캐시로 파일을 요청당 1회만 로드한다.
*
* 회귀 대상: read() 가 매 호출 캐시 파일(수십 KB)을 require 하면, 부팅 경로에서
* core/module/plugin 등록이 여러 번(관측상 13회) 호출해 OPcache 부재 시 요청당
* 십수 ms 를 낭비한다. memo 도입 후 첫 로드 결과를 재사용해 파일 접근을 1회로 고정한다.
*
* 검증: memo 가 채워진 뒤 캐시 파일을 삭제해도 read() 가 여전히 데이터를 반환하면
* (파일을 재접근하지 않는다는 증거), 요청당 1회 로드가 성립한다.
*/
public function test_read_memoizes_file_load_within_request(): void
{
File::ensureDirectoryExists(dirname($this->tmpCachePath));
File::put(
$this->tmpCachePath,
"<?php return ['core'=>[['listener'=>'X','hooks'=>[]]],'modules'=>[],'plugins'=>[]];"
);
$manager = new HookCacheManagerWithPath($this->tmpCachePath);
$first = $manager->read();
$this->assertIsArray($first);
$this->assertArrayHasKey('core', $first);
// 파일을 삭제 — memo 가 없으면 다음 read() 는 null(파일 부재)을 반환한다.
File::delete($this->tmpCachePath);
$second = $manager->read();
$this->assertSame(
$first,
$second,
'read() 는 파일을 재접근하지 않고 memo 를 반환해야 합니다 (요청당 1회 로드).'
);
// 다른 인스턴스도 동일 static memo 를 공유한다 (부팅 경로의 여러 호출처 = 여러 인스턴스).
$another = (new HookCacheManagerWithPath($this->tmpCachePath))->read();
$this->assertSame($first, $another, 'static memo 는 인스턴스 간 공유되어야 합니다.');
}
/**
* clear()/generate() 는 memo 를 무효화해 stale 데이터 반환을 막는다.
*
* 확장 install/update 로 캐시가 재생성되면 이후 read() 는 새 매핑을 반환해야 한다.
* memo 가 무효화되지 않으면 옛 매핑이 요청 내내 잔존하는 회귀가 발생한다.
*/
public function test_clear_invalidates_memo(): void
{
File::ensureDirectoryExists(dirname($this->tmpCachePath));
File::put($this->tmpCachePath, "<?php return ['core'=>[['listener'=>'A','hooks'=>[]]],'modules'=>[],'plugins'=>[]];");
$manager = new HookCacheManagerWithPath($this->tmpCachePath);
$this->assertIsArray($manager->read()); // memo 채움
// clear() 는 파일 + memo 를 모두 무효화한다.
$manager->clear();
// 파일이 없으므로 read() 는 null (memo 가 무효화되지 않았다면 옛 데이터를 반환했을 것).
$this->assertNull($manager->read(), 'clear() 후 read() 는 memo 를 버리고 null 폴백해야 합니다.');
}
}
// --- 테스트용 스텁 ---
class HookCacheStubAction implements HookListenerInterface
{
public static function getSubscribedHooks(): array
{
return [
'test.hookcache.action' => ['method' => 'handleAction', 'priority' => 10],
];
}
public function handle(...$args): void {}
public function handleAction(string $value): void {}
}
class HookCacheStubFilter implements HookListenerInterface
{
public static function getSubscribedHooks(): array
{
return [
'test.hookcache.filter' => ['method' => 'handleFilter', 'priority' => 10, 'type' => 'filter'],
];
}
public function handle(...$args): void {}
public function handleFilter(string $value): string
{
return $value.'_cached';
}
}
class HookCacheStubSync implements HookListenerInterface
{
public static function getSubscribedHooks(): array
{
return [
'test.hookcache.sync' => ['method' => 'handleSync', 'priority' => 5, 'sync' => true],
];
}
public function handle(...$args): void {}
public function handleSync(): void {}
}
/**
* 테스트에서 임시 캐시 경로를 주입하기 위한 서브클래스.
*/
class HookCacheManagerWithPath extends HookCacheManager
{
public function __construct(string $path)
{
$this->cacheFilePath = $path;
}
}
@@ -2,11 +2,9 @@
namespace Tests\Unit\Extension;
use App\Contracts\Repositories\IdentityPolicyRepositoryInterface;
use App\Extension\ModuleManager;
use App\Extension\PluginManager;
use App\Extension\TemplateManager;
use App\Listeners\NotificationHookListener;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
@@ -28,31 +26,18 @@ class InstallerCompletedGuardTest extends TestCase
parent::tearDown();
}
/**
* 주어진 콜백 실행 중 발생한 information_schema.tables 쿼리만 수집합니다.
*
* @param callable $callback 계측할 코드
* @return array<int, array<string, mixed>> information_schema.tables 쿼리 목록
*/
private function captureSchemaTableQueries(callable $callback): array
{
DB::enableQueryLog();
$callback();
$queries = DB::getQueryLog();
DB::disableQueryLog();
return array_filter(
$queries,
fn ($q) => str_contains($q['query'], 'information_schema.tables')
);
}
public function test_module_trait_skips_has_table_when_installer_completed(): void
{
config(['app.installer_completed' => true]);
$schemaQueries = $this->captureSchemaTableQueries(
fn () => ModuleManager::getActiveModuleIdentifiers()
DB::enableQueryLog();
ModuleManager::getActiveModuleIdentifiers();
$queries = DB::getQueryLog();
DB::disableQueryLog();
$schemaQueries = array_filter(
$queries,
fn ($q) => str_contains($q['query'], 'information_schema.tables')
);
$this->assertCount(0, $schemaQueries, 'installer_completed=true 에서는 information_schema.tables 쿼리가 발생하지 않아야 합니다');
@@ -62,8 +47,14 @@ class InstallerCompletedGuardTest extends TestCase
{
config(['app.installer_completed' => true]);
$schemaQueries = $this->captureSchemaTableQueries(
fn () => PluginManager::getActivePluginIdentifiers()
DB::enableQueryLog();
PluginManager::getActivePluginIdentifiers();
$queries = DB::getQueryLog();
DB::disableQueryLog();
$schemaQueries = array_filter(
$queries,
fn ($q) => str_contains($q['query'], 'information_schema.tables')
);
$this->assertCount(0, $schemaQueries);
@@ -73,8 +64,14 @@ class InstallerCompletedGuardTest extends TestCase
{
config(['app.installer_completed' => true]);
$schemaQueries = $this->captureSchemaTableQueries(
fn () => TemplateManager::getActiveTemplateIdentifiers()
DB::enableQueryLog();
TemplateManager::getActiveTemplateIdentifiers();
$queries = DB::getQueryLog();
DB::disableQueryLog();
$schemaQueries = array_filter(
$queries,
fn ($q) => str_contains($q['query'], 'information_schema.tables')
);
$this->assertCount(0, $schemaQueries);
@@ -84,105 +81,14 @@ class InstallerCompletedGuardTest extends TestCase
{
config(['app.installer_completed' => false]);
$schemaQueries = $this->captureSchemaTableQueries(
fn () => ModuleManager::getActiveModuleIdentifiers()
);
DB::enableQueryLog();
ModuleManager::getActiveModuleIdentifiers();
$queries = DB::getQueryLog();
DB::disableQueryLog();
$this->assertGreaterThan(0, count($schemaQueries), 'installer_completed=false 에서는 기존 hasTable 경로가 실행되어야 합니다');
}
/**
* NotificationHookListener::registerDynamicHooks() 의 hasTable 가드 검증.
*
* 부팅 시점 동적 훅 등록 경로 — 설치 완료 상태에서 매 요청
* `information_schema.tables` 조회(notification_definitions)가 사라져야 합니다.
*/
public function test_notification_listener_skips_has_table_when_installer_completed(): void
{
config(['app.installer_completed' => true]);
$listener = app(NotificationHookListener::class);
$schemaQueries = $this->captureSchemaTableQueries(
fn () => $listener->registerDynamicHooks()
);
$this->assertCount(0, $schemaQueries, 'installer_completed=true 에서는 notification_definitions hasTable 조회가 발생하지 않아야 합니다');
}
public function test_notification_listener_falls_back_to_has_table_when_installer_not_completed(): void
{
config(['app.installer_completed' => false]);
$listener = app(NotificationHookListener::class);
$schemaQueries = $this->captureSchemaTableQueries(
fn () => $listener->registerDynamicHooks()
);
$this->assertGreaterThan(0, count($schemaQueries), 'installer_completed=false 에서는 기존 hasTable 경로가 실행되어야 합니다');
}
/**
* IdentityPolicyRepository::listHookTargets() 의 hasTable 가드 검증.
*
* 부팅 시점 IDV 동적 hook target 동기화 경로 — 설치 완료 상태에서
* `information_schema.tables` 조회(identity_policies)가 사라져야 합니다.
*/
public function test_identity_policy_list_hook_targets_skips_has_table_when_installer_completed(): void
{
config(['app.installer_completed' => true]);
$repository = app(IdentityPolicyRepositoryInterface::class);
$schemaQueries = $this->captureSchemaTableQueries(
fn () => $repository->listHookTargets()
);
$this->assertCount(0, $schemaQueries, 'installer_completed=true 에서는 identity_policies hasTable 조회가 발생하지 않아야 합니다');
}
public function test_identity_policy_list_hook_targets_falls_back_when_installer_not_completed(): void
{
config(['app.installer_completed' => false]);
$repository = app(IdentityPolicyRepositoryInterface::class);
$schemaQueries = $this->captureSchemaTableQueries(
fn () => $repository->listHookTargets()
);
$this->assertGreaterThan(0, count($schemaQueries), 'installer_completed=false 에서는 기존 hasTable 경로가 실행되어야 합니다');
}
/**
* IdentityPolicyRepository::activeExtensionIdentifiers() 의 hasTable 가드 검증.
*
* `resolveByScopeTarget()` → `applyActiveExtensionScope()` → `activeExtensionIdentifiers()`
* 경로로 modules/plugins 테이블 hasTable 조회가 트리거되며, 설치 완료 상태에서는
* 해당 `information_schema.tables` 조회가 사라져야 합니다.
*/
public function test_active_extension_scope_skips_has_table_when_installer_completed(): void
{
config(['app.installer_completed' => true]);
$repository = app(IdentityPolicyRepositoryInterface::class);
$schemaQueries = $this->captureSchemaTableQueries(
fn () => $repository->resolveByScopeTarget('hook', 'core.auth.signup_before_submit')
);
$this->assertCount(0, $schemaQueries, 'installer_completed=true 에서는 modules/plugins hasTable 조회가 발생하지 않아야 합니다');
}
public function test_active_extension_scope_falls_back_when_installer_not_completed(): void
{
config(['app.installer_completed' => false]);
$repository = app(IdentityPolicyRepositoryInterface::class);
$schemaQueries = $this->captureSchemaTableQueries(
fn () => $repository->resolveByScopeTarget('hook', 'core.auth.signup_before_submit')
$schemaQueries = array_filter(
$queries,
fn ($q) => str_contains($q['query'], 'information_schema.tables')
);
$this->assertGreaterThan(0, count($schemaQueries), 'installer_completed=false 에서는 기존 hasTable 경로가 실행되어야 합니다');
@@ -8,6 +8,7 @@ use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\File;
use ReflectionMethod;
use Tests\TestCase;
@@ -28,21 +29,19 @@ class ModuleCleanupStaleEntriesTest extends TestCase
private ModuleManager $moduleManager;
/**
* 이 테스트는 파일시스템(활성 디렉토리)을 건드리지 않는다.
*
* 검증 대상은 cleanupStaleModuleEntries / removeModulePermissionsAndMenus 의 DB 권한
* 로직이므로, 실제 installModule/uninstallModule(파일 복사·삭제·마이그레이션·오토로드
* 포함)을 호출하는 대신 파일 무접촉 protected 메서드(createModulePermissions /
* assignPermissionsToRoles / removeModulePermissionsAndMenus)만 Reflection 으로 호출한다.
* 이커머스 활성 디렉토리는 setUp 의 loadModules() 로 이미 로드된 것을 재사용하며 절대
* 삭제/변형하지 않는다 — 과거 실제 install/uninstall 호출이 dev 이커머스 디렉토리를
* 삭제한 사고(feedback_test_must_protect_dev_directories)를 구조적으로 차단한다.
*/
private bool $ecommerceExistedBefore = false;
protected function setUp(): void
{
parent::setUp();
$modulesPath = base_path('modules');
$activePath = $modulesPath.'/sirsoft-ecommerce';
if (File::isDirectory($activePath) && ! File::exists($activePath.'/module.php')) {
File::deleteDirectory($activePath);
}
$this->ecommerceExistedBefore = File::isDirectory($activePath);
$this->moduleManager = app(ModuleManager::class);
$this->moduleManager->loadModules();
@@ -66,54 +65,38 @@ class ModuleCleanupStaleEntriesTest extends TestCase
User::factory()->create(['email' => 'test@test.com']);
}
/**
* 이커머스 모듈 권한을 DB 에 시드합니다 (파일시스템 무접촉).
*
* installModule 전체 대신 권한 생성/역할 할당 Phase 만 Reflection 으로 실행한다.
* 이미 로드된 이커머스 모듈 인스턴스를 사용하므로 활성 디렉토리를 건드리지 않는다.
*
* @return \App\Contracts\Extension\ModuleInterface 이커머스 모듈 인스턴스
*/
private function seedEcommercePermissions()
protected function tearDown(): void
{
$module = $this->moduleManager->getModule('sirsoft-ecommerce');
$this->assertNotNull($module, 'sirsoft-ecommerce 모듈이 로드되어 있어야 합니다.');
if (! $this->ecommerceExistedBefore) {
$activePath = base_path('modules/sirsoft-ecommerce');
if (File::isDirectory($activePath)) {
File::deleteDirectory($activePath);
}
}
$this->invokeProtected('createModulePermissions', $module);
$this->invokeProtected('assignPermissionsToRoles', $module);
return $module;
}
/**
* ModuleManager 의 protected 메서드를 호출합니다 (파일 무접촉 Phase 격리 실행용).
*
* @param string $method 메서드명
* @param mixed ...$args 인자
* @return mixed 반환값
*/
private function invokeProtected(string $method, ...$args)
{
return (new ReflectionMethod($this->moduleManager, $method))
->invoke($this->moduleManager, ...$args);
parent::tearDown();
}
public function test_cleanup_stale_module_entries_does_not_delete_live_permissions(): void
{
$module = $this->seedEcommercePermissions();
$this->moduleManager->installModule('sirsoft-ecommerce');
// 시드 후 ecommerce 모듈 권한 수 측정
$module = $this->moduleManager->getModule('sirsoft-ecommerce');
$this->assertNotNull($module);
// 설치 후 ecommerce 모듈 권한 수 측정
$countBefore = Permission::where('extension_type', ExtensionOwnerType::Module)
->where('extension_identifier', 'sirsoft-ecommerce')
->count();
$this->assertGreaterThan(
10,
$countBefore,
'ecommerce 모듈은 권한 시드 직후 다수의 권한을 보유해야 합니다 (카테고리 + action 조합).'
'ecommerce 모듈은 install 직후 다수의 권한을 보유해야 합니다 (카테고리 + action 조합).'
);
// cleanupStaleModuleEntries 를 직접 실행 — 정의와 저장이 일치하는 상태라면 아무것도 삭제되면 안 됨
$this->invokeProtected('cleanupStaleModuleEntries', $module);
$method = new ReflectionMethod($this->moduleManager, 'cleanupStaleModuleEntries');
$method->invoke($this->moduleManager, $module);
$countAfter = Permission::where('extension_type', ExtensionOwnerType::Module)
->where('extension_identifier', 'sirsoft-ecommerce')
@@ -129,7 +112,7 @@ class ModuleCleanupStaleEntriesTest extends TestCase
public function test_cleanup_stale_module_entries_removes_only_genuinely_stale_permissions(): void
{
$this->seedEcommercePermissions();
$this->moduleManager->installModule('sirsoft-ecommerce');
// 인위적으로 stale 권한 1건 삽입 (정의에 없는 identifier)
Permission::create([
@@ -149,7 +132,8 @@ class ModuleCleanupStaleEntriesTest extends TestCase
->where('identifier', '!=', 'sirsoft-ecommerce.removed-category.obsolete-action')
->count();
$this->invokeProtected('cleanupStaleModuleEntries', $module);
$method = new ReflectionMethod($this->moduleManager, 'cleanupStaleModuleEntries');
$method->invoke($this->moduleManager, $module);
// stale 1건만 삭제되고 나머지는 보존되어야 함
$this->assertNull(
@@ -177,7 +161,8 @@ class ModuleCleanupStaleEntriesTest extends TestCase
*/
public function test_cleanup_preserves_dynamic_permissions(): void
{
$module = $this->seedEcommercePermissions();
$this->moduleManager->installModule('sirsoft-ecommerce');
$module = $this->moduleManager->getModule('sirsoft-ecommerce');
// 런타임 동적 권한 모사: 정적 정의에 없는 식별자를 삽입
Permission::create([
@@ -196,7 +181,8 @@ class ModuleCleanupStaleEntriesTest extends TestCase
$wrapper->shouldReceive('getDynamicPermissionIdentifiers')
->andReturn(['sirsoft-ecommerce.dynamic-scope.action-alpha']);
$this->invokeProtected('cleanupStaleModuleEntries', $wrapper);
$method = new ReflectionMethod($this->moduleManager, 'cleanupStaleModuleEntries');
$method->invoke($this->moduleManager, $wrapper);
$this->assertNotNull(
Permission::where('identifier', 'sirsoft-ecommerce.dynamic-scope.action-alpha')->first(),
@@ -207,21 +193,17 @@ class ModuleCleanupStaleEntriesTest extends TestCase
/**
* uninstall(deleteData=false) 시 권한·메뉴·역할이 보존되어 재설치 경로를 비파괴적으로 만드는지 검증.
* 운영 정책: "동적 권한/메뉴는 데이터 삭제 옵션 체크 시에만 삭제".
*
* deleteData=false 경로는 removeModulePermissionsAndMenus 를 호출하지 않는 것과 동치이므로,
* 권한 시드 후 삭제 메서드를 호출하지 않고 권한이 그대로 보존됨을 검증한다(파일 무접촉).
*/
public function test_uninstall_without_delete_data_preserves_permissions(): void
{
$this->seedEcommercePermissions();
$this->moduleManager->installModule('sirsoft-ecommerce');
$countBefore = Permission::where('extension_type', ExtensionOwnerType::Module)
->where('extension_identifier', 'sirsoft-ecommerce')
->count();
$this->assertGreaterThan(0, $countBefore);
// deleteData=false → removeModulePermissionsAndMenus 미호출 (권한 삭제 안 함).
// 실제 uninstallModule 은 이 분기에서 권한 삭제 메서드를 건너뛴다.
$this->moduleManager->uninstallModule('sirsoft-ecommerce', deleteData: false);
$countAfter = Permission::where('extension_type', ExtensionOwnerType::Module)
->where('extension_identifier', 'sirsoft-ecommerce')
@@ -236,20 +218,17 @@ class ModuleCleanupStaleEntriesTest extends TestCase
/**
* uninstall(deleteData=true) 시 권한이 삭제되는지 (기존 동작 유지) 검증.
*
* deleteData=true 경로는 removeModulePermissionsAndMenus 를 호출하므로, 이 메서드를
* 직접 실행해 권한이 전수 삭제됨을 검증한다(파일 무접촉).
*/
public function test_uninstall_with_delete_data_removes_permissions(): void
{
$module = $this->seedEcommercePermissions();
$this->moduleManager->installModule('sirsoft-ecommerce');
$this->assertGreaterThan(
0,
Permission::where('extension_identifier', 'sirsoft-ecommerce')->count(),
);
$this->invokeProtected('removeModulePermissionsAndMenus', $module);
$this->moduleManager->uninstallModule('sirsoft-ecommerce', deleteData: true);
$this->assertSame(
0,
@@ -1,251 +0,0 @@
<?php
namespace Tests\Unit\Installer;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\PreserveGlobalState;
use PHPUnit\Framework\Attributes\RunClassInSeparateProcess;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
/**
* 설치 로그 기록 시 UTF-8 정규화(scrub) 회귀 테스트.
*
* 배경 (gnuboard/g7#62, dev-g7#445):
* Vendor 설치 방식 "Composer 실행" + 폴링 모드 조합에서 브라우저 콘솔에
* "Unexpected end of JSON input" 이 폭주하고 진행 상황이 표시되지 않는 회귀.
*
* 근본 원인: 폴링 워커가 composer install stdout 을 fgets() 로 읽어 정규화 없이
* addLog() 로 넘긴다. Windows 코드페이지(CP949) 출력이나 다운로드 진행바(\r 갱신)가
* 임의 바이트 경계에서 잘리면 invalid UTF-8 바이트가 생기는데,
* _addLogInternal() 은 mb_detect_encoding(strict=true) 감지 실패 시 raw 바이트를
* 그대로 로그에 저장한다. 그 로그를 포함한 폴링 응답 state-management.php 의
* json_encode() 가 invalid UTF-8 때문에 false 를 반환 → echo false = 빈 본문(HTTP 200)
* → 프론트 res.json() 이 "Unexpected end of JSON input" 실패.
*
* 본 테스트는 근본 지점을 검증한다: addLog() 에 invalid UTF-8 바이트를 주입해도
* getInstallationLogs() 로 읽은 로그 메시지가 항상 유효 UTF-8 이어서
* json_encode() 가 false 가 아니어야 한다.
*
* BASE_PATH 는 PHP 상수로 클래스 라이프사이클 단위 단 한 번 정의 (setUpBeforeClass).
* InstallerStateSchemaTest 와 동일한 temp 격리 패턴을 사용한다.
*/
#[RunClassInSeparateProcess]
#[PreserveGlobalState(false)]
class AddLogUtf8ScrubTest extends TestCase
{
private static string $sharedBase = '';
private static string $skipReason = '';
public static function setUpBeforeClass(): void
{
parent::setUpBeforeClass();
// 안전 가드: BASE_PATH 가 시스템 temp 하위가 아니면 (= 다른 테스트가 프로젝트 루트로 박은 경우)
// setUp 의 installation.log @unlink 가 실제 설치 로그를 파괴할 수 있으므로 skip.
$tempPrefix = realpath(sys_get_temp_dir()) ?: sys_get_temp_dir();
if (defined('BASE_PATH')) {
$resolved = realpath((string) BASE_PATH) ?: (string) BASE_PATH;
if (strpos($resolved, $tempPrefix) !== 0) {
self::$skipReason = 'BASE_PATH ('.$resolved.') 가 시스템 temp 하위가 아님 — '.
'다른 Installer 테스트의 BASE_PATH 정의가 선행됨. 격리 실행 필요: '.
'php vendor/bin/phpunit --filter=AddLogUtf8ScrubTest';
return;
}
self::$sharedBase = (string) BASE_PATH;
} else {
self::$sharedBase = sys_get_temp_dir().'/g7-installer-addlog-test-'.bin2hex(random_bytes(4));
define('BASE_PATH', self::$sharedBase);
}
$logDir = self::$sharedBase.'/storage/logs';
if (! is_dir($logDir)) {
mkdir($logDir, 0755, true);
}
// config.php 의 INSTALLER_BASE_URL 계산이 $_SERVER['SCRIPT_NAME'] 에 의존
if (! isset($_SERVER['SCRIPT_NAME'])) {
$_SERVER['SCRIPT_NAME'] = '/install/index.php';
}
require_once dirname(__DIR__, 3).'/public/install/includes/config.php';
require_once dirname(__DIR__, 3).'/public/install/includes/installer-state.php';
require_once dirname(__DIR__, 3).'/public/install/includes/progress-emitter.php';
}
public static function tearDownAfterClass(): void
{
if (self::$skipReason === '' && self::$sharedBase !== '') {
$logFile = self::$sharedBase.'/storage/logs/installation.log';
if (file_exists($logFile)) {
@unlink($logFile);
}
}
parent::tearDownAfterClass();
}
protected function setUp(): void
{
parent::setUp();
if (self::$skipReason !== '') {
$this->markTestSkipped(self::$skipReason);
}
// 각 테스트 시작 시 로그 초기화
$logFile = self::$sharedBase.'/storage/logs/installation.log';
if (file_exists($logFile)) {
@unlink($logFile);
}
}
/**
* invalid UTF-8 바이트 표본.
*
* - 잘린 한글 선행 바이트 (EC 99 은 3바이트 UTF-8 의 앞 2바이트, 마지막 바이트 누락)
* - 단독 0xFF (UTF-8 에서 절대 유효하지 않은 바이트)
* - CP949 로 인코딩된 한글이 감지 실패하는 케이스 모사
*
* @return array<string, array{string}>
*/
public static function invalidUtf8Provider(): array
{
return [
'truncated hangul lead bytes' => ["Downloading \xEC\x99 package"],
'lone 0xFF byte' => ["progress: abc\xFFdef 100%"],
'truncated 4-byte sequence' => ["emoji \xF0\x9F head"], // 4바이트 UTF-8 의 앞 2바이트만
'lone continuation byte' => ["tail\x80end"],
];
}
#[Test]
#[DataProvider('invalidUtf8Provider')]
public function addlog_stores_valid_utf8_even_for_invalid_input(string $rawMessage): void
{
// 사전 조건: 입력은 실제로 invalid UTF-8 이어야 테스트가 의미 있음
$this->assertFalse(
mb_check_encoding($rawMessage, 'UTF-8'),
'테스트 입력 자체가 invalid UTF-8 이어야 한다 (표본 점검).'
);
$written = addLog($rawMessage);
$this->assertTrue($written, 'addLog 는 성공적으로 로그를 기록해야 한다.');
$logs = getInstallationLogs();
$this->assertNotEmpty($logs, '기록한 로그가 조회되어야 한다.');
$message = $logs[count($logs) - 1]['message'] ?? '';
// 핵심 계약: 저장된 로그 메시지는 항상 유효 UTF-8 이어야 한다.
$this->assertTrue(
mb_check_encoding($message, 'UTF-8'),
'저장된 로그 메시지는 항상 유효 UTF-8 이어야 한다 (invalid 바이트는 scrub 대체). '.
'실패 시: composer 출력의 깨진 바이트가 로그에 raw 저장되어 폴링 응답 json_encode 가 무력화됨.'
);
}
#[Test]
#[DataProvider('invalidUtf8Provider')]
public function polling_response_json_encode_never_returns_false(string $rawMessage): void
{
addLog($rawMessage);
$logs = getInstallationLogs();
// 폴링 응답(state-management.php getState) 이 만드는 것과 동일한 구조를 모사.
$response = [
'status' => 'running',
'logs' => $logs,
'log_total' => getInstallationLogCount(),
];
// 근본 수정 후: logs 가 유효 UTF-8 이므로 substitute 플래그 없이도 false 가 아니어야 한다.
$encoded = json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
$this->assertNotFalse(
$encoded,
'invalid UTF-8 로그가 섞여도 폴링 응답 json_encode 는 false 를 반환하면 안 된다 '.
'(false → echo 빈 본문 → 프론트 "Unexpected end of JSON input").'
);
$this->assertIsString($encoded);
$this->assertNotSame('', $encoded, '인코딩 결과 본문이 비어 있으면 안 된다.');
}
#[Test]
public function addlog_preserves_valid_utf8_korean_unchanged(): void
{
// 정규화가 정상 UTF-8 한글을 훼손하지 않아야 한다 (회귀 방지).
// 첫 로그 줄은 UTF-8 BOM 이 붙어 getInstallationLogs 의 [timestamp] 파싱에 간섭하므로
// 워밍업 로그를 먼저 기록해 검증 대상 줄을 두 번째 이후로 밀어낸다.
addLog('warmup');
$korean = 'Composer 의존성 설치를 시작합니다.';
addLog($korean);
$logs = getInstallationLogs();
$message = $logs[count($logs) - 1]['message'] ?? '';
$this->assertSame($korean, $message, '정상 UTF-8 한글은 scrub 후에도 변형되지 않아야 한다.');
}
/**
* SSE 이벤트 스트림도 invalid UTF-8 로그로 인해 빈 data 라인을 송출하면 안 된다 (인코딩 계약).
*
* 폴링 모드로 제보됐으나(#62), 근본 원인(외부 유래 invalid UTF-8 → json_encode false)은
* SSE 모드에도 동일하게 존재한다. SseEmitter::emit 의 json_encode 가 false 를 반환하면
* "data: \n\n" 이 송출되어 프론트 EventSource 의 JSON.parse(e.data) 가 throw → 로그 이벤트 유실.
*
* SseEmitter::emit 은 내부에서 즉시 flush() 하므로 ob_get_clean() 으로 출력을 캡처할 수 없다
* (SSE 스트리밍 설계상 의도된 동작). 따라서 emit 이 사용하는 인코딩 계약을 직접 검증한다:
* JSON_INVALID_UTF8_SUBSTITUTE 를 적용하면 invalid UTF-8 이 섞여도 false 가 아니어야 한다.
*/
#[Test]
#[DataProvider('invalidUtf8Provider')]
public function sse_emit_encoding_contract_never_returns_false_for_invalid_utf8(string $rawMessage): void
{
// emit 이 실제 사용하는 것과 동일한 인코딩 호출.
$payload = json_encode(
['message' => $rawMessage],
JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE
);
$this->assertNotFalse(
$payload,
'SSE data 인코딩은 invalid UTF-8 로그가 섞여도 false 를 반환하면 안 된다 '.
'(false → "data: \n\n" → 프론트 JSON.parse throw → 로그 이벤트 유실).'
);
$this->assertIsString($payload);
// 프론트 JSON.parse(e.data) 와 동일하게 파싱 가능해야 한다.
$decoded = json_decode($payload, true);
$this->assertSame(JSON_ERROR_NONE, json_last_error());
$this->assertIsArray($decoded);
}
/**
* progress-emitter.php 의 SseEmitter::emit 이 JSON_INVALID_UTF8_SUBSTITUTE 를 적용하는지
* 소스 레벨로 회귀 검증한다 (PollingResponseFlushTest 정적 검증과 동일 방식).
*/
#[Test]
public function sse_emitter_source_uses_invalid_utf8_substitute_flag(): void
{
$source = (string) file_get_contents(
dirname(__DIR__, 3).'/public/install/includes/progress-emitter.php'
);
// SseEmitter 클래스 본문 추출
$classStart = strpos($source, 'class SseEmitter');
$this->assertNotFalse($classStart, 'SseEmitter 클래스를 찾을 수 없습니다.');
$classEnd = strpos($source, 'class NullEmitter', $classStart);
$sseBody = substr($source, $classStart, $classEnd !== false ? $classEnd - $classStart : null);
$this->assertStringContainsString(
'JSON_INVALID_UTF8_SUBSTITUTE',
$sseBody,
'SseEmitter::emit 의 json_encode 는 JSON_INVALID_UTF8_SUBSTITUTE 를 적용해 '.
'invalid UTF-8 로그로 인한 빈 SSE data 라인 송출을 차단해야 한다.'
);
}
}
+35 -40
View File
@@ -43,17 +43,12 @@ class DeleteDirectoryTest extends TestCase
define('INSTALLER_BASE_URL', '/install');
}
// 인스톨러 함수 로드 (pure PHPUnit TestCase 라서 Laravel base_path() 사용 불가).
// 프로젝트 루트 절대경로(__DIR__ 기준)로 로드한다 — 다른 인스톨러 테스트
// (#[RunClassInSeparateProcess] + temp BASE_PATH)가 메인 프로세스로 BASE_PATH 를
// 누수시켜도 그 temp 경로에는 public/install 이 없어 require 가 깨지므로, 누수된
// BASE_PATH 값과 무관하게 항상 실제 프로젝트 파일을 참조한다.
$installerRoot = dirname(__DIR__, 3);
require_once $installerRoot.'/public/install/includes/functions.php';
require_once $installerRoot.'/public/install/api/rollback-functions.php';
// 인스톨러 함수 로드 (pure PHPUnit TestCase 라서 Laravel base_path() 사용 불가 — BASE_PATH 상수 사용)
require_once BASE_PATH . '/public/install/includes/functions.php';
require_once BASE_PATH . '/public/install/api/rollback-functions.php';
// 임시 디렉토리 생성
$this->tempDir = sys_get_temp_dir().DIRECTORY_SEPARATOR.'g7_test_delete_'.uniqid();
$this->tempDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'g7_test_delete_' . uniqid();
mkdir($this->tempDir, 0755, true);
}
@@ -72,10 +67,10 @@ class DeleteDirectoryTest extends TestCase
public function test_preserves_gitkeep_file(): void
{
// Given: 디렉토리에 .gitkeep과 일반 파일이 있음
file_put_contents($this->tempDir.'/.gitkeep', '');
file_put_contents($this->tempDir.'/some_file.txt', 'test');
mkdir($this->tempDir.'/subdir', 0755);
file_put_contents($this->tempDir.'/subdir/nested.txt', 'test');
file_put_contents($this->tempDir . '/.gitkeep', '');
file_put_contents($this->tempDir . '/some_file.txt', 'test');
mkdir($this->tempDir . '/subdir', 0755);
file_put_contents($this->tempDir . '/subdir/nested.txt', 'test');
// When: deleteDirectory 호출 (기본: removeDir=false)
$result = deleteDirectory($this->tempDir);
@@ -83,9 +78,9 @@ class DeleteDirectoryTest extends TestCase
// Then: .gitkeep은 보존, 나머지는 삭제, 디렉토리 자체는 유지
$this->assertTrue($result);
$this->assertDirectoryExists($this->tempDir);
$this->assertFileExists($this->tempDir.'/.gitkeep');
$this->assertFileDoesNotExist($this->tempDir.'/some_file.txt');
$this->assertDirectoryDoesNotExist($this->tempDir.'/subdir');
$this->assertFileExists($this->tempDir . '/.gitkeep');
$this->assertFileDoesNotExist($this->tempDir . '/some_file.txt');
$this->assertDirectoryDoesNotExist($this->tempDir . '/subdir');
}
/**
@@ -94,8 +89,8 @@ class DeleteDirectoryTest extends TestCase
public function test_preserves_gitignore_file(): void
{
// Given: 디렉토리에 .gitignore와 일반 파일이 있음
file_put_contents($this->tempDir.'/.gitignore', '*');
file_put_contents($this->tempDir.'/data.log', 'log');
file_put_contents($this->tempDir . '/.gitignore', '*');
file_put_contents($this->tempDir . '/data.log', 'log');
// When
$result = deleteDirectory($this->tempDir);
@@ -103,8 +98,8 @@ class DeleteDirectoryTest extends TestCase
// Then
$this->assertTrue($result);
$this->assertDirectoryExists($this->tempDir);
$this->assertFileExists($this->tempDir.'/.gitignore');
$this->assertFileDoesNotExist($this->tempDir.'/data.log');
$this->assertFileExists($this->tempDir . '/.gitignore');
$this->assertFileDoesNotExist($this->tempDir . '/data.log');
}
/**
@@ -113,8 +108,8 @@ class DeleteDirectoryTest extends TestCase
public function test_keeps_directory_when_no_preserve_files_and_remove_dir_false(): void
{
// Given: 보호 파일 없이 일반 파일만 있음
file_put_contents($this->tempDir.'/file1.txt', 'test');
file_put_contents($this->tempDir.'/file2.txt', 'test');
file_put_contents($this->tempDir . '/file1.txt', 'test');
file_put_contents($this->tempDir . '/file2.txt', 'test');
// When: removeDir=false (기본값)
$result = deleteDirectory($this->tempDir);
@@ -122,8 +117,8 @@ class DeleteDirectoryTest extends TestCase
// Then: 디렉토리 자체는 유지, 내용물은 삭제
$this->assertTrue($result);
$this->assertDirectoryExists($this->tempDir);
$this->assertFileDoesNotExist($this->tempDir.'/file1.txt');
$this->assertFileDoesNotExist($this->tempDir.'/file2.txt');
$this->assertFileDoesNotExist($this->tempDir . '/file1.txt');
$this->assertFileDoesNotExist($this->tempDir . '/file2.txt');
}
/**
@@ -132,8 +127,8 @@ class DeleteDirectoryTest extends TestCase
public function test_keeps_directory_when_preserve_files_exist_even_with_remove_dir(): void
{
// Given: .gitkeep이 있음
file_put_contents($this->tempDir.'/.gitkeep', '');
file_put_contents($this->tempDir.'/other.txt', 'test');
file_put_contents($this->tempDir . '/.gitkeep', '');
file_put_contents($this->tempDir . '/other.txt', 'test');
// When: removeDir=true여도 보호 파일이 있으면 디렉토리 유지
$result = deleteDirectory($this->tempDir, true);
@@ -141,8 +136,8 @@ class DeleteDirectoryTest extends TestCase
// Then
$this->assertTrue($result);
$this->assertDirectoryExists($this->tempDir);
$this->assertFileExists($this->tempDir.'/.gitkeep');
$this->assertFileDoesNotExist($this->tempDir.'/other.txt');
$this->assertFileExists($this->tempDir . '/.gitkeep');
$this->assertFileDoesNotExist($this->tempDir . '/other.txt');
}
/**
@@ -151,7 +146,7 @@ class DeleteDirectoryTest extends TestCase
public function test_removes_directory_when_no_preserve_files_and_remove_dir_true(): void
{
// Given: 보호 파일 없음
file_put_contents($this->tempDir.'/file.txt', 'test');
file_put_contents($this->tempDir . '/file.txt', 'test');
// When
$result = deleteDirectory($this->tempDir, true);
@@ -166,10 +161,10 @@ class DeleteDirectoryTest extends TestCase
public function test_handles_nested_directories(): void
{
// Given: vendor 디렉토리 구조 시뮬레이션
file_put_contents($this->tempDir.'/.gitkeep', '');
mkdir($this->tempDir.'/laravel/framework/src', 0755, true);
file_put_contents($this->tempDir.'/laravel/framework/src/Application.php', '<?php');
file_put_contents($this->tempDir.'/autoload.php', '<?php');
file_put_contents($this->tempDir . '/.gitkeep', '');
mkdir($this->tempDir . '/laravel/framework/src', 0755, true);
file_put_contents($this->tempDir . '/laravel/framework/src/Application.php', '<?php');
file_put_contents($this->tempDir . '/autoload.php', '<?php');
// When
$result = deleteDirectory($this->tempDir);
@@ -177,9 +172,9 @@ class DeleteDirectoryTest extends TestCase
// Then: .gitkeep만 보존, 나머지 전부 삭제
$this->assertTrue($result);
$this->assertDirectoryExists($this->tempDir);
$this->assertFileExists($this->tempDir.'/.gitkeep');
$this->assertFileDoesNotExist($this->tempDir.'/autoload.php');
$this->assertDirectoryDoesNotExist($this->tempDir.'/laravel');
$this->assertFileExists($this->tempDir . '/.gitkeep');
$this->assertFileDoesNotExist($this->tempDir . '/autoload.php');
$this->assertDirectoryDoesNotExist($this->tempDir . '/laravel');
}
/**
@@ -200,24 +195,24 @@ class DeleteDirectoryTest extends TestCase
*/
public function test_returns_false_for_nonexistent_directory(): void
{
$result = deleteDirectory($this->tempDir.'/nonexistent');
$result = deleteDirectory($this->tempDir . '/nonexistent');
$this->assertFalse($result);
}
/**
* 임시 디렉토리를 완전히 정리합니다 (테스트용).
*
* @param string $dir 정리할 디렉토리 경로
* @param string $dir 정리할 디렉토리 경로
*/
private function cleanupTempDir(string $dir): void
{
if (! is_dir($dir)) {
if (!is_dir($dir)) {
return;
}
$items = array_diff(scandir($dir), ['.', '..']);
foreach ($items as $item) {
$path = $dir.DIRECTORY_SEPARATOR.$item;
$path = $dir . DIRECTORY_SEPARATOR . $item;
if (is_dir($path)) {
$this->cleanupTempDir($path);
} else {
@@ -1,134 +0,0 @@
<?php
namespace Tests\Unit\Installer;
use PHPUnit\Framework\Attributes\PreserveGlobalState;
use PHPUnit\Framework\Attributes\RunClassInSeparateProcess;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
/**
* 인스톨러 디렉토리 권한 재귀 스캔 깊이 제한 회귀 테스트.
*
* 배경 (dev-g7#445 후속):
* 인스톨러 2단계(요구사항 검증)의 checkDirectoryPermissions 가 storage 를 재귀 스캔하는데,
* checkSubdirectoriesRecursive 가 깊이 제한 없이 무한 재귀하여 storage/framework/testing/
* 하위에 누적된 수만 개 디렉토리를 전부 순회 → 2단계 응답이 8초 이상 지연되던 문제.
*
* 권한 안내는 트리 상위 얕은 깊이에서만 유의미하므로 재귀에 깊이 제한을 둔다.
* 본 테스트는 깊이 제한이 실제로 적용되어 제한 깊이를 넘는 하위는 순회하지 않음을 검증한다.
*
* BASE_PATH 는 PHP 상수로 클래스 라이프사이클 단위 단 한 번 정의 (setUpBeforeClass).
*/
#[RunClassInSeparateProcess]
#[PreserveGlobalState(false)]
class DirectoryPermissionScanDepthTest extends TestCase
{
private static string $sharedBase = '';
private static string $skipReason = '';
public static function setUpBeforeClass(): void
{
parent::setUpBeforeClass();
$tempPrefix = realpath(sys_get_temp_dir()) ?: sys_get_temp_dir();
if (defined('BASE_PATH')) {
$resolved = realpath((string) BASE_PATH) ?: (string) BASE_PATH;
if (strpos($resolved, $tempPrefix) !== 0) {
self::$skipReason = 'BASE_PATH ('.$resolved.') 가 시스템 temp 하위가 아님 — '.
'격리 실행 필요: php vendor/bin/phpunit --filter=DirectoryPermissionScanDepthTest';
return;
}
self::$sharedBase = (string) BASE_PATH;
} else {
self::$sharedBase = sys_get_temp_dir().'/g7-installer-dirscan-test-'.bin2hex(random_bytes(4));
define('BASE_PATH', self::$sharedBase);
}
if (! is_dir(self::$sharedBase)) {
mkdir(self::$sharedBase, 0755, true);
}
if (! isset($_SERVER['SCRIPT_NAME'])) {
$_SERVER['SCRIPT_NAME'] = '/install/index.php';
}
require_once dirname(__DIR__, 3).'/public/install/includes/config.php';
require_once dirname(__DIR__, 3).'/public/install/includes/functions.php';
}
public static function tearDownAfterClass(): void
{
parent::tearDownAfterClass();
}
protected function setUp(): void
{
parent::setUp();
if (self::$skipReason !== '') {
$this->markTestSkipped(self::$skipReason);
}
}
/**
* 깊이 제한을 넘는 하위 디렉토리는 재귀 스캔 대상에서 제외되어야 한다.
*
* storage/deep/a/b/c/... 처럼 깊은 트리를 만들고, checkSubdirectoriesRecursive 를
* 제한 깊이(2)로 호출하면 depth 3 이상 경로는 결과에 나타나지 않아야 한다.
*/
#[Test]
public function recursive_scan_respects_max_depth(): void
{
// BASE_PATH/scanroot 하위에 깊이 5의 중첩 디렉토리 생성 (전부 정상 권한)
$root = self::$sharedBase.'/scanroot';
$deep = $root.'/lvl1/lvl2/lvl3/lvl4/lvl5';
if (! is_dir($deep)) {
mkdir($deep, 0755, true);
}
// 깊이 2 제한으로 스캔 — 함수는 (path, maxDepth) 시그니처를 지원해야 한다.
$failed = checkSubdirectoriesRecursive($root, 2);
// 모든 디렉토리가 정상 권한이므로 실패 항목은 없어야 하고, 무엇보다
// 함수가 무한 재귀 없이 즉시 반환해야 한다 (깊이 제한 동작 확인).
$this->assertIsArray($failed);
// 깊이 제한이 동작하는지 간접 검증: 깊은 트리에서도 스캔이 즉시 끝나야 한다.
$t0 = microtime(true);
checkSubdirectoriesRecursive($root, 2);
$elapsed = microtime(true) - $t0;
$this->assertLessThan(
1.0,
$elapsed,
'깊이 제한된 재귀 스캔은 얕은 깊이만 순회하므로 즉시 완료되어야 한다.'
);
}
/**
* checkSubdirectoriesRecursive 가 maxDepth 파라미터를 받는 시그니처여야 한다.
*/
#[Test]
public function function_accepts_max_depth_parameter(): void
{
$ref = new \ReflectionFunction('checkSubdirectoriesRecursive');
$params = $ref->getParameters();
$this->assertGreaterThanOrEqual(
2,
count($params),
'checkSubdirectoriesRecursive 는 깊이 제한 파라미터를 받아야 한다 '.
'(무한 재귀로 storage 하위 수만 개 디렉토리를 순회해 인스톨러 2단계가 지연되던 문제 차단).'
);
// 두 번째 파라미터는 깊이 제한(정수, 기본값 존재)이어야 한다.
$depthParam = $params[1];
$this->assertTrue(
$depthParam->isDefaultValueAvailable(),
'깊이 제한 파라미터는 기본값을 가져 기존 호출부(check-configuration.php)가 변경 없이 동작해야 한다.'
);
}
}
@@ -16,7 +16,6 @@ use PHPUnit\Framework\TestCase;
class InstallerRuntimeHelperTest extends TestCase
{
private string $tempBase = '';
private string $skipReason = '';
protected function setUp(): void
@@ -24,7 +23,7 @@ class InstallerRuntimeHelperTest extends TestCase
parent::setUp();
// 격리된 BASE_PATH — 운영 환경 storage/installer 와 충돌 방지
$this->tempBase = sys_get_temp_dir().'/g7-installer-runtime-test-'.bin2hex(random_bytes(4));
$this->tempBase = sys_get_temp_dir() . '/g7-installer-runtime-test-' . bin2hex(random_bytes(4));
// 안전 가드: INSTALLER_RUNTIME_PATH(= BASE_PATH/storage/installer/runtime.php) 는
// PHP 상수라 한 프로세스에서 단 한 번만 정의된다. 다른 Installer 테스트가 먼저
@@ -35,9 +34,9 @@ class InstallerRuntimeHelperTest extends TestCase
if (defined('BASE_PATH')) {
$resolved = realpath((string) BASE_PATH) ?: (string) BASE_PATH;
if (strpos($resolved, $tempPrefix) !== 0) {
$this->skipReason = 'BASE_PATH ('.$resolved.') 가 시스템 temp 하위가 아님 — '
.'다른 Installer 테스트의 BASE_PATH 정의가 선행됨. 실제 storage/installer/runtime.php '
.'파괴 방지를 위해 skip. 격리 실행: php vendor/bin/phpunit --filter=InstallerRuntimeHelperTest';
$this->skipReason = 'BASE_PATH (' . $resolved . ') 가 시스템 temp 하위가 아님 — '
. '다른 Installer 테스트의 BASE_PATH 정의가 선행됨. 실제 storage/installer/runtime.php '
. '파괴 방지를 위해 skip. 격리 실행: php vendor/bin/phpunit --filter=InstallerRuntimeHelperTest';
$this->markTestSkipped($this->skipReason);
}
$this->tempBase = (string) BASE_PATH;
@@ -45,15 +44,15 @@ class InstallerRuntimeHelperTest extends TestCase
define('BASE_PATH', $this->tempBase);
}
if (! is_dir($this->tempBase.'/storage/installer')) {
@mkdir($this->tempBase.'/storage/installer', 0755, true);
if (! is_dir($this->tempBase . '/storage/installer')) {
@mkdir($this->tempBase . '/storage/installer', 0755, true);
}
// INSTALLER_RUNTIME_PATH 는 BASE_PATH 기반으로 한 번만 정의되므로,
// 첫 테스트가 끝까지 책임진다 (BASE_PATH 자체가 const 라 재정의 불가).
// installer-runtime.php 자체에 escapeEnvValue polyfill 이 있어 functions.php
// 미로드 환경에서도 mergeRuntimeIntoEnv 가 정상 동작한다.
require_once dirname(__DIR__, 3).'/public/install/includes/installer-runtime.php';
require_once dirname(__DIR__, 3) . '/public/install/includes/installer-runtime.php';
}
protected function tearDown(): void
@@ -152,7 +151,6 @@ class InstallerRuntimeHelperTest extends TestCase
public function test_build_runtime_includes_separate_read_when_specified(): void
{
$built = buildInstallerRuntimeFromState([
'use_read_db' => true, // Read DB 사용 선택 (판정 SSoT)
'db_write_host' => 'write-host',
'db_write_database' => 'g7',
'db_read_host' => 'read-host',
@@ -167,7 +165,6 @@ class InstallerRuntimeHelperTest extends TestCase
public function test_build_runtime_omits_read_when_same_as_write(): void
{
$built = buildInstallerRuntimeFromState([
'use_read_db' => true,
'db_write_host' => 'localhost',
'db_read_host' => 'localhost', // 동일 호스트 → 별도 read 불필요
]);
@@ -175,37 +172,6 @@ class InstallerRuntimeHelperTest extends TestCase
$this->assertArrayNotHasKey('read', $built['db']);
}
/**
* 이슈 #63 회귀 — use_read_db=false 인데 db_read_host 에 잘못된 값이 잔존한 경우
* read 커넥션을 만들지 않아야 한다 (Laravel 이 write 로 자동 fallback).
*/
public function test_build_runtime_omits_read_when_use_read_db_false(): void
{
$built = buildInstallerRuntimeFromState([
'use_read_db' => false,
'db_write_host' => 'mysql',
'db_write_database' => 'g7',
'db_read_host' => 'l3ocalhost', // 잔존 잘못된 값 (이슈 재현값)
'db_read_database' => 'wrong_db',
]);
$this->assertArrayNotHasKey('read', $built['db']);
}
/**
* 이슈 #63 회귀 — use_read_db 키 자체가 없는 레거시 state 도
* read 를 만들지 않아야 한다 (기본 미사용).
*/
public function test_build_runtime_omits_read_when_use_read_db_absent(): void
{
$built = buildInstallerRuntimeFromState([
'db_write_host' => 'mysql',
'db_read_host' => 'read-host', // use_read_db 미지정 → read 무시
]);
$this->assertArrayNotHasKey('read', $built['db']);
}
public function test_build_runtime_falls_back_to_legacy_db_keys(): void
{
// 일부 인스톨러 경로가 db_host/db_database 등 prefix 없는 키를 사용
@@ -307,7 +273,7 @@ ENV;
],
'prefix' => 'real_',
],
'app' => ['key' => 'base64:'.base64_encode(str_repeat('a', 32))],
'app' => ['key' => 'base64:' . base64_encode(str_repeat('a', 32))],
];
$merged = mergeRuntimeIntoEnv($envContent, $runtime);
@@ -321,14 +287,10 @@ ENV;
// Read 라인도 write 와 동기화되어 치환되어야 함
$this->assertStringNotContainsString('DB_WRITE_HOST=127.0.0.1', $merged);
$this->assertStringNotContainsString('DB_WRITE_DATABASE=g7'.PHP_EOL, $merged);
$this->assertStringNotContainsString('DB_WRITE_DATABASE=g7' . PHP_EOL, $merged);
}
/**
* 이슈 #63 — read 미지정(use_read_db=false) 시 DB_READ_* 를 빈 값으로 남긴다.
* write 값을 복사하지 않고 config/database.php 의 Elvis fallback 에 위임한다.
*/
public function test_merge_leaves_read_empty_when_read_not_specified(): void
public function test_merge_syncs_read_with_write_when_read_not_specified(): void
{
$envContent = "DB_READ_HOST=127.0.0.1\nDB_READ_DATABASE=g7\nDB_READ_USERNAME=root\nDB_READ_PASSWORD=\n";
@@ -346,14 +308,11 @@ ENV;
$merged = mergeRuntimeIntoEnv($envContent, $runtime);
// read 미지정 시 DB_READ_* 는 빈 값 — write 값이 복사되면 안 됨
$this->assertStringContainsString("DB_READ_HOST=\n", $merged);
$this->assertStringContainsString("DB_READ_DATABASE=\n", $merged);
$this->assertStringContainsString("DB_READ_USERNAME=\n", $merged);
$this->assertStringNotContainsString('DB_READ_HOST=w-host', $merged);
$this->assertStringNotContainsString('DB_READ_DATABASE=wdb', $merged);
// write 라인은 정상 기록
$this->assertStringContainsString('DB_WRITE_HOST=w-host', $merged);
// read 미지정 시 write 값으로 동기
$this->assertStringContainsString('DB_READ_HOST=w-host', $merged);
$this->assertStringContainsString('DB_READ_DATABASE=wdb', $merged);
$this->assertStringContainsString('DB_READ_USERNAME=wu', $merged);
$this->assertStringContainsString('DB_READ_PASSWORD="wp"', $merged);
}
public function test_merge_uses_separate_read_when_specified(): void
@@ -401,7 +360,7 @@ ENV;
$envContent = "DB_WRITE_HOST=user-input.com\nAPP_KEY=\n";
// runtime 에 db 키 자체가 없는 케이스 (이상 상태) — 기존 .env 값 보존
$runtime = ['app' => ['key' => 'base64:'.base64_encode(str_repeat('x', 32))]];
$runtime = ['app' => ['key' => 'base64:' . base64_encode(str_repeat('x', 32))]];
$merged = mergeRuntimeIntoEnv($envContent, $runtime);
@@ -11,19 +11,6 @@ use PHPUnit\Framework\TestCase;
*/
class InstallerWindowsCommandsTest extends TestCase
{
/**
* 프로젝트 루트 절대경로 (BASE_PATH 상수와 독립).
*
* 다른 인스톨러 테스트(#[RunClassInSeparateProcess] + temp BASE_PATH)가 메인
* 프로세스로 BASE_PATH 를 누수시키면, 그 temp 경로 하위에는 public/install 이 없어
* require 가 깨진다. 본 클래스는 __DIR__ 기준 절대경로로 인스톨러 파일을 로드해
* 누수된 BASE_PATH 값과 무관하게 항상 실제 프로젝트 파일을 참조한다.
*/
private function installerRoot(): string
{
return dirname(__DIR__, 3);
}
/**
* 테스트 전 인스톨러 설정 및 함수 파일을 로드합니다.
*/
@@ -53,8 +40,8 @@ class InstallerWindowsCommandsTest extends TestCase
define('INSTALLER_BASE_URL', '/install');
}
// functions.php 로드 (한 번만) — 누수된 BASE_PATH 와 무관하게 프로젝트 루트 절대경로 사용
require_once $this->installerRoot().'/public/install/includes/functions.php';
// functions.php 로드 (한 번만) — base_path() 대신 BASE_PATH 상수 직접 사용
require_once BASE_PATH . '/public/install/includes/functions.php';
}
/**
@@ -178,8 +165,8 @@ class InstallerWindowsCommandsTest extends TestCase
*/
public function test_translation_keys_exist(): void
{
$koTranslations = require $this->installerRoot().'/public/install/lang/ko.php';
$enTranslations = require $this->installerRoot().'/public/install/lang/en.php';
$koTranslations = require BASE_PATH . '/public/install/lang/ko.php';
$enTranslations = require BASE_PATH . '/public/install/lang/en.php';
$this->assertArrayHasKey('permission_windows_hint', $koTranslations, 'ko.php에 permission_windows_hint 키가 없습니다');
$this->assertArrayHasKey('permission_windows_hint', $enTranslations, 'en.php에 permission_windows_hint 키가 없습니다');
@@ -192,8 +179,8 @@ class InstallerWindowsCommandsTest extends TestCase
*/
public function test_directory_create_guide_translation_keys_exist(): void
{
$koTranslations = require $this->installerRoot().'/public/install/lang/ko.php';
$enTranslations = require $this->installerRoot().'/public/install/lang/en.php';
$koTranslations = require BASE_PATH . '/public/install/lang/ko.php';
$enTranslations = require BASE_PATH . '/public/install/lang/en.php';
$this->assertArrayHasKey('directory_create_guide', $koTranslations, 'ko.php에 directory_create_guide 키가 없습니다');
$this->assertArrayHasKey('directory_create_guide', $enTranslations, 'en.php에 directory_create_guide 키가 없습니다');
@@ -1,84 +0,0 @@
<?php
namespace Tests\Unit\Listeners;
use App\Contracts\Extension\HookListenerInterface;
use App\Listeners\ExtensionConfigCacheListener;
use Tests\TestCase;
/**
* ExtensionConfigCacheListener 회귀 테스트.
*
* 확장 활성화/비활성화 직후 config 캐시를 재생성하는 리스너.
* install/uninstall/update 는 ExtensionManager::updateComposerAutoload() 가 담당하므로,
* 이 리스너는 activate/deactivate 만 구독해야 한다(이중 재생성 회피). 구독 훅 집합이
* 바뀌면 config 캐시가 재생성되지 않거나(누락) 두 번 재생성되는(낭비) 회귀가 발생한다.
*/
class ExtensionConfigCacheListenerTest extends TestCase
{
public function test_implements_hook_listener_interface(): void
{
$this->assertInstanceOf(
HookListenerInterface::class,
new ExtensionConfigCacheListener
);
}
public function test_subscribes_only_activate_and_deactivate_hooks(): void
{
$hooks = ExtensionConfigCacheListener::getSubscribedHooks();
$expected = [
'core.modules.activated',
'core.modules.after_deactivate',
'core.plugins.activated',
'core.plugins.after_deactivate',
'core.templates.activated',
'core.templates.after_deactivate',
];
$this->assertEqualsCanonicalizing($expected, array_keys($hooks));
}
public function test_does_not_subscribe_install_uninstall_update_hooks(): void
{
// install/uninstall/update 는 updateComposerAutoload 가 config 캐시를 재생성하므로
// 이 리스너가 구독하면 이중 재생성이 된다. 구독 목록에서 제외되어야 한다.
$hookNames = array_keys(ExtensionConfigCacheListener::getSubscribedHooks());
foreach (['installed', 'updated'] as $lifecycle) {
foreach (['modules', 'plugins', 'templates'] as $type) {
$this->assertNotContains(
"core.{$type}.{$lifecycle}",
$hookNames,
"core.{$type}.{$lifecycle} 는 updateComposerAutoload 가 담당하므로 이 리스너가 구독하면 안 됩니다."
);
}
}
}
public function test_all_hooks_route_to_on_extension_toggled(): void
{
$hooks = ExtensionConfigCacheListener::getSubscribedHooks();
foreach ($hooks as $hookName => $config) {
$this->assertSame('onExtensionToggled', $config['method'], "{$hookName} 은 onExtensionToggled 로 라우팅되어야 합니다.");
$this->assertArrayHasKey('priority', $config);
}
}
public function test_all_hooks_are_synchronous(): void
{
// config 캐시 재생성은 인프라 작업이라 큐로 미루면 안 된다. Action 훅의 기본 등록은
// 큐 디스패치(HookListenerRegistrar::applySubscribedHooks) 이므로, sync 플래그가
// 없으면 워커 미가동 환경(대부분의 소규모 사이트)에서 config:cache 가 영영 재생성되지
// 않는다. 게다가 CLI 커맨드(plugin:deactivate 등)는 실행 후 프로세스가 종료되어 큐에
// 쌓인 작업을 처리할 주체가 없다. 모든 구독 훅은 sync=true 여야 한다.
$hooks = ExtensionConfigCacheListener::getSubscribedHooks();
foreach ($hooks as $hookName => $config) {
$this->assertArrayHasKey('sync', $config, "{$hookName} 은 sync 플래그가 있어야 합니다 (config 캐시 재생성은 동기 실행 필수).");
$this->assertTrue($config['sync'], "{$hookName} 은 sync=true 여야 합니다 — 큐로 미루면 워커 미가동 시 config 캐시가 재생성되지 않습니다.");
}
}
}
@@ -193,7 +193,7 @@ class InstallerRuntimeServiceProviderTest extends TestCase
public function test_provider_injects_app_key(): void
{
$this->withProductionEnv();
$key = 'base64:'.base64_encode(random_bytes(32));
$key = 'base64:' . base64_encode(random_bytes(32));
$this->writeRuntime([
'app' => ['key' => $key],
@@ -284,7 +284,6 @@ class InstallerRuntimeServiceProviderTest extends TestCase
public function test_recovers_stale_process_env_when_disk_env_is_healthy(): void
{
$this->skipUnlessBeta7CoreVersion();
$this->withProductionEnv();
// 디스크 .env 는 정합 자격증명 + INSTALLER_COMPLETED (finalize 완료 신호)
@@ -424,32 +423,6 @@ class InstallerRuntimeServiceProviderTest extends TestCase
$this->assertSame('root', getenv('DB_WRITE_USERNAME'), 'runtime.php 잔존 시 본 보정 미발동');
}
/**
* beta.7 stale-ENV 복구는 config/app.php version === '7.0.0-beta.7' 일 때만 발동한다
* (InstallerRuntimeServiceProvider::recoverStaleProcessEnvFromDiskEnv 의 한시 가드).
* 코어가 beta.7 을 지난 버전이면 복구가 의도적으로 비활성이므로, 복구 발동을 기대하는
* 테스트는 skip 한다. no-recovery 테스트들은 비활성 상태에서도 결과가 동일하여 영향 없음.
*/
private function skipUnlessBeta7CoreVersion(): void
{
$configPath = base_path('config/app.php');
$content = is_file($configPath) ? (string) @file_get_contents($configPath) : '';
$version = null;
if (preg_match("/'version'\s*=>\s*env\(\s*'APP_VERSION'\s*,\s*'([^']+)'\s*\)/", $content, $m)) {
$version = $m[1];
} elseif (preg_match("/'version'\s*=>\s*'([^']+)'/", $content, $m)) {
$version = $m[1];
}
if ($version !== '7.0.0-beta.7') {
$this->markTestSkipped(
'beta.7 stale-ENV 복구는 코어 version === 7.0.0-beta.7 일 때만 발동. '
.'현재 version='.($version ?? 'unknown').' → 한시 보정 비활성 (정상).'
);
}
}
/**
* @param array<string, mixed> $data
*/
@@ -460,7 +433,7 @@ class InstallerRuntimeServiceProviderTest extends TestCase
mkdir($dir, 0755, true);
}
$php = "<?php\n\nreturn ".var_export($data, true).";\n";
$php = "<?php\n\nreturn " . var_export($data, true) . ";\n";
file_put_contents($this->runtimePath, $php);
}
}
@@ -18,7 +18,7 @@ use Tests\TestCase;
* 덮어쓰지 않아야 한다. 그렇지 않으면 운영 PC 의 settings 값(debug=false) 때문에 PHPUnit / E2E 인프라
* (PlaywrightIssueToken 등) 가 의도치 않게 차단된다.
*
* 회귀 컨텍스트: 이슈 #238 Playwright 도입 작업 중 운영 환경(APP_ENV=production, debug.json mode=false) 에서
* 회귀 컨텍스트: 이슈 #238 Playwright 도입 작업 중 PO 환경(APP_ENV=production, debug.json mode=false) 에서
* --env=testing 으로 artisan 명령을 실행해도 SettingsServiceProvider 가 settings JSON 의 mode=false 로
* config('app.debug') 를 false 로 덮어쓰는 문제가 발견됨.
*/
+5 -246
View File
@@ -2,7 +2,6 @@
namespace Tests\Unit\Services;
use App\Extension\Helpers\CoreBackupHelper;
use App\Extension\Helpers\FilePermissionHelper;
use App\Services\CoreUpdateService;
use Illuminate\Support\Facades\Artisan;
@@ -1112,240 +1111,6 @@ MD;
$this->assertFalse(File::exists($tempDest.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'OrphanFile.php'));
}
// ========================================================================
// applyUpdate() — 기본(증분) 3-way 적용 + --prune (공개 #64)
// ========================================================================
/**
* 증분 모드(applyList 지정): 코어가 변경하지 않은 파일(applyList 미포함)은
* 스킵되어 사용자가 수정한 현재 디스크 내용이 보존됩니다.
*
* 이슈 #64 핵심 회귀 가드 — `.htaccess` 커스텀 블록 소실 방지.
*/
public function test_apply_update_incremental_preserves_user_modified_unchanged_file(): void
{
[$source, $fakeBase, $restore] = $this->prepareApplyUpdateEnv(['public']);
try {
// source(theirs): .htaccess 는 코어가 변경하지 않았다고 가정 → applyList 미포함
File::ensureDirectoryExists($source.DIRECTORY_SEPARATOR.'public');
File::put($source.DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.'.htaccess', "# core default\n");
File::put($source.DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.'index.php', "<?php // core v2\n");
// 활성(mine): 사용자가 .htaccess 에 커스텀 블록을 넣은 상태
File::ensureDirectoryExists($fakeBase.DIRECTORY_SEPARATOR.'public');
File::put($fakeBase.DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.'.htaccess', "# core default\n# USER CUSTOM CACHE BLOCK\n");
File::put($fakeBase.DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.'index.php', "<?php // core v1\n");
// 코어가 실제로 바꾼 파일은 index.php 뿐 (.htaccess 는 목록에 없음)
$applyList = ['public/index.php'];
$this->service->applyUpdate($source, null, prune: false, applyList: $applyList);
// .htaccess: 사용자 커스텀 블록 보존 (스킵)
$this->assertStringContainsString(
'USER CUSTOM CACHE BLOCK',
File::get($fakeBase.DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.'.htaccess'),
'.htaccess 는 applyList 에 없으므로 사용자 수정이 보존되어야 한다',
);
// index.php: 코어 변경분 적용
$this->assertStringContainsString(
'core v2',
File::get($fakeBase.DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.'index.php'),
);
} finally {
$restore();
}
}
/**
* 증분 모드: applyList 에 없는 신규 파일이 source 에 있어도 스킵됩니다.
* (코어가 실제 추가했다면 applyList 에 담겼을 것 — 목록이 최종 권위)
*/
public function test_apply_update_incremental_applies_only_listed_files(): void
{
[$source, $fakeBase, $restore] = $this->prepareApplyUpdateEnv(['app']);
try {
File::ensureDirectoryExists($source.DIRECTORY_SEPARATOR.'app');
File::put($source.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'Listed.php', '<?php // listed');
File::put($source.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'Unlisted.php', '<?php // unlisted');
File::ensureDirectoryExists($fakeBase.DIRECTORY_SEPARATOR.'app');
$this->service->applyUpdate($source, null, prune: false, applyList: ['app/Listed.php']);
$this->assertFileExists($fakeBase.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'Listed.php');
$this->assertFileDoesNotExist(
$fakeBase.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'Unlisted.php',
'applyList 에 없는 파일은 복사되지 않아야 한다',
);
} finally {
$restore();
}
}
/**
* end-to-end 회귀 (공개 #64 / 내부 #452): 코어 업데이트가 번들 확장의 변경된
* `_bundled` 파일을 실제로 반영합니다.
*
* computeApplyList(3-way 산출) → applyUpdate(적용) 전 체인을 실제 config 조합
* (protected 에 `modules`, targets 에 `modules/_bundled`)으로 검증한다.
* protected 필터가 `_bundled` 갱신을 삼키던 결함으로 인해, 코어 배포본에
* 새 번들(vendor-bundle.json/composer.json 갱신)이 포함돼도 활성 서버의
* `_bundled` 가 갱신되지 않아 이후 `module:update` 무결성 검증이 실패하던
* 회귀를 차단한다.
*/
public function test_incremental_apply_reflects_changed_bundled_extension_file(): void
{
[$source, $fakeBase, $restore] = $this->prepareApplyUpdateEnv(['modules/_bundled']);
try {
// 실제 config 조합 재현: protected 에 부모 도메인 포함
config(['app.update.protected_paths' => ['.env', 'storage', 'vendor', 'modules', 'plugins', 'templates', 'lang-packs']]);
$rel = 'modules/_bundled/sirsoft-ecommerce/vendor-bundle.json';
$relPlatform = str_replace('/', DIRECTORY_SEPARATOR, $rel);
// base(구버전) = 옛 해시, source(신버전) = 새 해시 (코어가 변경한 번들 파일)
File::ensureDirectoryExists(dirname($fakeBase.DIRECTORY_SEPARATOR.$relPlatform));
File::put($fakeBase.DIRECTORY_SEPARATOR.$relPlatform, '{"composer_json_sha256":"OLD"}');
File::ensureDirectoryExists(dirname($source.DIRECTORY_SEPARATOR.$relPlatform));
File::put($source.DIRECTORY_SEPARATOR.$relPlatform, '{"composer_json_sha256":"NEW-differs-in-length"}');
// 3-way 산출: base != theirs → changed 로 목록 포함되어야 한다
$applyResult = CoreBackupHelper::computeApplyList(
$fakeBase,
$source,
config('app.update.targets'),
config('app.update.protected_paths'),
config('app.update.excludes'),
);
$this->assertContains($rel, $applyResult['apply'], 'changed 된 _bundled 파일이 apply 목록에 포함되어야 한다');
// 적용: 활성(base) 파일이 신버전 내용으로 갱신되어야 한다
$this->service->applyUpdate($source, null, prune: false, applyList: $applyResult['apply']);
$this->assertSame(
'{"composer_json_sha256":"NEW-differs-in-length"}',
File::get($fakeBase.DIRECTORY_SEPARATOR.$relPlatform),
'코어 업데이트가 변경된 _bundled 번들 파일을 실제로 반영해야 한다',
);
} finally {
$restore();
}
}
/**
* 증분 모드는 orphan(소스에 없는 대상 파일)을 삭제하지 않습니다
* (사용자가 추가한 신규 파일 보존).
*/
public function test_apply_update_incremental_does_not_remove_orphans(): void
{
[$source, $fakeBase, $restore] = $this->prepareApplyUpdateEnv(['app']);
try {
File::ensureDirectoryExists($source.DIRECTORY_SEPARATOR.'app');
File::put($source.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'Core.php', '<?php // core');
File::ensureDirectoryExists($fakeBase.DIRECTORY_SEPARATOR.'app');
File::put($fakeBase.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'UserAdded.php', '<?php // user file');
$this->service->applyUpdate($source, null, prune: false, applyList: ['app/Core.php']);
$this->assertFileExists(
$fakeBase.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'UserAdded.php',
'증분 모드는 orphan 을 삭제하지 않아야 한다',
);
} finally {
$restore();
}
}
/**
* prune=true: 전체 덮어쓰기 + orphan 삭제 (기존 동작).
*/
public function test_apply_update_prune_removes_orphans_and_overwrites_all(): void
{
[$source, $fakeBase, $restore] = $this->prepareApplyUpdateEnv(['app']);
try {
File::ensureDirectoryExists($source.DIRECTORY_SEPARATOR.'app');
File::put($source.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'Core.php', '<?php // core v2');
File::ensureDirectoryExists($fakeBase.DIRECTORY_SEPARATOR.'app');
File::put($fakeBase.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'Core.php', '<?php // core v1');
File::put($fakeBase.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'Orphan.php', '<?php // orphan');
// prune 모드는 applyList 를 무시하고 전체 덮어쓰기
$this->service->applyUpdate($source, null, prune: true, applyList: ['app/Core.php']);
$this->assertStringContainsString('core v2', File::get($fakeBase.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'Core.php'));
$this->assertFileDoesNotExist(
$fakeBase.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'Orphan.php',
'prune 모드는 orphan 을 삭제해야 한다',
);
} finally {
$restore();
}
}
/**
* applyList=null (백업 부재 fallback): prune 이 아니어도 전체 덮어쓰기로 회귀.
*/
public function test_apply_update_null_apply_list_falls_back_to_full_overwrite(): void
{
[$source, $fakeBase, $restore] = $this->prepareApplyUpdateEnv(['app']);
try {
File::ensureDirectoryExists($source.DIRECTORY_SEPARATOR.'app');
File::put($source.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'A.php', '<?php // a');
File::put($source.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'B.php', '<?php // b');
File::ensureDirectoryExists($fakeBase.DIRECTORY_SEPARATOR.'app');
// applyList 미지정(null) → incremental=false → 전체 복사
$this->service->applyUpdate($source, null, prune: false, applyList: null);
$this->assertFileExists($fakeBase.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'A.php');
$this->assertFileExists($fakeBase.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'B.php');
} finally {
$restore();
}
}
/**
* applyUpdate 환경(격리 base_path + config targets)을 준비합니다.
*
* @param array<int, string> $targets config('app.update.targets') 로 설정할 값
* @return array{0:string, 1:string, 2:\Closure} [source 경로, fakeBase 경로, 복원 클로저]
*/
private function prepareApplyUpdateEnv(array $targets): array
{
$source = storage_path('test_apply3_src_'.uniqid());
$fakeBase = storage_path('test_apply3_base_'.uniqid());
$this->tempDirs[] = $source;
$this->tempDirs[] = $fakeBase;
File::ensureDirectoryExists($source);
File::ensureDirectoryExists($fakeBase);
$originalBasePath = base_path();
app()->setBasePath($fakeBase);
config([
'app.update.targets' => $targets,
'app.update.excludes' => [],
'app.update.protected_paths' => ['.env', 'storage', 'vendor', 'node_modules', '.git'],
]);
$restore = function () use ($originalBasePath): void {
app()->setBasePath($originalBasePath);
};
return [$source, $fakeBase, $restore];
}
// ========================================================================
// applyUpdate() — 신규 최상위 디렉토리 자동 발견 폴백 (회귀: lang-packs 누락)
// ========================================================================
@@ -1575,15 +1340,10 @@ MD;
}
/**
* 비회귀: `--prune` 모드에서 `_bundled` 최상위 사용자 항목은 보존하되, source 에
* 존재하는 코어 번들 확장 디렉토리 *내부* 의 stale 파일 정리는 그대로 유지되어야 한다.
*
* 주의: orphan(stale) 정리는 `--prune` 지정 시에만 수행된다 (공개 #64).
* 기본(증분) 모드는 orphan 을 삭제하지 않으므로 본 회귀 가드는 prune 컨텍스트로 검증한다.
* 기본 모드에서 stale 파일이 보존되는 동작은 별도 테스트
* (test_apply_update_incremental_does_not_remove_orphans)가 커버한다.
* 비회귀: `_bundled` 최상위 사용자 항목은 보존하되, source 에 존재하는 코어
* 번들 확장 디렉토리 *내부* 의 stale 파일 정리는 그대로 유지되어야 한다.
*/
public function test_apply_update_prune_still_cleans_stale_file_inside_bundled_extension(): void
public function test_apply_update_still_cleans_stale_file_inside_bundled_extension(): void
{
$sourcePath = storage_path('test_388_stale_src_'.uniqid());
$this->tempDirs[] = $sourcePath;
@@ -1619,13 +1379,12 @@ MD;
'app.update.protected_paths' => ['.env', 'storage', 'vendor', 'node_modules', '.git'],
]);
// --prune 컨텍스트: orphan(stale) 정리 활성화
$this->service->applyUpdate($sourcePath, null, prune: true);
$this->service->applyUpdate($sourcePath);
// 코어 번들 확장 내부의 stale 파일은 정리되어야 함
$this->assertFileDoesNotExist(
$baseExt.DIRECTORY_SEPARATOR.'old.json',
'--prune 모드에서 코어 번들 확장 내부의 stale 파일은 정리되어야 한다'
'코어 번들 확장 내부의 stale 파일은 정리되어야 한다'
);
// 사용자 추가 디렉토리는 보존
@@ -1,307 +0,0 @@
<?php
namespace Tests\Unit\Services;
use App\Extension\ModuleManager;
use App\Extension\PluginManager;
use App\Services\ExtensionBundleService;
use Illuminate\Support\Facades\File;
use Mockery;
use Tests\TestCase;
/**
* ExtensionBundleService 단위 테스트
*
* 활성 확장 IIFE/CSS 의 priority 정렬, `\n;\n` 구분자 병합, sourceMappingURL
* 처리, 확장별 fault tolerance, 캐시 파일 생성/정리를 검증한다.
*/
class ExtensionBundleServiceTest extends TestCase
{
private string $fixtureDir;
private ModuleManager $moduleManager;
private PluginManager $pluginManager;
protected function setUp(): void
{
parent::setUp();
$this->fixtureDir = storage_path('framework/testing/ext-bundle-fixtures');
File::ensureDirectoryExists($this->fixtureDir);
$this->moduleManager = Mockery::mock(ModuleManager::class);
$this->pluginManager = Mockery::mock(PluginManager::class);
// 번들 캐시 디렉토리 초기화 (테스트 격리)
$bundleDir = storage_path('app/ext-bundles');
if (is_dir($bundleDir)) {
foreach (glob($bundleDir.'/*.{js,css}', GLOB_BRACE) as $f) {
@unlink($f);
}
}
}
protected function tearDown(): void
{
if (is_dir($this->fixtureDir)) {
foreach (glob($this->fixtureDir.'/*') as $f) {
@unlink($f);
}
@rmdir($this->fixtureDir);
}
$bundleDir = storage_path('app/ext-bundles');
if (is_dir($bundleDir)) {
foreach (glob($bundleDir.'/*.{js,css}', GLOB_BRACE) as $f) {
@unlink($f);
}
}
Mockery::close();
parent::tearDown();
}
/**
* 지정 내용으로 fixture 에셋 파일을 만들고 절대 경로를 반환한다.
*/
private function writeFixture(string $name, string $content): string
{
$path = $this->fixtureDir.'/'.$name;
File::put($path, $content);
return $path;
}
/**
* hasAssets/getAssetLoadingConfig/getBuiltAssetAbsolutePaths/getIdentifier 를
* 노출하는 가짜 확장 인스턴스를 만든다.
*/
private function fakeExtension(string $identifier, int $priority, ?string $jsPath, ?string $cssPath, string $strategy = 'global'): object
{
$ext = Mockery::mock();
$ext->shouldReceive('hasAssets')->andReturn(true);
$ext->shouldReceive('getIdentifier')->andReturn($identifier);
$ext->shouldReceive('getAssetLoadingConfig')->andReturn([
'strategy' => $strategy,
'priority' => $priority,
'dependencies' => [],
]);
$paths = [];
if ($jsPath !== null) {
$paths['js'] = $jsPath;
}
if ($cssPath !== null) {
$paths['css'] = $cssPath;
}
$ext->shouldReceive('getBuiltAssetAbsolutePaths')->andReturn($paths);
return $ext;
}
private function service(): ExtensionBundleService
{
return new ExtensionBundleService($this->moduleManager, $this->pluginManager);
}
public function test_orders_global_assets_by_priority_ascending(): void
{
$a = $this->writeFixture('a.js', '(function(){})()');
$b = $this->writeFixture('b.js', '(function(){})()');
$c = $this->writeFixture('c.js', '(function(){})()');
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([
'ext-c' => $this->fakeExtension('ext-c', 30, $c, null),
'ext-a' => $this->fakeExtension('ext-a', 10, $a, null),
'ext-b' => $this->fakeExtension('ext-b', 20, $b, null),
]);
$ordered = $this->service()->getOrderedGlobalAssetPaths('module');
$this->assertSame(['ext-a', 'ext-b', 'ext-c'], array_keys($ordered));
}
public function test_skips_non_global_strategy(): void
{
$g = $this->writeFixture('g.js', '(function(){})()');
$l = $this->writeFixture('l.js', '(function(){})()');
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([
'ext-global' => $this->fakeExtension('ext-global', 100, $g, null, 'global'),
'ext-layout' => $this->fakeExtension('ext-layout', 100, $l, null, 'layout'),
]);
$ordered = $this->service()->getOrderedGlobalAssetPaths('module');
$this->assertArrayHasKey('ext-global', $ordered);
$this->assertArrayNotHasKey('ext-layout', $ordered);
}
public function test_js_bundle_joins_iife_with_semicolon_newline_separator(): void
{
// 세미콜론 없이 끝나는 IIFE 2개 (ecommerce 형태)
$a = $this->writeFixture('a.js', '(function(){window.A=1})()');
$b = $this->writeFixture('b.js', '(function(){window.B=2})()');
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([
'ext-a' => $this->fakeExtension('ext-a', 10, $a, null),
'ext-b' => $this->fakeExtension('ext-b', 20, $b, null),
]);
$js = $this->service()->buildJsBundle('module');
// 두 IIFE 가 모두 포함되고 `\n;\n` 구분자로 구분
$this->assertStringContainsString('window.A=1', $js);
$this->assertStringContainsString('window.B=2', $js);
$this->assertStringContainsString("\n;\n", $js);
// priority 순서 (a 가 b 보다 먼저)
$this->assertLessThan(strpos($js, 'window.B=2'), strpos($js, 'window.A=1'));
}
public function test_prod_strips_source_mapping_url(): void
{
$this->app['env'] = 'production';
app()->detectEnvironment(fn () => 'production');
$a = $this->writeFixture('a.js', "(function(){})()\n//# sourceMappingURL=a.js.map");
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([
'ext-a' => $this->fakeExtension('ext-a', 10, $a, null),
]);
$js = $this->service()->buildJsBundle('module');
$this->assertStringNotContainsString('sourceMappingURL', $js);
}
public function test_dev_rewrites_source_mapping_url_to_asset_serving_path(): void
{
// 기본 testing 환경 = 비프로덕션 → dev rewrite 경로
$a = $this->writeFixture('a.js', "(function(){})()\n//# sourceMappingURL=a.js.map");
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([
'ext-a' => $this->fakeExtension('ext-a', 10, $a, null),
]);
$js = $this->service()->buildJsBundle('module');
$this->assertStringContainsString('sourceMappingURL=/api/modules/assets/ext-a/dist/js/a.js.map', $js);
}
public function test_per_extension_fault_tolerance_skips_missing_file(): void
{
$good = $this->writeFixture('good.js', '(function(){window.GOOD=1})()');
$missing = $this->fixtureDir.'/does-not-exist.js';
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([
'ext-missing' => $this->fakeExtension('ext-missing', 10, $missing, null),
'ext-good' => $this->fakeExtension('ext-good', 20, $good, null),
]);
$js = $this->service()->buildJsBundle('module');
// 없는 파일은 skip, 정상 확장은 여전히 포함 (번들 전체 붕괴 안 함)
$this->assertStringContainsString('window.GOOD=1', $js);
}
public function test_css_with_relative_url_is_excluded(): void
{
$safe = $this->writeFixture('safe.css', '.a{color:red}');
$relative = $this->writeFixture('rel.css', '.b{background:url(./img/x.png)}');
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([
'ext-safe' => $this->fakeExtension('ext-safe', 10, null, $safe),
'ext-rel' => $this->fakeExtension('ext-rel', 20, null, $relative),
]);
$css = $this->service()->buildCssBundle('module');
$this->assertStringContainsString('.a{color:red}', $css);
$this->assertStringNotContainsString('url(./img/x.png)', $css);
}
public function test_empty_bundle_returns_empty_path(): void
{
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([]);
$path = $this->service()->getBundleFilePath('module', 'js', 12345);
$this->assertSame('', $path);
}
public function test_prod_writes_versioned_cache_file_and_reuses_it(): void
{
$this->app['env'] = 'production';
app()->detectEnvironment(fn () => 'production');
$a = $this->writeFixture('a.js', '(function(){window.A=1})()');
// getActiveModules 는 두 번 호출될 수 있으므로 안정적으로 반환
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([
'ext-a' => $this->fakeExtension('ext-a', 10, $a, null),
]);
$svc = $this->service();
$path1 = $svc->getBundleFilePath('module', 'js', 999);
$this->assertNotSame('', $path1);
$this->assertFileExists($path1);
$this->assertStringContainsString('module.999.js', $path1);
// 같은 version 재요청 → 동일 파일 (캐시 히트)
$path2 = $svc->getBundleFilePath('module', 'js', 999);
$this->assertSame($path1, $path2);
}
public function test_cleanup_removes_stale_version_bundles_only(): void
{
$bundleDir = storage_path('app/ext-bundles');
File::ensureDirectoryExists($bundleDir);
File::put($bundleDir.'/module.100.js', 'old');
File::put($bundleDir.'/module.200.js', 'current');
File::put($bundleDir.'/plugin.100.css', 'old');
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([]);
$deleted = $this->service()->cleanupStaleBundles(200);
// version 200 외 파일만 삭제 (module.100.js, plugin.100.css = 2건)
$this->assertSame(2, $deleted);
$this->assertFileExists($bundleDir.'/module.200.js');
$this->assertFileDoesNotExist($bundleDir.'/module.100.js');
$this->assertFileDoesNotExist($bundleDir.'/plugin.100.css');
}
public function test_clear_bundles_by_type(): void
{
$bundleDir = storage_path('app/ext-bundles');
File::ensureDirectoryExists($bundleDir);
File::put($bundleDir.'/module.100.js', 'm');
File::put($bundleDir.'/plugin.100.js', 'p');
$deleted = $this->service()->clearBundles('module');
$this->assertSame(1, $deleted);
$this->assertFileDoesNotExist($bundleDir.'/module.100.js');
$this->assertFileExists($bundleDir.'/plugin.100.js');
}
public function test_plugin_bundle_orders_by_priority_gdpr_first_when_lowest(): void
{
// gdpr 가 priority 50 으로 최상단(제약 1 회귀 가드) — 이름 하드코딩 아닌 선언 결과
$gdpr = $this->writeFixture('gdpr.js', '(function(){window.GDPR=1})()');
$other = $this->writeFixture('other.js', '(function(){window.OTHER=1})()');
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([
'sirsoft-other' => $this->fakeExtension('sirsoft-other', 100, $other, null),
'sirsoft-gdpr' => $this->fakeExtension('sirsoft-gdpr', 50, $gdpr, null),
]);
$ordered = $this->service()->getOrderedGlobalAssetPaths('plugin');
$this->assertSame('sirsoft-gdpr', array_key_first($ordered));
$js = $this->service()->buildJsBundle('plugin');
$this->assertLessThan(strpos($js, 'window.OTHER=1'), strpos($js, 'window.GDPR=1'));
}
}
@@ -5,7 +5,6 @@ namespace Tests\Unit\Services;
use App\Models\NotificationDefinition;
use App\Services\NotificationDefinitionService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
/**
@@ -164,53 +163,4 @@ class NotificationDefinitionServiceTest extends TestCase
$this->assertEquals(['mail', 'database'], $result->channels);
$this->assertEquals(['core.auth.after_register', 'core.auth.after_login'], $result->hooks);
}
/**
* getAllActive() 캐시 히트 시 notification_definitions DB 조회가 0건인지 확인.
*
* 서빙 API 부팅 비용 최적화 검증 (계획서 §2-1 나): 동적 훅(알림) 등록 경로
* (NotificationHookListener::registerDynamicHooks → getAllActive)는 이미
* `['notification']` 태그로 캐시되어 있으므로, 첫 요청(캐시 워밍) 이후에는
* 매 요청 DB 조회가 발생하지 않아야 한다 (37ms 캐시 미스는 첫 요청 1회 비용).
*
* @scenario cache_state=present_but_testing_env, listener_type=action_sync, regeneration_trigger=extension_update, registration_source=plugin
*
* @effects notification_getAllActive_cache_hit_issues_zero_db_query
*/
public function test_get_all_active_cache_hit_issues_zero_db_query(): void
{
NotificationDefinition::create([
'type' => 'cache_hit_probe',
'hook_prefix' => 'core.auth',
'extension_type' => 'core',
'extension_identifier' => 'core',
'name' => ['ko' => '캐시 히트 검증'],
'variables' => [],
'channels' => ['mail'],
'hooks' => ['core.auth.after_register'],
'is_active' => true,
'is_default' => true,
]);
// 1차 호출: 캐시 워밍 (DB 조회 발생)
$this->service->invalidateAllCache();
$this->service->getAllActive();
// 2차 호출: 캐시 히트 → notification_definitions 조회 0건이어야 함
DB::enableQueryLog();
$this->service->getAllActive();
$queries = DB::getQueryLog();
DB::disableQueryLog();
$definitionQueries = array_filter(
$queries,
fn ($q) => str_contains($q['query'], 'notification_definitions')
);
$this->assertCount(
0,
$definitionQueries,
'캐시 히트 시 notification_definitions DB 조회가 발생하지 않아야 합니다 (동적 훅 등록 비용 제거)'
);
}
}
@@ -1,128 +0,0 @@
<?php
namespace Tests\Unit\Support;
use App\Support\ConfigCacheHelper;
use Illuminate\Support\Facades\Artisan;
use Tests\TestCase;
/**
* ConfigCacheHelper 회귀 테스트.
*
* config 소스(config/*.php, .env, settings JSON, 활성 확장 목록)를 바꾸는 라이프사이클
* 지점이 config:clear 만 하고 config:cache 를 재생성하지 않아, 한 번 캐시가 비워지면
* config:cache 가 영구히 비활성 상태로 남던 결함을 단일 헬퍼로 막는다.
*
* rebuild() 는 testing 환경에서 early return 하므로(격리 보호), 실제 config:cache 생성
* 경로는 환경을 임시로 'production' 으로 강제하고 Artisan 을 mock 하여 검증한다.
* 실제 Artisan config:cache 를 호출하면 테스트 격리가 깨지므로 절대 실행하지 않는다.
*/
class ConfigCacheHelperTest extends TestCase
{
protected function tearDown(): void
{
// 환경 강제 복원 (다른 테스트 오염 방지)
app()->detectEnvironment(fn () => 'testing');
parent::tearDown();
}
public function test_rebuild_clears_but_never_caches_in_testing_environment(): void
{
// 기본 테스트 환경 = testing → config:clear 는 수행(값 반영 보장), config:cache 는 스킵(격리 보호).
$calls = [];
Artisan::shouldReceive('call')->andReturnUsing(function ($command) use (&$calls) {
$calls[] = $command;
return 0;
});
ConfigCacheHelper::rebuild();
$this->assertContains('config:clear', $calls);
$this->assertNotContains('config:cache', $calls, 'testing 환경에서는 config:cache 를 생성하지 않아야 합니다 (격리 보호).');
}
public function test_rebuild_clears_then_caches_when_installed(): void
{
// 비-testing 환경 + 설치 완료 상태 강제
app()->detectEnvironment(fn () => 'production');
config(['app.installer_completed' => true]);
$calls = [];
Artisan::shouldReceive('call')->andReturnUsing(function ($command) use (&$calls) {
$calls[] = $command;
return 0;
});
ConfigCacheHelper::rebuild();
// config:clear 가 config:cache 보다 먼저 (stale 제거 후 재생성).
$this->assertContains('config:clear', $calls);
$this->assertContains('config:cache', $calls);
$this->assertLessThan(
array_search('config:cache', $calls, true),
array_search('config:clear', $calls, true),
'config:clear 는 config:cache 보다 먼저 실행되어야 합니다.'
);
}
public function test_rebuild_clears_only_when_not_installed(): void
{
// 비-testing + 설치 미완료 → clear 만, 재생성은 스킵(불완전 config 박제 방지)
app()->detectEnvironment(fn () => 'production');
config(['app.installer_completed' => false]);
// 설치 플래그 파일도 없어야 함 (isInstalled false 보장) — 존재 시 이 테스트는
// 환경상 스킵될 수 있으나, 로컬 dev 에서 g7_installed 가 있으면 결과가 달라진다.
if (file_exists(storage_path('app/g7_installed'))) {
$this->markTestSkipped('storage/app/g7_installed 존재 — 미설치 경로 검증 불가');
}
$calls = [];
Artisan::shouldReceive('call')->andReturnUsing(function ($command) use (&$calls) {
$calls[] = $command;
return 0;
});
ConfigCacheHelper::rebuild();
$this->assertContains('config:clear', $calls);
$this->assertNotContains('config:cache', $calls, '설치 미완료 시 config:cache 를 생성하지 않아야 합니다.');
}
public function test_clear_only_helper_never_caches(): void
{
app()->detectEnvironment(fn () => 'production');
config(['app.installer_completed' => true]);
$calls = [];
Artisan::shouldReceive('call')->andReturnUsing(function ($command) use (&$calls) {
$calls[] = $command;
return 0;
});
ConfigCacheHelper::clear();
$this->assertContains('config:clear', $calls);
$this->assertNotContains('config:cache', $calls, 'clear() 는 config:cache 를 재생성하지 않아야 합니다.');
}
public function test_clear_calls_config_clear_even_in_testing(): void
{
// clear() 는 config:clear 만 수행(재생성 없음). testing 에서도 clear 는 격리를 깨지 않으므로 실행한다.
$calls = [];
Artisan::shouldReceive('call')->andReturnUsing(function ($command) use (&$calls) {
$calls[] = $command;
return 0;
});
ConfigCacheHelper::clear();
$this->assertSame(['config:clear'], $calls);
}
}
@@ -1,48 +0,0 @@
feature: admin_user_cross_navigation
description: >
관리자 ↔ 유저 화면 상호 이동 링크 (#450). 관리자 사이드바 "사이트 보기",
관리자 게시물 조회 ↔ 유저 게시판, 유저 게시판 → 관리자(게시물 조회+게시판 관리),
유저 상품 상세 ↔ 관리자 상품 수정. 유저측 관리자 진입 링크는 세부 권한 플래그로 게이트.
모바일 사이드바 드로어 상단 잘림 수정 포함.
test_files:
- modules/_bundled/sirsoft-board/tests/Feature/PostResourcePermissionTest.php
- modules/_bundled/sirsoft-ecommerce/tests/Feature/Http/Controllers/Public/PublicProductControllerTest.php
- tests/Playwright/specs/admin/cross-navigation-and-mobile-drawer.spec.ts
# 입력 axis
# link : 크로스링크 종류 (출발→도착 surface)
# permitted: 유저측 관리자 진입 권한 보유 여부 (관리자측/항상노출 링크는 n/a 로 컷)
axes:
link: [admin_sidebar_to_user_site, admin_board_to_user_board, user_board_to_admin, user_product_to_admin_edit, admin_product_to_user_detail]
permitted: [true, false, na]
# 의미 없는 조합 컷:
# - 항상 노출(게이트 없음) 링크는 permitted 축이 무의미 → na 만 유지, true/false 컷
# - 게이트 있는 유저측 링크는 na 컷 (true/false 만)
exclusions:
- { link: admin_sidebar_to_user_site, permitted: true, reason: "관리자 전용 화면, 게이트 없음" }
- { link: admin_sidebar_to_user_site, permitted: false, reason: "관리자 전용 화면, 게이트 없음" }
- { link: admin_board_to_user_board, permitted: true, reason: "관리자 화면, 항상 노출" }
- { link: admin_board_to_user_board, permitted: false, reason: "관리자 화면, 항상 노출" }
- { link: admin_product_to_user_detail, permitted: true, reason: "관리자 화면, 편집모드 노출(권한 무관)" }
- { link: admin_product_to_user_detail, permitted: false, reason: "관리자 화면, 편집모드 노출(권한 무관)" }
- { link: user_board_to_admin, permitted: na, reason: "게이트 있음 — true/false 만 유효" }
- { link: user_product_to_admin_edit, permitted: na, reason: "게이트 있음 — true/false 만 유효" }
# 후속 효과 체인 — 각 링크가 실제로 수행/노출하는 결과
effects:
- new_tab_navigation
- board_admin_gate_true_shows_link
- board_admin_gate_false_hides_link
- product_edit_gate_true_shows_link
- product_edit_gate_false_hides_link
- drawer_starts_below_header
# 라우팅 식별자 전환 (#450): 상품=product_code, 게시판=slug
- product_detail_routes_by_code
- board_admin_routes_by_slug
# 보조 흐름
sub_flows:
- id: mobile_drawer
effects: [drawer_starts_below_header]
@@ -18,7 +18,7 @@ axes:
layout_dir: [bundled, active]
exclusions:
- { locale: ja, layout_dir: active, reason: "ja 증분은 번역 API 키 필요 — 환경 제약, 후속" }
- { locale: ja, layout_dir: active, reason: "ja 증분은 ANTHROPIC_API_KEY 필요 — 환경 제약, PO 후속" }
effects:
- hardcoded_korean_text_removed_from_layout
@@ -27,7 +27,7 @@ effects:
- en_partial_defines_bulk_status_change
- translation_engine_resolves_key_for_ko_and_en
- active_dir_reflects_keyed_layout_and_lang
- ja_bundle_increment_pending_api_key # 환경 제약 (번역 API 키)
- ja_bundle_increment_pending_api_key # 환경 제약 (PO ANTHROPIC_API_KEY)
test_files:
- templates/_bundled/sirsoft-admin_basic/__tests__/layouts/admin-user-list-bulk-status-i18n.test.tsx
@@ -41,23 +41,11 @@ axes:
lang_packs_pending_depth: [depth_2, depth_3, depth_5, depth_unbounded] # locatePendingLangPacksSourceDeep
user_added_bundled_entry: [dir_present, file_present, absent] # _bundled/ 바로 아래 사용자 추가 항목
bundled_target_domain: [modules, plugins, templates, lang-packs] # 보존 대상 4종
# 기본=코어 변경분만 적용(3-way) + --prune (공개 #64)
apply_mode: [incremental, prune, fallback_no_backup] # 파일 적용 방식
three_way_verdict: [unchanged_same, added_new, changed_size, changed_md5] # base↔theirs 판정
user_local_modification: [modified, untouched] # mine 이 base 와 다른지 (사용자 수정)
# targets 의 {domain}/_bundled 가 상위 protected({domain}) 를 오버라이드해 apply 되는지 (공개 #64 / 내부 #452)
bundled_apply_override: [override_applies, sibling_active_preserved, target_equals_protected_still_blocked]
protected_override_domain: [modules, plugins, templates, lang-packs] # 오버라이드 대상 4종 확장
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 외 다른 효과 없음" }
- { apply_mode: prune, three_way_verdict: unchanged_same, reason: "prune 은 3-way 판정을 건너뛰고 전체 덮어쓰기 — three_way_verdict 무의미" }
- { apply_mode: fallback_no_backup, three_way_verdict: unchanged_same, reason: "백업 부재 시 base 자체가 없어 3-way 불가 — 전체 덮어쓰기로 회귀" }
- { apply_mode: incremental, user_local_modification: modified, three_way_verdict: changed_size, reason: "코어+사용자 동시 변경 — 코어 버전으로 갱신(§6 한계), 백업에서 복구 가능" }
- { apply_mode: prune, bundled_apply_override: override_applies, reason: "prune 은 3-way/protected 필터를 우회하고 전체 덮어쓰기 — 오버라이드 판정 자체가 무의미" }
- { bundled_apply_override: target_equals_protected_still_blocked, protected_override_domain: modules, reason: "target==protected 방어는 storage 같은 동일 경로 케이스로 검증 — 도메인 무관 (protected_override_domain 축과 직교 아님)" }
effects:
- applyDiscoveredTopLevelPaths_does_not_remove_active_subdirs_when_source_only_has_bundled
@@ -81,31 +69,14 @@ effects:
# 사용자가 _bundled/ 바로 아래 직접 만든 항목 보존 (확장 3종 + 언어팩).
# effect 명 = 실제 테스트 메서드명 (CoreUpdateServiceTest / FilePermissionHelperTest).
- test_apply_update_preserves_user_added_bundled_subdir_all_domains
- test_apply_update_prune_still_cleans_stale_file_inside_bundled_extension # prune 모드에서만 stale 정리
- test_apply_update_still_cleans_stale_file_inside_bundled_extension
- test_preserve_top_level_orphans_keeps_top_level_dir_and_file
- test_preserve_top_level_orphans_still_cleans_nested_orphans
- test_preserve_top_level_orphans_defaults_to_existing_behavior
# 기본=코어 변경분만 적용(3-way) + --prune (공개 #64).
# effect 명 = 실제 테스트 메서드명 (CoreBackupHelperApplyListTest / CoreUpdateServiceTest).
- test_unchanged_file_is_excluded_from_apply_list # base==theirs → 제외
- test_new_file_is_added_to_apply_list # base 없음 → added
- test_size_differing_file_is_changed # size 다름 → changed
- test_same_size_different_content_file_is_changed # md5 다름 → changed
- test_apply_update_incremental_preserves_user_modified_unchanged_file # 이슈 #64 회귀 가드 (.htaccess)
- test_apply_update_incremental_applies_only_listed_files # 목록만 적용
- test_apply_update_incremental_does_not_remove_orphans # 증분=삭제 안 함
- test_apply_update_prune_removes_orphans_and_overwrites_all # prune=전체 덮어쓰기+삭제
- test_apply_update_null_apply_list_falls_back_to_full_overwrite # 백업 부재 fallback
# targets 의 {domain}/_bundled 가 상위 protected 를 오버라이드해 코어 업데이트로 번들 확장 파일이 갱신됨 (공개 #64 / 내부 #452).
# effect 명 = 실제 테스트 메서드명 (CoreBackupHelperApplyListTest / CoreUpdateServiceTest).
- test_bundled_target_overrides_parent_protected_path # 4종 확장 전수 (dataProvider)
- test_target_equal_to_protected_is_still_excluded # target==protected 는 여전히 제외 (방어 유지)
- test_incremental_apply_reflects_changed_bundled_extension_file # computeApplyList→applyUpdate end-to-end 반영
test_files:
- tests/Unit/Services/CoreUpdateServiceTest.php
- tests/Unit/Helpers/FilePermissionHelperTest.php
- tests/Unit/Extension/CoreBackupHelperApplyListTest.php
- tests/Feature/Upgrades/Upgrade_7_0_0_beta_5RecoveryTest.php
# 본 시나리오 매니페스트의 axes cross product 는 50+ 케이스이나, 실제 핵심 회귀 가드는
@@ -15,48 +15,28 @@ description: |
구성 (정책 결정 2026-05-11):
1. `spawn_failure_mode` 기본값 `abort` — 4분기 모두 UpgradeHandoffException throw.
2. `[STEPS_EXECUTED]` stdout 라인 프로토콜 — 자식이 실행한 step 수(count) + 범위 내
발견된 스텝 파일 수(discovered) 명시. 부모는 신호 미수신 또는 executed=0 &&
discovered>0 (스텝 파일이 있는데 실행 못함) 을 silent skip 으로 판정. executed=0 &&
discovered=0 (스텝 파일 부재) 은 정상 통과 — from<to 여도 실패 아님 (스텝 불필요 릴리즈).
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.
분기 개정 (discovered 축 세분화): `child_silent_skip_zero_steps` 를 discovered 축으로
세분화. 범위 내 스텝 파일이 애초에 없어 0건인 경우(discovered=0)를 정상 통과로 재분류하여,
스텝이 필요 없는 패치 릴리즈(예: 7.0.0→7.0.1) 를 실패로 오판하던 결함을 차단.
재실행 권한 안내 (§8, resume_exec_context 축): spawn 자식 실패로 스텝이 미실행 상태로
남으면 운영자에게 `core:execute-upgrade-steps` 재실행을 안내한다. sudo(root) 로 실행 중이면
안내받은 명령을 root 로 그대로 재실행할 경우 스텝 생성 파일이 root 소유가 되어 이후 웹서버
요청이 쓰기 실패한다. 실행 사용자(root 여부) × 웹서버 계정 식별성으로 4분기 안내:
non_root(명령만) / root_web_known(sudo -u {계정} + 경고) / root_web_symmetric(root 서비스
구성, 명령만) / root_web_unknown(placeholder + 계정명 미상 경고). 공유 호스팅에서 웹서버·
PHP·실행 유저가 동일하면 non_root 로 처리된다.
axes:
spawn_branch: [proc_open_disabled, proc_open_resource_fail, child_abnormal_exit, child_silent_skip_no_signal, child_zero_steps_with_discovered, child_zero_steps_no_step_files]
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] count 발행 상태
steps_discovered_signal: [discovered_positive, discovered_zero, absent] # 범위 내 발견된 스텝 파일 수 (신버전 자식만 발행, 구버전=absent)
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 연동)
resume_exec_context: [non_root, root_web_known, root_web_symmetric, root_web_unknown] # 핸드오프 재실행 권한 안내 분기 (실행 사용자 × 웹서버 계정 식별성)
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_zero_steps_with_discovered, reason: "from==to + force 케이스는 step 0건이 정상 동작이므로 silent skip 가드 미트리거" }
- { 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 시뮬 불가" }
- { child_process_origin: beta_4_or_earlier, steps_discovered_signal: discovered_positive, reason: "discovered 필드는 신버전 자식만 발행 — 구버전 자식은 항상 absent" }
- { child_process_origin: beta_4_or_earlier, steps_discovered_signal: discovered_zero, reason: "동일 — 구버전 자식은 discovered 필드 미발행(absent)" }
- { spawn_branch: child_zero_steps_no_step_files, steps_discovered_signal: discovered_positive, reason: "스텝 파일 부재 브랜치는 정의상 discovered=0 — positive 모순" }
- { spawn_branch: child_zero_steps_with_discovered, steps_discovered_signal: discovered_zero, reason: "스텝 파일 존재 브랜치는 정의상 discovered>0 — zero 모순" }
effects:
# §2 spawn_failure_mode + failSpawnWithMode
@@ -65,17 +45,12 @@ effects:
- 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 가드 (count + discovered)
- ExecuteUpgradeStepsCommand_emits_STEPS_EXECUTED_with_count_and_discovered_on_normal_completion
# §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
# discovered 기반 분기 — executed=0 을 discovered 로 구분
- handleSpawnExit_zero_executed_zero_discovered_returns_true # 케이스 B: 스텝 파일 부재 정상 통과
- handleSpawnExit_zero_executed_positive_discovered_dispatches_to_failSpawnWithMode # 케이스 A: gnuboard/g7#28 silent skip
- handleSpawnExit_zero_executed_null_discovered_from_lt_to_dispatches_to_failSpawnWithMode # 구버전 자식 레거시 판정
- spawnUpgradeStepsProcess_no_step_files_returns_true_even_when_from_lt_to # 7.0.0→7.0.1 실증
- runUpgradeSteps_notifies_discovered_zero_when_no_step_in_range
- 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
@@ -92,16 +67,10 @@ effects:
- 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
# §8 핸드오프 재실행 권한 안내 (sudo/root × 웹서버 계정 식별성 4분기)
- renderResumeGuidance_non_root_prints_command_verbatim_without_permission_warning
- renderResumeGuidance_root_web_known_prefixes_sudo_u_and_warns_with_account_name
- renderResumeGuidance_root_web_symmetric_prints_command_verbatim
- renderResumeGuidance_root_web_unknown_uses_placeholder_and_generic_warning
test_files:
- tests/Feature/Console/CoreUpdateCommandSpawnFailureTest.php
- tests/Feature/Console/CoreUpdateCommandHandoffTest.php
- tests/Feature/Console/CoreUpdateResumeGuidanceTest.php
- tests/Feature/Upgrades/MultiVersionUpgradePathTest.php
- tests/Unit/Extension/Helpers/FilePermissionHelperSymlinkTest.php
+1 -1
View File
@@ -72,7 +72,7 @@ effects:
# 소멸 / 탈퇴
- expire_lots_records_per_item_expired_transaction_with_expired_at
- expire_lots_decrements_balance_and_is_idempotent_on_rerun
- withdrawal_records_expired_activity_log_with_amount_currency_userid_before_delete # §6.1 요구 #8
- withdrawal_records_expired_activity_log_with_amount_currency_userid_before_delete # §6.1 PO #8
# 캐시 정합 (§3.5)
- cache_recalculated_for_user_after_every_balance_changing_path
- cache_pending_derived_from_order_options_not_ledger
@@ -1,71 +0,0 @@
# audit:allow test-scenario-coverage reason: 서버측 확장 번들 병합 도입 회귀 가드. 입력 axis(활성 조합·환경·에셋 종류)의 cross-product 는 test_files 의 Unit/Feature 가 cover 하고, effects 는 병합 계약(순서/구분자/소스맵/캐시/폴백)과 브라우저 실측(요청수/gdpr race)을 enumerate.
feature: 확장(모듈/플러그인) 프론트엔드 IIFE/CSS 서버측 번들 병합
description: |
활성 모듈/플러그인의 global 전략 프론트엔드 에셋을 타입별로 하나의 번들로
서버에서 병합해 서빙, 확장 수에 비례하던 HTTP 요청을 종류별 1건으로 줄인다.
각 확장 IIFE 자가등록 계약은 유지(priority 순 물리 병합 = 실행 순서).
핵심 동작:
- ExtensionBundleService 가 getOrderedGlobalAssetPaths(uasort priority) →
buildJsBundle(`\n;\n` join, sourceMappingURL 처리) → getBundleFilePath(캐시)
- PublicModule/PluginController::serveBundle{Js,Css} → fileResponse(ETag/304)
- blade bundleUrls → ModuleAssetLoader.loadBundle(module) → loadBundle(plugin)
- 확장 캐시 버전 bump 시 새 파일명 자동 무효화, ext-bundles:cleanup GC
- bundleUrls 부재 시 개별 로딩 폴백(회귀 안전)
axes:
ext_type: [module, plugin]
asset_kind: [js, css, both]
active_combo: [none, one, multiple]
strategy: [global, layout, lazy]
environment: [production, non_production]
version_state: [first_request, cache_hit, version_bumped]
source_map_state: [present, absent]
css_url_state: [no_url, absolute_url, relative_url]
file_state: [all_present, one_missing]
priority_order: [ascending, gdpr_lowest]
bundle_urls_present: [present, absent_fallback]
exclusions:
- { strategy: layout, active_combo: none, reason: "layout/lazy 전략은 번들 대상 아님 — 개별 레이아웃 처리" }
- { active_combo: none, version_state: cache_hit, reason: "활성 에셋 0건이면 캐시 파일을 만들지 않음 (빈 경로)" }
effects:
- ordered_by_priority_ascending_only_no_name_hardcode
- non_global_strategy_excluded_from_bundle
- js_iife_joined_with_semicolon_newline_separator
- prod_strips_source_mapping_url
- dev_rewrites_source_mapping_url_to_asset_serving_path
- per_extension_fault_tolerance_skips_missing_file_keeps_rest
- css_with_relative_url_excluded_from_bundle
- empty_bundle_returns_empty_path_and_empty_ok_response
- prod_writes_versioned_cache_file_and_reuses_on_same_version
- non_production_rebuilds_every_request_no_disk_cache
- cleanup_removes_stale_version_bundles_only
- clear_bundles_by_type_scopes_to_prefix
- plugin_bundle_gdpr_first_when_priority_lowest
- bundle_endpoint_serves_with_etag_and_304
- bundle_url_same_origin_only
- loadbundle_single_script_single_link_append
- loadbundle_dedup_guard_no_double_load
- loadbundle_null_urls_noop
- concat_iife_self_registration_preserved
- missing_bundle_urls_falls_back_to_individual_loading
- individual_iife_requests_absent_in_browser
- gdpr_interceptor_still_active_after_merge
- extension_handlers_registered_no_console_error
test_files:
- tests/Unit/Services/ExtensionBundleServiceTest.php
- tests/Feature/Api/Public/ExtensionBundleServingTest.php
- resources/js/core/modules/__tests__/ModuleAssetLoader.test.ts
- tests/Playwright/specs/extension-bundle-loading.spec.ts
validation:
audit_rules:
- extension-bundle-url-same-origin
- extension-bundle-concat-separator
- extension-bundle-asset-path-getter
- clears-template-caches-no-file-delete
@@ -1,61 +0,0 @@
# audit:allow test-scenario-coverage reason: lifecycle_event 축(install/update/uninstall/core_update/activate)은 FQCN 추출·classmap 상태 축과 직교하는 재생성 관심사라 cross product 가 인위적. 재생성 효과는 test_files 의 HooksCacheCommandTest(extension:update-autoload 재생성) + ExtensionManagerComposerTest 가 커버하고, FQCN/classmap/vendor격리는 ExtensionSourceClassmapTest 가 per-case 커버. effects 전량은 아래 @effects 마킹으로 검증.
coverage_strategy: pairwise
feature: 확장 소스 classmap (Extension Source Classmap / B2)
description: |
서빙 API 부팅 비용 최적화. 확장 소스 클래스(Modules\*, Plugins\*)를 autoload-extensions.php 의
src_classmap 에 사전 계산(FQCN → 경로)하여 진입점에서 ClassLoader::addClassMap() 으로 등록한다.
findFile 이 파일시스템 스캔(is_dir/file_exists stat) 없이 in-memory 맵에서 즉시 경로를 반환
→ cold OPcache / 느린 파일시스템 환경의 findFile 비용 제거.
핵심 동작:
- buildSourceClassmap: PSR-4 디렉토리 재귀 스캔 + 토큰 기반 FQCN 추출(class/interface/trait/enum)
- 소스 클래스만 대상 — 서드파티 vendor 는 각 확장 vendor/autoload.php(별도 ClassLoader) 격리 유지
- 지연 로드: classmap 은 경로만 제공, include 는 실제 사용 시점 (매 요청 전량 로드 아님)
- PSR-4 폴백 보존: classmap 미포함 클래스는 기존 PSR-4 경로로 폴백 (안전망)
- 재생성: psr4 와 동일 생명주기 — install/update/uninstall → updateComposerAutoload,
코어 업데이트 → extension:update-autoload. activate/deactivate 는 autoload 미수정
(collectAutoloads 가 설치된 전체 포함 → 비활성도 이미 맵에 존재)
axes:
declaration_kind: [class, interface, trait, enum]
extension_type: [module, plugin]
classmap_state: [present_hit, absent_psr4_fallback, path_outside_namespace]
lifecycle_event: [install, update, uninstall, activate_no_regen, core_update]
exclusions:
- { classmap_state: path_outside_namespace, declaration_kind: interface, reason: "네임스페이스 불일치 제외는 선언 종류 무관 — class 케이스로 대표" }
- { classmap_state: path_outside_namespace, declaration_kind: trait, reason: "동일" }
- { classmap_state: path_outside_namespace, declaration_kind: enum, reason: "동일" }
- { lifecycle_event: activate_no_regen, classmap_state: absent_psr4_fallback, reason: "활성화는 autoload 미수정 — classmap 상태 무관(이미 설치 시 생성됨)" }
effects:
# FQCN 추출 정확성
- extracts_fqcn_for_class_declaration
- extracts_fqcn_for_interface_declaration
- extracts_fqcn_for_trait_declaration
- extracts_fqcn_for_enum_declaration
- maps_fqcn_to_correct_relative_path
# 포함/제외 범위
- ignores_files_outside_declared_namespace
- skips_files_without_top_level_declaration
- missing_directory_returns_empty
# vendor 격리 (설계 불변조건)
- generated_src_classmap_excludes_vendor_paths
- generated_src_classmap_only_extension_namespaces
# 런타임 등록 + 폴백
- classmap_present_findFile_hits_without_filesystem_stat
- classmap_absent_findFile_falls_back_to_psr4
- class_loading_remains_lazy_include_on_use
# 재생성 생명주기
- install_regenerates_src_classmap_via_updateComposerAutoload
- update_regenerates_src_classmap
- uninstall_regenerates_src_classmap
- core_update_regenerates_src_classmap_via_extension_update_autoload
- activate_does_not_regenerate_but_installed_classes_already_mapped
test_files:
- tests/Unit/Extension/ExtensionSourceClassmapTest.php
- tests/Unit/Extension/ExtensionManagerComposerTest.php
- tests/Feature/Console/HooksCacheCommandTest.php
+2 -2
View File
@@ -98,7 +98,7 @@ effects:
- guest_order_form_hidden_for_logged_in_member # 후속 보완 — 회원에게 폼 노출 차단 (redirect 발화 전 깜빡 입력 방지)
- guest_order_form_clears_session_token_on_entry_for_standard_form_visibility # 후속 보완 — 자동 redirect 대신 토큰 초기화. eBay/Best Buy/카페24/11번가/G마켓 표준 패턴 정합
- header_and_mobile_nav_order_lookup_routes_via_login_redirect_param # 후속 보완 — '주문조회' 클릭 시 /login?redirect=/mypage/orders 진입. 회원/비회원 단일 진입점, 로그아웃된 회원 막다른 길 차단
- guest_order_form_failure_shows_inline_error_box_instead_of_toast # 후속 보완 — 통일 not_found 메시지를 toast 대신 폼 상단 인라인 박스로 노출. UX 결정. 재시도 시 자동 초기화
- guest_order_form_failure_shows_inline_error_box_instead_of_toast # 후속 보완 — 통일 not_found 메시지를 toast 대신 폼 상단 인라인 박스로 노출. PO UX 결정. 재시도 시 자동 초기화
# 진입 동선 (단계 5 그룹 D)
- header_lookup_link_visible_only_when_no_currentUser
- mobile_nav_lookup_link_visible_only_when_no_currentUser
@@ -214,4 +214,4 @@ notes: |
검증 + Playwright E2E spec 으로 회귀 가드한다.
axes 중 `e2e_browser` 는 단일(chromium) 로 시작하며, Firefox/WebKit 확장은 그룹 D 완료 후
결정에 따라.
PO 결정에 따라.
-67
View File
@@ -1,67 +0,0 @@
feature: 정적 훅 매핑 캐시 (Static Hook Cache)
description: |
서빙 API 부팅 비용 최적화. 매 요청 코어(app/Listeners 재귀 스캔) + 모듈/플러그인
(getHookListeners) 정적 훅 리스너의 발견·리플렉션·getSubscribedHooks() 클래스 로딩을
bootstrap/cache/hooks.php 캐시로 제거한다.
핵심 동작:
- 캐시 우선 등록: registerCoreHookListenersFromCache / registerExtensionHookListenersFromCache
가 존재하면 스캔·리플렉션 없이 사전 계산 매핑으로 등록
- 바이트 동일 게이트: HookListenerRegistrar::registerFromCache 가 register 와 동일한
applySubscribedHooks 에 위임 → 훅 매핑(이름·우선순위·콜백 수) 완전 일치, 발화 누락 0
- 안전 폴백: 캐시 부재/손상/구조 불일치/테스트 환경에서 기존 스캔 경로로 폴백
- 동적 훅(알림)은 캐시 대상 아님 — dynamic 플래그만 저장하여 boot 후반부 지연 실행 순서 유지.
getAllActive() 는 이미 ['notification'] 태그 캐시라 캐시 히트 시 DB 조회 0
- 재생성(무효화=재생성): 확장 install/update → updateComposerAutoload,
코어 업데이트 → clearAllCaches → extension:update-autoload, 코어 리스너 배포 → hooks:cache
# registration 축(cache_state·registration_source·listener_type)과 regeneration_trigger 는
# 상호 직교 관심사(등록 시점 vs 재생성 시점)라 full cross product 는 인위적 조합을 만든다.
# pairwise 로 모든 축 값 쌍을 커버하되 케이스 수를 실측 검증 가능한 범위로 유지한다.
coverage_strategy: pairwise
axes:
cache_state: [absent, present_valid, corrupted_broken_structure, present_but_testing_env]
registration_source: [core, module, plugin]
listener_type: [action_queued, action_sync, filter, dynamic]
regeneration_trigger: [extension_update, core_update, hooks_cache_command, hooks_clear_command]
exclusions:
- { cache_state: present_but_testing_env, registration_source: core, reason: "테스트 환경은 항상 스캔 폴백 — 캐시 경로 미진입 (registration_source 무관)" }
- { listener_type: dynamic, registration_source: module, reason: "동적 훅(registerDynamicHooks)은 코어 NotificationHookListener 전용 — 모듈/플러그인 매니저는 동적 훅 미처리" }
- { listener_type: dynamic, registration_source: plugin, reason: "동일 — 동적 훅은 코어 boot 후반부 전용" }
- { regeneration_trigger: hooks_clear_command, cache_state: absent, reason: "이미 부재 상태 clear 는 무동작 성공 (route:clear 동형)" }
effects:
# 바이트 동일 게이트 (발화 누락 0)
- cache_path_registration_byte_identical_to_scan_path
- cache_registered_action_dispatches_queue_job
- cache_registered_sync_action_executes_immediately
- cache_registered_filter_executes_synchronously_and_returns_value
# 안전 폴백
- absent_cache_falls_back_to_scan_registration
- corrupted_cache_returns_null_and_falls_back_to_scan
- testing_env_always_scans_ignoring_cache_file
# 동적 훅
- dynamic_listener_flagged_in_core_cache
- dynamic_flagged_listener_deferred_to_boot_tail_like_scan_path
- notification_getAllActive_cache_hit_issues_zero_db_query
# 캐시 생성 구조
- generate_produces_three_bucket_cache_core_modules_plugins
- each_cache_entry_has_listener_hooks_and_dynamic_keys
- listener_class_not_autoloaded_at_boot_when_registered_from_cache
# 재생성 (무효화=재생성)
- extension_update_regenerates_hook_cache_via_updateComposerAutoload
- core_update_regenerates_hook_cache_via_clearAllCaches_extension_update_autoload
- hooks_cache_command_generates_cache_file
- hooks_clear_command_removes_cache_file
- hooks_clear_is_safe_when_cache_absent
- removed_core_listener_dropped_from_cache_after_regeneration
test_files:
- tests/Unit/Extension/HookCacheManagerTest.php
- tests/Unit/Extension/HookListenerRegistrarTest.php
- tests/Feature/Console/HooksCacheCommandTest.php
- tests/Unit/Services/NotificationDefinitionServiceTest.php
- tests/Unit/Extension/InstallerCompletedGuardTest.php
@@ -1,4 +1,4 @@
# audit:allow test-scenario-coverage reason: 본 매니페스트는(트리 버전 배지 레이아웃+확장 / 버전 기록·복원 / 모달 편집 스크롤 격리) 시나리오 매트릭스 SSoT. 축이 직교(5축)라 full cross product fingerprint 마킹이 실효 없고, 회귀 가드는 test_files 의 통과 테스트(Vitest 단위 18건 + PHPUnit Feature/Unit + Playwright E2E 3건 example.com 실측 + Chrome MCP 9축 매트릭스 라이브 실측 — 내부 검증 이력)로 effects 전수를 커버. 편집기 도메인 선례(layout-editor-page-state-switcher/preview-canvas)와 동일 면제 방식.
# audit:allow test-scenario-coverage reason: 본 매니페스트는(트리 버전 배지 레이아웃+확장 / 버전 기록·복원 / 모달 편집 스크롤 격리) 시나리오 매트릭스 SSoT. 축이 직교(5축)라 full cross product fingerprint 마킹이 실효 없고, 회귀 가드는 test_files 의 통과 테스트(Vitest 단위 18건 + PHPUnit Feature/Unit + Playwright E2E 3건 example.com 실측 + Chrome MCP 9축 매트릭스 라이브 실측 —.claude/history/20260610_1030_*)로 effects 전수를 커버. 편집기 도메인 선례(layout-editor-page-state-switcher/preview-canvas)와 동일 면제 방식.
feature: 레이아웃 편집기 라우트 트리 버전 배지 + 모달 편집 캔버스 스크롤 유지
phase: S9-followup
session: S9-followup
@@ -3,7 +3,7 @@
feature: 어드민 목록 화면의 list_info 헤더 + iteration admin-card 시각 여백 정합 (#408 보강)
description: |
이슈 #408 후속 — 검수자가 어드민 알림 정의 화면에서 두 가지 시각 여백 부족을 지적:
이슈 #408 후속 — PO 가 어드민 알림 정의 화면에서 두 가지 시각 여백 부족을 지적:
1. 카운트 + 페이지당 셀렉트 묶음 (list_info 헤더) 의 위/아래 여백 없음
2. iteration 으로 반복되는 admin-card 의 하단 margin 이 자산 default mb-6
(1.5rem) 으로 너무 큼
@@ -3,7 +3,7 @@
feature: 게시판/이커머스 어드민 페이지 root wrapper 시맨틱 자산 매핑 (#408 보강)
description: |
이슈 #408 §2-1 매핑 결정 적용 — board/ec admin 레이아웃의 페이지 root wrapper
이슈 #408 §2-1 PO 매핑 결정 적용 — board/ec admin 레이아웃의 페이지 root wrapper
raw className 잔존분을 admin_basic 시맨틱 자산으로 정합.
결정 요약:
@@ -1,41 +0,0 @@
# audit:allow test-scenario-coverage reason: axes cross product 중 의미적으로 핵심인 격리/폴백/전체성공 케이스만 docblock 매핑. probe_item 축의 각 항목(os_info/cpu_info/memory_usage/disk_usage 등)은 모두 동일한 safeSystemProbe 격리 경로를 타므로 cpu_info 1건으로 대표 검증(나머지는 형식적 확장). E2E axis 없음 — 순수 백엔드 JSON API 로 레이아웃/프론트 렌더 변경 없음.
feature: 관리자 시스템 정보(system-info) probe 실패 격리
description: |
`GET /api/admin/settings/system-info` 는 OS·CPU·메모리·디스크·PHP 확장·DB 등
여러 시스템 정보를 수집한다. 이 중 일부 probe (php_uname / shell_exec / disk_*_space
등) 는 호스팅의 disable_functions / open_basedir 제약으로 예외·Error 를 던질 수 있다.
SettingsService::safeSystemProbe 가 각 항목 수집을 개별 격리하여, 한 항목의 실패가
전체 API 를 500 으로 떨어뜨리지 않고 해당 항목만 'unknown'(사용량 배열은 percentage 0)
폴백으로 채우도록 한다. 개별 실패는 Log::warning, 격리를 뚫은 전체 실패는 컨트롤러
Log::error 로 기록된다.
공개 이슈 gnuboard/g7#59 의 회귀 가드 — 공개 #40(대시보드 리소스 API) 격리가
DashboardService 에만 적용되고 SettingsService::buildSystemInfo 에는 disk 한 곳만
부분 보강되어, CPU/메모리 등 다른 probe 로 재발한 결함의 재발 차단.
axes:
probe_item: [cpu_info, os_info, memory_usage, disk_usage, php_memory_limit, mysql_version]
probe_outcome: [success, throws_error, throws_exception]
auth_state: [authenticated_with_permission, authenticated_without_permission, unauthenticated]
exclusions:
- { probe_item: os_info, probe_outcome: throws_exception, reason: "각 probe_item 은 동일 safeSystemProbe 경로 — cpu_info 대표 검증으로 커버, 나머지는 형식적 확장" }
- { auth_state: unauthenticated, probe_outcome: throws_error, reason: "인증 가드가 probe 실행 전에 401/403 으로 차단 — probe_outcome 과 무관" }
effects:
- failing_probe_isolated_and_api_returns_200
- failed_item_filled_with_unknown_fallback
- usage_array_fallback_keeps_total_used_free_unknown_and_percentage_zero
- all_probes_success_returns_full_payload
- unauthenticated_returns_401
- without_permission_returns_403
# E2E axis 없음: system-info 는 순수 백엔드 JSON API. 레이아웃 JSON / 컴포넌트 TSX /
# 엔진 TS / 핸들러 변경이 없으므로 Playwright spec 동반 의무(frontend-change-requires-e2e)
# 대상 아님. 격리 검증의 본체는 Feature/Unit 테스트가 담당.
test_files:
- tests/Feature/Api/Admin/SettingsControllerTest.php
+2 -2
View File
@@ -1,4 +1,4 @@
# audit:allow test-scenario-coverage reason: 본 매니페스트는 웹소켓 토글 전 계층 SSoT 시나리오 매트릭스 SSoT. 핵심 회귀 가드는 test_files 의 통과 테스트로 커버. Chrome MCP 라이브 axis 는 실환경 실측.
# audit:allow test-scenario-coverage reason: 본 매니페스트는 웹소켓 토글 전 계층 SSoT 시나리오 매트릭스 SSoT. 핵심 회귀 가드는 test_files 의 통과 테스트로 커버. Chrome MCP 라이브 axis 는 PO 환경 실측.
feature: websocket_enabled 토글 전 계층 단일 SSoT 가드 (공개#50)
@@ -32,7 +32,7 @@ effects:
- channel_auth_returns_401_when_unauthenticated
- channel_auth_passes_toggle_guard_when_on_and_authenticated
- websocket_manager_skips_initialize_when_appkey_empty
- front_no_wss_connection_attempt_when_toggle_off # Chrome MCP 라이브 실측 (실환경)
- front_no_wss_connection_attempt_when_toggle_off # Chrome MCP 라이브 실측 (PO 환경)
test_files:
- tests/Unit/Providers/SettingsServiceProviderWebsocketConfigTest.php