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

@@ -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 키가 없습니다');