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

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