Files
Gnuboard7/tests/Unit/Services/ModuleServiceAssetTest.php
HeuJung d17ea28da5 fix(core,board,ecommerce,page,kginicis): 정책값 하드코딩·계약 분리 결함 일괄 수정
관리자 환경설정이 값을 저장은 하지만 실제 동작에는 닿지 않던 결함군을 정리했다.
설정 화면(min/max)·저장 검증(FormRequest)·런타임 적용(Service) 세 계층이 각자
리터럴을 들고 있어 서로 조용히 갈라지던 것이 공통 원인이다.

경계값 SSoT 도입:
- config/core.php `settings_limits` 를 단일 출처로 두고, FormRequest 는 이 값으로
 규칙을 만들고 화면은 설정 응답의 `_meta.limits` 로 같은 값을 받아 바인딩한다.
- 게시판·이커머스도 각 모듈 config 의 limits 를 동일 구조로 노출한다.

적용되지 않던 정책을 실제로 적용:
- 비밀번호 최소 길이·특수문자 필수(신규 지정 7개 경로. 로그인은 제외 — 정책을
 올렸을 때 기존 회원이 자기 계정에 접근조차 못 하는 데드락을 막기 위함)
- 계정 잠금 시간 0 = 무한대(전용 컬럼 분리. timestamp 상한과 NULL 규약 때문에
 기존 컬럼 재사용이 불가능하다) + 관리자 수동 해제 경로
- 업로드 최대 크기·허용 확장자, 게시판 첨부 개수·댓글 깊이, 페이지 첨부 정책,
 장바구니 수량·구매 한도, 마일리지 사용 한도, 주문 부가세

파생 결함:
- 큐 Job(sync 드라이버)이 진행 중인 요청의 Request 바인딩을 덮어써, 뒤이어 실행되는
 훅 리스너가 헤더를 잃고 조용히 건너뛰었다. Job 이 원 바인딩을 복원하도록 고치고,
 전송 헤더가 필요한 리스너는 동기 실행으로 선언한다.
- 확장 업데이트 실패 시 상태만 되돌리고 상태 캐시를 비우지 않아, 그 확장의 관리자
 화면만 캐시 TTL(기본 하루) 동안 404 로 남았다. 실패 경로에도 무효화를 대칭으로
 두고, 빈 목록 자체를 캐시하지 않는다.
- 글 작성 시 첨부 파일이 Service 로 전달되지 않아 검증·권한은 통과하고 첨부만 사라졌다.
- 환경설정 저장 실패 안내가 내부 설정 키를 그대로 노출했다(105개 항목에 라벨 부여).

재발 방지:
- audit 룰 3종(레이아웃 경계 리터럴 / FormRequest 경계 불일치 / Service 재클램프)
- 테스트 실행 범위 강제 훅(check-test-scope)
- 트러블슈팅 사례 2건(큐 Job 요청 오염 / 확장 상태 캐시 고착)

공개 이슈: gnuboard/g7
2026-07-30 07:52:24 +09:00

293 lines
8.7 KiB
PHP

<?php
namespace Tests\Unit\Services;
use App\Enums\ExtensionStatus;
use App\Models\Module;
use App\Services\ModuleService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* ModuleService::getAssetFilePath() 단위 테스트
*
* 모듈 에셋 파일 경로 조회 및 MIME 타입 결정을 테스트합니다.
*/
class ModuleServiceAssetTest extends TestCase
{
use RefreshDatabase;
private ModuleService $moduleService;
private string $testModulePath;
protected function setUp(): void
{
parent::setUp();
$this->moduleService = app(ModuleService::class);
$this->testModulePath = base_path('modules/test-module');
// 테스트용 디렉토리 생성
if (! file_exists($this->testModulePath.'/dist/js')) {
mkdir($this->testModulePath.'/dist/js', 0755, true);
}
}
protected function tearDown(): void
{
// 테스트용 파일 및 디렉토리 정리
if (file_exists($this->testModulePath)) {
$this->deleteDirectory($this->testModulePath);
}
parent::tearDown();
}
/**
* 디렉토리 재귀 삭제 헬퍼
*/
private function deleteDirectory(string $dir): bool
{
if (! file_exists($dir)) {
return true;
}
if (! is_dir($dir)) {
return unlink($dir);
}
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') {
continue;
}
if (! $this->deleteDirectory($dir.DIRECTORY_SEPARATOR.$item)) {
return false;
}
}
return rmdir($dir);
}
/**
* 존재하는 파일 경로 반환 성공 테스트
*/
public function test_returns_success_for_existing_file(): void
{
// Arrange
Module::factory()->create([
'identifier' => 'test-module',
'status' => ExtensionStatus::Active->value,
]);
$filePath = $this->testModulePath.'/dist/js/module.iife.js';
file_put_contents($filePath, 'console.log("test");');
// Act
$result = $this->moduleService->getAssetFilePath('test-module', 'dist/js/module.iife.js');
// Assert
$this->assertTrue($result['success']);
$this->assertEquals($filePath, $result['filePath']);
$this->assertEquals('application/javascript', $result['mimeType']);
}
/**
* JS 파일 MIME 타입 테스트
*/
public function test_returns_correct_mime_type_for_js(): void
{
// Arrange
Module::factory()->create([
'identifier' => 'test-module',
'status' => ExtensionStatus::Active->value,
]);
$filePath = $this->testModulePath.'/dist/js/app.js';
file_put_contents($filePath, 'console.log("test");');
// Act
$result = $this->moduleService->getAssetFilePath('test-module', 'dist/js/app.js');
// Assert
$this->assertTrue($result['success']);
$this->assertEquals('application/javascript', $result['mimeType']);
}
/**
* CSS 파일 MIME 타입 테스트
*/
public function test_returns_correct_mime_type_for_css(): void
{
// Arrange
Module::factory()->create([
'identifier' => 'test-module',
'status' => ExtensionStatus::Active->value,
]);
$cssPath = $this->testModulePath.'/dist/css';
if (! file_exists($cssPath)) {
mkdir($cssPath, 0755, true);
}
$filePath = $cssPath.'/module.css';
file_put_contents($filePath, '.module { color: blue; }');
// Act
$result = $this->moduleService->getAssetFilePath('test-module', 'dist/css/module.css');
// Assert
$this->assertTrue($result['success']);
$this->assertTrue(str_starts_with($result['mimeType'], 'text/css'));
}
/**
* JSON 파일 MIME 타입 테스트
*/
public function test_returns_correct_mime_type_for_json(): void
{
// Arrange
Module::factory()->create([
'identifier' => 'test-module',
'status' => ExtensionStatus::Active->value,
]);
$filePath = $this->testModulePath.'/dist/js/manifest.json';
file_put_contents($filePath, '{"version":3,"sources":[]}');
// Act
$result = $this->moduleService->getAssetFilePath('test-module', 'dist/js/manifest.json');
// Assert
$this->assertTrue($result['success']);
$this->assertEquals('application/json', $result['mimeType']);
}
/**
* 소스맵(.map)은 JSON 으로 타입 지정하지 않는다.
*
* 소스맵에는 원본 코드 전문(sourcesContent)이 담겨 있어, 서빙 허용 자체를 로컬 환경으로
* 한정하고 MIME 표에서도 제외했다(#471 / 공개 #72). 표에 되돌아오면 그 조치가 조용히
* 풀린 것이므로 명시적으로 고정한다.
*/
public function test_source_map_is_not_typed_as_json(): void
{
// Arrange
Module::factory()->create([
'identifier' => 'test-module',
'status' => ExtensionStatus::Active->value,
]);
$filePath = $this->testModulePath.'/dist/js/module.iife.js.map';
file_put_contents($filePath, '{"version":3,"sources":[]}');
// Act
$result = $this->moduleService->getAssetFilePath('test-module', 'dist/js/module.iife.js.map');
// Assert
$this->assertNotEquals('application/json', $result['mimeType']);
}
/**
* 이미지 MIME 타입 테스트 (PNG)
*/
public function test_returns_correct_mime_type_for_images(): void
{
// Arrange
Module::factory()->create([
'identifier' => 'test-module',
'status' => ExtensionStatus::Active->value,
]);
$imagesPath = $this->testModulePath.'/dist/images';
if (! file_exists($imagesPath)) {
mkdir($imagesPath, 0755, true);
}
$filePath = $imagesPath.'/logo.png';
// 최소 PNG 헤더
file_put_contents($filePath, base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='));
// Act
$result = $this->moduleService->getAssetFilePath('test-module', 'dist/images/logo.png');
// Assert
$this->assertTrue($result['success']);
$this->assertEquals('image/png', $result['mimeType']);
}
/**
* 폰트 MIME 타입 테스트 (WOFF2)
*/
public function test_returns_correct_mime_type_for_fonts(): void
{
// Arrange
Module::factory()->create([
'identifier' => 'test-module',
'status' => ExtensionStatus::Active->value,
]);
$fontsPath = $this->testModulePath.'/dist/fonts';
if (! file_exists($fontsPath)) {
mkdir($fontsPath, 0755, true);
}
$filePath = $fontsPath.'/roboto.woff2';
file_put_contents($filePath, 'wOF2'); // WOFF2 magic bytes
// Act
$result = $this->moduleService->getAssetFilePath('test-module', 'dist/fonts/roboto.woff2');
// Assert
$this->assertTrue($result['success']);
$this->assertEquals('font/woff2', $result['mimeType']);
}
/**
* 존재하지 않는 모듈 오류 테스트
*/
public function test_returns_error_for_nonexistent_module(): void
{
// Act
$result = $this->moduleService->getAssetFilePath('nonexistent-module', 'dist/js/module.iife.js');
// Assert
$this->assertFalse($result['success']);
$this->assertEquals('module_not_found', $result['error']);
}
/**
* 비활성 모듈 오류 테스트
*/
public function test_returns_error_for_inactive_module(): void
{
// Arrange
Module::factory()->create([
'identifier' => 'inactive-module',
'status' => ExtensionStatus::Inactive->value,
]);
// Act
$result = $this->moduleService->getAssetFilePath('inactive-module', 'dist/js/module.iife.js');
// Assert
$this->assertFalse($result['success']);
$this->assertEquals('module_not_found', $result['error']);
}
/**
* 존재하지 않는 파일 오류 테스트
*/
public function test_returns_error_for_nonexistent_file(): void
{
// Arrange
Module::factory()->create([
'identifier' => 'test-module',
'status' => ExtensionStatus::Active->value,
]);
// Act
$result = $this->moduleService->getAssetFilePath('test-module', 'dist/js/nonexistent.js');
// Assert
$this->assertFalse($result['success']);
$this->assertEquals('file_not_found', $result['error']);
}
}