Files
Gnuboard7/tests/Feature/View/TemplateExternalsRenderingTest.php
T
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

259 lines
12 KiB
PHP

<?php
namespace Tests\Feature\View;
use App\Contracts\Extension\TemplateManagerInterface;
use App\Models\Template;
use App\Services\TemplateService;
use App\Support\TemplateExternals;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\File;
use Tests\TestCase;
class TemplateExternalsRenderingTest extends TestCase
{
use RefreshDatabase;
private string $fixtureTemplatePath;
protected function setUp(): void
{
parent::setUp();
if (! file_exists(public_path('build/core/template-engine.min.js'))) {
$this->markTestSkipped('Core template engine not built. Run npm run build to generate build files.');
}
$this->fixtureTemplatePath = base_path('templates/test-userexternals');
$this->deleteFixtureTemplate();
}
protected function tearDown(): void
{
$this->deleteFixtureTemplate();
parent::tearDown();
}
public function test_blade_partials_render_all_external_types_attributes_and_positions(): void
{
$externals = TemplateExternals::normalize($this->externalsFixture());
$head = view('partials.template-externals-head', ['templateExternals' => $externals])->render();
$beforeCore = view('partials.template-externals-scripts', [
'templateExternals' => $externals,
'position' => 'before-core',
])->render();
$beforeTemplate = view('partials.template-externals-scripts', [
'templateExternals' => $externals,
'position' => 'before-template',
])->render();
$bodyEnd = view('partials.template-externals-scripts', [
'templateExternals' => $externals,
'position' => 'body-end',
])->render();
$this->assertSame(1, substr_count($head, 'rel="preconnect" href="https://cdn.example.com"'));
$this->assertStringContainsString('rel="dns-prefetch" href="https://static.example.com"', $head);
$this->assertStringContainsString('rel="stylesheet" href="https://cdn.example.com/main.css"', $head);
$this->assertStringContainsString('id="style-main"', $head);
$this->assertStringContainsString('integrity="sha384-style"', $head);
$this->assertStringContainsString('referrerpolicy="no-referrer"', $head);
$this->assertStringContainsString('media="screen"', $head);
$this->assertStringContainsString('crossorigin="anonymous"', $head);
$this->assertStringContainsString('rel="preload" href="https://cdn.example.com/font.woff2"', $head);
$this->assertStringContainsString('as="font"', $head);
$this->assertStringContainsString('type="font/woff2"', $head);
$this->assertStringContainsString('fetchpriority="high"', $head);
$this->assertStringContainsString('rel="modulepreload" href="https://cdn.example.com/module.js"', $head);
$this->assertStringContainsString('src="https://cdn.example.com/head.js"', $head);
$this->assertStringContainsString('async', $head);
$this->assertBefore($head, 'rel="preconnect" href="https://cdn.example.com"', 'rel="stylesheet" href="https://cdn.example.com/main.css"');
$this->assertStringContainsString('src="https://cdn.example.com/before-core.js"', $beforeCore);
$this->assertStringContainsString('src="https://cdn.example.com/before-template.js"', $beforeTemplate);
$this->assertStringContainsString('defer', $beforeTemplate);
$this->assertStringContainsString('src="https://cdn.example.com/default-position.js"', $beforeTemplate);
$this->assertStringContainsString('src="https://cdn.example.com/body-end.js"', $bodyEnd);
}
public function test_admin_response_renders_sirsoft_admin_basic_externals_before_template_css(): void
{
$templateService = app(TemplateService::class);
$templateService->installTemplate('sirsoft-admin_basic');
$template = Template::where('identifier', 'sirsoft-admin_basic')->firstOrFail();
$templateService->activateTemplate($template->id);
$response = $this->get('/admin');
$response->assertStatus(200);
$html = $response->getContent();
$this->assertStringContainsString('href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"', $html);
$this->assertStringContainsString('href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/static/pretendard.min.css"', $html);
$this->assertStringContainsString('href="https://cdn.jsdelivr.net/npm/flag-icons@7.2.3/css/flag-icons.min.css"', $html);
$this->assertBefore($html, 'href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"', '/api/templates/assets/sirsoft-admin_basic/css/components.css?v=');
$this->assertBefore($html, 'href="https://cdn.jsdelivr.net"', 'href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/static/pretendard.min.css"');
}
public function test_user_response_renders_template_externals_with_same_manifest_syntax(): void
{
$this->createFixtureTemplate('test-userexternals', 'user', [
[
'id' => 'user-style',
'type' => 'style',
'url' => 'https://cdn.example.com/user.css',
'preconnect' => 'https://cdn.example.com',
],
[
'id' => 'user-script',
'type' => 'script',
'url' => 'https://cdn.example.com/user.js',
'position' => 'body-end',
],
]);
$templateManager = app(TemplateManagerInterface::class);
$templateManager->loadTemplates();
$templateManager->installTemplate('test-userexternals');
$templateManager->activateTemplate('test-userexternals', true);
$response = $this->get('/');
$response->assertStatus(200);
$html = $response->getContent();
$this->assertStringContainsString('href="https://cdn.example.com/user.css"', $html);
$this->assertStringContainsString('src="https://cdn.example.com/user.js"', $html);
$this->assertStringContainsString('"templateType":"user"', $html);
$this->assertBefore($html, 'href="https://cdn.example.com"', 'href="https://cdn.example.com/user.css"');
}
/**
* @return array<int, array<string, mixed>>
*/
private function externalsFixture(): array
{
return [
['type' => 'preconnect', 'url' => 'https://cdn.example.com', 'crossorigin' => 'anonymous'],
['type' => 'dns-prefetch', 'url' => 'https://static.example.com'],
[
'id' => 'style-main',
'type' => 'style',
'url' => 'https://cdn.example.com/main.css',
'preconnect' => 'https://cdn.example.com',
'crossorigin' => true,
'integrity' => 'sha384-style',
'referrerpolicy' => 'no-referrer',
'media' => 'screen',
],
[
'id' => 'font-main',
'type' => 'webfont',
'url' => 'https://fonts.example.com/font.css',
'preconnect' => 'https://fonts.example.com',
'crossorigin' => 'anonymous',
],
[
'id' => 'preload-font',
'type' => 'preload',
'url' => 'https://cdn.example.com/font.woff2',
'as' => 'font',
'mimeType' => 'font/woff2',
'fetchpriority' => 'high',
'crossorigin' => 'use-credentials',
],
[
'id' => 'module-main',
'type' => 'modulepreload',
'url' => 'https://cdn.example.com/module.js',
'mimeType' => 'text/javascript',
'fetchpriority' => 'auto',
],
['id' => 'script-head', 'type' => 'script', 'url' => 'https://cdn.example.com/head.js', 'position' => 'head', 'async' => true],
['id' => 'script-before-core', 'type' => 'script', 'url' => 'https://cdn.example.com/before-core.js', 'position' => 'before-core'],
['id' => 'script-before-template', 'type' => 'script', 'url' => 'https://cdn.example.com/before-template.js', 'position' => 'before-template', 'defer' => true],
['id' => 'script-default', 'type' => 'script', 'url' => 'https://cdn.example.com/default-position.js'],
['id' => 'script-body-end', 'type' => 'script', 'url' => 'https://cdn.example.com/body-end.js', 'position' => 'body-end'],
];
}
private function createFixtureTemplate(string $identifier, string $type, array $externals): void
{
File::makeDirectory($this->fixtureTemplatePath.'/dist/js', 0755, true);
File::makeDirectory($this->fixtureTemplatePath.'/dist/css', 0755, true);
File::makeDirectory($this->fixtureTemplatePath.'/layouts/errors', 0755, true);
File::put($this->fixtureTemplatePath.'/template.json', json_encode([
'identifier' => $identifier,
'vendor' => 'test',
'name' => ['ko' => 'Test User Externals', 'en' => 'Test User Externals'],
'version' => '1.0.0',
'license' => 'MIT',
'description' => ['ko' => 'Test template', 'en' => 'Test template'],
'type' => $type,
'locales' => ['ko', 'en'],
'dependencies' => ['modules' => [], 'plugins' => []],
'assets' => [
'css' => ['dist/css/components.css'],
'js' => ['dist/js/components.iife.js'],
],
'components' => ['basic' => [], 'composite' => [], 'layout' => []],
// 에러 레이아웃 식별자는 디렉토리 접두사를 포함한다 (실제 템플릿과 동일 규약).
// 접두사를 빼면 활성화 검증이 layouts/error_404.json 을 찾다가 실패한다.
'error_config' => [
'layouts' => [
'404' => 'errors/404',
'403' => 'errors/403',
'500' => 'errors/500',
],
],
'externals' => $externals,
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
File::put($this->fixtureTemplatePath.'/components.json', json_encode(['components' => []], JSON_PRETTY_PRINT));
// 사용자 템플릿은 홈 라우트가 있어야 `/` 요청이 렌더된다 — 없으면 catch-all 이 404 를
// 돌려주어 externals 가 실린 화면 자체를 검사할 수 없다.
File::put($this->fixtureTemplatePath.'/routes.json', json_encode([
'routes' => [
['path' => '/', 'layout' => 'home', 'auth_required' => false],
],
], JSON_PRETTY_PRINT));
File::put($this->fixtureTemplatePath.'/layouts/home.json', json_encode([
'version' => '1.0.0',
'layout_name' => 'home',
'meta' => ['title' => 'Home'],
'components' => [],
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
File::put($this->fixtureTemplatePath.'/dist/js/components.iife.js', '// test bundle');
File::put($this->fixtureTemplatePath.'/dist/css/components.css', '/* test css */');
$errorLayout = json_encode([
'version' => '1.0.0',
'layout_name' => 'error_template',
'meta' => ['title' => 'Error'],
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
File::put($this->fixtureTemplatePath.'/layouts/errors/404.json', $errorLayout);
File::put($this->fixtureTemplatePath.'/layouts/errors/403.json', $errorLayout);
File::put($this->fixtureTemplatePath.'/layouts/errors/500.json', $errorLayout);
}
private function deleteFixtureTemplate(): void
{
if (isset($this->fixtureTemplatePath) && File::exists($this->fixtureTemplatePath)) {
File::deleteDirectory($this->fixtureTemplatePath);
}
}
private function assertBefore(string $html, string $before, string $after): void
{
$beforePosition = strpos($html, $before);
$afterPosition = strpos($html, $after);
$this->assertNotFalse($beforePosition, "Expected to find [{$before}].");
$this->assertNotFalse($afterPosition, "Expected to find [{$after}].");
$this->assertLessThan($afterPosition, $beforePosition, "Expected [{$before}] before [{$after}].");
}
}