v7.0.0 release
This commit is contained in:
1 parent
0e7fa04b03
commit
c4ea9a6cd1
3582 files changed
+626189
-160151
No files matched your search
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
@@ -33,7 +34,7 @@ class AdminAuthTest extends TestCase
|
||||
);
|
||||
|
||||
// isAdmin() 에 필요한 type=admin permission 최소 1개 보장
|
||||
$adminPermission = \App\Models\Permission::firstOrCreate(
|
||||
$adminPermission = Permission::firstOrCreate(
|
||||
['identifier' => 'admin.test_default'],
|
||||
[
|
||||
'name' => json_encode(['ko' => 'admin default', 'en' => 'admin default']),
|
||||
@@ -102,6 +103,60 @@ class AdminAuthTest extends TestCase
|
||||
$response->assertUnauthorized();
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept 헤더 없이 비인증 관리자 API 접근 시 401 JSON 반환 테스트 (공개#39).
|
||||
*
|
||||
* Accept 헤더가 없으면 expectsJson()===false 가 되어 Laravel 기본 폴백이
|
||||
* route('login') redirect 를 시도 → 미정의 라우트로 HTTP 500 이 되던 결함.
|
||||
* bootstrap/app.php 핸들러의 is('api/*') 가드로 항상 401 JSON 이 되어야 한다.
|
||||
*/
|
||||
public function test_unauthenticated_admin_api_returns_401_without_accept_header(): void
|
||||
{
|
||||
// raw get() — 기본 Accept 미부착 (getJson() 은 Accept 강제하므로 재현 불가)
|
||||
$response = $this->get('/api/admin/auth/user');
|
||||
|
||||
$response->assertStatus(401);
|
||||
$response->assertHeaderMissing('Location'); // redirect 미발생
|
||||
$this->assertArrayHasKey('message', $response->json());
|
||||
$this->assertStringNotContainsString('login', (string) $response->getContent()); // RouteNotFoundException 미발동
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept: text/html (브라우저 직접 접근) 으로 비인증 관리자 API 접근 시에도 401 JSON 반환 (공개#39).
|
||||
*/
|
||||
public function test_unauthenticated_admin_api_returns_401_with_html_accept_header(): void
|
||||
{
|
||||
$response = $this->get('/api/admin/auth/user', ['Accept' => 'text/html']);
|
||||
|
||||
$response->assertStatus(401);
|
||||
$response->assertHeaderMissing('Location');
|
||||
$this->assertArrayHasKey('message', $response->json());
|
||||
}
|
||||
|
||||
/**
|
||||
* 무효 토큰 + Accept 헤더 없이 비인증 관리자 API 접근 시 401 JSON 반환 (공개#39).
|
||||
*/
|
||||
public function test_invalid_token_admin_api_returns_401_without_accept_header(): void
|
||||
{
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer invalid-token-value',
|
||||
])->get('/api/admin/auth/user');
|
||||
|
||||
$response->assertStatus(401);
|
||||
$response->assertHeaderMissing('Location');
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 엔드포인트 한정이 아님 — 다른 /api/admin/* 경로도 동일하게 401 JSON 반환 (공개#39).
|
||||
*/
|
||||
public function test_other_admin_api_endpoint_returns_401_without_accept_header(): void
|
||||
{
|
||||
$response = $this->get('/api/admin/dashboard/resources');
|
||||
|
||||
$response->assertStatus(401);
|
||||
$response->assertHeaderMissing('Location');
|
||||
}
|
||||
|
||||
/**
|
||||
* 일반 사용자는 관리자 API 접근 불가 테스트
|
||||
*/
|
||||
@@ -146,7 +201,7 @@ class AdminAuthTest extends TestCase
|
||||
|
||||
// 새 토큰으로 API 접근 가능 확인
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer ' . $newToken,
|
||||
'Authorization' => 'Bearer '.$newToken,
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/auth/user');
|
||||
|
||||
|
||||
@@ -0,0 +1,601 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Http\Controllers\Api\Admin\AdminTemplateAssetController;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\Template;
|
||||
use App\Models\TemplateLayout;
|
||||
use App\Models\TemplateLayoutVersion;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* AdminTemplateAssetController 회귀 테스트
|
||||
*
|
||||
* 회귀 원인: 본 컨트롤러가 `$this->logApiUsage(...)` 를 호출했으나
|
||||
* `AdminBaseController` 에는 그 메서드가 정의되어 있지 않아 500 에러 발생.
|
||||
* 또한 `getEditorAssets` 가 `public/manifest.json` 위치를 가정했지만 실제
|
||||
* 빌드 결과물은 `dist/js/components.iife.js` 에 위치해 manifest_present=false
|
||||
* 로 떨어졌다. 본 테스트는 두 결함을 함께 가드.
|
||||
*/
|
||||
class AdminTemplateAssetControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
'modules/sirsoft-ecommerce',
|
||||
];
|
||||
|
||||
private User $adminUser;
|
||||
|
||||
private string $adminToken;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$editPermission = Permission::firstOrCreate([
|
||||
'identifier' => 'core.templates.layouts.edit',
|
||||
], [
|
||||
'name' => '레이아웃 편집',
|
||||
'display_name' => '레이아웃 편집',
|
||||
'type' => 'admin',
|
||||
]);
|
||||
|
||||
$role = Role::firstOrCreate(['identifier' => 'super-admin'], [
|
||||
'name' => 'Super Admin',
|
||||
'display_name' => 'Super Admin',
|
||||
'is_default' => false,
|
||||
]);
|
||||
$role->permissions()->syncWithoutDetaching([$editPermission->id]);
|
||||
|
||||
$this->adminUser = User::factory()->create();
|
||||
$this->adminUser->roles()->syncWithoutDetaching([$role->id]);
|
||||
|
||||
$this->adminToken = $this->adminUser->createToken('admin')->plainTextToken;
|
||||
}
|
||||
|
||||
public function test_get_editor_assets_returns_200_without_fatal_error(): void
|
||||
{
|
||||
// sirsoft-basic 템플릿이 활성 디렉토리 또는 _bundled 디렉토리에 존재해야 한다
|
||||
// (본 저장소에는 _bundled/sirsoft-basic 이 들어 있으므로 항상 통과)
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => "Bearer {$this->adminToken}",
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/templates/sirsoft-basic/editor-assets');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertJsonStructure([
|
||||
'success',
|
||||
'message',
|
||||
'data' => ['identifier', 'js', 'css', 'manifest_present'],
|
||||
]);
|
||||
|
||||
// 빌드된 IIFE 파일이 _bundled 또는 활성 디렉토리에 존재하면 manifest_present=true
|
||||
// 빌드되지 않았으면 false (빌드 누락 케이스도 200 으로 흘러야 함)
|
||||
$data = $response->json('data');
|
||||
$this->assertIsArray($data['js']);
|
||||
$this->assertIsArray($data['css']);
|
||||
$this->assertIsBool($data['manifest_present']);
|
||||
|
||||
// 빌드되어 있다면 js 배열에 components.iife.js URL 이 1 개 이상 들어 있어야 함
|
||||
if ($data['manifest_present']) {
|
||||
$this->assertNotEmpty($data['js']);
|
||||
$this->assertStringContainsString('components.iife.js', $data['js'][0]);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_serve_components_returns_200_without_fatal_error(): void
|
||||
{
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => "Bearer {$this->adminToken}",
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/templates/sirsoft-basic/editor/components.json');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertJsonStructure(['success', 'message', 'data']);
|
||||
}
|
||||
|
||||
public function test_serve_routes_returns_200_without_fatal_error(): void
|
||||
{
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => "Bearer {$this->adminToken}",
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/templates/sirsoft-basic/editor/routes.json');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertJsonStructure(['success', 'message', 'data']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 편집기 routes 응답의 각 라우트에 source 태깅(`{kind, identifier}`)이 포함된다.
|
||||
*
|
||||
* 회귀: 편집기 진입 routes fetch 를 가드 엔드포인트로 전환할 때,
|
||||
* 가드 컨트롤러가 raw routes.json 을 그대로 반환해 source 태깅이 빠졌다. 편집기
|
||||
* `buildRouteTree`(useRouteTree)는 `route.source.kind` 로 그룹핑하므로, source 가
|
||||
* 없으면 클라이언트가 `undefined.kind` 접근에서 throw → 라우트 트리 전체가 network
|
||||
* 에러로 무너졌다(유효한 토큰으로도 편집기 진입 불가). public getRoutes 와 동일하게
|
||||
* 모든 라우트에 source 를 태깅해야 한다.
|
||||
*/
|
||||
public function test_serve_routes_tags_every_route_with_source(): void
|
||||
{
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => "Bearer {$this->adminToken}",
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/templates/sirsoft-basic/editor/routes.json');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$routes = $response->json('data.routes');
|
||||
$this->assertIsArray($routes);
|
||||
$this->assertNotEmpty($routes, '편집기 routes 응답에 라우트가 1개 이상 있어야 한다');
|
||||
|
||||
foreach ($routes as $route) {
|
||||
$this->assertArrayHasKey('source', $route, "라우트({$route['path']})에 source 태깅 누락");
|
||||
$this->assertIsArray($route['source']);
|
||||
$this->assertArrayHasKey('kind', $route['source']);
|
||||
$this->assertContains(
|
||||
$route['source']['kind'],
|
||||
['template', 'module', 'plugin', 'core'],
|
||||
"라우트({$route['path']}) source.kind 가 허용 값이 아님"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 편집기 routes 응답이 base 레이아웃 + 인라인 모달 목록을 함께 반환한다.
|
||||
*
|
||||
* 위지윅 편집기 라우트 트리의 `[공통 레이아웃]` ·
|
||||
* `[모달]` 그룹은 base/modal 정보가 필요하나, 종전 routes 응답은 `{version, routes}`
|
||||
* 만 반환해 두 그룹이 영구히 미표시였다(클라이언트가 `baseLayouts:[], modals:[]` 하드
|
||||
* 코딩으로 디그레이드). 백엔드가 레이아웃 파일에서 `meta.is_base` base 레이아웃과
|
||||
* 인라인 `modals[]` 를 수집해 응답에 실어야 두 그룹이 트리에 표시된다.
|
||||
*/
|
||||
public function test_serve_routes_includes_base_layouts_and_modals(): void
|
||||
{
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => "Bearer {$this->adminToken}",
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/templates/sirsoft-basic/editor/routes.json');
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
// base_layouts / modals 키가 응답에 존재하고 배열이어야 한다.
|
||||
$response->assertJsonStructure([
|
||||
'data' => ['version', 'routes', 'base_layouts', 'modals'],
|
||||
]);
|
||||
|
||||
$baseLayouts = $response->json('data.base_layouts');
|
||||
$modals = $response->json('data.modals');
|
||||
$this->assertIsArray($baseLayouts);
|
||||
$this->assertIsArray($modals);
|
||||
|
||||
// sirsoft-basic 은 `_user_base`(meta.is_base) 를 가진다 — base 레이아웃 1개 이상.
|
||||
$this->assertNotEmpty($baseLayouts, 'base_layouts 에 base 레이아웃이 1개 이상 있어야 한다');
|
||||
$baseNames = array_column($baseLayouts, 'layout_name');
|
||||
$this->assertContains('_user_base', $baseNames, '`_user_base` 가 base_layouts 에 포함돼야 한다');
|
||||
foreach ($baseLayouts as $base) {
|
||||
$this->assertArrayHasKey('layout_name', $base);
|
||||
$this->assertArrayHasKey('label', $base);
|
||||
}
|
||||
|
||||
// sirsoft-basic 의 모달은 전부 partial 참조(`{"partial": "..."}`)이며
|
||||
// 라우트 레이아웃은 하위 디렉토리(`auth/`, `shop/` 등)에 있다. 종전 수집 로직은
|
||||
// (1) partial 참조 모달을 건너뛰고 (2) 최상위 디렉토리만 읽어 모달을 전부 누락했다.
|
||||
// 이제 partial 을 해석하고 재귀 순회하므로 모달이 1건 이상 수집돼야 한다.
|
||||
$this->assertNotEmpty($modals, 'partial 참조 모달도 수집돼 `[모달]` 그룹이 표시돼야 한다');
|
||||
|
||||
// 모달 항목 구조 검증.
|
||||
foreach ($modals as $modal) {
|
||||
$this->assertArrayHasKey('modal_id', $modal);
|
||||
$this->assertArrayHasKey('host_layout', $modal);
|
||||
$this->assertArrayHasKey('label', $modal);
|
||||
$this->assertIsString($modal['modal_id']);
|
||||
$this->assertIsString($modal['host_layout']);
|
||||
$this->assertNotSame('', $modal['modal_id'], 'partial 해석 후 modal_id 가 실제 값이어야 한다');
|
||||
}
|
||||
|
||||
// base 호스트(`_user_base`)의 partial 모달이 host_layout 매칭으로 수집됐는지 확인.
|
||||
$hostLayouts = array_column($modals, 'host_layout');
|
||||
$this->assertContains('_user_base', $hostLayouts, 'base 호스트의 partial 모달이 수집돼야 한다');
|
||||
|
||||
// 하위 디렉토리 라우트(`auth/register`)의 partial 모달도 재귀 순회로 수집됐는지 확인.
|
||||
$this->assertContains('auth/register', $hostLayouts, '하위 디렉토리 라우트의 모달이 수집돼야 한다');
|
||||
}
|
||||
|
||||
/**
|
||||
* 편집기 `[모달]` 그룹은 활성 모듈/플러그인 레이아웃의 모달도 수집해야 한다.
|
||||
*
|
||||
* 회귀: `collectEditorBaseAndModals()` 가 `templates/{id}/layouts` 만 스캔하고
|
||||
* `modules/{id}/resources/layouts` · `plugins/{id}/resources/layouts` 는 누락해,
|
||||
* 모듈/플러그인 화면(편집기 트리에 라우트로 노출됨)의 모달이 `[모달]` 그룹에
|
||||
* 영구히 미표시였다(예: ecommerce 주문 상세의 비회원 비밀번호 재설정 모달).
|
||||
* 계획서 8.4.5("대상 템플릿의 모든 레이아웃의 modals 섹션을 스캔") 위반.
|
||||
*
|
||||
* host_layout 은 라우트 트리 layout 규약(`{moduleId}.admin/...`)과 일치해야
|
||||
* 트리에서 호스트 화면 노드와 매칭된다.
|
||||
*/
|
||||
public function test_serve_routes_includes_module_layout_modals(): void
|
||||
{
|
||||
// 모달 수집은 `getActiveModules()`(modules 테이블 status=active) 기준이므로
|
||||
// ecommerce 모듈을 활성 상태로 시드한다. requiredExtensions 는 마이그레이션 경로만
|
||||
// 등록하고 active 행을 만들지 않는다.
|
||||
\App\Models\Module::query()->updateOrCreate(
|
||||
['identifier' => 'sirsoft-ecommerce'],
|
||||
[
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => 'E-Commerce',
|
||||
'version' => '1.0.0',
|
||||
'status' => \App\Enums\ExtensionStatus::Active->value,
|
||||
]
|
||||
);
|
||||
app(\App\Contracts\Repositories\ModuleRepositoryInterface::class); // 바인딩 보장
|
||||
\Illuminate\Support\Facades\Cache::flush(); // 활성 식별자 캐시 무효화
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => "Bearer {$this->adminToken}",
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/templates/sirsoft-admin_basic/editor/routes.json');
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
$modals = $response->json('data.modals');
|
||||
$this->assertIsArray($modals);
|
||||
|
||||
$hostLayouts = array_column($modals, 'host_layout');
|
||||
$modalIds = array_column($modals, 'modal_id');
|
||||
|
||||
// ecommerce 주문 상세는 모달 5개를 partial 참조로 선언한다.
|
||||
// host_layout 은 모듈 라우트 layout 규약(`{moduleId}.{layout_name}`)을 따른다.
|
||||
$this->assertContains(
|
||||
'sirsoft-ecommerce.admin_ecommerce_order_detail',
|
||||
$hostLayouts,
|
||||
'모듈 레이아웃(주문 상세)의 모달이 `[모달]` 그룹에 수집돼야 한다'
|
||||
);
|
||||
|
||||
// develop 신규 비회원 비밀번호 재설정 모달이 편집 진입점으로 노출돼야 한다.
|
||||
$this->assertContains(
|
||||
'modal_reset_guest_password',
|
||||
$modalIds,
|
||||
'비회원 비밀번호 재설정 모달이 편집기 트리에 노출돼야 한다'
|
||||
);
|
||||
|
||||
// 모달 라벨은 modal_id 원문이 아니라 Modal 컴포넌트 props.title 의 친화 제목(대개 $t: 키)
|
||||
// 으로 채워져야 한다. G7 모달은 제목을 props.title 에 두므로 최상위 title 만 읽으면
|
||||
// 라벨이 비어 트리에 modal_id 원문이 노출되는 회귀를 차단한다.
|
||||
$resetGuest = collect($modals)->firstWhere('modal_id', 'modal_reset_guest_password');
|
||||
$this->assertNotEmpty(
|
||||
$resetGuest['label'] ?? null,
|
||||
'props.title 기반 모달 라벨이 채워져야 한다 (modal_id 원문 노출 방지)'
|
||||
);
|
||||
$this->assertStringStartsWith(
|
||||
'$t:',
|
||||
$resetGuest['label'],
|
||||
'모달 라벨은 props.title 의 다국어 키를 그대로 전달해야 한다'
|
||||
);
|
||||
|
||||
// 모든 모달은 친화 라벨을 가져야 한다 — (1) 라벨 미부여(modal_id 원문 노출) 0건,
|
||||
// (2) props.title 이 표현식(`{{...}}` 삼항·필터)인 모달은 라벨로 부적합하므로
|
||||
// meta.editor_label 정적 키가 부여돼 표현식 라벨이 트리에 노출되지 않아야 한다.
|
||||
$noLabel = collect($modals)->filter(fn ($m) => empty($m['label']))->pluck('modal_id')->all();
|
||||
$this->assertSame([], $noLabel, '라벨 미부여 모달이 없어야 한다(트리에 modal_id 원문 노출 방지): '.implode(', ', $noLabel));
|
||||
|
||||
$exprLabel = collect($modals)
|
||||
->filter(fn ($m) => is_string($m['label']) && str_contains($m['label'], '{{'))
|
||||
->pluck('modal_id')->all();
|
||||
$this->assertSame([], $exprLabel, '표현식 라벨 모달은 meta.editor_label 정적 키가 부여돼야 한다: '.implode(', ', $exprLabel));
|
||||
}
|
||||
|
||||
/**
|
||||
* 편집기 routes 응답에 레이아웃별 현재(최신) 저장 버전 맵이 동봉된다.
|
||||
*
|
||||
* 라우트 트리 버전 배지의 데이터 소스 — 버전 이력이 있는 레이아웃만 최신 버전
|
||||
* 번호로 포함되고, 이력이 없는(원본) 레이아웃은 맵에 없어야 한다(배지 미표시).
|
||||
*/
|
||||
public function test_serve_routes_includes_layout_versions_map(): void
|
||||
{
|
||||
$template = Template::where('identifier', 'sirsoft-basic')->first()
|
||||
?? Template::factory()->create(['identifier' => 'sirsoft-basic']);
|
||||
$layout = TemplateLayout::factory()->create([
|
||||
'template_id' => $template->id,
|
||||
'name' => 'home',
|
||||
]);
|
||||
TemplateLayoutVersion::factory()->create(['layout_id' => $layout->id, 'version' => 1]);
|
||||
TemplateLayoutVersion::factory()->create(['layout_id' => $layout->id, 'version' => 2]);
|
||||
TemplateLayout::factory()->create([
|
||||
'template_id' => $template->id,
|
||||
'name' => 'never-saved',
|
||||
]);
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => "Bearer {$this->adminToken}",
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/templates/sirsoft-basic/editor/routes.json');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$versions = $response->json('data.layout_versions');
|
||||
$this->assertIsArray($versions);
|
||||
$this->assertSame(2, $versions['home'] ?? null, '이력 보유 레이아웃은 최신 버전 번호로 표시');
|
||||
$this->assertArrayNotHasKey('never-saved', $versions, '이력 없는 레이아웃은 맵 미포함(배지 미표시)');
|
||||
}
|
||||
|
||||
/**
|
||||
* 편집기 routes 엔드포인트는 비로그인 시 401 로 진입을 차단한다.
|
||||
*
|
||||
* 종전엔 편집기가 공개 routes.json 을 호출해 세션 만료 상태에서도
|
||||
* 200 을 받아 편집기 접근이 허용됐다. 가드 엔드포인트는 auth:sanctum 으로 차단.
|
||||
*/
|
||||
public function test_serve_routes_requires_authentication(): void
|
||||
{
|
||||
$response = $this->withHeaders([
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/templates/sirsoft-basic/editor/routes.json');
|
||||
|
||||
$response->assertStatus(401);
|
||||
}
|
||||
|
||||
public function test_serve_editor_spec_returns_200_without_fatal_error(): void
|
||||
{
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => "Bearer {$this->adminToken}",
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/templates/sirsoft-basic/editor/editor-spec.json');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertJsonStructure(['success', 'message', 'data' => ['identifier', 'spec']]);
|
||||
}
|
||||
|
||||
public function test_serve_language_returns_200_without_fatal_error(): void
|
||||
{
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => "Bearer {$this->adminToken}",
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/templates/sirsoft-basic/editor/lang/ko.json');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertJsonStructure(['success', 'message', 'data']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 표시 권한 후보 엔드포인트 — 코어 + 활성 확장 권한을 {key, name} 으로 반환.
|
||||
*
|
||||
* 속성 모달 표시 권한 TagInput 후보 주입. 종전 G7Config 상시 노출에서
|
||||
* 편집 권한 가드된 편집기 전용 엔드포인트로 전환(노출 범위 한정).
|
||||
*/
|
||||
public function test_serve_permission_candidates_returns_key_name_list(): void
|
||||
{
|
||||
Permission::firstOrCreate([
|
||||
'identifier' => 'core.users.read',
|
||||
], [
|
||||
'name' => ['ko' => '사용자 조회', 'en' => 'View Users'],
|
||||
'type' => 'admin',
|
||||
]);
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => "Bearer {$this->adminToken}",
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/templates/sirsoft-basic/editor/permission-candidates.json');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertJsonStructure([
|
||||
'success',
|
||||
'message',
|
||||
'data' => ['identifier', 'permissions' => [['key', 'name']]],
|
||||
]);
|
||||
|
||||
$keys = array_column($response->json('data.permissions'), 'key');
|
||||
$this->assertContains('core.users.read', $keys, '표시 권한 후보에 코어 권한 키가 포함되어야 한다');
|
||||
// 모든 항목이 {key, name} 형태이며 key 가 비어있지 않다
|
||||
foreach ($response->json('data.permissions') as $row) {
|
||||
$this->assertArrayHasKey('key', $row);
|
||||
$this->assertArrayHasKey('name', $row);
|
||||
$this->assertNotSame('', $row['key']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 표시 권한 후보 엔드포인트는 편집 권한(core.templates.layouts.edit) 가드 하에만 접근 가능.
|
||||
* 권한 없는 사용자는 403 — 권한 카탈로그 노출이 편집 권한자에게만 한정됨을 보장.
|
||||
*/
|
||||
public function test_serve_permission_candidates_requires_edit_permission(): void
|
||||
{
|
||||
$noPermUser = User::factory()->create();
|
||||
$token = $noPermUser->createToken('noperm')->plainTextToken;
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => "Bearer {$token}",
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/templates/sirsoft-basic/editor/permission-candidates.json');
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
/**
|
||||
* 편집기 프리뷰 CSS 엔드포인트 — text/css 200 + 다크 셀렉터 격리 치환.
|
||||
*
|
||||
* sirsoft-basic 의 darkMode.previewIsolation 선언(.dark → .g7le-preview-dark)에 따라,
|
||||
* 빌드 CSS 의 다크 조상 셀렉터(`.dark .foo`)가 프리뷰 마커로 치환돼야 한다. 동시에
|
||||
* 유틸리티 클래스(`.dark\:bg-x` — 이스케이프 콜론)는 보존돼야 한다(사용자 토큰 무손실).
|
||||
*/
|
||||
public function test_serve_editor_css_isolates_dark_ancestor_selector(): void
|
||||
{
|
||||
$cssPath = base_path('templates/_bundled/sirsoft-basic/dist/css/components.css');
|
||||
if (! file_exists($cssPath)) {
|
||||
$this->markTestSkipped('sirsoft-basic dist CSS 미빌드 — 빌드 후 검증');
|
||||
}
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => "Bearer {$this->adminToken}",
|
||||
'Accept' => 'text/css',
|
||||
])->get('/api/admin/templates/sirsoft-basic/editor/components.css');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertStringContainsString('text/css', (string) $response->headers->get('Content-Type'));
|
||||
|
||||
$css = $response->getContent();
|
||||
// 다크 조상 셀렉터가 프리뷰 마커로 치환됨 — 원본 빌드에 `.dark ` 가 있었다면.
|
||||
$original = (string) file_get_contents($cssPath);
|
||||
if (preg_match('/\.dark(?=[\s,){>~+])/', $original)) {
|
||||
$this->assertStringContainsString('.g7le-preview-dark', $css, '다크 조상 셀렉터가 프리뷰 마커로 치환되어야 한다');
|
||||
// 원본 `.dark ` 조상 셀렉터(공백/조합자 경계)는 더 이상 남지 않아야 한다.
|
||||
$this->assertSame(0, preg_match('/\.dark(?=[\s,){>~+])/', $css), '치환 후 원본 다크 조상 셀렉터가 남으면 안 된다');
|
||||
}
|
||||
// 유틸리티 클래스(.dark\:...)는 보존 — 이스케이프 콜론은 치환 대상 아님.
|
||||
if (str_contains($original, '.dark\\:')) {
|
||||
$this->assertStringContainsString('.dark\\:', $css, '다크 유틸리티 클래스(.dark\\:)는 보존되어야 한다');
|
||||
}
|
||||
|
||||
// @layer 평탄화 — 편집기 CSS 는 어드민 호스트 CSS 와의 cross-build 레이어 우선순위
|
||||
// 충돌을 피하려 unlayered 로 평탄화돼야 한다(결함). 원본에 @layer {} 블록이
|
||||
// 있었다면 서빙된 CSS 에는 블록 오프너가 남지 않아야 한다.
|
||||
if (preg_match('/@layer\s+[^;{]*\{/', $original)) {
|
||||
$this->assertSame(0, preg_match('/@layer\s+[^;{]*\{/', $css), '서빙 CSS 에 @layer 블록 래퍼가 남으면 cross-build 우선순위 충돌');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 편집기 CSS 엔드포인트는 편집 권한 가드 하에만 접근 가능 (403 경계).
|
||||
*/
|
||||
public function test_serve_editor_css_requires_edit_permission(): void
|
||||
{
|
||||
$noPermUser = User::factory()->create();
|
||||
$token = $noPermUser->createToken('noperm')->plainTextToken;
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => "Bearer {$token}",
|
||||
'Accept' => 'text/css',
|
||||
])->get('/api/admin/templates/sirsoft-basic/editor/components.css');
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
/**
|
||||
* editor-assets 매니페스트의 css URL 은 편집기 전용 CSS 엔드포인트를 가리켜야 한다
|
||||
* 일반 자산 서빙(public)이 아님.
|
||||
*/
|
||||
public function test_editor_assets_css_points_to_editor_endpoint(): void
|
||||
{
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => "Bearer {$this->adminToken}",
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/templates/sirsoft-basic/editor-assets');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$css = $response->json('data.css');
|
||||
if (! empty($css)) {
|
||||
$this->assertStringContainsString('/editor/components.css', $css[0], 'CSS URL 은 편집기 전용 엔드포인트여야 한다');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* private 메서드를 reflection 으로 호출하는 헬퍼 (순수 CSS 변환 로직 단위 검증용).
|
||||
*
|
||||
* @param string $method 메서드명
|
||||
* @param array<int, mixed> $args 인자
|
||||
* @return mixed 반환값
|
||||
*/
|
||||
private function invokePrivate(string $method, array $args): mixed
|
||||
{
|
||||
$ctrl = app(AdminTemplateAssetController::class);
|
||||
$ref = new \ReflectionMethod($ctrl, $method);
|
||||
$ref->setAccessible(true);
|
||||
|
||||
return $ref->invokeArgs($ctrl, $args);
|
||||
}
|
||||
|
||||
/**
|
||||
* flattenCssLayers — `@layer NAME { ... }` 블록 래퍼를 제거해 내부 규칙을 unlayered 로
|
||||
* 평탄화한다. cross-build 레이어 우선순위 충돌 방지의 핵심 로직(결함). 중첩 레이어·
|
||||
* 짝 불일치 폴백·@layer 선언만(블록 없음) 보존을 함께 가드.
|
||||
*/
|
||||
public function test_flatten_css_layers_unwraps_blocks_preserves_rules(): void
|
||||
{
|
||||
$css = '@layer base{a{color:red}}@layer utilities{.x{top:0}.y{left:0}}';
|
||||
$out = $this->invokePrivate('flattenCssLayers', [$css]);
|
||||
|
||||
$this->assertSame(0, preg_match('/@layer\s+[^;{]*\{/', $out), '@layer 블록 래퍼가 모두 제거되어야 한다');
|
||||
$this->assertStringContainsString('a{color:red}', $out, '내부 규칙은 보존');
|
||||
$this->assertStringContainsString('.x{top:0}', $out);
|
||||
$this->assertStringContainsString('.y{left:0}', $out);
|
||||
}
|
||||
|
||||
public function test_flatten_css_layers_handles_nested_layers(): void
|
||||
{
|
||||
$css = '@layer outer{.a{top:0}@layer inner{.b{left:0}}.c{right:0}}';
|
||||
$out = $this->invokePrivate('flattenCssLayers', [$css]);
|
||||
|
||||
$this->assertSame(0, preg_match('/@layer\s+[^;{]*\{/', $out), '중첩 @layer 도 전부 평탄화');
|
||||
$this->assertStringContainsString('.a{top:0}', $out);
|
||||
$this->assertStringContainsString('.b{left:0}', $out);
|
||||
$this->assertStringContainsString('.c{right:0}', $out);
|
||||
}
|
||||
|
||||
public function test_flatten_css_layers_preserves_bare_layer_declaration(): void
|
||||
{
|
||||
// 블록 없는 선언(`@layer a, b;`)은 레이어 순서 선언이므로 그대로 보존.
|
||||
$css = '@layer base, utilities;@layer base{.a{top:0}}';
|
||||
$out = $this->invokePrivate('flattenCssLayers', [$css]);
|
||||
|
||||
$this->assertStringContainsString('@layer base, utilities;', $out, '블록 없는 @layer 선언은 보존');
|
||||
$this->assertStringContainsString('.a{top:0}', $out);
|
||||
$this->assertSame(0, preg_match('/@layer\s+[^;{]*\{/', $out), '블록 래퍼만 제거');
|
||||
}
|
||||
|
||||
public function test_flatten_css_layers_unbalanced_brace_falls_back_safely(): void
|
||||
{
|
||||
// 짝 불일치(`}` 부족) — 평탄화 포기하고 원문 보존(프리뷰가 깨지지 않도록 안전 폴백).
|
||||
$css = '@layer base{.a{top:0}'; // 닫는 중괄호 1개 부족
|
||||
$out = $this->invokePrivate('flattenCssLayers', [$css]);
|
||||
|
||||
$this->assertStringContainsString('.a{top:0}', $out, '폴백 시 내용 보존');
|
||||
}
|
||||
|
||||
public function test_flatten_css_layers_noop_when_no_layers(): void
|
||||
{
|
||||
// @layer 비사용 CSS(예 Bootstrap)는 변형 없이 그대로(no-op).
|
||||
$css = '.btn{color:blue}[data-bs-theme=dark] .btn{color:white}';
|
||||
$out = $this->invokePrivate('flattenCssLayers', [$css]);
|
||||
|
||||
$this->assertSame($css, $out, '@layer 가 없으면 변형하지 않는다');
|
||||
}
|
||||
|
||||
/**
|
||||
* rewriteDarkSelectors — 다크 조상 셀렉터(`.dark` 후손 결합자/그룹 경계 앞)만 치환하고,
|
||||
* 유틸리티 클래스(`.dark\:bg-x` — 이스케이프 콜론)는 보존(라이브러리 중립 치환).
|
||||
*/
|
||||
public function test_rewrite_dark_selectors_only_ancestor_not_utility(): void
|
||||
{
|
||||
$css = '.dark .foo{color:red}.dark\\:bg-x{background:blue}:where(.dark .dark\\:bg-y){top:0}';
|
||||
$out = $this->invokePrivate('rewriteDarkSelectors', [$css, '.dark', '.g7le-preview-dark']);
|
||||
|
||||
// 조상 셀렉터(.dark 공백/그룹경계 앞)는 치환
|
||||
$this->assertStringContainsString('.g7le-preview-dark .foo{', $out);
|
||||
$this->assertStringContainsString(':where(.g7le-preview-dark .dark\\:bg-y)', $out);
|
||||
// 유틸리티 클래스(.dark\:)는 보존
|
||||
$this->assertStringContainsString('.dark\\:bg-x{background:blue}', $out);
|
||||
// 치환 후 조상 .dark 잔존 없음
|
||||
$this->assertSame(0, preg_match('/\.dark(?=[\s,){>~+])/', $out));
|
||||
}
|
||||
|
||||
/**
|
||||
* darkMode.previewIsolation.flattenLayers 미선언 시 평탄화 옵트아웃 — 라이브러리 중립.
|
||||
*
|
||||
* resolveDarkPreviewIsolation 가 `flattenLayers` 를 반환하고, false 면 serveEditorCss 가
|
||||
* flattenCssLayers 를 호출하지 않아 @layer 가 보존됨을 검증. 디스크 fixture 대신 isolation
|
||||
* 분기 로직을 직접 호출해 가드(라이브러리 중립 핵심 분기).
|
||||
*/
|
||||
public function test_resolve_dark_preview_isolation_includes_flatten_flag(): void
|
||||
{
|
||||
// sirsoft-basic 은 editor-spec 에 flattenLayers:true 선언 — 반환값에 flag=true.
|
||||
$iso = $this->invokePrivate('resolveDarkPreviewIsolation', ['sirsoft-basic']);
|
||||
|
||||
$this->assertIsArray($iso);
|
||||
$this->assertArrayHasKey('flattenLayers', $iso, '반환값에 flattenLayers 키 포함');
|
||||
$this->assertTrue($iso['flattenLayers'], 'sirsoft-basic 은 flattenLayers:true 옵트인');
|
||||
$this->assertSame('.dark', $iso['rewrite']);
|
||||
$this->assertSame('.g7le-preview-dark', $iso['replace']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\Template;
|
||||
use App\Models\TemplateLayout;
|
||||
use App\Models\User;
|
||||
use App\Services\LayoutService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* ComputedInheritedSaveTest — computed 부모/자식 상속 저장 라운드트립
|
||||
*
|
||||
* computed 는 init_actions 와 정반대로 **부모 키 편집 가능·키 덮어쓰기**가 정책이다(shallow merge,
|
||||
* 자식 우선). 핵심 사실(plan):
|
||||
* - 편집 응답 raw.computed 는 병합본(부모+자식), 자식 원본은 `__editor.original.computed` 보존.
|
||||
* - 키별 출처 맵 `__computedSource:{ [key]: 'base'|'route' }` 가 편집 모드에만 부착(computed 객체
|
||||
* 외부 최상위 키). 운영/저장 페이로드에는 없다.
|
||||
* - 저장 시 클라이언트가 `__editor.original` 에서 자식 computed 만 복원해 PUT:
|
||||
* ① 자식 고유 키만 → 그대로 영속
|
||||
* ② 부모 키를 자식이 덮으면 그 키가 자식 식으로 자식 원본에 들어가 영속(덮기 영속)
|
||||
* ③ 미덮은 부모 키는 자식 원본에 없으므로 PUT 에서 제외
|
||||
* - 백엔드 `validated()` 는 `content.computed` 를 `['nullable','array']` 로 통째 보존한다.
|
||||
* - `__computedSource` 메타는 편집 응답 전용 — 저장 시 페이로드에 박히면 안 되고, 저장돼도 운영
|
||||
* `_computed` 평가에 영향이 없다(computed 키가 아니므로 미평가).
|
||||
*/
|
||||
class ComputedInheritedSaveTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $adminUser;
|
||||
|
||||
private Template $template;
|
||||
|
||||
private string $token;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->adminUser = $this->createAdminUser(['core.templates.read', 'core.templates.layouts.edit']);
|
||||
$this->token = $this->adminUser->createToken('test-token')->plainTextToken;
|
||||
$this->template = Template::factory()->create();
|
||||
}
|
||||
|
||||
private function createAdminUser(array $permissions = []): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$permissionIds = [];
|
||||
foreach ($permissions as $identifier) {
|
||||
$permission = Permission::firstOrCreate(
|
||||
['identifier' => $identifier],
|
||||
[
|
||||
'name' => json_encode(['ko' => $identifier, 'en' => $identifier]),
|
||||
'description' => json_encode(['ko' => $identifier, 'en' => $identifier]),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
]
|
||||
);
|
||||
$permissionIds[] = $permission->id;
|
||||
}
|
||||
$adminRole = Role::firstOrCreate(
|
||||
['identifier' => 'admin'],
|
||||
[
|
||||
'name' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'is_system' => true,
|
||||
'priority' => 0,
|
||||
]
|
||||
);
|
||||
$adminRole->permissions()->syncWithoutDetaching($permissionIds);
|
||||
$user->roles()->syncWithoutDetaching([$adminRole->id]);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
private function authRequest()
|
||||
{
|
||||
return $this->withHeaders(['Authorization' => 'Bearer '.$this->token, 'Accept' => 'application/json']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 부모(base) 레이아웃 생성 — 슬롯 + computed 보유.
|
||||
*
|
||||
* @param array<string, string> $computed
|
||||
*/
|
||||
private function makeParent(array $computed): TemplateLayout
|
||||
{
|
||||
return TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => '_admin_base',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => '_admin_base',
|
||||
'components' => [
|
||||
['id' => 'shell', 'name' => 'Div', 'type' => 'basic', 'props' => [], 'children' => [
|
||||
['id' => 'content_slot', 'name' => 'Div', 'type' => 'basic', 'slot' => 'content', 'props' => []],
|
||||
]],
|
||||
],
|
||||
'data_sources' => [],
|
||||
'computed' => $computed,
|
||||
],
|
||||
'extends' => null,
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 자식 레이아웃 생성 — 부모를 extends, computed 보유.
|
||||
*
|
||||
* @param array<string, string> $computed
|
||||
*/
|
||||
private function makeChild(array $computed): TemplateLayout
|
||||
{
|
||||
return TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'dashboard',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'dashboard',
|
||||
'extends' => '_admin_base',
|
||||
'slots' => ['content' => [['id' => 'root', 'name' => 'Div', 'type' => 'basic', 'props' => []]]],
|
||||
'data_sources' => [],
|
||||
'computed' => $computed,
|
||||
],
|
||||
'extends' => '_admin_base',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 자식 content PUT 후 갱신된 DB content 반환.
|
||||
*
|
||||
* @param array<string, string> $childComputed
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function putChild(TemplateLayout $child, array $childComputed): array
|
||||
{
|
||||
$content = [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'dashboard',
|
||||
'extends' => '_admin_base',
|
||||
'slots' => ['content' => [['id' => 'root', 'name' => 'Div', 'type' => 'basic', 'props' => []]]],
|
||||
'data_sources' => [],
|
||||
'computed' => $childComputed,
|
||||
];
|
||||
|
||||
$response = $this->authRequest()->putJson(
|
||||
"/api/admin/templates/{$this->template->identifier}/layouts/{$child->name}",
|
||||
['expected_lock_version' => (int) $child->lock_version, 'content' => $content],
|
||||
);
|
||||
$response->assertStatus(200);
|
||||
$child->refresh();
|
||||
|
||||
return $child->content;
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_persists_only_child_own_computed_keys(): void
|
||||
{
|
||||
// ① 자식 고유 키만 PUT → 그대로 영속, 부모 키 미포함
|
||||
// ③ 미덮은 부모 키는 자식 PUT 에서 제외(클라이언트 __editor.original 복원)
|
||||
$this->makeParent(['isReadOnly' => '{{ !canEdit }}', 'pageTitle' => '{{ "공통" }}']);
|
||||
$child = $this->makeChild(['rowCount' => '{{ items.length }}']);
|
||||
|
||||
$stored = $this->putChild($child, ['rowCount' => '{{ items.length }}']);
|
||||
|
||||
$this->assertArrayHasKey('computed', $stored);
|
||||
$this->assertArrayHasKey('rowCount', $stored['computed']);
|
||||
$this->assertSame('{{ items.length }}', $stored['computed']['rowCount']);
|
||||
// 미덮은 부모 키는 자식 행에 영속되면 안 됨
|
||||
$this->assertArrayNotHasKey('isReadOnly', $stored['computed']);
|
||||
$this->assertArrayNotHasKey('pageTitle', $stored['computed']);
|
||||
// 출처 맵 메타는 저장되지 않음
|
||||
$this->assertArrayNotHasKey('__computedSource', $stored);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_persists_overridden_parent_key_with_child_expression(): void
|
||||
{
|
||||
// ② 부모 키를 자식이 덮으면 그 키가 자식 식으로 영속(덮기 영속)
|
||||
$this->makeParent(['isReadOnly' => '{{ !canEdit }}']);
|
||||
$child = $this->makeChild(['isReadOnly' => '{{ false }}']);
|
||||
|
||||
$stored = $this->putChild($child, ['isReadOnly' => '{{ false }}']);
|
||||
|
||||
$this->assertArrayHasKey('isReadOnly', $stored['computed']);
|
||||
$this->assertSame('{{ false }}', $stored['computed']['isReadOnly'], '덮은 키는 자식 식으로 영속');
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_does_not_persist_computed_source_meta(): void
|
||||
{
|
||||
// ④ __computedSource 메타가 자식 content 에 박혀 와도 저장 페이로드에 영속되지 않음을 가드.
|
||||
// 백엔드 validated() 는 content.computed 를 통째 보존하나, __computedSource 는 computed 의
|
||||
// 형제 최상위 키이며 rules() 에 미명시라 validated() 에서 탈락한다(저장 0).
|
||||
$this->makeParent(['isReadOnly' => '{{ !canEdit }}']);
|
||||
$child = $this->makeChild(['rowCount' => '{{ items.length }}']);
|
||||
|
||||
$content = [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'dashboard',
|
||||
'extends' => '_admin_base',
|
||||
'slots' => ['content' => [['id' => 'root', 'name' => 'Div', 'type' => 'basic', 'props' => []]]],
|
||||
'data_sources' => [],
|
||||
'computed' => ['rowCount' => '{{ items.length }}'],
|
||||
// 편집 응답에서 새어 들어온 출처 맵 메타(위조/우회)
|
||||
'__computedSource' => ['isReadOnly' => 'base', 'rowCount' => 'route'],
|
||||
];
|
||||
|
||||
$response = $this->authRequest()->putJson(
|
||||
"/api/admin/templates/{$this->template->identifier}/layouts/{$child->name}",
|
||||
['expected_lock_version' => 0, 'content' => $content],
|
||||
);
|
||||
$response->assertStatus(200);
|
||||
$child->refresh();
|
||||
|
||||
$this->assertArrayNotHasKey('__computedSource', $child->content, '출처 맵 메타가 영속되면 안 됨(validated 탈락)');
|
||||
$this->assertSame(['rowCount' => '{{ items.length }}'], $child->content['computed']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_excludes_reverted_key_from_payload(): void
|
||||
{
|
||||
// ⑤ 되돌린 키 PUT 제외 — 자식이 이전에 덮었던 키를 되돌리면(자식 computed 에서 제거),
|
||||
// 그 키는 자식 PUT 에 포함되지 않아 재로드 시 부모 식으로 복귀한다.
|
||||
$this->makeParent(['isReadOnly' => '{{ !canEdit }}']);
|
||||
// 초기엔 자식이 덮은 상태로 저장
|
||||
$child = $this->makeChild(['isReadOnly' => '{{ false }}', 'rowCount' => '{{ items.length }}']);
|
||||
$this->putChild($child, ['isReadOnly' => '{{ false }}', 'rowCount' => '{{ items.length }}']);
|
||||
|
||||
// 되돌림 — 자식 computed 에서 isReadOnly 제거 후 재저장(자식 고유 키만 남김)
|
||||
$stored = $this->putChild($child, ['rowCount' => '{{ items.length }}']);
|
||||
|
||||
$this->assertArrayNotHasKey('isReadOnly', $stored['computed'], '되돌린 키는 자식 행에서 제거');
|
||||
$this->assertArrayHasKey('rowCount', $stored['computed']);
|
||||
|
||||
// 재로드 시 isReadOnly 는 부모 식으로 복귀
|
||||
$merged = app(LayoutService::class)->loadAndMergeLayout($this->template->id, 'dashboard', true);
|
||||
$this->assertSame('{{ !canEdit }}', $merged['computed']['isReadOnly'], '되돌린 키는 부모 식으로 평가');
|
||||
$this->assertSame('base', $merged['__computedSource']['isReadOnly']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_leaves_parent_row_unchanged_and_remerges_on_reload(): void
|
||||
{
|
||||
// ⑥ 부모 레이아웃 행 불변 + 재로드 시 부모+자식 병합·출처 맵 재부착
|
||||
$parent = $this->makeParent(['isReadOnly' => '{{ !canEdit }}', 'pageTitle' => '{{ "공통" }}']);
|
||||
$child = $this->makeChild(['isReadOnly' => '{{ false }}', 'rowCount' => '{{ items.length }}']);
|
||||
|
||||
$this->putChild($child, ['isReadOnly' => '{{ false }}', 'rowCount' => '{{ items.length }}']);
|
||||
|
||||
// 부모 행 불변
|
||||
$parent->refresh();
|
||||
$this->assertSame(
|
||||
['isReadOnly' => '{{ !canEdit }}', 'pageTitle' => '{{ "공통" }}'],
|
||||
$parent->content['computed'],
|
||||
);
|
||||
$this->assertSame(0, (int) $parent->lock_version);
|
||||
|
||||
// 재로드(with_source_meta=1) — shallow merge 자식 우선 + 출처 맵
|
||||
$merged = app(LayoutService::class)->loadAndMergeLayout($this->template->id, 'dashboard', true);
|
||||
|
||||
// 자식 덮은 키 = 자식 식 / 미덮은 부모 키 = 부모 식 / 자식 고유 키 = 자식 식
|
||||
$this->assertSame('{{ false }}', $merged['computed']['isReadOnly']);
|
||||
$this->assertSame('{{ "공통" }}', $merged['computed']['pageTitle']);
|
||||
$this->assertSame('{{ items.length }}', $merged['computed']['rowCount']);
|
||||
|
||||
// 출처 맵: 덮은 키=route / 미덮은 부모 키=base / 자식 고유=route
|
||||
$this->assertSame('route', $merged['__computedSource']['isReadOnly']);
|
||||
$this->assertSame('base', $merged['__computedSource']['pageTitle']);
|
||||
$this->assertSame('route', $merged['__computedSource']['rowCount']);
|
||||
|
||||
// 자식 원본은 __editor.original 에 자식 computed 만 보존
|
||||
$this->assertSame(
|
||||
['isReadOnly' => '{{ false }}', 'rowCount' => '{{ items.length }}'],
|
||||
$merged['__editor']['original']['computed'],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,6 @@ use App\Models\User;
|
||||
use App\Services\DashboardService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
@@ -40,7 +39,6 @@ class DashboardControllerTest extends TestCase
|
||||
*
|
||||
* @param array $permissions 사용자에게 부여할 권한 식별자 목록
|
||||
* @param string|null $scopeType 권한 스코프 타입 (null: 전체, 'self': 본인, 'role': 역할)
|
||||
* @return User
|
||||
*/
|
||||
private function createAdminUser(array $permissions = ['core.dashboard.read'], ?string $scopeType = null): User
|
||||
{
|
||||
@@ -265,8 +263,6 @@ class DashboardControllerTest extends TestCase
|
||||
*
|
||||
* 실제 시스템 명령(PowerShell, wmic 등) 호출을 피하고
|
||||
* 테스트 성능을 향상시키기 위해 모킹된 값을 반환합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function mockDashboardResourceService(): void
|
||||
{
|
||||
@@ -279,6 +275,35 @@ class DashboardControllerTest extends TestCase
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 내부 probe 가 예외를 던져도 리소스 조회가 200 으로 응답하는지 테스트 (공개#40).
|
||||
*
|
||||
* getSystemResources 전체를 mock 하지 않고 내부 probe(getCpuUsage)만 throw 시켜
|
||||
* safeProbe 격리가 실제로 동작하는지 검증한다.
|
||||
*/
|
||||
public function test_resources_returns_200_when_probe_fails(): void
|
||||
{
|
||||
$this->partialMock(DashboardService::class, function ($mock) {
|
||||
$mock->shouldAllowMockingProtectedMethods();
|
||||
$mock->shouldReceive('getCpuUsage')->andThrow(new \ErrorException('open_basedir restriction in effect'));
|
||||
// memory/disk 는 실제 실행 (Windows/Linux 무관 정상 구조 반환)
|
||||
});
|
||||
|
||||
$response = $this->authRequest()->getJson('/api/admin/dashboard/resources');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertSame('gray', $response->json('data.cpu.color'));
|
||||
$this->assertSame(0, $response->json('data.cpu.percentage'));
|
||||
// memory/disk 구조는 정상 유지
|
||||
$response->assertJsonStructure([
|
||||
'data' => [
|
||||
'cpu' => ['percentage', 'color'],
|
||||
'memory' => ['percentage', 'used', 'total', 'color'],
|
||||
'disk' => ['percentage', 'used', 'total', 'color'],
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_resources_returns_correct_structure(): void
|
||||
{
|
||||
$this->mockDashboardResourceService();
|
||||
|
||||
@@ -191,6 +191,44 @@ class AdminIdentityMessageControllerTest extends TestCase
|
||||
$this->assertTrue($template->is_default);
|
||||
}
|
||||
|
||||
public function test_template_reset_restores_definition_is_default_flag(): void
|
||||
{
|
||||
// 시드 정의(is_default=true)의 템플릿을 운영자가 편집하면 definition.is_default 가 false 로 내려간다.
|
||||
$template = IdentityMessageTemplate::whereHas('definition', fn ($q) => $q
|
||||
->where('scope_value', 'signup')
|
||||
)->firstOrFail();
|
||||
|
||||
$definitionId = $template->definition_id;
|
||||
$this->assertTrue(
|
||||
IdentityMessageDefinition::findOrFail($definitionId)->is_default,
|
||||
'시드 정의는 초기 상태에서 is_default=true 여야 합니다.'
|
||||
);
|
||||
|
||||
// 운영자 편집 → definition.is_default false 로 하강
|
||||
$this->authRequest()->patchJson(
|
||||
'/api/admin/identity/messages/templates/'.$template->id,
|
||||
[
|
||||
'subject' => ['ko' => '커스텀', 'en' => 'Custom'],
|
||||
'body' => ['ko' => '커스텀 본문', 'en' => 'Custom body'],
|
||||
],
|
||||
)->assertStatus(200);
|
||||
|
||||
$this->assertFalse(
|
||||
IdentityMessageDefinition::findOrFail($definitionId)->is_default,
|
||||
'편집 후 definition.is_default 가 false 로 전환되어야 합니다 (결함 C 전제).'
|
||||
);
|
||||
|
||||
// reset → definition.is_default 가 true 로 복원되어야 한다 ('기본' 배지/reset 버튼 노출 조건 정상화)
|
||||
$this->authRequest()->postJson(
|
||||
'/api/admin/identity/messages/templates/'.$template->id.'/reset',
|
||||
)->assertStatus(200);
|
||||
|
||||
$this->assertTrue(
|
||||
IdentityMessageDefinition::findOrFail($definitionId)->is_default,
|
||||
'reset 후 시드 정의의 definition.is_default 가 true 로 복원되어야 합니다 (결함 C).'
|
||||
);
|
||||
}
|
||||
|
||||
public function test_definition_toggle_active_flips_state(): void
|
||||
{
|
||||
$definition = IdentityMessageDefinition::where('scope_value', 'signup')->firstOrFail();
|
||||
|
||||
@@ -279,6 +279,102 @@ class AdminIdentityPolicyCrudTest extends TestCase
|
||||
$this->assertContains('conditions', $fresh->user_overrides ?? []);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 선언 정책의 purpose(인증 목적) 운영자 편집.
|
||||
*
|
||||
* 인증 목적은 어떤 정책이든 운영자가 자유로이 부여할 수 있어야 한다.
|
||||
* 변경 시 user_overrides 에 'purpose' 가 추가되어 모듈 재sync 시 운영자 값이 보존된다.
|
||||
*/
|
||||
public function test_http_update_module_policy_persists_purpose_change(): void
|
||||
{
|
||||
$policy = IdentityPolicy::create($this->makePolicyData([
|
||||
'key' => 'http.module.purpose',
|
||||
'source_type' => 'module',
|
||||
'source_identifier' => 'sirsoft-board',
|
||||
'purpose' => 'sensitive_action',
|
||||
'scope' => 'hook',
|
||||
'target' => 'sirsoft-board.post.before_create',
|
||||
]));
|
||||
|
||||
$response = $this->authRequest()->putJson("/api/admin/identity/policies/{$policy->id}", [
|
||||
'purpose' => 'inicis.adult_verification',
|
||||
]);
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('data.purpose', 'inicis.adult_verification');
|
||||
|
||||
$fresh = $policy->fresh();
|
||||
$this->assertSame('inicis.adult_verification', $fresh->purpose);
|
||||
$this->assertContains('purpose', $fresh->user_overrides ?? []);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 선언 정책의 applies_to(적용 대상) / priority 운영자 편집.
|
||||
*
|
||||
* 키/시점(scope)/위치(target) 외의 필드는 운영자가 자유로이 수정 가능.
|
||||
*/
|
||||
public function test_http_update_module_policy_persists_applies_to_and_priority(): void
|
||||
{
|
||||
$policy = IdentityPolicy::create($this->makePolicyData([
|
||||
'key' => 'http.module.applies',
|
||||
'source_type' => 'module',
|
||||
'source_identifier' => 'sirsoft-board',
|
||||
'applies_to' => 'both',
|
||||
'priority' => 100,
|
||||
]));
|
||||
|
||||
$response = $this->authRequest()->putJson("/api/admin/identity/policies/{$policy->id}", [
|
||||
'applies_to' => 'self',
|
||||
'priority' => 50,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('data.applies_to', 'self')
|
||||
->assertJsonPath('data.priority', 50);
|
||||
|
||||
$fresh = $policy->fresh();
|
||||
$this->assertSame('self', $fresh->applies_to->value);
|
||||
$this->assertSame(50, $fresh->priority);
|
||||
$this->assertContains('applies_to', $fresh->user_overrides ?? []);
|
||||
$this->assertContains('priority', $fresh->user_overrides ?? []);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 선언 정책의 key/scope/target 은 readonly — 훅 지점 식별자라 운영자 변경 불가.
|
||||
*
|
||||
* 이 3개 필드는 update 요청에 실려와도 Controller 화이트리스트에서 드롭되어 원래 값을 유지한다.
|
||||
*/
|
||||
public function test_http_update_module_policy_drops_key_scope_target(): void
|
||||
{
|
||||
$policy = IdentityPolicy::create($this->makePolicyData([
|
||||
'key' => 'http.module.readonly',
|
||||
'source_type' => 'module',
|
||||
'source_identifier' => 'sirsoft-board',
|
||||
'scope' => 'hook',
|
||||
'target' => 'sirsoft-board.post.before_create',
|
||||
]));
|
||||
|
||||
$response = $this->authRequest()->putJson("/api/admin/identity/policies/{$policy->id}", [
|
||||
'key' => 'tampered.key',
|
||||
'scope' => 'route',
|
||||
'target' => 'tampered.target',
|
||||
'grace_minutes' => 7,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
$fresh = $policy->fresh();
|
||||
$this->assertSame('http.module.readonly', $fresh->key);
|
||||
$this->assertSame('hook', $fresh->scope->value);
|
||||
$this->assertSame('sirsoft-board.post.before_create', $fresh->target);
|
||||
// 화이트리스트 필드는 정상 반영
|
||||
$this->assertSame(7, $fresh->grace_minutes);
|
||||
// readonly 필드는 user_overrides 에 기록되지 않음
|
||||
$this->assertNotContains('key', $fresh->user_overrides ?? []);
|
||||
$this->assertNotContains('scope', $fresh->user_overrides ?? []);
|
||||
$this->assertNotContains('target', $fresh->user_overrides ?? []);
|
||||
}
|
||||
|
||||
public function test_http_update_admin_policy_persists_conditions_change(): void
|
||||
{
|
||||
$policy = IdentityPolicy::create($this->makePolicyData([
|
||||
@@ -389,6 +485,176 @@ class AdminIdentityPolicyCrudTest extends TestCase
|
||||
$response->assertStatus(401);
|
||||
}
|
||||
|
||||
// ====================================================================
|
||||
// priority 동률 차단 — 같은 scope+target 에 동일 priority 활성 정책 거부
|
||||
// ====================================================================
|
||||
|
||||
/**
|
||||
* 같은 scope+target 에 동일 priority 활성 정책이 이미 있으면 신규 저장은 422.
|
||||
*/
|
||||
public function test_http_store_rejects_duplicate_priority_on_same_target(): void
|
||||
{
|
||||
IdentityPolicy::create($this->makePolicyData([
|
||||
'key' => 'http.tie.existing',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.tie.target',
|
||||
'priority' => 100,
|
||||
'enabled' => true,
|
||||
]));
|
||||
|
||||
$response = $this->authRequest()->postJson('/api/admin/identity/policies', [
|
||||
'key' => 'http.tie.new',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.tie.target',
|
||||
'purpose' => 'sensitive_action',
|
||||
'grace_minutes' => 0,
|
||||
'applies_to' => 'both',
|
||||
'fail_mode' => 'block',
|
||||
'enabled' => true,
|
||||
'priority' => 100,
|
||||
]);
|
||||
|
||||
$response->assertStatus(422)
|
||||
->assertJsonValidationErrors(['priority']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 같은 scope+target 이라도 priority 가 다르면 저장 허용.
|
||||
*/
|
||||
public function test_http_store_allows_different_priority_on_same_target(): void
|
||||
{
|
||||
IdentityPolicy::create($this->makePolicyData([
|
||||
'key' => 'http.tie.existing2',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.tie.target2',
|
||||
'priority' => 100,
|
||||
'enabled' => true,
|
||||
]));
|
||||
|
||||
$response = $this->authRequest()->postJson('/api/admin/identity/policies', [
|
||||
'key' => 'http.tie.new2',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.tie.target2',
|
||||
'purpose' => 'sensitive_action',
|
||||
'grace_minutes' => 0,
|
||||
'applies_to' => 'both',
|
||||
'fail_mode' => 'block',
|
||||
'enabled' => true,
|
||||
'priority' => 90,
|
||||
]);
|
||||
|
||||
$response->assertStatus(201);
|
||||
}
|
||||
|
||||
/**
|
||||
* 기존 정책이 비활성이면 동일 priority 라도 저장 허용 (비활성은 enforce 안 되어 무해).
|
||||
*/
|
||||
public function test_http_store_allows_duplicate_priority_when_existing_disabled(): void
|
||||
{
|
||||
IdentityPolicy::create($this->makePolicyData([
|
||||
'key' => 'http.tie.disabled',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.tie.target3',
|
||||
'priority' => 100,
|
||||
'enabled' => false,
|
||||
]));
|
||||
|
||||
$response = $this->authRequest()->postJson('/api/admin/identity/policies', [
|
||||
'key' => 'http.tie.new3',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.tie.target3',
|
||||
'purpose' => 'sensitive_action',
|
||||
'grace_minutes' => 0,
|
||||
'applies_to' => 'both',
|
||||
'fail_mode' => 'block',
|
||||
'enabled' => true,
|
||||
'priority' => 100,
|
||||
]);
|
||||
|
||||
$response->assertStatus(201);
|
||||
}
|
||||
|
||||
/**
|
||||
* 신규 정책이 비활성이면 동률이어도 저장 허용 (비활성은 enforce 안 됨).
|
||||
*/
|
||||
public function test_http_store_allows_duplicate_priority_when_new_disabled(): void
|
||||
{
|
||||
IdentityPolicy::create($this->makePolicyData([
|
||||
'key' => 'http.tie.active',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.tie.target4',
|
||||
'priority' => 100,
|
||||
'enabled' => true,
|
||||
]));
|
||||
|
||||
$response = $this->authRequest()->postJson('/api/admin/identity/policies', [
|
||||
'key' => 'http.tie.new4',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.tie.target4',
|
||||
'purpose' => 'sensitive_action',
|
||||
'grace_minutes' => 0,
|
||||
'applies_to' => 'both',
|
||||
'fail_mode' => 'block',
|
||||
'enabled' => false,
|
||||
'priority' => 100,
|
||||
]);
|
||||
|
||||
$response->assertStatus(201);
|
||||
}
|
||||
|
||||
/**
|
||||
* 수정 시 동일 priority 활성 정책이 다른 행에 있으면 422 (자기 자신은 제외).
|
||||
*/
|
||||
public function test_http_update_rejects_duplicate_priority_against_other_policy(): void
|
||||
{
|
||||
IdentityPolicy::create($this->makePolicyData([
|
||||
'key' => 'http.tie.update.a',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.tie.update',
|
||||
'priority' => 100,
|
||||
'enabled' => true,
|
||||
]));
|
||||
$editing = IdentityPolicy::create($this->makePolicyData([
|
||||
'key' => 'http.tie.update.b',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.tie.update',
|
||||
'priority' => 50,
|
||||
'enabled' => true,
|
||||
]));
|
||||
|
||||
// editing 정책을 100 으로 바꾸면 a 와 동률 → 거부
|
||||
$response = $this->authRequest()->putJson("/api/admin/identity/policies/{$editing->id}", [
|
||||
'priority' => 100,
|
||||
]);
|
||||
|
||||
$response->assertStatus(422)
|
||||
->assertJsonValidationErrors(['priority']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 수정 시 자기 자신의 기존 priority 를 그대로 두는 변경(다른 필드만 수정)은 통과 — self 제외 확인.
|
||||
*/
|
||||
public function test_http_update_allows_keeping_own_priority(): void
|
||||
{
|
||||
$editing = IdentityPolicy::create($this->makePolicyData([
|
||||
'key' => 'http.tie.update.self',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.tie.update.self',
|
||||
'priority' => 100,
|
||||
'enabled' => true,
|
||||
]));
|
||||
|
||||
// 자기 자신만 그 target+priority 를 점유 — priority 100 유지하며 grace 변경
|
||||
$response = $this->authRequest()->putJson("/api/admin/identity/policies/{$editing->id}", [
|
||||
'priority' => 100,
|
||||
'grace_minutes' => 33,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('data.priority', 100);
|
||||
$this->assertSame(33, $editing->fresh()->grace_minutes);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\Template;
|
||||
use App\Models\TemplateLayout;
|
||||
use App\Models\User;
|
||||
use App\Services\LayoutService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* InitActionsInheritedSaveTest — init_actions 부모/자식 상속 저장 라운드트립
|
||||
*
|
||||
* 부모(_user_base) + 자식(extends) init_actions 가 편집 모드(with_source_meta=1)에서 병합·메타
|
||||
* 부착되어 노출되지만, 자식 저장은 자식 init_actions 만 영속하고 부모분/`__source` 는 PUT 에서
|
||||
* 제거된다. 핵심 사실(plan):
|
||||
* - 편집 응답 raw 는 병합본(부모+자식), 자식 원본은 `__editor.original` 에 별도 보존
|
||||
* (LayoutService::loadAndMergeLayoutInternal).
|
||||
* - 저장 시 클라이언트가 `__editor.original` 에서 자식 원본만 복원해 PUT → 부모분 자동 제외.
|
||||
* - 백엔드 `validated()` 는 `content.init_actions` 를 `['nullable','array']` 로 통째 보존하므로
|
||||
* 자식이 보낸 배열을 가공 없이 적재한다(R9 부류). `__source` 마킹은 운영/저장 페이로드에 없다.
|
||||
*
|
||||
* 위조 PUT(부모 init_action 을 자식 content 에 섞어 보냄)은 백엔드가 거부하지 않고 그대로
|
||||
* 적재한다 — init_actions 는 노드 트리가 아니라 최상위 배열이라 `stripInheritedFromLayoutContent`
|
||||
* 의 노드 마스킹 대상이 아니기 때문이다. 따라서 부모분 제외의 SSoT 는 클라이언트(`__editor.original`)
|
||||
* 이며, 백엔드가 보장하는 것은 `__source` 같은 편집 전용 메타가 페이로드에 섞여도 저장 후 재로드
|
||||
* 시 운영 동작에 영향이 없다는 점이다. 본 테스트는 그 실제 동작을 그대로 가드한다.
|
||||
*/
|
||||
class InitActionsInheritedSaveTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $adminUser;
|
||||
|
||||
private Template $template;
|
||||
|
||||
private string $token;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->adminUser = $this->createAdminUser(['core.templates.read', 'core.templates.layouts.edit']);
|
||||
$this->token = $this->adminUser->createToken('test-token')->plainTextToken;
|
||||
$this->template = Template::factory()->create();
|
||||
}
|
||||
|
||||
private function createAdminUser(array $permissions = []): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$permissionIds = [];
|
||||
foreach ($permissions as $identifier) {
|
||||
$permission = Permission::firstOrCreate(
|
||||
['identifier' => $identifier],
|
||||
[
|
||||
'name' => json_encode(['ko' => $identifier, 'en' => $identifier]),
|
||||
'description' => json_encode(['ko' => $identifier, 'en' => $identifier]),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
]
|
||||
);
|
||||
$permissionIds[] = $permission->id;
|
||||
}
|
||||
$adminRole = Role::firstOrCreate(
|
||||
['identifier' => 'admin'],
|
||||
[
|
||||
'name' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'is_system' => true,
|
||||
'priority' => 0,
|
||||
]
|
||||
);
|
||||
$adminRole->permissions()->syncWithoutDetaching($permissionIds);
|
||||
$user->roles()->syncWithoutDetaching([$adminRole->id]);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
private function authRequest()
|
||||
{
|
||||
return $this->withHeaders(['Authorization' => 'Bearer '.$this->token, 'Accept' => 'application/json']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 부모(base) 레이아웃 생성 — 슬롯 + init_actions 보유.
|
||||
*/
|
||||
private function makeParent(array $initActions): TemplateLayout
|
||||
{
|
||||
return TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => '_user_base',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => '_user_base',
|
||||
'components' => [
|
||||
['id' => 'shell', 'name' => 'Div', 'type' => 'basic', 'props' => [], 'children' => [
|
||||
['id' => 'content_slot', 'name' => 'Div', 'type' => 'basic', 'slot' => 'content', 'props' => []],
|
||||
]],
|
||||
],
|
||||
'data_sources' => [],
|
||||
'init_actions' => $initActions,
|
||||
],
|
||||
'extends' => null,
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 자식 레이아웃 생성 — 부모를 extends, init_actions 보유.
|
||||
*/
|
||||
private function makeChild(array $initActions): TemplateLayout
|
||||
{
|
||||
return TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'home',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'home',
|
||||
'extends' => '_user_base',
|
||||
'slots' => [
|
||||
'content' => [
|
||||
['id' => 'root', 'name' => 'Div', 'type' => 'basic', 'props' => []],
|
||||
],
|
||||
],
|
||||
'data_sources' => [],
|
||||
'init_actions' => $initActions,
|
||||
],
|
||||
'extends' => '_user_base',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 자식 레이아웃에 content 를 PUT 하고 갱신된 DB content 를 반환.
|
||||
*
|
||||
* @param array<string, mixed> $content
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function putChild(TemplateLayout $child, array $content): array
|
||||
{
|
||||
$response = $this->authRequest()->putJson(
|
||||
"/api/admin/templates/{$this->template->identifier}/layouts/{$child->name}",
|
||||
['expected_lock_version' => 0, 'content' => $content],
|
||||
);
|
||||
$response->assertStatus(200);
|
||||
$child->refresh();
|
||||
|
||||
return $child->content;
|
||||
}
|
||||
|
||||
/**
|
||||
* 자식 PUT 의 기본 content 골격(extends + slots + 자식 init_actions).
|
||||
*
|
||||
* @param array<int, array<string, mixed>> $childInitActions
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function childContent(array $childInitActions): array
|
||||
{
|
||||
return [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'home',
|
||||
'extends' => '_user_base',
|
||||
'slots' => [
|
||||
'content' => [
|
||||
['id' => 'root', 'name' => 'Div', 'type' => 'basic', 'props' => []],
|
||||
],
|
||||
],
|
||||
'data_sources' => [],
|
||||
'init_actions' => $childInitActions,
|
||||
];
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_persists_only_child_init_actions_on_save(): void
|
||||
{
|
||||
// ① 자식 [화면동작] 편집 후 PUT → 자식 init_actions 만 (부모분 미포함, __source 부재)
|
||||
// ② DB 저장된 자식 content.init_actions = 자식 원본만 (부모 복제 0)
|
||||
$this->makeParent([['handler' => 'initTheme'], ['handler' => 'initCartKey']]);
|
||||
$child = $this->makeChild([['handler' => 'toast']]);
|
||||
|
||||
$childActions = [
|
||||
['handler' => 'toast', 'params' => ['message' => 'hi']],
|
||||
['handler' => 'setState', 'target' => 'local', 'params' => ['ready' => true]],
|
||||
];
|
||||
|
||||
$stored = $this->putChild($child, $this->childContent($childActions));
|
||||
|
||||
$this->assertArrayHasKey('init_actions', $stored);
|
||||
$this->assertCount(2, $stored['init_actions'], '자식 init_actions 만 저장되어야 함(부모 복제 0)');
|
||||
$this->assertSame('toast', $stored['init_actions'][0]['handler']);
|
||||
$this->assertSame('setState', $stored['init_actions'][1]['handler']);
|
||||
|
||||
// 부모 핸들러(initTheme/initCartKey)는 자식 content 에 없어야 함
|
||||
$handlers = array_column($stored['init_actions'], 'handler');
|
||||
$this->assertNotContains('initTheme', $handlers, '부모 init_action 이 자식에 영속되면 안 됨');
|
||||
$this->assertNotContains('initCartKey', $handlers);
|
||||
|
||||
// __source 메타가 페이로드에 섞이지 않음
|
||||
foreach ($stored['init_actions'] as $item) {
|
||||
$this->assertArrayNotHasKey('__source', $item, '편집 전용 __source 메타가 저장되면 안 됨');
|
||||
}
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_remerges_parent_and_reattaches_source_meta_on_reload(): void
|
||||
{
|
||||
// ③ 저장 후 재로드(with_source_meta=1) → 부모+자식 다시 병합·메타 재부착(영속 아님)
|
||||
$this->makeParent([['handler' => 'initTheme'], ['handler' => 'initCartKey']]);
|
||||
$child = $this->makeChild([['handler' => 'toast']]);
|
||||
|
||||
// 자식 저장(자식 init_actions 만)
|
||||
$this->putChild($child, $this->childContent([['handler' => 'toast']]));
|
||||
|
||||
// DB content 자체에는 부모분·__source 가 없다(영속 아님)
|
||||
$child->refresh();
|
||||
$this->assertCount(1, $child->content['init_actions']);
|
||||
$this->assertArrayNotHasKey('__source', $child->content['init_actions'][0]);
|
||||
|
||||
// 편집 모드 재로드 → 부모 먼저 + 자식 나중 순서로 병합, __source 메타 재부착
|
||||
$merged = app(LayoutService::class)->loadAndMergeLayout($this->template->id, 'home', true);
|
||||
|
||||
$this->assertArrayHasKey('initActions', $merged, '병합본은 initActions 키로 노출');
|
||||
$this->assertCount(3, $merged['initActions'], '부모 2 + 자식 1 = 3 병합');
|
||||
$this->assertSame('initTheme', $merged['initActions'][0]['handler']);
|
||||
$this->assertSame('initCartKey', $merged['initActions'][1]['handler']);
|
||||
$this->assertSame('toast', $merged['initActions'][2]['handler']);
|
||||
|
||||
// __source 재부착: 부모=base/_user_base, 자식=route/home
|
||||
$this->assertSame(['kind' => 'base', 'layout' => '_user_base'], $merged['initActions'][0]['__source']);
|
||||
$this->assertSame(['kind' => 'base', 'layout' => '_user_base'], $merged['initActions'][1]['__source']);
|
||||
$this->assertSame(['kind' => 'route', 'layout' => 'home'], $merged['initActions'][2]['__source']);
|
||||
|
||||
// 자식 원본은 __editor.original 에 별도 보존(자식분만)
|
||||
$this->assertArrayHasKey('__editor', $merged);
|
||||
$this->assertCount(1, $merged['__editor']['original']['init_actions']);
|
||||
$this->assertSame('toast', $merged['__editor']['original']['init_actions'][0]['handler']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_persists_parent_init_actions_when_editing_base_layout(): void
|
||||
{
|
||||
// ④ base 편집 모드 저장 → 부모(_user_base) 행에 부모 init_actions 영속
|
||||
$parent = $this->makeParent([['handler' => 'initTheme']]);
|
||||
$this->makeChild([['handler' => 'toast']]);
|
||||
|
||||
$newParentActions = [
|
||||
['handler' => 'initTheme'],
|
||||
['handler' => 'initCartKey'],
|
||||
];
|
||||
|
||||
$response = $this->authRequest()->putJson(
|
||||
"/api/admin/templates/{$this->template->identifier}/layouts/{$parent->name}",
|
||||
['expected_lock_version' => 0, 'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => '_user_base',
|
||||
'components' => [
|
||||
['id' => 'shell', 'name' => 'Div', 'type' => 'basic', 'props' => [], 'children' => [
|
||||
['id' => 'content_slot', 'name' => 'Div', 'type' => 'basic', 'slot' => 'content', 'props' => []],
|
||||
]],
|
||||
],
|
||||
'data_sources' => [],
|
||||
'init_actions' => $newParentActions,
|
||||
]],
|
||||
);
|
||||
$response->assertStatus(200);
|
||||
|
||||
$parent->refresh();
|
||||
$this->assertArrayHasKey('init_actions', $parent->content);
|
||||
$this->assertCount(2, $parent->content['init_actions']);
|
||||
$this->assertSame('initTheme', $parent->content['init_actions'][0]['handler']);
|
||||
$this->assertSame('initCartKey', $parent->content['init_actions'][1]['handler']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_leaves_parent_row_unchanged_when_child_is_saved(): void
|
||||
{
|
||||
// ④ 보강 — 자식 저장이 부모 행을 변경하지 않음
|
||||
$parent = $this->makeParent([['handler' => 'initTheme'], ['handler' => 'initCartKey']]);
|
||||
$child = $this->makeChild([['handler' => 'toast']]);
|
||||
|
||||
$this->putChild($child, $this->childContent([
|
||||
['handler' => 'toast'],
|
||||
['handler' => 'navigate', 'params' => ['path' => '/']],
|
||||
]));
|
||||
|
||||
$parent->refresh();
|
||||
$this->assertCount(2, $parent->content['init_actions'], '부모 행 init_actions 불변');
|
||||
$this->assertSame('initTheme', $parent->content['init_actions'][0]['handler']);
|
||||
$this->assertSame('initCartKey', $parent->content['init_actions'][1]['handler']);
|
||||
$this->assertSame(0, (int) $parent->lock_version, '부모 lock_version 불변');
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_ignores_forged_source_meta_in_child_payload_on_reload(): void
|
||||
{
|
||||
// ⑤ 위조 PUT — 자식 content 에 __source 가 박힌 부모 init_action 을 섞어 보냄.
|
||||
// init_actions 는 노드 트리가 아니라 최상위 배열이라 백엔드 노드 마스킹 대상이 아니다.
|
||||
// 백엔드는 배열을 그대로 적재하지만(거부하지 않음), 부모분 제외의 SSoT 는 클라이언트의
|
||||
// __editor.original 이다. 본 테스트는 "편집 전용 __source 가 페이로드에 섞여 저장돼도
|
||||
// 재로드/운영 동작이 깨지지 않는다"는 백엔드 계약을 가드한다(plan dispatch 안전성).
|
||||
$this->makeParent([['handler' => 'initTheme']]);
|
||||
$child = $this->makeChild([['handler' => 'toast']]);
|
||||
|
||||
$forged = [
|
||||
// 부모 항목을 __source 메타까지 그대로 위조해 자식 content 에 포함
|
||||
['handler' => 'initTheme', '__source' => ['kind' => 'base', 'layout' => '_user_base']],
|
||||
['handler' => 'toast', '__source' => ['kind' => 'route', 'layout' => 'home']],
|
||||
];
|
||||
|
||||
$stored = $this->putChild($child, $this->childContent($forged));
|
||||
|
||||
// 백엔드는 최상위 배열을 통째 보존(R9) — 거부하지 않음
|
||||
$this->assertCount(2, $stored['init_actions']);
|
||||
|
||||
// 재로드(with_source_meta=1) 시 부모분이 다시 앞에 붙고 __source 가 재계산된다.
|
||||
// 위조로 박힌 __source 가 운영 dispatch 화이트리스트에 미포함이라 런타임 무영향이며,
|
||||
// 재로드 병합은 위조 항목을 자식분(route)으로 취급해 부모(_user_base) 항목을 그 앞에 붙인다.
|
||||
$merged = app(LayoutService::class)->loadAndMergeLayout($this->template->id, 'home', true);
|
||||
|
||||
// 부모 1 + 자식 2(위조 포함) = 3
|
||||
$this->assertCount(3, $merged['initActions']);
|
||||
// 부모 항목이 가장 앞 + base 메타로 재스탬프(위조 메타에 가려지지 않음)
|
||||
$this->assertSame('initTheme', $merged['initActions'][0]['handler']);
|
||||
$this->assertSame(['kind' => 'base', 'layout' => '_user_base'], $merged['initActions'][0]['__source']);
|
||||
// 자식 구간(위조 항목 포함)은 route/home 으로 재스탬프
|
||||
$this->assertSame(['kind' => 'route', 'layout' => 'home'], $merged['initActions'][1]['__source']);
|
||||
$this->assertSame(['kind' => 'route', 'layout' => 'home'], $merged['initActions'][2]['__source']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\Template;
|
||||
use App\Models\TemplateLayout;
|
||||
use App\Models\User;
|
||||
use App\Services\LayoutService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* InitialStateInheritedSaveTest — initLocal/initGlobal/initIsolated 상속 저장 라운드트립
|
||||
*
|
||||
*
|
||||
* 초기 상태(initLocal/initGlobal/initIsolated)는 computed 와 같은 부류로 shallow merge(자식 우선,
|
||||
* 상속 키 편집 가능·덮기)다. 핵심 사실(plan):
|
||||
* - 편집 응답 raw.initLocal 은 병합본, 자식 원본은 `__editor.original.initLocal` 보존.
|
||||
* - 저장 시 클라이언트가 자식 원본만 복원해 PUT → 미덮은 부모 키 제외, 덮은/고유 키만 영속.
|
||||
* - legacy `state` 키는 `initLocal` 의 deprecated alias — 자식이 `state` 만 보유하면 편집기가
|
||||
* `initLocal` 로 정규화해 PUT(state 키 제거)한다.
|
||||
* - 백엔드 `validated()` 는 `content.initLocal/initGlobal/initIsolated` 를 `['nullable','array']`
|
||||
* 로 통째 보존하므로 하위 키가 탈락하지 않는다(R9 부류 — 미명시 시 떨궈 격리 초기값 손실).
|
||||
* - 부모 레이아웃 행은 자식 저장에 영향받지 않고, 재로드 시 부모+자식이 다시 병합된다.
|
||||
*/
|
||||
class InitialStateInheritedSaveTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $adminUser;
|
||||
|
||||
private Template $template;
|
||||
|
||||
private string $token;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->adminUser = $this->createAdminUser(['core.templates.read', 'core.templates.layouts.edit']);
|
||||
$this->token = $this->adminUser->createToken('test-token')->plainTextToken;
|
||||
$this->template = Template::factory()->create();
|
||||
}
|
||||
|
||||
private function createAdminUser(array $permissions = []): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$permissionIds = [];
|
||||
foreach ($permissions as $identifier) {
|
||||
$permission = Permission::firstOrCreate(
|
||||
['identifier' => $identifier],
|
||||
[
|
||||
'name' => json_encode(['ko' => $identifier, 'en' => $identifier]),
|
||||
'description' => json_encode(['ko' => $identifier, 'en' => $identifier]),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
]
|
||||
);
|
||||
$permissionIds[] = $permission->id;
|
||||
}
|
||||
$adminRole = Role::firstOrCreate(
|
||||
['identifier' => 'admin'],
|
||||
[
|
||||
'name' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'is_system' => true,
|
||||
'priority' => 0,
|
||||
]
|
||||
);
|
||||
$adminRole->permissions()->syncWithoutDetaching($permissionIds);
|
||||
$user->roles()->syncWithoutDetaching([$adminRole->id]);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
private function authRequest()
|
||||
{
|
||||
return $this->withHeaders(['Authorization' => 'Bearer '.$this->token, 'Accept' => 'application/json']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 부모(base) 레이아웃 생성 — 슬롯 + 초기 상태 키 보유.
|
||||
*
|
||||
* @param array<string, mixed> $initialState initLocal/initGlobal/initIsolated 키 포함
|
||||
*/
|
||||
private function makeParent(array $initialState): TemplateLayout
|
||||
{
|
||||
return TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => '_user_base',
|
||||
'content' => array_merge([
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => '_user_base',
|
||||
'components' => [
|
||||
['id' => 'shell', 'name' => 'Div', 'type' => 'basic', 'props' => [], 'children' => [
|
||||
['id' => 'content_slot', 'name' => 'Div', 'type' => 'basic', 'slot' => 'content', 'props' => []],
|
||||
]],
|
||||
],
|
||||
'data_sources' => [],
|
||||
], $initialState),
|
||||
'extends' => null,
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 자식 레이아웃 생성 — 부모를 extends, 초기 상태 키 보유.
|
||||
*
|
||||
* @param array<string, mixed> $initialState
|
||||
*/
|
||||
private function makeChild(array $initialState): TemplateLayout
|
||||
{
|
||||
return TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'home',
|
||||
'content' => array_merge([
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'home',
|
||||
'extends' => '_user_base',
|
||||
'slots' => ['content' => [['id' => 'root', 'name' => 'Div', 'type' => 'basic', 'props' => []]]],
|
||||
'data_sources' => [],
|
||||
], $initialState),
|
||||
'extends' => '_user_base',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 자식 content PUT 후 갱신된 DB content 반환.
|
||||
*
|
||||
* @param array<string, mixed> $childInitialState
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function putChild(TemplateLayout $child, array $childInitialState): array
|
||||
{
|
||||
$content = array_merge([
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'home',
|
||||
'extends' => '_user_base',
|
||||
'slots' => ['content' => [['id' => 'root', 'name' => 'Div', 'type' => 'basic', 'props' => []]]],
|
||||
'data_sources' => [],
|
||||
], $childInitialState);
|
||||
|
||||
$response = $this->authRequest()->putJson(
|
||||
"/api/admin/templates/{$this->template->identifier}/layouts/{$child->name}",
|
||||
['expected_lock_version' => (int) $child->lock_version, 'content' => $content],
|
||||
);
|
||||
$response->assertStatus(200);
|
||||
$child->refresh();
|
||||
|
||||
return $child->content;
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_persists_only_child_init_local_and_strips_inherited(): void
|
||||
{
|
||||
// ① 자식 [초기상태] 편집 후 PUT → 자식 initLocal 만 (부모 상속분 strip)
|
||||
// ③ 미덮은 부모 키 PUT 제외
|
||||
$this->makeParent(['initLocal' => ['theme' => 'light', 'perPage' => 20]]);
|
||||
$child = $this->makeChild(['initLocal' => ['keyword' => 'g7']]);
|
||||
|
||||
$stored = $this->putChild($child, ['initLocal' => ['keyword' => 'g7']]);
|
||||
|
||||
$this->assertArrayHasKey('initLocal', $stored);
|
||||
$this->assertSame(['keyword' => 'g7'], $stored['initLocal'], '자식 고유 키만 영속');
|
||||
$this->assertArrayNotHasKey('theme', $stored['initLocal'], '미덮은 부모 키 제외');
|
||||
$this->assertArrayNotHasKey('perPage', $stored['initLocal']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_persists_overridden_inherited_key_with_child_value(): void
|
||||
{
|
||||
// ② 상속 키 덮은 경우 그 키는 자식 값으로 PUT(덮기 영속)
|
||||
$this->makeParent(['initLocal' => ['perPage' => 20]]);
|
||||
$child = $this->makeChild(['initLocal' => ['perPage' => 50]]);
|
||||
|
||||
$stored = $this->putChild($child, ['initLocal' => ['perPage' => 50]]);
|
||||
|
||||
$this->assertSame(50, $stored['initLocal']['perPage'], '덮은 상속 키는 자식 값으로 영속');
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_migrates_legacy_state_to_init_local_on_save(): void
|
||||
{
|
||||
// ④ legacy state→initLocal 이관 PUT(state 키 제거)
|
||||
// 자식이 legacy `state` 만 보유했다가 편집기가 initLocal 로 정규화해 저장하는 시나리오.
|
||||
$this->makeParent(['initLocal' => ['theme' => 'light']]);
|
||||
$child = $this->makeChild(['state' => ['draft' => 'memo']]);
|
||||
|
||||
// 정규화 후 PUT — state 제거 + initLocal 로 이관
|
||||
$stored = $this->putChild($child, ['initLocal' => ['draft' => 'memo']]);
|
||||
|
||||
$this->assertArrayHasKey('initLocal', $stored);
|
||||
$this->assertSame(['draft' => 'memo'], $stored['initLocal']);
|
||||
$this->assertArrayNotHasKey('state', $stored, 'legacy state 키는 저장 후 제거');
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_preserves_nested_subkeys_across_init_buckets(): void
|
||||
{
|
||||
// ⑤ initLocal/initGlobal/initIsolated 하위 키 validated() 미탈락(R9 부류)
|
||||
$this->makeParent([]);
|
||||
$child = $this->makeChild([]);
|
||||
|
||||
$childState = [
|
||||
'initLocal' => ['filter' => ['status' => 'active', 'page' => 1], 'keyword' => 'g7'],
|
||||
'initGlobal' => ['cartCount' => 0, 'theme' => 'dark'],
|
||||
'initIsolated' => ['sliderState' => ['idx' => 0], 'wizard' => ['step' => 1]],
|
||||
];
|
||||
|
||||
$stored = $this->putChild($child, $childState);
|
||||
|
||||
// 하위 키가 통째 보존되어야 함(R9 — 미명시 시 떨궈 격리 초기값 손실)
|
||||
$this->assertSame(['status' => 'active', 'page' => 1], $stored['initLocal']['filter']);
|
||||
$this->assertSame('g7', $stored['initLocal']['keyword']);
|
||||
$this->assertSame(0, $stored['initGlobal']['cartCount']);
|
||||
$this->assertSame('dark', $stored['initGlobal']['theme']);
|
||||
$this->assertSame(['idx' => 0], $stored['initIsolated']['sliderState']);
|
||||
$this->assertSame(['step' => 1], $stored['initIsolated']['wizard']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_leaves_parent_row_unchanged_when_child_is_saved(): void
|
||||
{
|
||||
// ⑥ 부모 레이아웃 행 불변
|
||||
$parent = $this->makeParent(['initLocal' => ['theme' => 'light', 'perPage' => 20]]);
|
||||
$child = $this->makeChild(['initLocal' => ['perPage' => 50]]);
|
||||
|
||||
$this->putChild($child, ['initLocal' => ['perPage' => 50]]);
|
||||
|
||||
$parent->refresh();
|
||||
$this->assertSame(['theme' => 'light', 'perPage' => 20], $parent->content['initLocal'], '부모 행 불변');
|
||||
$this->assertSame(0, (int) $parent->lock_version);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_documents_empty_string_initial_value_becomes_null_on_save(): void
|
||||
{
|
||||
// 코어 동작 가드 — Laravel 글로벌 미들웨어 ConvertEmptyStringsToNull 이 요청 본문의 빈
|
||||
// 문자열을 검증 전에 null 로 변환한다. 따라서 편집기가 빈 텍스트 입력칸을 `''` 로 시드해
|
||||
// PUT 해도 저장된 initLocal 값은 null 이 된다(레이아웃 content 전 저장 경로 공통).
|
||||
// 본 작업이 도입한 동작이 아니라 프레임워크 전역 동작이며, 런타임 `_local` 주입에서
|
||||
// null 과 '' 는 동등(빈 값)하게 취급되므로 폼 자동바인딩에 영향이 없다.
|
||||
$this->makeParent([]);
|
||||
$child = $this->makeChild([]);
|
||||
|
||||
$stored = $this->putChild($child, ['initLocal' => ['keyword' => '', 'tag' => 'x']]);
|
||||
|
||||
$this->assertNull($stored['initLocal']['keyword'], '빈 문자열 초기값은 저장 시 null 로 변환됨(프레임워크 전역 동작)');
|
||||
$this->assertSame('x', $stored['initLocal']['tag'], '비-빈 값은 그대로 보존');
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_remerges_parent_and_child_on_reload(): void
|
||||
{
|
||||
// ⑦ 재로드 시 부모+자식 재병합(shallow merge 자식 우선)
|
||||
$this->makeParent([
|
||||
'initLocal' => ['theme' => 'light', 'perPage' => 20],
|
||||
'initGlobal' => ['cartCount' => 0],
|
||||
]);
|
||||
$child = $this->makeChild(['initLocal' => ['perPage' => 50, 'keyword' => 'g7']]);
|
||||
|
||||
$this->putChild($child, ['initLocal' => ['perPage' => 50, 'keyword' => 'g7']]);
|
||||
|
||||
// DB 자체에는 자식분만(부모 상속분 strip)
|
||||
$child->refresh();
|
||||
$this->assertSame(['perPage' => 50, 'keyword' => 'g7'], $child->content['initLocal']);
|
||||
|
||||
// 재로드(with_source_meta=1) — shallow merge: 자식 덮은 키 우선 + 미덮은 부모 키 보존
|
||||
$merged = app(LayoutService::class)->loadAndMergeLayout($this->template->id, 'home', true);
|
||||
|
||||
$this->assertSame('light', $merged['initLocal']['theme'], '미덮은 부모 키 보존');
|
||||
$this->assertSame(50, $merged['initLocal']['perPage'], '덮은 키는 자식 값');
|
||||
$this->assertSame('g7', $merged['initLocal']['keyword'], '자식 고유 키');
|
||||
$this->assertSame(0, $merged['initGlobal']['cartCount'], '부모 initGlobal 보존');
|
||||
|
||||
// 자식 원본은 __editor.original 에 자식분만 보존
|
||||
$this->assertSame(['perPage' => 50, 'keyword' => 'g7'], $merged['__editor']['original']['initLocal']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,578 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Models\LayoutExtension;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\Template;
|
||||
use App\Models\TemplateLayout;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 레이아웃 편집기 저장 흐름 — 낙관적 잠금
|
||||
*
|
||||
* 코드 편집기 ↔ 레이아웃 편집기 동시 저장 시 silent overwrite 방지를 위한
|
||||
* `lock_version` + `expected_lock_version` 흐름을 검증합니다.
|
||||
*
|
||||
* @see tests/scenarios/layout-optimistic-lock.yaml
|
||||
*/
|
||||
class LayoutControllerEditorSaveTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
private User $adminUser;
|
||||
|
||||
private User $normalUser;
|
||||
|
||||
private Template $template;
|
||||
|
||||
private string $token;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->adminUser = $this->createAdminUser([
|
||||
'core.templates.read',
|
||||
'core.templates.layouts.edit',
|
||||
]);
|
||||
$this->token = $this->adminUser->createToken('test-token')->plainTextToken;
|
||||
|
||||
$this->normalUser = User::factory()->create();
|
||||
$this->template = Template::factory()->create();
|
||||
}
|
||||
|
||||
private function createAdminUser(array $permissions = []): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$permissionIds = [];
|
||||
foreach ($permissions as $identifier) {
|
||||
$permission = Permission::firstOrCreate(
|
||||
['identifier' => $identifier],
|
||||
[
|
||||
'name' => json_encode(['ko' => $identifier, 'en' => $identifier]),
|
||||
'description' => json_encode(['ko' => $identifier, 'en' => $identifier]),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
]
|
||||
);
|
||||
$permissionIds[] = $permission->id;
|
||||
}
|
||||
|
||||
$adminRole = Role::firstOrCreate(
|
||||
['identifier' => 'admin'],
|
||||
[
|
||||
'name' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'is_system' => true,
|
||||
'priority' => 0,
|
||||
]
|
||||
);
|
||||
$adminRole->permissions()->syncWithoutDetaching($permissionIds);
|
||||
$user->roles()->syncWithoutDetaching([$adminRole->id]);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
private function authRequest()
|
||||
{
|
||||
return $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$this->token,
|
||||
'Accept' => 'application/json',
|
||||
]);
|
||||
}
|
||||
|
||||
private function makeLayout(int $lockVersion = 0): TemplateLayout
|
||||
{
|
||||
return TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'editor-target',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'editor-target',
|
||||
'endpoint' => '/api/admin/test',
|
||||
'components' => [],
|
||||
'data_sources' => [],
|
||||
],
|
||||
'lock_version' => $lockVersion,
|
||||
]);
|
||||
}
|
||||
|
||||
private function defaultUpdatePayload(int $expectedLockVersion): array
|
||||
{
|
||||
return [
|
||||
'expected_lock_version' => $expectedLockVersion,
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'editor-target',
|
||||
'endpoint' => '/api/admin/test',
|
||||
'components' => [
|
||||
[
|
||||
'id' => 'edited',
|
||||
'name' => 'Div',
|
||||
'type' => 'basic',
|
||||
'props' => ['className' => 'p-4'],
|
||||
],
|
||||
],
|
||||
'data_sources' => [],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_200_and_increments_lock_version_when_expected_matches(): void
|
||||
{
|
||||
$layout = $this->makeLayout(lockVersion: 0);
|
||||
|
||||
$response = $this->authRequest()->putJson(
|
||||
"/api/admin/templates/{$this->template->identifier}/layouts/{$layout->name}",
|
||||
$this->defaultUpdatePayload(expectedLockVersion: 0),
|
||||
);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertEquals(1, $response->json('data.lock_version'));
|
||||
|
||||
$layout->refresh();
|
||||
$this->assertEquals(1, $layout->lock_version);
|
||||
}
|
||||
|
||||
/**
|
||||
* (D13) — 편집기 색 모드 × 디바이스 스타일 편집은 node 에 `responsive` /
|
||||
* `if` (최상위) 키를 추가한다. ValidLayoutStructure 는 화이트리스트가 아니라 형식
|
||||
* 검증이므로 미언급 키를 거부하지 않고, content.components 는 'array' 규칙으로 통째
|
||||
* 보존된다(validated() drop 은 meta/seo 등 nested 명시 키에만 해당 — node 내부 아님).
|
||||
* 저장 → DB 재로드 시 responsive/if 가 그대로 보존됨을 가드한다(백엔드 코드 변경 없음).
|
||||
*/
|
||||
#[Test]
|
||||
public function it_preserves_node_responsive_and_if_overrides_on_save_and_reload(): void
|
||||
{
|
||||
$layout = $this->makeLayout(lockVersion: 0);
|
||||
|
||||
$payload = $this->defaultUpdatePayload(expectedLockVersion: 0);
|
||||
$payload['content']['components'] = [
|
||||
[
|
||||
'id' => 'scoped-node',
|
||||
'name' => 'Div',
|
||||
'type' => 'basic',
|
||||
'props' => ['className' => 'bg-white dark:bg-slate-800'],
|
||||
'if' => '{{ _global?.currentUser?.uuid }}',
|
||||
'responsive' => [
|
||||
'mobile' => [
|
||||
'props' => ['className' => 'block'],
|
||||
'if' => '{{ query?.tab === "m" }}',
|
||||
],
|
||||
'600-900' => [
|
||||
'props' => ['className' => 'flex'],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$response = $this->authRequest()->putJson(
|
||||
"/api/admin/templates/{$this->template->identifier}/layouts/{$layout->name}",
|
||||
$payload,
|
||||
);
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
// DB 재로드 — responsive/if 가 그대로 보존되어야 한다.
|
||||
$node = $layout->fresh()->content['components'][0];
|
||||
|
||||
$this->assertSame('{{ _global?.currentUser?.uuid }}', $node['if'], '최상위 if 보존');
|
||||
$this->assertArrayHasKey('responsive', $node, 'responsive 브랜치 보존');
|
||||
$this->assertSame('block', $node['responsive']['mobile']['props']['className']);
|
||||
$this->assertSame('{{ query?.tab === "m" }}', $node['responsive']['mobile']['if']);
|
||||
$this->assertSame('flex', $node['responsive']['600-900']['props']['className']);
|
||||
// 라이트/다크 공존 className 도 보존
|
||||
$this->assertSame('bg-white dark:bg-slate-800', $node['props']['className']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_409_when_expected_version_is_stale(): void
|
||||
{
|
||||
$layout = $this->makeLayout(lockVersion: 5);
|
||||
|
||||
$response = $this->authRequest()->putJson(
|
||||
"/api/admin/templates/{$this->template->identifier}/layouts/{$layout->name}",
|
||||
$this->defaultUpdatePayload(expectedLockVersion: 3),
|
||||
);
|
||||
|
||||
$response->assertStatus(409);
|
||||
$this->assertEquals('concurrent_modification', $response->json('errors.error'));
|
||||
$this->assertEquals(5, $response->json('errors.current_version'));
|
||||
$this->assertEquals(3, $response->json('errors.your_version'));
|
||||
|
||||
$layout->refresh();
|
||||
$this->assertEquals(5, $layout->lock_version, 'lock_version 은 충돌 시 증가하지 않아야 한다');
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_422_when_expected_lock_version_is_missing(): void
|
||||
{
|
||||
$layout = $this->makeLayout(lockVersion: 0);
|
||||
|
||||
$payload = $this->defaultUpdatePayload(expectedLockVersion: 0);
|
||||
unset($payload['expected_lock_version']);
|
||||
|
||||
$response = $this->authRequest()->putJson(
|
||||
"/api/admin/templates/{$this->template->identifier}/layouts/{$layout->name}",
|
||||
$payload,
|
||||
);
|
||||
|
||||
$response->assertStatus(422)
|
||||
->assertJsonValidationErrors(['expected_lock_version']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function concurrent_save_only_first_client_succeeds(): void
|
||||
{
|
||||
$layout = $this->makeLayout(lockVersion: 0);
|
||||
|
||||
// 두 클라이언트 모두 lock_version=0 를 로드한 상태
|
||||
$payloadA = $this->defaultUpdatePayload(expectedLockVersion: 0);
|
||||
$payloadA['content']['components'][0]['id'] = 'edit_by_A';
|
||||
|
||||
$payloadB = $this->defaultUpdatePayload(expectedLockVersion: 0);
|
||||
$payloadB['content']['components'][0]['id'] = 'edit_by_B';
|
||||
|
||||
// 첫 번째 저장 — 성공
|
||||
$responseA = $this->authRequest()->putJson(
|
||||
"/api/admin/templates/{$this->template->identifier}/layouts/{$layout->name}",
|
||||
$payloadA,
|
||||
);
|
||||
$responseA->assertStatus(200);
|
||||
|
||||
// 두 번째 저장 — 같은 expected=0 으로 시도, current=1 이므로 409
|
||||
$responseB = $this->authRequest()->putJson(
|
||||
"/api/admin/templates/{$this->template->identifier}/layouts/{$layout->name}",
|
||||
$payloadB,
|
||||
);
|
||||
$responseB->assertStatus(409);
|
||||
|
||||
$layout->refresh();
|
||||
$this->assertEquals(1, $layout->lock_version);
|
||||
// A 의 변경이 반영되어 있어야 한다
|
||||
$this->assertEquals('edit_by_A', $layout->content['components'][0]['id']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_exposes_lock_version_in_layout_resource(): void
|
||||
{
|
||||
$layout = $this->makeLayout(lockVersion: 7);
|
||||
|
||||
$response = $this->authRequest()->getJson(
|
||||
"/api/admin/templates/{$this->template->identifier}/layouts/{$layout->name}",
|
||||
);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertEquals(7, $response->json('data.lock_version'));
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// Phase 3 S5a-2 결함 I — 편집기 응답 메타 노드 마스킹 백엔드 2차 가드
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
#[Test]
|
||||
public function it_strips_base_and_extension_and_partial_nodes_from_payload(): void
|
||||
{
|
||||
$layout = $this->makeLayout(lockVersion: 0);
|
||||
|
||||
$payload = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'editor-target',
|
||||
'endpoint' => '/api/admin/test',
|
||||
// 편집기 응답이 그대로 전송된 케이스 — base/extension/partial 노드가 섞여 있음
|
||||
'components' => [
|
||||
[
|
||||
'id' => 'base-header',
|
||||
'name' => 'Div',
|
||||
'type' => 'basic',
|
||||
'_fromBase' => true,
|
||||
'__source' => ['kind' => 'base', 'layout' => '_base'],
|
||||
],
|
||||
[
|
||||
'id' => 'ext-banner',
|
||||
'name' => 'AdBanner',
|
||||
'type' => 'composite',
|
||||
'__source' => ['kind' => 'extension', 'extensionId' => 7],
|
||||
],
|
||||
[
|
||||
'id' => 'partial-fragment',
|
||||
'name' => 'Section',
|
||||
'type' => 'basic',
|
||||
'__source' => ['kind' => 'partial'],
|
||||
],
|
||||
[
|
||||
'id' => 'route-main',
|
||||
'name' => 'Main',
|
||||
'type' => 'basic',
|
||||
'__source' => ['kind' => 'route', 'layout' => 'editor-target'],
|
||||
],
|
||||
],
|
||||
'data_sources' => [],
|
||||
],
|
||||
];
|
||||
|
||||
$response = $this->authRequest()->putJson(
|
||||
"/api/admin/templates/{$this->template->identifier}/layouts/{$layout->name}",
|
||||
$payload,
|
||||
);
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
$layout->refresh();
|
||||
$components = $layout->content['components'];
|
||||
|
||||
// base / extension / partial 출처 노드 3건은 제거되어 1건만 남아야 한다
|
||||
$this->assertCount(1, $components, 'base/extension/partial 출처 노드는 저장 전에 제거되어야 한다');
|
||||
$this->assertEquals('route-main', $components[0]['id']);
|
||||
// 살아남은 route 노드의 __source 메타도 제거되어야 한다 (저장 형식 = 원본 형식)
|
||||
$this->assertArrayNotHasKey('__source', $components[0]);
|
||||
$this->assertArrayNotHasKey('_fromBase', $components[0]);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_strips_inherited_nodes_recursively_inside_route_children(): void
|
||||
{
|
||||
$layout = $this->makeLayout(lockVersion: 0);
|
||||
|
||||
$payload = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'editor-target',
|
||||
'endpoint' => '/api/admin/test',
|
||||
'components' => [
|
||||
[
|
||||
'id' => 'route-main',
|
||||
'name' => 'Main',
|
||||
'type' => 'basic',
|
||||
'__source' => ['kind' => 'route', 'layout' => 'editor-target'],
|
||||
'children' => [
|
||||
[
|
||||
'id' => 'keep-me',
|
||||
'name' => 'P',
|
||||
'type' => 'basic',
|
||||
],
|
||||
[
|
||||
'id' => 'inherited-from-base',
|
||||
'name' => 'Header',
|
||||
'type' => 'basic',
|
||||
'_fromBase' => true,
|
||||
],
|
||||
[
|
||||
'id' => 'injected-from-ext',
|
||||
'name' => 'AdBanner',
|
||||
'type' => 'composite',
|
||||
'__source' => ['kind' => 'extension', 'extensionId' => 3],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
'data_sources' => [],
|
||||
],
|
||||
];
|
||||
|
||||
$response = $this->authRequest()->putJson(
|
||||
"/api/admin/templates/{$this->template->identifier}/layouts/{$layout->name}",
|
||||
$payload,
|
||||
);
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
$layout->refresh();
|
||||
$components = $layout->content['components'];
|
||||
$this->assertCount(1, $components);
|
||||
$children = $components[0]['children'];
|
||||
$this->assertCount(1, $children, 'route 노드 안의 base/extension 자손도 재귀 제거되어야 한다');
|
||||
$this->assertEquals('keep-me', $children[0]['id']);
|
||||
$this->assertArrayNotHasKey('_fromBase', $children[0]);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_uses_editor_original_container_when_present_for_extends_child(): void
|
||||
{
|
||||
// extends 자식 레이아웃을 만들고, 편집 모드 응답이 __editor.original 으로 자식 원본을 동봉한 케이스.
|
||||
// 백엔드 2차 가드가 그 원본을 SSoT 로 사용해 저장한다.
|
||||
$baseLayout = TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => '_base',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => '_base',
|
||||
'endpoint' => '/api/admin/test',
|
||||
'components' => [
|
||||
['type' => 'basic', 'name' => 'Slot', 'slot' => 'main'],
|
||||
],
|
||||
],
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
$childLayout = TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'child-page',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'child-page',
|
||||
'extends' => '_base',
|
||||
'slots' => [
|
||||
'main' => [
|
||||
['type' => 'basic', 'name' => 'OriginalContent'],
|
||||
],
|
||||
],
|
||||
],
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
// 편집기 응답 시뮬레이션 — 머지된 components + __editor.original 컨테이너 동봉
|
||||
$payload = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'child-page',
|
||||
'components' => [
|
||||
[
|
||||
'type' => 'basic',
|
||||
'name' => 'Slot',
|
||||
'_fromBase' => true,
|
||||
'__source' => ['kind' => 'base', 'layout' => '_base'],
|
||||
'children' => [
|
||||
[
|
||||
'type' => 'basic',
|
||||
'name' => 'EditedContent',
|
||||
'__source' => ['kind' => 'route', 'layout' => 'child-page'],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
'lock_version' => 0,
|
||||
'__editor' => [
|
||||
'original' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'child-page',
|
||||
'extends' => '_base',
|
||||
'slots' => [
|
||||
'main' => [
|
||||
['type' => 'basic', 'name' => 'EditedContent'],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$response = $this->authRequest()->putJson(
|
||||
"/api/admin/templates/{$this->template->identifier}/layouts/{$childLayout->name}",
|
||||
$payload,
|
||||
);
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
$childLayout->refresh();
|
||||
// 자식 레이아웃 원본 형식으로 저장되어야 한다 — extends + slots
|
||||
$this->assertEquals('_base', $childLayout->content['extends']);
|
||||
$this->assertArrayHasKey('slots', $childLayout->content);
|
||||
$this->assertEquals('EditedContent', $childLayout->content['slots']['main'][0]['name']);
|
||||
// 머지된 components 는 자식에 박히지 않아야 한다
|
||||
$this->assertArrayNotHasKey('components', $childLayout->content);
|
||||
// 응답 전용 메타 모두 제거
|
||||
$this->assertArrayNotHasKey('lock_version', $childLayout->content);
|
||||
$this->assertArrayNotHasKey('__editor', $childLayout->content);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_drops_response_only_lock_version_meta_from_content(): void
|
||||
{
|
||||
$layout = $this->makeLayout(lockVersion: 0);
|
||||
|
||||
$payload = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'editor-target',
|
||||
'endpoint' => '/api/admin/test',
|
||||
// 응답 전용 메타 — 페이로드에 잘못 포함된 케이스
|
||||
'lock_version' => 42,
|
||||
'components' => [
|
||||
[
|
||||
'id' => 'route-main',
|
||||
'name' => 'Main',
|
||||
'type' => 'basic',
|
||||
],
|
||||
],
|
||||
'data_sources' => [],
|
||||
],
|
||||
];
|
||||
|
||||
$response = $this->authRequest()->putJson(
|
||||
"/api/admin/templates/{$this->template->identifier}/layouts/{$layout->name}",
|
||||
$payload,
|
||||
);
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
$layout->refresh();
|
||||
// content 안의 lock_version 메타는 저장되지 않아야 한다
|
||||
$this->assertArrayNotHasKey('lock_version', $layout->content);
|
||||
// 실제 lock_version 은 DB 컬럼 기반으로 1 증가
|
||||
$this->assertEquals(1, $layout->lock_version);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function layout_extension_update_shares_same_concurrency_guard(): void
|
||||
{
|
||||
$extension = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => 'extension_point',
|
||||
'target_name' => 'header',
|
||||
'source_type' => 'template',
|
||||
'source_identifier' => $this->template->identifier,
|
||||
'content' => [
|
||||
'extension_point' => 'header',
|
||||
'components' => [],
|
||||
],
|
||||
'lock_version' => 4,
|
||||
]);
|
||||
|
||||
// stale expected → 409
|
||||
$stale = $this->authRequest()->putJson(
|
||||
"/api/admin/templates/{$this->template->identifier}/layout-extensions/{$extension->id}",
|
||||
[
|
||||
'expected_lock_version' => 2,
|
||||
'content' => [
|
||||
'extension_point' => 'header',
|
||||
'components' => [['type' => 'basic', 'name' => 'Span']],
|
||||
],
|
||||
],
|
||||
);
|
||||
$stale->assertStatus(409);
|
||||
$this->assertEquals('concurrent_modification', $stale->json('errors.error'));
|
||||
|
||||
// match → 200, lock_version 증가
|
||||
$ok = $this->authRequest()->putJson(
|
||||
"/api/admin/templates/{$this->template->identifier}/layout-extensions/{$extension->id}",
|
||||
[
|
||||
'expected_lock_version' => 4,
|
||||
'content' => [
|
||||
'extension_point' => 'header',
|
||||
'components' => [['type' => 'basic', 'name' => 'Span']],
|
||||
],
|
||||
],
|
||||
);
|
||||
$ok->assertStatus(200);
|
||||
|
||||
$extension->refresh();
|
||||
$this->assertEquals(5, $extension->lock_version);
|
||||
}
|
||||
}
|
||||
@@ -23,9 +23,22 @@ class LayoutControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 레이아웃/템플릿 요청 경로가 GDPR 정책 테이블을 조회하므로
|
||||
* 해당 플러그인 마이그레이션을 테스트 DB 에 포함시킨다.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
private User $adminUser;
|
||||
|
||||
private User $normalUser;
|
||||
|
||||
private Template $template;
|
||||
|
||||
private string $token;
|
||||
|
||||
protected function setUp(): void
|
||||
@@ -89,7 +102,7 @@ class LayoutControllerTest extends TestCase
|
||||
'description' => json_encode(['ko' => '시스템 관리자', 'en' => 'System Administrator']),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'type' => 'admin',
|
||||
'type' => 'admin',
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
@@ -146,6 +159,7 @@ class LayoutControllerTest extends TestCase
|
||||
'template_id',
|
||||
'name',
|
||||
'endpoint',
|
||||
'route_path',
|
||||
'components',
|
||||
'data_sources',
|
||||
'metadata',
|
||||
@@ -156,6 +170,30 @@ class LayoutControllerTest extends TestCase
|
||||
$this->assertCount(3, $response->json('data'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 목록 응답에 route_path 필드가 포함된다 (코드 편집기 ?route= 동기화용).
|
||||
*
|
||||
* 팩토리 템플릿은 실제 routes.json 이 없어 매핑이 비므로 route_path 는 null 이다.
|
||||
* 실제 routes.json 기반 매핑 검증은 TemplateService 단위 테스트가 담당.
|
||||
*/
|
||||
public function test_layout_list_includes_route_path_field(): void
|
||||
{
|
||||
// Arrange
|
||||
TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'home',
|
||||
]);
|
||||
|
||||
// Act
|
||||
$response = $this->authRequest()
|
||||
->getJson("/api/admin/templates/{$this->template->identifier}/layouts");
|
||||
|
||||
// Assert
|
||||
$response->assertStatus(200);
|
||||
$this->assertArrayHasKey('route_path', $response->json('data.0'));
|
||||
$this->assertNull($response->json('data.0.route_path'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 인증되지 않은 사용자 접근 거부
|
||||
*/
|
||||
@@ -307,6 +345,7 @@ class LayoutControllerTest extends TestCase
|
||||
]);
|
||||
|
||||
$updateData = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'test-layout',
|
||||
@@ -343,6 +382,10 @@ class LayoutControllerTest extends TestCase
|
||||
'id' => $layout->id,
|
||||
'name' => 'test-layout',
|
||||
]);
|
||||
|
||||
// 현재(최신) 버전 번호 동봉.
|
||||
// 첫 저장은 baseline(v1) + 이번 저장본(v2) 두 버전을 적재하므로 current_version=2.
|
||||
$this->assertSame(2, $response->json('data.current_version'));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -356,6 +399,7 @@ class LayoutControllerTest extends TestCase
|
||||
]);
|
||||
|
||||
$invalidData = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'test',
|
||||
@@ -381,6 +425,7 @@ class LayoutControllerTest extends TestCase
|
||||
{
|
||||
// Arrange
|
||||
$updateData = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'nonexistent',
|
||||
@@ -417,6 +462,7 @@ class LayoutControllerTest extends TestCase
|
||||
]);
|
||||
|
||||
$updateData = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'test',
|
||||
@@ -492,6 +538,7 @@ class LayoutControllerTest extends TestCase
|
||||
'data_sources',
|
||||
'metadata',
|
||||
'changes_summary',
|
||||
'created_by_name',
|
||||
'created_at',
|
||||
],
|
||||
],
|
||||
@@ -500,6 +547,59 @@ class LayoutControllerTest extends TestCase
|
||||
$this->assertCount(3, $response->json('data'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 버전 목록에 저장자 이름(created_by_name)이 노출되되 created_by ID 는 제외
|
||||
*
|
||||
* @effects version_resource_exposes_creator_name_not_id, version_row_shows_creator_name_or_unknown_fallback
|
||||
*/
|
||||
public function test_layout_versions_expose_creator_name_not_id(): void
|
||||
{
|
||||
// Arrange — 저장자 User 와 버전 생성
|
||||
$author = User::factory()->create(['name' => '버전작성자']);
|
||||
$layout = TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'authored-layout',
|
||||
]);
|
||||
TemplateLayoutVersion::factory()->create([
|
||||
'layout_id' => $layout->id,
|
||||
'created_by' => $author->id,
|
||||
]);
|
||||
|
||||
// Act
|
||||
$response = $this->authRequest()
|
||||
->getJson("/api/admin/templates/{$this->template->identifier}/layouts/{$layout->name}/versions");
|
||||
|
||||
// Assert — 이름은 노출, created_by ID 는 응답에 없음
|
||||
$response->assertStatus(200);
|
||||
$first = $response->json('data.0');
|
||||
$this->assertSame('버전작성자', $first['created_by_name']);
|
||||
$this->assertArrayNotHasKey('created_by', $first);
|
||||
}
|
||||
|
||||
/**
|
||||
* 탈퇴/미상 저장자(created_by null)는 created_by_name 이 null
|
||||
*/
|
||||
public function test_layout_versions_creator_name_null_when_no_creator(): void
|
||||
{
|
||||
// Arrange — created_by null 버전
|
||||
$layout = TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'anon-layout',
|
||||
]);
|
||||
TemplateLayoutVersion::factory()->create([
|
||||
'layout_id' => $layout->id,
|
||||
'created_by' => null,
|
||||
]);
|
||||
|
||||
// Act
|
||||
$response = $this->authRequest()
|
||||
->getJson("/api/admin/templates/{$this->template->identifier}/layouts/{$layout->name}/versions");
|
||||
|
||||
// Assert
|
||||
$response->assertStatus(200);
|
||||
$this->assertNull($response->json('data.0.created_by_name'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 존재하지 않는 레이아웃의 버전 조회 시 404 응답
|
||||
*/
|
||||
@@ -550,6 +650,8 @@ class LayoutControllerTest extends TestCase
|
||||
'components' => ['component' => 'test'],
|
||||
'data_sources' => [],
|
||||
'metadata' => ['key' => 'value'],
|
||||
// extends 기반 레이아웃처럼 slots 에 실제 컴포넌트가 있는 경우 — 분해 키엔 안 잡힘.
|
||||
'slots' => ['content' => [['name' => 'Div']]],
|
||||
],
|
||||
'changes_summary' => ['updated' => 'components'],
|
||||
]);
|
||||
@@ -572,6 +674,9 @@ class LayoutControllerTest extends TestCase
|
||||
'data_sources',
|
||||
'metadata',
|
||||
'changes_summary',
|
||||
'created_by_name',
|
||||
// 단건 조회는 content 원본 전체(full_content) 노출 — 버전 비교 diff 용
|
||||
'full_content',
|
||||
'created_at',
|
||||
],
|
||||
])
|
||||
@@ -580,6 +685,35 @@ class LayoutControllerTest extends TestCase
|
||||
]);
|
||||
|
||||
$this->assertEquals(2, $response->json('data.version'));
|
||||
// full_content 는 slots 등 분해되지 않는 키까지 원본 그대로 보존해야 한다 (diff 정확성).
|
||||
$this->assertSame(
|
||||
[['name' => 'Div']],
|
||||
$response->json('data.full_content.slots.content')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 버전 목록(index)에는 full_content 를 포함하지 않는다 (페이로드 비대화 회피)
|
||||
*/
|
||||
public function test_version_index_excludes_full_content(): void
|
||||
{
|
||||
// Arrange
|
||||
$layout = TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'index-no-full',
|
||||
]);
|
||||
TemplateLayoutVersion::factory()->create([
|
||||
'layout_id' => $layout->id,
|
||||
'content' => ['slots' => ['content' => [['name' => 'Div']]]],
|
||||
]);
|
||||
|
||||
// Act
|
||||
$response = $this->authRequest()
|
||||
->getJson("/api/admin/templates/{$this->template->identifier}/layouts/{$layout->name}/versions");
|
||||
|
||||
// Assert — 목록 항목에 full_content 키 없음
|
||||
$response->assertStatus(200);
|
||||
$this->assertArrayNotHasKey('full_content', $response->json('data.0'));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -808,15 +942,19 @@ class LayoutControllerTest extends TestCase
|
||||
// Assert
|
||||
$response->assertStatus(200);
|
||||
|
||||
// 버전 3이 생성되었는지 확인 (복원 전의 content를 저장)
|
||||
// 버전 3이 생성되었는지 확인 (복원 결과 = 복원된 content 를 저장)
|
||||
$newVersion = TemplateLayoutVersion::where('layout_id', $layout->id)
|
||||
->where('version', 3)
|
||||
->first();
|
||||
|
||||
$this->assertNotNull($newVersion);
|
||||
// 새 버전은 복원 전의 content (v3)를 저장하여 히스토리 보존
|
||||
$this->assertEquals('/api/v3', $newVersion->content['endpoint']);
|
||||
$this->assertEquals(['version' => '3'], $newVersion->content['components']);
|
||||
// 새 버전은 복원된 content (v1)를 담는다 — "현재 상태가 v1 으로 돌아갔음"을 표현.
|
||||
// (종전엔 복원 전 content 를 저장해 복원인데 "추가"로 표기되던 결함 수정.)
|
||||
$this->assertEquals('/api/v1', $newVersion->content['endpoint']);
|
||||
$this->assertEquals(['version' => '1'], $newVersion->content['components']);
|
||||
|
||||
// changes_summary 는 복원 직전(레이아웃의 v3 content) 대비 변경 — 복원으로 줄거나 바뀐다.
|
||||
$this->assertNotNull($newVersion->changes_summary);
|
||||
|
||||
// 레이아웃이 v1으로 복원되었는지 확인
|
||||
$layout->refresh();
|
||||
@@ -885,6 +1023,7 @@ class LayoutControllerTest extends TestCase
|
||||
$this->assertEquals(0, $initialVersionCount);
|
||||
|
||||
$updateData = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'test-layout',
|
||||
@@ -943,9 +1082,10 @@ class LayoutControllerTest extends TestCase
|
||||
],
|
||||
]);
|
||||
|
||||
// Act - 첫 번째 업데이트
|
||||
// Act - 첫 번째 업데이트 (factory 초기 lock_version=0)
|
||||
$response1 = $this->authRequest()
|
||||
->putJson("/api/admin/templates/{$userTemplate->identifier}/layouts/{$layout->name}", [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'test-layout',
|
||||
@@ -957,9 +1097,10 @@ class LayoutControllerTest extends TestCase
|
||||
]);
|
||||
$response1->assertStatus(200);
|
||||
|
||||
// Act - 두 번째 업데이트
|
||||
// Act - 두 번째 업데이트 (첫 저장으로 lock_version=1 로 증가)
|
||||
$response2 = $this->authRequest()
|
||||
->putJson("/api/admin/templates/{$userTemplate->identifier}/layouts/{$layout->name}", [
|
||||
'expected_lock_version' => 1,
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'test-layout',
|
||||
@@ -976,12 +1117,12 @@ class LayoutControllerTest extends TestCase
|
||||
->orderBy('version', 'asc')
|
||||
->get();
|
||||
|
||||
// 첫 번째 업데이트: 2개 버전 (v1: old, v2: new)
|
||||
// 두 번째 업데이트: 2개 버전 추가 (v3: old, v4: new)
|
||||
// 총 4개 버전
|
||||
$this->assertCount(4, $versions);
|
||||
// 첫 번째 업데이트: baseline(v1: initial) + 수정본(v2: first_update)
|
||||
// 두 번째 업데이트: 수정본(v3: second_update) — baseline 은 이미 있어 추가 안 함
|
||||
// 총 3개 버전 (PUT 당 1건 + 최초 1회 baseline)
|
||||
$this->assertCount(3, $versions);
|
||||
|
||||
// 버전 1: 최초 content
|
||||
// 버전 1: 수정 전 원본 baseline (initial)
|
||||
$this->assertEquals(1, $versions[0]->version);
|
||||
$this->assertEquals('initial', $versions[0]->content['metadata']['step']);
|
||||
|
||||
@@ -989,13 +1130,9 @@ class LayoutControllerTest extends TestCase
|
||||
$this->assertEquals(2, $versions[1]->version);
|
||||
$this->assertEquals('first_update', $versions[1]->content['metadata']['step']);
|
||||
|
||||
// 버전 3: 두 번째 업데이트 전 content (first_update)
|
||||
// 버전 3: 두 번째 업데이트된 content
|
||||
$this->assertEquals(3, $versions[2]->version);
|
||||
$this->assertEquals('first_update', $versions[2]->content['metadata']['step']);
|
||||
|
||||
// 버전 4: 두 번째 업데이트된 content
|
||||
$this->assertEquals(4, $versions[3]->version);
|
||||
$this->assertEquals('second_update', $versions[3]->content['metadata']['step']);
|
||||
$this->assertEquals('second_update', $versions[2]->content['metadata']['step']);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1024,6 +1161,7 @@ class LayoutControllerTest extends TestCase
|
||||
]);
|
||||
|
||||
$updateData = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'test-layout',
|
||||
@@ -1071,6 +1209,7 @@ class LayoutControllerTest extends TestCase
|
||||
]);
|
||||
|
||||
$updateData = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'test-layout',
|
||||
@@ -1120,6 +1259,238 @@ class LayoutControllerTest extends TestCase
|
||||
$this->assertEquals('setState', $layout->content['init_actions'][0]['handler']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 업데이트 시 meta 하위의 비-SEO 메타 키 보존 (guest_only / is_error_layout / error_code / keywords)
|
||||
*
|
||||
* validated() 는 rules() 에 명시된 키만 반환하므로, content.meta 가 'array' 규칙이고
|
||||
* 하위에 title/description 등 일부 키만 명시돼 있으면 명시되지 않은 meta 하위 키는 저장 시
|
||||
* 누락된다. guest_only 가 사라지면 비로그인 전용 레이아웃(로그인/회원가입/비번찾기/재설정)이
|
||||
* 편집기 저장 후 reload 시 "이미 로그인" 가드가 오발화한다.
|
||||
*/
|
||||
public function test_update_layout_preserves_non_seo_meta_keys(): void
|
||||
{
|
||||
// Arrange
|
||||
$layout = TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'auth/forgot_password',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'auth/forgot_password',
|
||||
'meta' => [
|
||||
'title' => '$t:auth.forgot_password.title',
|
||||
'guest_only' => true,
|
||||
],
|
||||
'endpoint' => '/api/test',
|
||||
'components' => [['id' => 'root', 'type' => 'layout', 'name' => 'Container']],
|
||||
'data_sources' => [],
|
||||
],
|
||||
]);
|
||||
|
||||
$updateData = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'auth/forgot_password',
|
||||
'meta' => [
|
||||
'title' => '$t:auth.forgot_password.title',
|
||||
'guest_only' => true,
|
||||
'is_error_layout' => true,
|
||||
'error_code' => 404,
|
||||
'keywords' => '{{page?.data?.keywords ?? \'\'}}',
|
||||
],
|
||||
'endpoint' => '/api/admin/test',
|
||||
'components' => [['id' => 'root', 'type' => 'layout', 'name' => 'Container']],
|
||||
'data_sources' => [],
|
||||
],
|
||||
];
|
||||
|
||||
// Act
|
||||
$response = $this->authRequest()
|
||||
->putJson("/api/admin/templates/{$this->template->identifier}/layouts/auth/forgot_password", $updateData);
|
||||
|
||||
// Assert
|
||||
$response->assertStatus(200);
|
||||
|
||||
$layout->refresh();
|
||||
$this->assertTrue($layout->content['meta']['guest_only'], 'guest_only 가 저장 시 유실됨');
|
||||
$this->assertTrue($layout->content['meta']['is_error_layout'], 'is_error_layout 가 저장 시 유실됨');
|
||||
$this->assertEquals(404, $layout->content['meta']['error_code'], 'error_code 가 저장 시 유실됨');
|
||||
$this->assertEquals('{{page?.data?.keywords ?? \'\'}}', $layout->content['meta']['keywords'], 'keywords 가 저장 시 유실됨');
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 업데이트 시 meta.seo 하위의 비표준 키 보존 (vars / page_type / extensions / toggle_setting)
|
||||
*
|
||||
* content.meta.seo 도 'array' 규칙이고 enabled/data_sources/priority 등 일부 하위 키만
|
||||
* 명시돼 있어, 명시되지 않은 seo 하위 키(SEO 페이지 생성기가 소비하는 vars/page_type 등)가
|
||||
* 저장 시 누락된다.
|
||||
*/
|
||||
public function test_update_layout_preserves_non_standard_seo_keys(): void
|
||||
{
|
||||
// Arrange
|
||||
$layout = TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'board/index',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'board/index',
|
||||
'endpoint' => '/api/test',
|
||||
'components' => [['id' => 'root', 'type' => 'layout', 'name' => 'Container']],
|
||||
'data_sources' => [],
|
||||
],
|
||||
]);
|
||||
|
||||
$updateData = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'board/index',
|
||||
'meta' => [
|
||||
'title' => 'Board',
|
||||
'seo' => [
|
||||
'enabled' => true,
|
||||
'page_type' => 'board',
|
||||
'toggle_setting' => '$module_settings:sirsoft-board:seo.seo_board',
|
||||
'vars' => [
|
||||
'site_name' => '$core_settings:general.site_name',
|
||||
'board_name' => '{{posts.data.board.name ?? \'\'}}',
|
||||
],
|
||||
'extensions' => [
|
||||
['type' => 'module', 'id' => 'sirsoft-board'],
|
||||
],
|
||||
],
|
||||
],
|
||||
'endpoint' => '/api/admin/test',
|
||||
'components' => [['id' => 'root', 'type' => 'layout', 'name' => 'Container']],
|
||||
'data_sources' => [],
|
||||
],
|
||||
];
|
||||
|
||||
// Act
|
||||
$response = $this->authRequest()
|
||||
->putJson("/api/admin/templates/{$this->template->identifier}/layouts/board/index", $updateData);
|
||||
|
||||
// Assert
|
||||
$response->assertStatus(200);
|
||||
|
||||
$layout->refresh();
|
||||
$seo = $layout->content['meta']['seo'];
|
||||
$this->assertEquals('board', $seo['page_type'], 'seo.page_type 가 저장 시 유실됨');
|
||||
$this->assertEquals('$module_settings:sirsoft-board:seo.seo_board', $seo['toggle_setting'], 'seo.toggle_setting 가 저장 시 유실됨');
|
||||
$this->assertArrayHasKey('vars', $seo, 'seo.vars 가 저장 시 유실됨');
|
||||
$this->assertEquals('$core_settings:general.site_name', $seo['vars']['site_name']);
|
||||
$this->assertArrayHasKey('extensions', $seo, 'seo.extensions 가 저장 시 유실됨');
|
||||
$this->assertEquals('sirsoft-board', $seo['extensions'][0]['id']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 업데이트 시 content 직속 상태/액션 키 보존 (initLocal / initGlobal / errorHandling / global_state / actions)
|
||||
*
|
||||
* 이 키들은 엔진이 상태 초기화/에러 처리/액션에 소비하지만 rules() 에 없어 validated() 에서
|
||||
* 누락된다. 저장 시마다 레이아웃 동작 정의가 사라지는 손상.
|
||||
*/
|
||||
public function test_update_layout_preserves_content_top_state_action_keys(): void
|
||||
{
|
||||
// Arrange
|
||||
$layout = TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'test-layout',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'test-layout',
|
||||
'endpoint' => '/api/test',
|
||||
'components' => [['id' => 'root', 'type' => 'layout', 'name' => 'Container']],
|
||||
'data_sources' => [],
|
||||
],
|
||||
]);
|
||||
|
||||
$updateData = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'test-layout',
|
||||
'endpoint' => '/api/admin/test',
|
||||
'components' => [['id' => 'root', 'type' => 'layout', 'name' => 'Container']],
|
||||
'data_sources' => [],
|
||||
'initLocal' => ['driverTestResults' => [], 'activeChannel' => null],
|
||||
'initGlobal' => ['reviewImagePreview' => null],
|
||||
'errorHandling' => [
|
||||
'404' => ['handler' => 'showErrorPage', 'params' => ['target' => 'content']],
|
||||
],
|
||||
'global_state' => ['searchActiveTab' => 'all'],
|
||||
'actions' => [
|
||||
['id' => 'selectBank', 'handler' => 'setState', 'params' => ['target' => '_local.bank', 'value' => 'x']],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
// Act
|
||||
$response = $this->authRequest()
|
||||
->putJson("/api/admin/templates/{$this->template->identifier}/layouts/test-layout", $updateData);
|
||||
|
||||
// Assert
|
||||
$response->assertStatus(200);
|
||||
|
||||
$layout->refresh();
|
||||
$this->assertArrayHasKey('initLocal', $layout->content, 'initLocal 이 저장 시 유실됨');
|
||||
$this->assertArrayHasKey('initGlobal', $layout->content, 'initGlobal 이 저장 시 유실됨');
|
||||
$this->assertArrayHasKey('errorHandling', $layout->content, 'errorHandling 이 저장 시 유실됨');
|
||||
$this->assertArrayHasKey('global_state', $layout->content, 'global_state 가 저장 시 유실됨');
|
||||
$this->assertArrayHasKey('actions', $layout->content, 'actions 가 저장 시 유실됨');
|
||||
$this->assertEquals('all', $layout->content['global_state']['searchActiveTab']);
|
||||
$this->assertEquals('showErrorPage', $layout->content['errorHandling']['404']['handler']);
|
||||
$this->assertEquals('selectBank', $layout->content['actions'][0]['id']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 업데이트 시 플러그인 settings 전용 키 보존 (pageConfig / schema)
|
||||
*
|
||||
* 플러그인 설정 레이아웃이 content 직속에 두는 pageConfig/schema 키도 저장 시 누락된다.
|
||||
*/
|
||||
public function test_update_layout_preserves_plugin_settings_keys(): void
|
||||
{
|
||||
// Arrange
|
||||
$layout = TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'plugin_settings',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'plugin_settings',
|
||||
'endpoint' => '/api/test',
|
||||
'components' => [['id' => 'root', 'type' => 'layout', 'name' => 'Container']],
|
||||
'data_sources' => [],
|
||||
],
|
||||
]);
|
||||
|
||||
$updateData = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'plugin_settings',
|
||||
'endpoint' => '/api/admin/test',
|
||||
'components' => [['id' => 'root', 'type' => 'layout', 'name' => 'Container']],
|
||||
'data_sources' => [],
|
||||
'pageConfig' => ['notice' => '$t:plugin.notice'],
|
||||
'schema' => [
|
||||
'is_test_mode' => ['type' => 'boolean', 'default' => true],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
// Act
|
||||
$response = $this->authRequest()
|
||||
->putJson("/api/admin/templates/{$this->template->identifier}/layouts/plugin_settings", $updateData);
|
||||
|
||||
// Assert
|
||||
$response->assertStatus(200);
|
||||
|
||||
$layout->refresh();
|
||||
$this->assertArrayHasKey('pageConfig', $layout->content, 'pageConfig 가 저장 시 유실됨');
|
||||
$this->assertArrayHasKey('schema', $layout->content, 'schema 가 저장 시 유실됨');
|
||||
$this->assertEquals('$t:plugin.notice', $layout->content['pageConfig']['notice']);
|
||||
$this->assertTrue($layout->content['schema']['is_test_mode']['default']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 업데이트 시 extends 레이아웃도 모든 필드 보존
|
||||
*/
|
||||
@@ -1175,6 +1546,7 @@ class LayoutControllerTest extends TestCase
|
||||
]);
|
||||
|
||||
$updateData = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'test-child-layout',
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\Template;
|
||||
use App\Models\TemplateLayout;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* LayoutControllerTopLevelPatchTest — 최상위/중첩 키 validated 보존 회귀 가드 (R9)
|
||||
*
|
||||
* 페이지 설정 탭이 패치하는 최상위 키(errorHandling/initIsolated/transition_overlay) 와
|
||||
* data_sources nested 키(onSuccess/onError/errorHandling/contentType/initLocal/initIsolated/
|
||||
* if/conditions/refetchOnMount/channel/event/channel_type/target_source/onReceive) 가 PUT →
|
||||
* DB 라운드트립에서 `validated()` 에 의해 탈락되지 않음을 전수 가드한다.
|
||||
*
|
||||
* 근거: `content.data_sources` 는 `['array', ValidDataSourceMerge]` 로 `.*` 하위 규칙이 없어
|
||||
* Laravel validated() 가 배열을 통째 보존한다(노드 내부 미가공). `content.errorHandling` 동일.
|
||||
* `content.initIsolated` 는 본 작업에서 신규 명시(미명시 시 누락 — 이 테스트가 가드).
|
||||
*/
|
||||
class LayoutControllerTopLevelPatchTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $adminUser;
|
||||
|
||||
private Template $template;
|
||||
|
||||
private string $token;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->adminUser = $this->createAdminUser(['core.templates.read', 'core.templates.layouts.edit']);
|
||||
$this->token = $this->adminUser->createToken('test-token')->plainTextToken;
|
||||
$this->template = Template::factory()->create();
|
||||
}
|
||||
|
||||
private function createAdminUser(array $permissions = []): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$permissionIds = [];
|
||||
foreach ($permissions as $identifier) {
|
||||
$permission = Permission::firstOrCreate(
|
||||
['identifier' => $identifier],
|
||||
[
|
||||
'name' => json_encode(['ko' => $identifier, 'en' => $identifier]),
|
||||
'description' => json_encode(['ko' => $identifier, 'en' => $identifier]),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
]
|
||||
);
|
||||
$permissionIds[] = $permission->id;
|
||||
}
|
||||
$adminRole = Role::firstOrCreate(
|
||||
['identifier' => 'admin'],
|
||||
[
|
||||
'name' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'is_system' => true,
|
||||
'priority' => 0,
|
||||
]
|
||||
);
|
||||
$adminRole->permissions()->syncWithoutDetaching($permissionIds);
|
||||
$user->roles()->syncWithoutDetaching([$adminRole->id]);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
private function authRequest()
|
||||
{
|
||||
return $this->withHeaders(['Authorization' => 'Bearer '.$this->token, 'Accept' => 'application/json']);
|
||||
}
|
||||
|
||||
private function makeLayout(): TemplateLayout
|
||||
{
|
||||
return TemplateLayout::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'patch-target',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'patch-target',
|
||||
'endpoint' => '/api/admin/test',
|
||||
'components' => [],
|
||||
'data_sources' => [],
|
||||
],
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
private function putContent(TemplateLayout $layout, array $contentOverrides): array
|
||||
{
|
||||
$content = array_merge([
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'patch-target',
|
||||
'endpoint' => '/api/admin/test',
|
||||
'components' => [
|
||||
['id' => 'root', 'name' => 'Div', 'type' => 'basic', 'props' => []],
|
||||
],
|
||||
'data_sources' => [],
|
||||
], $contentOverrides);
|
||||
|
||||
$response = $this->authRequest()->putJson(
|
||||
"/api/admin/templates/{$this->template->identifier}/layouts/{$layout->name}",
|
||||
['expected_lock_version' => 0, 'content' => $content],
|
||||
);
|
||||
$response->assertStatus(200);
|
||||
$layout->refresh();
|
||||
|
||||
return $layout->content;
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_preserves_data_source_nested_keys_on_save(): void
|
||||
{
|
||||
$layout = $this->makeLayout();
|
||||
$ds = [
|
||||
'id' => 'products',
|
||||
'type' => 'api',
|
||||
'endpoint' => '/api/products',
|
||||
'contentType' => 'multipart/form-data',
|
||||
'refetchOnMount' => true,
|
||||
'onSuccess' => [['handler' => 'setState', 'target' => 'local', 'params' => ['loaded' => true]]],
|
||||
'onError' => [['handler' => 'toast', 'params' => ['message' => '{{error.message}}']]],
|
||||
'errorHandling' => ['403' => ['handler' => 'showErrorPage', 'target' => '403']],
|
||||
'errorCondition' => ['if' => '{{response?.data?.x !== true}}', 'errorCode' => 403],
|
||||
'initLocal' => 'form',
|
||||
'initGlobal' => ['key' => 'cartCount', 'path' => 'count'],
|
||||
'initIsolated' => 'sliderState',
|
||||
'if' => '{{ route.id }}',
|
||||
'conditions' => [['field' => 'x', 'op' => '==', 'value' => 1]],
|
||||
];
|
||||
|
||||
$stored = $this->putContent($layout, ['data_sources' => [$ds]]);
|
||||
$savedDs = $stored['data_sources'][0];
|
||||
|
||||
foreach (['contentType', 'refetchOnMount', 'onSuccess', 'onError', 'errorHandling', 'errorCondition', 'initLocal', 'initGlobal', 'initIsolated', 'if', 'conditions'] as $key) {
|
||||
$this->assertArrayHasKey($key, $savedDs, "data_source.$key 가 저장 시 탈락됨 (R9)");
|
||||
}
|
||||
$this->assertSame('multipart/form-data', $savedDs['contentType']);
|
||||
$this->assertTrue($savedDs['refetchOnMount']);
|
||||
$this->assertCount(1, $savedDs['onSuccess']);
|
||||
$this->assertSame('showErrorPage', $savedDs['errorHandling']['403']['handler']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_preserves_websocket_data_source_keys_on_save(): void
|
||||
{
|
||||
$layout = $this->makeLayout();
|
||||
$ds = [
|
||||
'id' => 'live',
|
||||
'type' => 'websocket',
|
||||
'channel' => 'core.admin.dashboard',
|
||||
'event' => 'dashboard.stats.updated',
|
||||
'channel_type' => 'private',
|
||||
'target_source' => 'dashboard_stats',
|
||||
'onReceive' => [['handler' => 'refetchDataSource', 'params' => ['dataSourceId' => 'dashboard_stats']]],
|
||||
];
|
||||
$stored = $this->putContent($layout, ['data_sources' => [$ds]]);
|
||||
$savedDs = $stored['data_sources'][0];
|
||||
foreach (['channel', 'event', 'channel_type', 'target_source', 'onReceive'] as $key) {
|
||||
$this->assertArrayHasKey($key, $savedDs, "websocket data_source.$key 탈락 (R9)");
|
||||
}
|
||||
$this->assertSame('private', $savedDs['channel_type']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_preserves_top_level_error_handling_codes_on_save(): void
|
||||
{
|
||||
$layout = $this->makeLayout();
|
||||
$stored = $this->putContent($layout, [
|
||||
'errorHandling' => [
|
||||
'403' => ['handler' => 'showErrorPage', 'target' => '403'],
|
||||
'default' => ['handler' => 'toast', 'params' => ['message' => '{{error.message}}']],
|
||||
],
|
||||
]);
|
||||
$this->assertArrayHasKey('errorHandling', $stored);
|
||||
$this->assertSame('showErrorPage', $stored['errorHandling']['403']['handler']);
|
||||
$this->assertSame('toast', $stored['errorHandling']['default']['handler']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_preserves_node_top_level_data_key_on_save(): void
|
||||
{
|
||||
// dataKey 는 노드 **최상위** 구조 키(`node.dataKey`, props 아님 —/DynamicRenderer.tsx:2470).
|
||||
// 저장 경로에서 `content.components` 는 `['array']`(하위 `.*` 규칙 없음)라 validated() 가
|
||||
// 컴포넌트 트리를 통째 보존하고, `stripInheritedNode` 는 `__source`/`_fromBase` 만 제거하므로
|
||||
// dataKey 는 살아남는다. 누군가 `content.components.*` 하위 규칙을 추가하면 dataKey 가 조용히
|
||||
// 떨어지는 회귀가 발생하므로 그 회귀를 본 가드가 차단한다(if/actions 등 다른 노드 최상위 키와 동일 부류).
|
||||
$layout = $this->makeLayout();
|
||||
$stored = $this->putContent($layout, [
|
||||
'components' => [
|
||||
[
|
||||
'id' => 'order_form',
|
||||
'name' => 'Form',
|
||||
'type' => 'basic',
|
||||
'dataKey' => 'form',
|
||||
'props' => [],
|
||||
'children' => [
|
||||
['id' => 'inner', 'name' => 'Div', 'type' => 'basic', 'dataKey' => '_global.formData', 'props' => []],
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->assertArrayHasKey('dataKey', $stored['components'][0], 'node.dataKey 가 저장 시 탈락됨');
|
||||
$this->assertSame('form', $stored['components'][0]['dataKey']);
|
||||
// props 오염 0 가드 — dataKey 가 props 로 새지 않음
|
||||
$this->assertArrayNotHasKey('dataKey', $stored['components'][0]['props'] ?? [], 'dataKey 가 props 로 새면 안 됨');
|
||||
// 중첩 자식의 노드 최상위 dataKey(접두 표현식 포함)도 보존
|
||||
$this->assertSame('_global.formData', $stored['components'][0]['children'][0]['dataKey']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_preserves_top_level_init_isolated_on_save(): void
|
||||
{
|
||||
// initIsolated 는 본 작업 신규 명시 키 — 미명시였다면 validated() 가 떨궜다(R9 가드).
|
||||
$layout = $this->makeLayout();
|
||||
$stored = $this->putContent($layout, [
|
||||
'initIsolated' => ['sliderState' => ['idx' => 0], 'wizard' => ['step' => 1]],
|
||||
]);
|
||||
$this->assertArrayHasKey('initIsolated', $stored);
|
||||
$this->assertSame(0, $stored['initIsolated']['sliderState']['idx']);
|
||||
$this->assertSame(1, $stored['initIsolated']['wizard']['step']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_preserves_top_level_computed_on_save(): void
|
||||
{
|
||||
// [자동 계산] 탭이 패치하는 최상위 computed — `content.computed` 는 `['array']`(하위 `.*`
|
||||
// 규칙 없음)라 validated() 가 맵을 통째 보존. 누군가 하위 규칙을 추가하면 키가 조용히
|
||||
// 떨어지는 회귀를 차단한다(부모/자식 병합본 저장 라운드트립).
|
||||
$layout = $this->makeLayout();
|
||||
$stored = $this->putContent($layout, [
|
||||
'computed' => [
|
||||
'isReadOnly' => '{{ _local.forced ?? false }}',
|
||||
'total' => '{{ products.data.data.length }}',
|
||||
],
|
||||
]);
|
||||
$this->assertArrayHasKey('computed', $stored);
|
||||
$this->assertSame('{{ _local.forced ?? false }}', $stored['computed']['isReadOnly']);
|
||||
$this->assertSame('{{ products.data.data.length }}', $stored['computed']['total']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_preserves_top_level_transition_overlay_on_save(): void
|
||||
{
|
||||
// [로딩 화면] 탭이 패치하는 최상위 transition_overlay — 하위 키가 rules 에 명시돼 있어
|
||||
// validated() 가 명시 하위(enabled/style/target/fallback_target/skeleton.*/spinner.*/
|
||||
// wait_for)를 보존한다. 명시 누락 하위 키가 생기면 조용히 떨어지는 회귀를 차단.
|
||||
$layout = $this->makeLayout();
|
||||
// wait_for 는 progressive 데이터소스만 허용(withValidator) — 동반 data_source 를 둔다.
|
||||
$stored = $this->putContent($layout, [
|
||||
'data_sources' => [
|
||||
['id' => 'products', 'type' => 'api', 'endpoint' => '/api/products', 'loading_strategy' => 'progressive'],
|
||||
],
|
||||
'transition_overlay' => [
|
||||
'enabled' => true,
|
||||
'style' => 'skeleton',
|
||||
'target' => 'main-content',
|
||||
'skeleton' => ['component' => 'PageSkeleton', 'animation' => 'wave', 'iteration_count' => 3],
|
||||
'wait_for' => ['products'],
|
||||
],
|
||||
]);
|
||||
$this->assertArrayHasKey('transition_overlay', $stored);
|
||||
$ov = $stored['transition_overlay'];
|
||||
$this->assertTrue($ov['enabled']);
|
||||
$this->assertSame('skeleton', $ov['style']);
|
||||
$this->assertSame('main-content', $ov['target']);
|
||||
$this->assertSame('PageSkeleton', $ov['skeleton']['component']);
|
||||
$this->assertSame('wave', $ov['skeleton']['animation']);
|
||||
$this->assertSame(3, $ov['skeleton']['iteration_count']);
|
||||
$this->assertSame(['products'], $ov['wait_for']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_preserves_node_top_level_isolated_state_on_save(): void
|
||||
{
|
||||
// [격리 영역] 컨트롤이 부여하는 node.isolatedState / node.isolatedScopeId 는 노드 최상위
|
||||
// 구조 키(props 아님). dataKey 와 동일하게 components 트리 통째 보존으로 살아남는다.
|
||||
$layout = $this->makeLayout();
|
||||
$stored = $this->putContent($layout, [
|
||||
'components' => [
|
||||
[
|
||||
'id' => 'scroll_area',
|
||||
'name' => 'Div',
|
||||
'type' => 'basic',
|
||||
'isolatedState' => ['idx' => 0],
|
||||
'isolatedScopeId' => 'scroll_area-scope',
|
||||
'props' => [],
|
||||
],
|
||||
],
|
||||
]);
|
||||
$this->assertArrayHasKey('isolatedState', $stored['components'][0], 'node.isolatedState 탈락');
|
||||
$this->assertArrayHasKey('isolatedScopeId', $stored['components'][0], 'node.isolatedScopeId 탈락');
|
||||
$this->assertSame('scroll_area-scope', $stored['components'][0]['isolatedScopeId']);
|
||||
$this->assertArrayNotHasKey('isolatedState', $stored['components'][0]['props'] ?? [], 'props 오염 금지');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Models\Template;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 레이아웃 편집기 부팅 응답 검증
|
||||
*
|
||||
* /admin/layout-editor/{identifier} 진입 시:
|
||||
* - admin.blade.php 가 서빙됨
|
||||
* - window.G7Config.activeModules / activePlugins 키가 페이지에 노출됨
|
||||
* - 기존 modules / plugins 키도 보존됨(비파괴적 보강)
|
||||
* - 비활성 템플릿도 부팅 응답 정상 반환(편집은 가능)
|
||||
*
|
||||
* 코어 라우팅(/admin/{any?})이 모든 admin 경로를 admin.blade 로 보내므로
|
||||
* 별도 라우트 추가 없이 클라이언트 사이드 분기(template-engine.ts 의
|
||||
* checkLayoutEditorMode)가 편집 모드 진입을 결정한다.
|
||||
*/
|
||||
class LayoutEditorBootstrapTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 같은 스위트의 GDPR 미들웨어 의존 테스트와 migrate:fresh 정합성을 맞추기 위해.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
private function createSuperUser(): User
|
||||
{
|
||||
return User::factory()->create([
|
||||
'is_super' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
private function createActiveAdminTemplate(): Template
|
||||
{
|
||||
return Template::factory()->create([
|
||||
'identifier' => 'sirsoft-admin_basic',
|
||||
'type' => 'admin',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function admin_layout_editor_url_serves_admin_blade(): void
|
||||
{
|
||||
$this->createActiveAdminTemplate();
|
||||
|
||||
$user = $this->createSuperUser();
|
||||
$this->actingAs($user, 'web');
|
||||
|
||||
$response = $this->get('/admin/layout-editor/sirsoft-admin_basic');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertSee('window.G7Config', false);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function admin_blade_emits_active_modules_meta_key_in_g7config(): void
|
||||
{
|
||||
$this->createActiveAdminTemplate();
|
||||
|
||||
$user = $this->createSuperUser();
|
||||
$this->actingAs($user, 'web');
|
||||
|
||||
$response = $this->get('/admin/layout-editor/sirsoft-admin_basic');
|
||||
|
||||
$response->assertStatus(200);
|
||||
// window.G7Config 객체에 activeModules / activePlugins 키가 포함되어야 함
|
||||
$response->assertSee('activeModules:', false);
|
||||
$response->assertSee('activePlugins:', false);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function admin_blade_preserves_legacy_modules_plugins_keys(): void
|
||||
{
|
||||
$this->createActiveAdminTemplate();
|
||||
|
||||
$user = $this->createSuperUser();
|
||||
$this->actingAs($user, 'web');
|
||||
|
||||
$response = $this->get('/admin/layout-editor/sirsoft-admin_basic');
|
||||
|
||||
$response->assertStatus(200);
|
||||
// 기존 키 (modules / plugins / moduleAssets / pluginAssets) 보존
|
||||
$response->assertSee('modules:', false);
|
||||
$response->assertSee('plugins:', false);
|
||||
$response->assertSee('moduleAssets:', false);
|
||||
$response->assertSee('pluginAssets:', false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,622 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Enums\LayoutExtensionType;
|
||||
use App\Enums\LayoutSourceType;
|
||||
use App\Models\LayoutExtension;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\Template;
|
||||
use App\Models\TemplateLayout;
|
||||
use App\Models\TemplateLayoutExtensionVersion;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* LayoutExtensionController API 테스트
|
||||
*
|
||||
* 레이아웃 확장 편집·버전관리·미리보기 엔드포인트를 검증합니다.
|
||||
*/
|
||||
class LayoutExtensionControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 레이아웃/템플릿 요청 경로가 GDPR 정책 테이블을 조회하므로
|
||||
* 해당 플러그인 마이그레이션을 테스트 DB 에 포함시킨다.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
private User $adminUser;
|
||||
|
||||
private User $normalUser;
|
||||
|
||||
private Template $template;
|
||||
|
||||
private string $token;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->adminUser = $this->createAdminUser([
|
||||
'core.templates.read',
|
||||
'core.templates.layouts.edit',
|
||||
]);
|
||||
$this->token = $this->adminUser->createToken('test-token')->plainTextToken;
|
||||
|
||||
$this->normalUser = User::factory()->create();
|
||||
$this->template = Template::factory()->create();
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자 사용자 생성 (필요한 권한 포함)
|
||||
*
|
||||
* @param array<string> $permissions 부여할 권한 식별자 목록
|
||||
*/
|
||||
private function createAdminUser(array $permissions = []): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$permissionIds = [];
|
||||
foreach ($permissions as $permissionIdentifier) {
|
||||
$permission = Permission::firstOrCreate(
|
||||
['identifier' => $permissionIdentifier],
|
||||
[
|
||||
'name' => json_encode(['ko' => $permissionIdentifier, 'en' => $permissionIdentifier]),
|
||||
'description' => json_encode(['ko' => $permissionIdentifier, 'en' => $permissionIdentifier]),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'type' => 'admin',
|
||||
]
|
||||
);
|
||||
$permissionIds[] = $permission->id;
|
||||
}
|
||||
|
||||
$testRole = Role::create([
|
||||
'identifier' => 'admin_test_'.uniqid(),
|
||||
'name' => json_encode(['ko' => '테스트 관리자', 'en' => 'Test Administrator']),
|
||||
'description' => json_encode(['ko' => '테스트 관리자', 'en' => 'Test Administrator']),
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$adminRole = Role::firstOrCreate(
|
||||
['identifier' => 'admin'],
|
||||
[
|
||||
'name' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
|
||||
'description' => json_encode(['ko' => '시스템 관리자', 'en' => 'System Administrator']),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'type' => 'admin',
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
|
||||
$testRole->permissions()->sync($permissionIds);
|
||||
$user->roles()->attach($adminRole->id, ['assigned_at' => now(), 'assigned_by' => null]);
|
||||
$user->roles()->attach($testRole->id, ['assigned_at' => now(), 'assigned_by' => null]);
|
||||
|
||||
return $user->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* 인증된 요청 헬퍼
|
||||
*/
|
||||
private function authRequest(): static
|
||||
{
|
||||
return $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$this->token,
|
||||
'Accept' => 'application/json',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트용 extension_point 확장 생성
|
||||
*/
|
||||
private function makeExtensionPoint(array $overrides = []): LayoutExtension
|
||||
{
|
||||
return LayoutExtension::factory()->create(array_merge([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'header',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-test',
|
||||
'content' => ['extension_point' => 'header', 'components' => []],
|
||||
], $overrides));
|
||||
}
|
||||
|
||||
/**
|
||||
* index - 출처별 그룹핑 구조 반환
|
||||
*/
|
||||
public function test_index_returns_source_grouped_extensions(): void
|
||||
{
|
||||
LayoutExtension::factory()->count(2)->create([
|
||||
'template_id' => $this->template->id,
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'module-a',
|
||||
]);
|
||||
LayoutExtension::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'source_type' => LayoutSourceType::Plugin,
|
||||
'source_identifier' => 'plugin-b',
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()
|
||||
->getJson("/api/admin/templates/{$this->template->identifier}/layout-extensions");
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonStructure([
|
||||
'success',
|
||||
'data' => [
|
||||
'*' => ['source_identifier', 'source_type', 'source_label', 'extensions'],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->assertCount(2, $response->json('data'));
|
||||
}
|
||||
|
||||
/**
|
||||
* index - 각 확장에 host_layouts 부착
|
||||
*
|
||||
* 라우트 트리가 클릭(캔버스 로드) 없이도 layoutName 매칭으로 화면별 연결 확장 목록을
|
||||
* 정적 구성할 수 있도록, 목록 응답의 각 확장에 호스트 레이아웃 목록이 포함되어야 한다.
|
||||
* overlay = [target_layout], extension_point = 그 확장점을 포함하는 레이아웃 전체.
|
||||
*/
|
||||
public function test_index_attaches_host_layouts_to_each_extension(): void
|
||||
{
|
||||
// overlay — 실재 target_id 노드에 편집 가능 components 를 주입 (modals/
|
||||
// data_sources 전용·target_id 부재 overlay 는 시각 편집 호스트로 인정 안 됨).
|
||||
TemplateLayout::create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'admin_user_detail',
|
||||
'content' => ['components' => [['name' => 'Div', 'props' => ['id' => 'detail_panel']]]],
|
||||
]);
|
||||
LayoutExtension::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'admin_user_detail',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'module-overlay',
|
||||
'content' => [
|
||||
'target_layout' => 'admin_user_detail',
|
||||
'injections' => [['target_id' => 'detail_panel', 'position' => 'append_child', 'components' => [['name' => 'Div']]]],
|
||||
],
|
||||
]);
|
||||
|
||||
// extension_point — 슬롯을 포함하는 레이아웃 2개 생성 후 그 슬롯 대상 확장 등록
|
||||
TemplateLayout::create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'shop_checkout',
|
||||
'content' => ['components' => [['type' => 'extension_point', 'name' => 'checkout.payment']]],
|
||||
]);
|
||||
TemplateLayout::create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'shop_reorder',
|
||||
'content' => ['components' => [['type' => 'extension_point', 'name' => 'checkout.payment']]],
|
||||
]);
|
||||
LayoutExtension::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'checkout.payment',
|
||||
'source_type' => LayoutSourceType::Plugin,
|
||||
'source_identifier' => 'plugin-pay',
|
||||
// extension_point 가 편집 가능 컴포넌트를 실제로 주입해야 시각 편집 호스트로 인정.
|
||||
'content' => ['extension_point' => 'checkout.payment', 'components' => [['name' => 'Div']]],
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()
|
||||
->getJson("/api/admin/templates/{$this->template->identifier}/layout-extensions");
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
$allExtensions = collect($response->json('data'))->flatMap(fn ($g) => $g['extensions']);
|
||||
|
||||
$overlay = $allExtensions->firstWhere('target_name', 'admin_user_detail');
|
||||
$this->assertNotNull($overlay);
|
||||
$this->assertSame(['admin_user_detail'], $overlay['host_layouts']);
|
||||
|
||||
$ep = $allExtensions->firstWhere('target_name', 'checkout.payment');
|
||||
$this->assertNotNull($ep);
|
||||
$this->assertContains('shop_checkout', $ep['host_layouts']);
|
||||
$this->assertContains('shop_reorder', $ep['host_layouts']);
|
||||
}
|
||||
|
||||
/**
|
||||
* index - 템플릿 오버라이드에 가려진 확장은 트리에서 제외됨
|
||||
*
|
||||
* 회귀: 편집 화면 좌측 트리가 화면에 실제 적용되지 않는 "가려진 행"을
|
||||
* 노출하여, 관리자가 그 행을 편집해도 반영되지 않던 문제.
|
||||
*/
|
||||
public function test_index_excludes_overridden_extensions(): void
|
||||
{
|
||||
// 플러그인 Extension Point 원본
|
||||
LayoutExtension::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'address_search_slot',
|
||||
'source_type' => LayoutSourceType::Plugin,
|
||||
'source_identifier' => 'sirsoft-daum_postcode',
|
||||
'priority' => 100,
|
||||
'is_active' => true,
|
||||
]);
|
||||
// 템플릿 오버라이드 (위 플러그인 확장을 가림)
|
||||
LayoutExtension::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'address_search_slot',
|
||||
'source_type' => LayoutSourceType::Template,
|
||||
'source_identifier' => $this->template->identifier,
|
||||
'override_target' => 'sirsoft-daum_postcode',
|
||||
'priority' => 50,
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()
|
||||
->getJson("/api/admin/templates/{$this->template->identifier}/layout-extensions");
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
// 가려진 플러그인 원본(2건 등록)은 트리에서 제외되고 오버라이드 행 1건만 노출.
|
||||
// 오버라이드 행은 is_override=true 로 표시된다.
|
||||
$allExtensions = collect($response->json('data'))->flatMap(fn ($g) => $g['extensions']);
|
||||
$slotExtensions = $allExtensions->where('target_name', 'address_search_slot');
|
||||
$this->assertCount(1, $slotExtensions, '오버라이드에 가려진 원본이 함께 노출됨');
|
||||
$this->assertTrue($slotExtensions->first()['is_override'], '오버라이드 행에 is_override 플래그 누락');
|
||||
$this->assertSame('template', $slotExtensions->first()['source_type']);
|
||||
}
|
||||
|
||||
/**
|
||||
* index - 권한 없는 사용자 403
|
||||
*/
|
||||
public function test_index_forbidden_for_unauthorized_user(): void
|
||||
{
|
||||
$response = $this->actingAs($this->normalUser)
|
||||
->getJson("/api/admin/templates/{$this->template->identifier}/layout-extensions");
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
/**
|
||||
* show - content 직렬화
|
||||
*/
|
||||
public function test_show_returns_extension_with_serialized_content(): void
|
||||
{
|
||||
$extension = $this->makeExtensionPoint();
|
||||
|
||||
$response = $this->authRequest()
|
||||
->getJson("/api/admin/templates/{$this->template->identifier}/layout-extensions/{$extension->id}");
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('data.id', $extension->id)
|
||||
->assertJsonStructure(['data' => ['id', 'extension_type', 'target_name', 'content', 'is_modified']]);
|
||||
|
||||
$this->assertIsString($response->json('data.content'));
|
||||
}
|
||||
|
||||
/**
|
||||
* show - 호스트 레이아웃 후보 반환
|
||||
*/
|
||||
public function test_show_returns_host_layouts_for_overlay(): void
|
||||
{
|
||||
// 호스트 레이아웃: injection target_id 노드가 실재 (편집 가능 컴포넌트를
|
||||
// 실재 target_id 에 주입하는 overlay 만 시각 편집 호스트로 인정).
|
||||
TemplateLayout::create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => 'admin_user_detail',
|
||||
'content' => ['components' => [['name' => 'Div', 'props' => ['id' => 'detail_panel']]]],
|
||||
]);
|
||||
$extension = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'admin_user_detail',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-test',
|
||||
'content' => [
|
||||
'target_layout' => 'admin_user_detail',
|
||||
'injections' => [['target_id' => 'detail_panel', 'position' => 'append_child', 'components' => [['name' => 'Div']]]],
|
||||
],
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()
|
||||
->getJson("/api/admin/templates/{$this->template->identifier}/layout-extensions/{$extension->id}");
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('data.host_layouts', ['admin_user_detail']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 시각 편집기 inject_props 교차 저장 페이로드 — 호스트 노드
|
||||
* 속성 모달에서 편집한 주입 props 가 그 확장 행으로 저장되고 original_content_hash 보존.
|
||||
*/
|
||||
public function test_inject_props_cross_save_preserves_hash(): void
|
||||
{
|
||||
$originalContent = [
|
||||
'target_layout' => 'admin_user_detail',
|
||||
'injections' => [
|
||||
['target_id' => 'user_detail_tabs', 'position' => 'inject_props', 'props' => ['tabs' => ['_append' => [['id' => 'old']]]]],
|
||||
],
|
||||
];
|
||||
$extension = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'admin_user_detail',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-test',
|
||||
'content' => $originalContent,
|
||||
'original_content_hash' => hash('sha256', json_encode($originalContent, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)),
|
||||
]);
|
||||
$originalHash = $extension->original_content_hash;
|
||||
|
||||
// 시각 편집기 교차 저장 = injection props 만 교체한 전체 content PUT.
|
||||
$newContent = $originalContent;
|
||||
$newContent['injections'][0]['props'] = ['tabs' => ['_append' => [['id' => 'edited']]]];
|
||||
|
||||
$response = $this->authRequest()
|
||||
->putJson("/api/admin/templates/{$this->template->identifier}/layout-extensions/{$extension->id}", [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => $newContent,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$extension->refresh();
|
||||
// 주입 props 갱신 + 수정 감지용 original_content_hash 불변(보존).
|
||||
$this->assertSame('edited', $extension->content['injections'][0]['props']['tabs']['_append'][0]['id']);
|
||||
$this->assertEquals($originalHash, $extension->original_content_hash);
|
||||
// 버전 적재(편집 이력).
|
||||
$this->assertGreaterThanOrEqual(1, TemplateLayoutExtensionVersion::where('extension_id', $extension->id)->count());
|
||||
}
|
||||
|
||||
/**
|
||||
* show - 다른 템플릿의 확장 ID 는 404
|
||||
*/
|
||||
public function test_show_returns_404_for_extension_of_other_template(): void
|
||||
{
|
||||
$otherTemplate = Template::factory()->create();
|
||||
$extension = LayoutExtension::factory()->create(['template_id' => $otherTemplate->id]);
|
||||
|
||||
$response = $this->authRequest()
|
||||
->getJson("/api/admin/templates/{$this->template->identifier}/layout-extensions/{$extension->id}");
|
||||
|
||||
$response->assertStatus(404);
|
||||
}
|
||||
|
||||
/**
|
||||
* update - 200 + 버전 2건 생성 + original_content_hash 불변
|
||||
*/
|
||||
public function test_update_succeeds_and_creates_versions(): void
|
||||
{
|
||||
$originalContent = ['extension_point' => 'header', 'components' => []];
|
||||
$extension = $this->makeExtensionPoint([
|
||||
'content' => $originalContent,
|
||||
'original_content_hash' => hash('sha256', json_encode($originalContent, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)),
|
||||
]);
|
||||
$originalHash = $extension->original_content_hash;
|
||||
|
||||
$newContent = ['extension_point' => 'header', 'components' => [['type' => 'basic', 'name' => 'Span']]];
|
||||
|
||||
$response = $this->authRequest()
|
||||
->putJson("/api/admin/templates/{$this->template->identifier}/layout-extensions/{$extension->id}", [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => $newContent,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
$this->assertEquals(2, TemplateLayoutExtensionVersion::where('extension_id', $extension->id)->count());
|
||||
|
||||
$extension->refresh();
|
||||
$this->assertEquals($newContent, $extension->content);
|
||||
$this->assertEquals($originalHash, $extension->original_content_hash);
|
||||
|
||||
// 현재(최신) 버전 번호 동봉.
|
||||
// 첫 저장은 baseline(v1) + 이번 저장본(v2) 두 버전 적재 → current_version=2.
|
||||
$this->assertSame(2, $response->json('data.current_version'));
|
||||
}
|
||||
|
||||
/**
|
||||
* index - 각 확장에 current_version 부착
|
||||
*
|
||||
* 라우트 트리 확장 노드 버전 배지의 데이터 소스 — 버전 이력이 있는 확장은 최신 버전
|
||||
* 번호, 이력이 없는(원본) 확장은 null 이어야 한다(배지 미표시).
|
||||
*/
|
||||
public function test_index_attaches_current_version_to_each_extension(): void
|
||||
{
|
||||
$withHistory = $this->makeExtensionPoint();
|
||||
TemplateLayoutExtensionVersion::factory()->create(['extension_id' => $withHistory->id, 'version' => 1]);
|
||||
TemplateLayoutExtensionVersion::factory()->create(['extension_id' => $withHistory->id, 'version' => 5]);
|
||||
$noHistory = $this->makeExtensionPoint();
|
||||
|
||||
$response = $this->authRequest()
|
||||
->getJson("/api/admin/templates/{$this->template->identifier}/layout-extensions");
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
$byId = [];
|
||||
foreach ($response->json('data') as $group) {
|
||||
foreach ($group['extensions'] as $ext) {
|
||||
$byId[$ext['id']] = $ext;
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertArrayHasKey('current_version', $byId[$withHistory->id]);
|
||||
$this->assertSame(5, $byId[$withHistory->id]['current_version']);
|
||||
$this->assertNull($byId[$noHistory->id]['current_version']);
|
||||
}
|
||||
|
||||
/**
|
||||
* update - expected_lock_version 불일치 시 409 Conflict (낙관적 잠금)
|
||||
*/
|
||||
public function test_update_returns_409_on_lock_version_mismatch(): void
|
||||
{
|
||||
// 신규 확장은 lock_version=0. expected_lock_version=1 을 보내면 불일치 → 409.
|
||||
$extension = $this->makeExtensionPoint([
|
||||
'content' => ['extension_point' => 'header', 'components' => []],
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()
|
||||
->putJson("/api/admin/templates/{$this->template->identifier}/layout-extensions/{$extension->id}", [
|
||||
'expected_lock_version' => 1,
|
||||
'content' => ['extension_point' => 'header', 'components' => [['type' => 'basic', 'name' => 'Span']]],
|
||||
]);
|
||||
|
||||
$response->assertStatus(409)
|
||||
->assertJsonPath('errors.error', 'concurrent_modification')
|
||||
->assertJsonPath('errors.current_version', 0)
|
||||
->assertJsonPath('errors.your_version', 1);
|
||||
|
||||
// 충돌 시 저장되지 않음 — content 불변 + 버전 미적재.
|
||||
$extension->refresh();
|
||||
$this->assertEquals([], $extension->content['components']);
|
||||
$this->assertEquals(0, TemplateLayoutExtensionVersion::where('extension_id', $extension->id)->count());
|
||||
}
|
||||
|
||||
/**
|
||||
* update - 잘못된 구조는 422
|
||||
*/
|
||||
public function test_update_rejects_invalid_structure(): void
|
||||
{
|
||||
$extension = $this->makeExtensionPoint();
|
||||
|
||||
// extension_point 와 target_layout 둘 다 없는 잘못된 content
|
||||
$response = $this->authRequest()
|
||||
->putJson("/api/admin/templates/{$this->template->identifier}/layout-extensions/{$extension->id}", [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => ['components' => []],
|
||||
]);
|
||||
|
||||
$response->assertStatus(422);
|
||||
}
|
||||
|
||||
/**
|
||||
* update - 권한 없는 사용자 403
|
||||
*/
|
||||
public function test_update_forbidden_for_unauthorized_user(): void
|
||||
{
|
||||
$extension = $this->makeExtensionPoint();
|
||||
|
||||
$response = $this->actingAs($this->normalUser)
|
||||
->putJson("/api/admin/templates/{$this->template->identifier}/layout-extensions/{$extension->id}", [
|
||||
'content' => ['extension_point' => 'header', 'components' => []],
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
/**
|
||||
* versions - 버전 목록 조회
|
||||
*/
|
||||
public function test_versions_returns_version_list(): void
|
||||
{
|
||||
$extension = $this->makeExtensionPoint();
|
||||
TemplateLayoutExtensionVersion::factory()->count(3)->sequence(
|
||||
['version' => 1],
|
||||
['version' => 2],
|
||||
['version' => 3],
|
||||
)->create(['extension_id' => $extension->id]);
|
||||
|
||||
$response = $this->authRequest()
|
||||
->getJson("/api/admin/templates/{$this->template->identifier}/layout-extensions/{$extension->id}/versions");
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertCount(3, $response->json('data'));
|
||||
}
|
||||
|
||||
/**
|
||||
* showVersion - 특정 버전 조회
|
||||
*/
|
||||
public function test_show_version_returns_specific_version(): void
|
||||
{
|
||||
$extension = $this->makeExtensionPoint();
|
||||
TemplateLayoutExtensionVersion::factory()->create([
|
||||
'extension_id' => $extension->id,
|
||||
'version' => 1,
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()
|
||||
->getJson("/api/admin/templates/{$this->template->identifier}/layout-extensions/{$extension->id}/versions/1");
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonPath('data.version', 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* restoreVersion - content 복원 + 새 버전 생성
|
||||
*/
|
||||
public function test_restore_version_restores_content(): void
|
||||
{
|
||||
$oldContent = ['extension_point' => 'header', 'components' => [['type' => 'basic', 'name' => 'Span']]];
|
||||
$extension = $this->makeExtensionPoint(['content' => ['extension_point' => 'footer']]);
|
||||
|
||||
$version = TemplateLayoutExtensionVersion::factory()->create([
|
||||
'extension_id' => $extension->id,
|
||||
'version' => 1,
|
||||
'content' => $oldContent,
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()
|
||||
->postJson("/api/admin/templates/{$this->template->identifier}/layout-extensions/{$extension->id}/versions/{$version->id}/restore");
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
$extension->refresh();
|
||||
$this->assertEquals($oldContent, $extension->content);
|
||||
}
|
||||
|
||||
/**
|
||||
* restoreVersion - 존재하지 않는 버전 404
|
||||
*/
|
||||
public function test_restore_version_returns_404_for_missing_version(): void
|
||||
{
|
||||
$extension = $this->makeExtensionPoint();
|
||||
|
||||
$response = $this->authRequest()
|
||||
->postJson("/api/admin/templates/{$this->template->identifier}/layout-extensions/{$extension->id}/versions/99999/restore");
|
||||
|
||||
$response->assertStatus(404);
|
||||
}
|
||||
|
||||
/**
|
||||
* storePreview - overlay 타입 미리보기 토큰 반환
|
||||
*/
|
||||
public function test_store_preview_returns_token_for_overlay(): void
|
||||
{
|
||||
$extension = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->template->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'admin/dashboard',
|
||||
'source_type' => LayoutSourceType::Plugin,
|
||||
'source_identifier' => 'sirsoft-analytics',
|
||||
'content' => ['target_layout' => 'admin/dashboard', 'injections' => []],
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()
|
||||
->postJson("/api/admin/templates/{$this->template->identifier}/layout-extensions/{$extension->id}/preview", [
|
||||
'content' => ['target_layout' => 'admin/dashboard', 'injections' => []],
|
||||
]);
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJsonStructure(['data' => ['token', 'preview_url', 'expires_at']]);
|
||||
}
|
||||
|
||||
/**
|
||||
* storePreview - extension_point 타입은 preview_layout 없으면 422
|
||||
*/
|
||||
public function test_store_preview_requires_preview_layout_for_extension_point(): void
|
||||
{
|
||||
$extension = $this->makeExtensionPoint();
|
||||
|
||||
$response = $this->authRequest()
|
||||
->postJson("/api/admin/templates/{$this->template->identifier}/layout-extensions/{$extension->id}/preview", [
|
||||
'content' => ['extension_point' => 'header', 'components' => []],
|
||||
]);
|
||||
|
||||
$response->assertStatus(422);
|
||||
}
|
||||
}
|
||||
@@ -24,9 +24,22 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 레이아웃/템플릿 요청 경로가 GDPR 정책 테이블을 조회하므로
|
||||
* 해당 플러그인 마이그레이션을 테스트 DB 에 포함시킨다.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
private User $adminUser;
|
||||
|
||||
private Template $userTemplate;
|
||||
|
||||
private Template $adminTemplate;
|
||||
|
||||
private string $token;
|
||||
|
||||
/**
|
||||
@@ -66,7 +79,7 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
'props' => $props,
|
||||
];
|
||||
|
||||
if (!empty($children)) {
|
||||
if (! empty($children)) {
|
||||
$component['children'] = $children;
|
||||
}
|
||||
|
||||
@@ -183,12 +196,12 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
/**
|
||||
* 전체 버전 히스토리 플로우 통합 테스트
|
||||
*
|
||||
* 시나리오:
|
||||
* 시나리오 (PUT 당 버전 1건 — 저장 시점 content 스냅샷):
|
||||
* 1. 레이아웃 생성
|
||||
* 2. 레이아웃 수정 (버전 1 자동 생성)
|
||||
* 3. 다시 수정 (버전 2 자동 생성)
|
||||
* 4. 버전 목록 조회
|
||||
* 5. 특정 버전 조회
|
||||
* 2. 레이아웃 수정 (버전 1 = 첫 저장본 스냅샷)
|
||||
* 3. 다시 수정 (버전 2 = 두 번째 저장본 스냅샷)
|
||||
* 4. 버전 목록 조회 (2건)
|
||||
* 5. 특정 버전 조회 (버전 1 = 첫 저장본)
|
||||
* 6. 버전 1로 복원
|
||||
* 7. 복원 후 새 버전(3) 생성 확인
|
||||
*/
|
||||
@@ -215,8 +228,9 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
// 초기 버전은 생성되지 않음
|
||||
$this->assertEquals(0, TemplateLayoutVersion::where('layout_id', $layout->id)->count());
|
||||
|
||||
// 2. 레이아웃 첫 수정 (버전 1 생성)
|
||||
// 2. 레이아웃 첫 수정 (버전 1 생성) — factory lock_version=0 시작
|
||||
$updateData1 = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => $this->makeLayoutContent(
|
||||
'test-layout',
|
||||
'/api/admin/test',
|
||||
@@ -237,20 +251,30 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
|
||||
$this->assertCount(2, $responseData['components']);
|
||||
|
||||
// LayoutService::updateLayoutContent 는 PUT 당 2개 버전 저장 (이전 롤백용 + 현재 기록용)
|
||||
// 첫 수정 시: v1 = 수정 전 원본 baseline + v2 = 첫 수정본 → 2건.
|
||||
$this->assertEquals(2, TemplateLayoutVersion::where('layout_id', $layout->id)->count());
|
||||
|
||||
$version1 = TemplateLayoutVersion::where('layout_id', $layout->id)
|
||||
->where('version', 1)
|
||||
->first();
|
||||
|
||||
// 버전 1 = 수정 전 원본 baseline (header-1 만, metadata status:initial). 비교 대상 없어 변경 요약 0.
|
||||
$version1 = TemplateLayoutVersion::where('layout_id', $layout->id)->where('version', 1)->first();
|
||||
$this->assertNotNull($version1);
|
||||
$this->assertCount(1, $version1->content['components']);
|
||||
$this->assertEquals('header-1', $version1->content['components'][0]['id']);
|
||||
$this->assertNotNull($version1->changes_summary);
|
||||
$this->assertEquals(['status' => 'initial'], $version1->content['metadata']);
|
||||
$this->assertEquals(0, $version1->changes_summary['char_diff']);
|
||||
|
||||
// 3. 레이아웃 두 번째 수정 (버전 2 생성)
|
||||
// 버전 2 = 첫 수정본(updateData1) — header-1 + footer-1, 원본 대비 변경 요약 0 아님.
|
||||
$version2first = TemplateLayoutVersion::where('layout_id', $layout->id)->where('version', 2)->first();
|
||||
$this->assertNotNull($version2first);
|
||||
$this->assertCount(2, $version2first->content['components']);
|
||||
$this->assertEqualsCanonicalizing(
|
||||
['header-1', 'footer-1'],
|
||||
array_column($version2first->content['components'], 'id')
|
||||
);
|
||||
$this->assertNotEquals(0, $version2first->changes_summary['char_diff']);
|
||||
|
||||
// 3. 레이아웃 두 번째 수정 (버전 2 생성) — 첫 저장으로 lock_version=1
|
||||
$updateData2 = [
|
||||
'expected_lock_version' => 1,
|
||||
'content' => $this->makeLayoutContent(
|
||||
'test-layout',
|
||||
'/api/admin/test',
|
||||
@@ -269,19 +293,25 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
// 2회 PUT = 4개 버전 (PUT 당 2개)
|
||||
$this->assertEquals(4, TemplateLayoutVersion::where('layout_id', $layout->id)->count());
|
||||
// baseline(v1) + 첫 수정본(v2) + 두 번째 수정본(v3) = 3건.
|
||||
$this->assertEquals(3, TemplateLayoutVersion::where('layout_id', $layout->id)->count());
|
||||
|
||||
// 4. 버전 목록 조회
|
||||
// 최신 버전(버전 3)의 changes_summary 는 직전(버전 2) 대비 변경을 정확히 담는다 —
|
||||
// sidebar-1 추가 + 변경 → char_diff 0 아님 (종전 결함: 최신 버전이 자기 비교로 항상 0).
|
||||
$version3 = TemplateLayoutVersion::where('layout_id', $layout->id)->where('version', 3)->first();
|
||||
$this->assertNotNull($version3);
|
||||
$this->assertNotEquals(0, $version3->changes_summary['char_diff']);
|
||||
// sidebar-1 추가 → 새 라인 발생 (added 카운트 > 0)
|
||||
$this->assertGreaterThan(0, $version3->changes_summary['added']);
|
||||
|
||||
// 4. 버전 목록 조회 — baseline + 2회 수정 = 3건
|
||||
$response = $this->authRequest()
|
||||
->getJson("/api/admin/templates/{$this->userTemplate->identifier}/layouts/{$layout->name}/versions");
|
||||
|
||||
$response->assertStatus(200);
|
||||
// LayoutService::updateLayoutContent 는 PUT 당 2개 버전 저장 (이전 + 현재)
|
||||
// 2회 PUT = 4개 버전
|
||||
$this->assertCount(4, $response->json('data'));
|
||||
$this->assertCount(3, $response->json('data'));
|
||||
|
||||
// 5. 특정 버전 조회 (버전 1)
|
||||
// 5. 특정 버전 조회 (버전 1 = 수정 전 원본 baseline)
|
||||
$response = $this->authRequest()
|
||||
->getJson("/api/admin/templates/{$this->userTemplate->identifier}/layouts/{$layout->name}/versions/1");
|
||||
|
||||
@@ -289,6 +319,7 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
|
||||
$versionData = $response->json('data');
|
||||
$this->assertEquals(1, (int) $versionData['version']);
|
||||
// 버전 1 = 수정 전 원본 (header-1 만).
|
||||
$this->assertCount(1, $versionData['components']);
|
||||
$this->assertEquals('header-1', $versionData['components'][0]['id']);
|
||||
|
||||
@@ -298,10 +329,10 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
// 7. 복원은 saveVersion 1회 호출 (복원 전 content 저장). 4 + 1 = 5 버전
|
||||
$this->assertEquals(5, TemplateLayoutVersion::where('layout_id', $layout->id)->count());
|
||||
// 7. 복원은 saveVersion 1회 호출 (복원 전 content 저장). 3 + 1 = 4 버전
|
||||
$this->assertEquals(4, TemplateLayoutVersion::where('layout_id', $layout->id)->count());
|
||||
|
||||
// 레이아웃의 현재 content가 버전 1로 복원되었는지 확인 (버전 번호가 아닌 실제 내용 기준)
|
||||
// 레이아웃의 현재 content가 버전 1(수정 전 원본 = header-1 만)로 복원되었는지 확인.
|
||||
$layout->refresh();
|
||||
$this->assertCount(1, $layout->content['components']);
|
||||
$this->assertEquals('header-1', $layout->content['components'][0]['id']);
|
||||
@@ -312,9 +343,9 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
* 유저 템플릿만 버전이 저장되는지 검증
|
||||
*
|
||||
* - 유저 템플릿(type='user'): 버전 저장됨
|
||||
* - 관리자 템플릿(type='admin'): 버전 저장되지 않음 (레이아웃 편집 불가)
|
||||
* - 관리자 템플릿(type='admin'): 버전 저장됨 (admin/user 구분 없이 모든 템플릿 편집 가능)
|
||||
*/
|
||||
public function test_version_saved_only_for_user_templates(): void
|
||||
public function test_version_saved_for_all_template_types(): void
|
||||
{
|
||||
// 유저 템플릿 레이아웃 생성
|
||||
$userLayout = TemplateLayout::factory()->create([
|
||||
@@ -338,9 +369,10 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
),
|
||||
]);
|
||||
|
||||
// 유저 템플릿 레이아웃 수정
|
||||
// 유저 템플릿 레이아웃 수정 (factory lock_version=0)
|
||||
$this->authRequest()
|
||||
->putJson("/api/admin/templates/{$this->userTemplate->identifier}/layouts/{$userLayout->name}", [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => $this->makeLayoutContent(
|
||||
'user-layout',
|
||||
'/api/admin/user',
|
||||
@@ -349,9 +381,10 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
])
|
||||
->assertStatus(200);
|
||||
|
||||
// 관리자 템플릿 레이아웃 수정
|
||||
// 관리자 템플릿 레이아웃 수정 (factory lock_version=0)
|
||||
$this->authRequest()
|
||||
->putJson("/api/admin/templates/{$this->adminTemplate->identifier}/layouts/{$adminLayout->name}", [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => $this->makeLayoutContent(
|
||||
'admin-layout',
|
||||
'/api/admin/dashboard',
|
||||
@@ -360,11 +393,11 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
])
|
||||
->assertStatus(200);
|
||||
|
||||
// 유저 템플릿은 버전이 생성됨 (PUT 당 2개: 이전 + 현재)
|
||||
// 유저 템플릿: 첫 수정 → baseline(v1) + 수정본(v2) = 2건
|
||||
$this->assertEquals(2, TemplateLayoutVersion::where('layout_id', $userLayout->id)->count());
|
||||
|
||||
// 관리자 템플릿은 버전이 생성되지 않음 (레이아웃 편집 불가 정책)
|
||||
$this->assertEquals(0, TemplateLayoutVersion::where('layout_id', $adminLayout->id)->count());
|
||||
// 관리자 템플릿도 동일하게 버전이 생성됨 (admin/user 구분 없이 편집 가능)
|
||||
$this->assertEquals(2, TemplateLayoutVersion::where('layout_id', $adminLayout->id)->count());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -419,6 +452,7 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
|
||||
$response = $this->authRequest()
|
||||
->putJson("/api/admin/templates/{$this->userTemplate->identifier}/layouts/{$layout->name}", [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => $this->makeLayoutContent(
|
||||
'large-layout',
|
||||
'/api/admin/large',
|
||||
@@ -432,7 +466,7 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
// 성공 확인
|
||||
$response->assertStatus(200);
|
||||
|
||||
// 버전이 생성되었는지 확인 (1 PUT = 2 버전: 이전 + 현재)
|
||||
// 버전이 생성되었는지 확인 (첫 수정 = baseline + 수정본 = 2 버전)
|
||||
$this->assertEquals(2, TemplateLayoutVersion::where('layout_id', $layout->id)->count());
|
||||
|
||||
// 성능 검증: 5초 이내 완료 (Windows + MySQL + RefreshDatabase 환경 고려한 여유값)
|
||||
@@ -471,9 +505,10 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
),
|
||||
]);
|
||||
|
||||
// 복잡한 변경 수행
|
||||
// 복잡한 변경 수행 (factory lock_version=0)
|
||||
$response = $this->authRequest()
|
||||
->putJson("/api/admin/templates/{$this->userTemplate->identifier}/layouts/{$layout->name}", [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => $this->makeLayoutContent(
|
||||
'accuracy-test',
|
||||
'/api/admin/accuracy',
|
||||
@@ -496,42 +531,28 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
// 생성된 버전 확인
|
||||
$version = TemplateLayoutVersion::where('layout_id', $layout->id)->first();
|
||||
// 생성된 버전 확인 — 버전 2(수정본)의 changes_summary 검증 (v1 은 baseline, 변경 요약 0).
|
||||
$version = TemplateLayoutVersion::where('layout_id', $layout->id)->where('version', 2)->first();
|
||||
$this->assertNotNull($version);
|
||||
|
||||
$summary = $version->changes_summary;
|
||||
$this->assertNotNull($summary);
|
||||
$this->assertIsArray($summary);
|
||||
|
||||
// changes_summary 구조 검증
|
||||
// changes_summary 구조 검증 — 라인 단위 카운트(added/removed 정수) + char_diff.
|
||||
// modified 는 라인 diff 에 대응 개념이 없어 두지 않는다.
|
||||
$this->assertArrayHasKey('added', $summary);
|
||||
$this->assertArrayHasKey('removed', $summary);
|
||||
$this->assertArrayHasKey('modified', $summary);
|
||||
$this->assertArrayHasKey('char_diff', $summary);
|
||||
$this->assertArrayNotHasKey('modified', $summary);
|
||||
$this->assertIsInt($summary['added']);
|
||||
$this->assertIsInt($summary['removed']);
|
||||
|
||||
// 3번째 컴포넌트 (sidebar)가 추가되었는지 확인
|
||||
$addedPaths = $summary['added'];
|
||||
$this->assertTrue(
|
||||
collect($addedPaths)->contains(fn($path) => str_contains($path, 'components.2')),
|
||||
'Sidebar component should be added at index 2'
|
||||
);
|
||||
|
||||
// 1번째 컴포넌트 (header)의 title이 수정되었는지 확인
|
||||
$modifiedPaths = $summary['modified'];
|
||||
$this->assertTrue(
|
||||
collect($modifiedPaths)->contains(fn($path) => str_contains($path, 'components.0.props.title')),
|
||||
'Header title should be modified'
|
||||
);
|
||||
|
||||
// metadata 변경 확인
|
||||
$this->assertTrue(
|
||||
collect($modifiedPaths)->contains(fn($path) => str_contains($path, 'metadata.status')),
|
||||
'Metadata status should be modified'
|
||||
);
|
||||
$this->assertTrue(
|
||||
collect($addedPaths)->contains(fn($path) => str_contains($path, 'metadata.version')),
|
||||
'Metadata version should be added'
|
||||
);
|
||||
// sidebar 컴포넌트 추가 + header title/metadata 수정 → 추가/삭제 라인이 발생한다.
|
||||
// (값 변경은 라인 삭제+추가로 표현되므로 added/removed 모두 양수)
|
||||
$this->assertGreaterThan(0, $summary['added'], '추가/수정으로 새 라인이 생긴다');
|
||||
$this->assertGreaterThan(0, $summary['removed'], '값 수정으로 옛 라인이 삭제된다');
|
||||
$this->assertNotEquals(0, $summary['char_diff']);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -549,11 +570,12 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
),
|
||||
]);
|
||||
|
||||
// 거의 동시에 여러 번 수정
|
||||
// 순차 수정 — 매 저장으로 lock_version 이 1씩 증가하므로 직전 값을 전달 (i-1: 0,1,2,3,4).
|
||||
$promises = [];
|
||||
for ($i = 1; $i <= 5; $i++) {
|
||||
$response = $this->authRequest()
|
||||
->putJson("/api/admin/templates/{$this->userTemplate->identifier}/layouts/{$layout->name}", [
|
||||
'expected_lock_version' => $i - 1,
|
||||
'content' => $this->makeLayoutContent(
|
||||
'concurrent-test',
|
||||
'/api/admin/concurrent',
|
||||
@@ -570,16 +592,15 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
}
|
||||
|
||||
// 버전 번호가 올바르게 증가했는지 확인
|
||||
// (LayoutService 는 PUT 당 2개 버전 저장: 이전 롤백용 + 현재 기록용 — 5회 PUT = 10 버전)
|
||||
// (첫 PUT = baseline + 수정본 = 2건, 이후 4회 PUT = 각 1건 → 2 + 4 = 6 버전)
|
||||
$versions = TemplateLayoutVersion::where('layout_id', $layout->id)
|
||||
->orderBy('version')
|
||||
->pluck('version')
|
||||
->toArray();
|
||||
|
||||
// 5 PUT × 2 (이전 + 현재) = 10 버전
|
||||
$this->assertCount(10, $versions);
|
||||
$this->assertCount(6, $versions);
|
||||
$this->assertEquals(
|
||||
range(1, 10),
|
||||
range(1, 6),
|
||||
$versions,
|
||||
'Version numbers should be sequential without gaps'
|
||||
);
|
||||
@@ -620,9 +641,10 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
'content' => $initialContent,
|
||||
]);
|
||||
|
||||
// 수정 (버전 1 생성)
|
||||
// 수정 (factory lock_version=0) — v1=원본 baseline, v2=수정본 생성
|
||||
$this->authRequest()
|
||||
->putJson("/api/admin/templates/{$this->userTemplate->identifier}/layouts/{$layout->name}", [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => $this->makeLayoutContent(
|
||||
'integrity-test',
|
||||
'/api/admin/integrity',
|
||||
@@ -689,9 +711,10 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
),
|
||||
]);
|
||||
|
||||
// 빈 배열에서 데이터 추가
|
||||
// 빈 배열에서 데이터 추가 (factory lock_version=0)
|
||||
$response = $this->authRequest()
|
||||
->putJson("/api/admin/templates/{$this->userTemplate->identifier}/layouts/{$layout->name}", [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => $this->makeLayoutContent(
|
||||
'empty-test',
|
||||
'/api/admin/empty',
|
||||
@@ -703,29 +726,21 @@ class LayoutVersionIntegrationTest extends TestCase
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
// 버전이 생성되었는지 확인
|
||||
$version = TemplateLayoutVersion::where('layout_id', $layout->id)->first();
|
||||
// 버전 1 = 빈 원본 baseline — 빈 배열이 올바르게 저장되었는지 확인
|
||||
$version = TemplateLayoutVersion::where('layout_id', $layout->id)->where('version', 1)->first();
|
||||
$this->assertNotNull($version);
|
||||
|
||||
// 빈 배열이 올바르게 저장되었는지 확인
|
||||
$this->assertEquals([], $version->content['components']);
|
||||
$this->assertEquals([], $version->content['data_sources']);
|
||||
$this->assertEquals([], $version->content['metadata']);
|
||||
|
||||
// changes_summary에서 추가 항목 확인
|
||||
// 추가된 데이터의 변경 요약은 버전 2(수정본)에 기록된다.
|
||||
$version = TemplateLayoutVersion::where('layout_id', $layout->id)->where('version', 2)->first();
|
||||
$this->assertNotNull($version);
|
||||
|
||||
// changes_summary 에서 추가 라인 수 확인 — 컴포넌트 + 데이터소스 + 메타데이터가
|
||||
// 통째로 추가되었으므로 여러 라인이 added 로 집계된다(카운트 정수).
|
||||
$summary = $version->changes_summary;
|
||||
$addedPaths = $summary['added'];
|
||||
$this->assertTrue(
|
||||
collect($addedPaths)->contains(fn($path) => str_contains($path, 'components.0')),
|
||||
'Header component should be added'
|
||||
);
|
||||
$this->assertTrue(
|
||||
collect($addedPaths)->contains(fn($path) => str_contains($path, 'data_sources.0')),
|
||||
'API data source should be added'
|
||||
);
|
||||
$this->assertTrue(
|
||||
collect($addedPaths)->contains(fn($path) => str_contains($path, 'metadata.key')),
|
||||
'Metadata key should be added'
|
||||
);
|
||||
$this->assertIsInt($summary['added']);
|
||||
$this->assertGreaterThan(0, $summary['added'], '컴포넌트/데이터소스/메타데이터 추가로 라인이 늘어난다');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 페이지 설정 편집기 엔드포인트 4종 — 가드/응답/403 경계.
|
||||
*
|
||||
* 대상:
|
||||
* - GET seo-candidates.json (SeoCandidateController) — page_type/toggle/vars 후보
|
||||
* - POST seo-og-preview (SeoOgPreviewController) — og/twitter cascade + 필터 diff
|
||||
* - POST seo-bot-preview (SeoBotPreviewController) — dirty 레이아웃 봇 HTML
|
||||
* - GET broadcast-catalog.json (BroadcastCatalogController) — 채널/이벤트 카탈로그
|
||||
*
|
||||
* 모두 `core.templates.layouts.edit` 가드(편집 권한자만, Bearer fetch). 후보 미존재 시
|
||||
* 빈 목록 디그레이드(편집기 자유 텍스트 폴백). 백엔드 정합의 SSoT.
|
||||
*/
|
||||
class PageSettingsEditorEndpointsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
private string $adminToken;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$editPermission = Permission::firstOrCreate([
|
||||
'identifier' => 'core.templates.layouts.edit',
|
||||
], [
|
||||
'name' => '레이아웃 편집',
|
||||
'display_name' => '레이아웃 편집',
|
||||
'type' => 'admin',
|
||||
]);
|
||||
|
||||
$role = Role::firstOrCreate(['identifier' => 'super-admin'], [
|
||||
'name' => 'Super Admin',
|
||||
'display_name' => 'Super Admin',
|
||||
'is_default' => false,
|
||||
]);
|
||||
$role->permissions()->syncWithoutDetaching([$editPermission->id]);
|
||||
|
||||
$admin = User::factory()->create();
|
||||
$admin->roles()->syncWithoutDetaching([$role->id]);
|
||||
$this->adminToken = $admin->createToken('admin')->plainTextToken;
|
||||
}
|
||||
|
||||
private function authHeaders(): array
|
||||
{
|
||||
return [
|
||||
'Authorization' => "Bearer {$this->adminToken}",
|
||||
'Accept' => 'application/json',
|
||||
];
|
||||
}
|
||||
|
||||
private function noPermToken(): string
|
||||
{
|
||||
return User::factory()->create()->createToken('noperm')->plainTextToken;
|
||||
}
|
||||
|
||||
// ── SEO 후보 ──
|
||||
|
||||
public function test_seo_candidates_returns_200_with_candidate_shape(): void
|
||||
{
|
||||
$response = $this->withHeaders($this->authHeaders())
|
||||
->getJson('/api/admin/templates/sirsoft-basic/editor/seo-candidates.json?page_type=post');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertJsonStructure([
|
||||
'success',
|
||||
'data' => ['identifier', 'page_types', 'toggle_settings', 'vars', 'extensions'],
|
||||
]);
|
||||
$this->assertIsArray($response->json('data.page_types'));
|
||||
$this->assertIsArray($response->json('data.toggle_settings'));
|
||||
$this->assertIsArray($response->json('data.vars'));
|
||||
$this->assertIsArray($response->json('data.extensions'));
|
||||
}
|
||||
|
||||
public function test_seo_candidates_extensions_carry_type_id_and_label(): void
|
||||
{
|
||||
// 확장 SEO 연동 칩(`g7le-seo-extensions`)의 활성 모듈/플러그인 후보 shape.
|
||||
// 각 항목은 {type, id, label} — label 은 확장 getName() 로케일 해석값(폴백=id).
|
||||
// (RefreshDatabase 환경엔 활성 확장이 0건일 수 있으므로 빈 배열 허용 — shape 만 보증.
|
||||
// requiredExtensions 는 마이그레이션 경로만 등록하지 활성화하지 않는다.)
|
||||
$response = $this->withHeaders($this->authHeaders())
|
||||
->getJson('/api/admin/templates/sirsoft-basic/editor/seo-candidates.json');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$extensions = $response->json('data.extensions');
|
||||
$this->assertIsArray($extensions);
|
||||
foreach ($extensions as $ext) {
|
||||
$this->assertArrayHasKey('type', $ext);
|
||||
$this->assertContains($ext['type'], ['module', 'plugin']);
|
||||
$this->assertArrayHasKey('id', $ext);
|
||||
$this->assertIsString($ext['id']);
|
||||
$this->assertArrayHasKey('label', $ext);
|
||||
$this->assertIsString($ext['label']);
|
||||
$this->assertNotSame('', $ext['label'], 'label 은 폴백(id)이라도 비어선 안 된다');
|
||||
}
|
||||
}
|
||||
|
||||
public function test_seo_candidates_requires_edit_permission(): void
|
||||
{
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$this->noPermToken(),
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/templates/sirsoft-basic/editor/seo-candidates.json');
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
// ── OG 미리보기 ──
|
||||
|
||||
public function test_seo_og_preview_computes_cascade_and_missing(): void
|
||||
{
|
||||
// extensions/page_type 둘 다 비면 defaultsAvailable=false + missing 표기.
|
||||
$response = $this->withHeaders($this->authHeaders())
|
||||
->postJson('/api/admin/templates/sirsoft-basic/editor/seo-og-preview', [
|
||||
'seo' => ['enabled' => true, 'og' => ['title' => '테스트 제목']],
|
||||
'seed_context' => [],
|
||||
'route_params' => [],
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertJsonStructure([
|
||||
'data' => ['defaultsAvailable', 'missing', 'og', 'twitter', 'structured'],
|
||||
]);
|
||||
$this->assertFalse($response->json('data.defaultsAvailable'));
|
||||
$this->assertContains('extensions', $response->json('data.missing'));
|
||||
$this->assertContains('page_type', $response->json('data.missing'));
|
||||
// og 키별 cascade 항목 shape.
|
||||
$ogKeys = array_column($response->json('data.og'), 'key');
|
||||
$this->assertContains('title', $ogKeys);
|
||||
foreach ($response->json('data.og') as $row) {
|
||||
$this->assertArrayHasKey('source', $row);
|
||||
$this->assertArrayHasKey('overriddenByLayout', $row);
|
||||
$this->assertArrayHasKey('lockedByFilter', $row);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_seo_og_preview_layout_override_source(): void
|
||||
{
|
||||
// 레이아웃이 og.title 을 직접 선언 → 그 키 source=layout, overriddenByLayout=true.
|
||||
$response = $this->withHeaders($this->authHeaders())
|
||||
->postJson('/api/admin/templates/sirsoft-basic/editor/seo-og-preview', [
|
||||
'seo' => ['enabled' => true, 'og' => ['title' => '레이아웃 제목']],
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$titleRow = collect($response->json('data.og'))->firstWhere('key', 'title');
|
||||
$this->assertNotNull($titleRow);
|
||||
$this->assertTrue($titleRow['overriddenByLayout']);
|
||||
$this->assertSame('layout', $titleRow['source']);
|
||||
}
|
||||
|
||||
public function test_seo_og_preview_requires_edit_permission(): void
|
||||
{
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$this->noPermToken(),
|
||||
'Accept' => 'application/json',
|
||||
])->postJson('/api/admin/templates/sirsoft-basic/editor/seo-og-preview', ['seo' => []]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
public function test_seo_og_preview_validates_required_seo(): void
|
||||
{
|
||||
$response = $this->withHeaders($this->authHeaders())
|
||||
->postJson('/api/admin/templates/sirsoft-basic/editor/seo-og-preview', []);
|
||||
|
||||
$response->assertStatus(422);
|
||||
}
|
||||
|
||||
// ── 봇 HTML 미리보기 ──
|
||||
|
||||
public function test_seo_bot_preview_disabled_returns_null_html(): void
|
||||
{
|
||||
// meta.seo.enabled=false → renderFromResolved null → enabled=false.
|
||||
$response = $this->withHeaders($this->authHeaders())
|
||||
->postJson('/api/admin/templates/sirsoft-basic/editor/seo-bot-preview', [
|
||||
'layout' => ['meta' => ['seo' => ['enabled' => false]], 'components' => []],
|
||||
'url' => '/test',
|
||||
'locale' => 'ko',
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertJsonStructure(['data' => ['identifier', 'enabled', 'html']]);
|
||||
$this->assertFalse($response->json('data.enabled'));
|
||||
$this->assertNull($response->json('data.html'));
|
||||
}
|
||||
|
||||
public function test_seo_bot_preview_enabled_returns_html(): void
|
||||
{
|
||||
$response = $this->withHeaders($this->authHeaders())
|
||||
->postJson('/api/admin/templates/sirsoft-basic/editor/seo-bot-preview', [
|
||||
'layout' => [
|
||||
'layout_name' => 'preview/test',
|
||||
'meta' => ['seo' => ['enabled' => true, 'title' => '봇 미리보기']],
|
||||
'components' => [],
|
||||
],
|
||||
'url' => '/preview/test',
|
||||
'locale' => 'ko',
|
||||
'seed_context' => [],
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertTrue($response->json('data.enabled'));
|
||||
$html = $response->json('data.html');
|
||||
$this->assertIsString($html);
|
||||
// 봇 미리보기는 SEO 설정 산출물만 — head 안 SEO 메타(og/twitter)·title 태그는 포함.
|
||||
$this->assertStringContainsString('<head>', $html);
|
||||
$this->assertStringContainsString('<title>', $html);
|
||||
$this->assertStringContainsString('property="og:', $html);
|
||||
// body 컴포넌트 마크업·CSS·시스템 메타는 SEO 산출물이 아니므로 미포함.
|
||||
$this->assertStringNotContainsString('<body', $html);
|
||||
$this->assertStringNotContainsString('stylesheet', $html);
|
||||
$this->assertStringNotContainsString('charset', $html);
|
||||
}
|
||||
|
||||
public function test_seo_bot_preview_validates_required_layout(): void
|
||||
{
|
||||
$response = $this->withHeaders($this->authHeaders())
|
||||
->postJson('/api/admin/templates/sirsoft-basic/editor/seo-bot-preview', []);
|
||||
|
||||
$response->assertStatus(422);
|
||||
}
|
||||
|
||||
public function test_seo_bot_preview_requires_edit_permission(): void
|
||||
{
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$this->noPermToken(),
|
||||
'Accept' => 'application/json',
|
||||
])->postJson('/api/admin/templates/sirsoft-basic/editor/seo-bot-preview', [
|
||||
'layout' => ['meta' => ['seo' => ['enabled' => false]]],
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
// ── 웹소켓 카탈로그 ──
|
||||
|
||||
public function test_broadcast_catalog_returns_channels_with_core(): void
|
||||
{
|
||||
$response = $this->withHeaders($this->authHeaders())
|
||||
->getJson('/api/admin/templates/sirsoft-basic/editor/broadcast-catalog.json');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertJsonStructure(['data' => ['identifier', 'channels', 'events']]);
|
||||
$channelNames = array_column($response->json('data.channels'), 'name');
|
||||
$this->assertContains('core.admin.dashboard', $channelNames, '코어 채널이 카탈로그에 포함되어야 한다');
|
||||
// 각 채널에 출처(source.kind) 부착.
|
||||
foreach ($response->json('data.channels') as $ch) {
|
||||
$this->assertArrayHasKey('source', $ch);
|
||||
$this->assertArrayHasKey('kind', $ch['source']);
|
||||
}
|
||||
// 이벤트는 동적 발행이라 빈 목록(자유 텍스트 폴백).
|
||||
$this->assertSame([], $response->json('data.events'));
|
||||
}
|
||||
|
||||
public function test_broadcast_catalog_requires_edit_permission(): void
|
||||
{
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$this->noPermToken(),
|
||||
'Accept' => 'application/json',
|
||||
])->getJson('/api/admin/templates/sirsoft-basic/editor/broadcast-catalog.json');
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
}
|
||||
@@ -430,6 +430,65 @@ class SettingsControllerTest extends TestCase
|
||||
->assertJson(['success' => true]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 본인인증 탭 — purpose id 에 점(.)이 포함된 목적별 프로바이더 매핑 저장 성공.
|
||||
*
|
||||
* 회귀 방지: KG이니시스 플러그인이 선언한 purpose id `inicis.adult_verification` 처럼
|
||||
* 점을 포함하는 purpose 를 매핑하면, 프론트엔드 폼 바인딩이 dot-notation name
|
||||
* (`identity.purpose_providers.inicis.adult_verification`) 을 중첩 객체로 풀어
|
||||
* `purpose_providers.inicis = { adult_verification: '...' }` 형태로 전송한다.
|
||||
* 백엔드 조회(IdentityVerificationManager::resolveForPurpose)는 config dot-path 라
|
||||
* 이 중첩 구조가 정상이지만, validation rule 이 1단계 깊이만 string 으로 허용하면
|
||||
* 중첩된 `inicis` 가 배열이 되어 422 ("문자열이어야 합니다.") 가 발생했던 사례.
|
||||
* 환경설정 > 본인인증 > 목적별 프로바이더 저장이 전면 차단됐음.
|
||||
*/
|
||||
public function test_store_saves_identity_purpose_providers_with_dotted_purpose_id(): void
|
||||
{
|
||||
$response = $this->authRequest()->postJson('/api/admin/settings', [
|
||||
'_tab' => 'identity',
|
||||
'identity' => [
|
||||
'default_provider' => 'g7:core.mail',
|
||||
'purpose_providers' => [
|
||||
'signup' => '',
|
||||
'password_reset' => null,
|
||||
// 점(.)을 포함한 purpose id → 폼 바인딩이 중첩 객체로 풀어 전송
|
||||
'inicis' => [
|
||||
'adult_verification' => 'inicis',
|
||||
],
|
||||
],
|
||||
'challenge_ttl_minutes' => 15,
|
||||
'max_attempts' => 5,
|
||||
],
|
||||
]);
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJson(['success' => true]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 본인인증 탭 — 점 포함 purpose 매핑 값이 max:100 을 초과하면 중첩 경로로 검증 실패.
|
||||
*
|
||||
* nested 허용으로 완화하되, 값 길이 제약(string|max:100)은 임의 깊이에서도 유지되어야 한다.
|
||||
*/
|
||||
public function test_store_validates_nested_purpose_provider_value_length(): void
|
||||
{
|
||||
$response = $this->authRequest()->postJson('/api/admin/settings', [
|
||||
'_tab' => 'identity',
|
||||
'identity' => [
|
||||
'purpose_providers' => [
|
||||
'inicis' => [
|
||||
'adult_verification' => str_repeat('x', 101), // max:100 초과
|
||||
],
|
||||
],
|
||||
'challenge_ttl_minutes' => 15,
|
||||
'max_attempts' => 5,
|
||||
],
|
||||
]);
|
||||
|
||||
$response->assertStatus(422)
|
||||
->assertJsonValidationErrors(['identity.purpose_providers.inicis.adult_verification']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 본인인증 탭 — challenge_ttl_minutes 범위(1~1440) 검증.
|
||||
*/
|
||||
@@ -691,7 +750,7 @@ class SettingsControllerTest extends TestCase
|
||||
* 메모리 사용량은 디스크 사용량과 동일한 구조(total/used/free/percentage)로 반환된다.
|
||||
*
|
||||
* 회귀 테스트: memory_get_usage(true)는 PHP 프로세스 메모리만 반환하여
|
||||
* 서버 물리 RAM과 무관한 값(6~12MB)이 노출되던 이슈(#298) 방지.
|
||||
* 서버 물리 RAM과 무관한 값(6~12MB)이 노출되던 이슈 방지.
|
||||
*/
|
||||
public function test_system_info_memory_usage_has_disk_like_structure(): void
|
||||
{
|
||||
@@ -716,7 +775,7 @@ class SettingsControllerTest extends TestCase
|
||||
* 그대로 노출되지 않는다.
|
||||
*
|
||||
* 회귀 테스트: Windows 11/Server 2025에서 wmic 제거로 인해
|
||||
* "operable program or batch file."가 그대로 노출되던 이슈(#298) 방지.
|
||||
* "operable program or batch file."가 그대로 노출되던 이슈 방지.
|
||||
*/
|
||||
public function test_system_info_cpu_info_is_not_shell_error_tail(): void
|
||||
{
|
||||
@@ -735,7 +794,7 @@ class SettingsControllerTest extends TestCase
|
||||
* 두 번째 호출부터는 하드웨어 정보가 캐시에서 제공된다.
|
||||
*
|
||||
* 회귀 테스트: PowerShell(CIM) 호출이 수백ms ~ 수초 걸려 탭 전환
|
||||
* UX 를 저해하던 이슈(#298) 방지. server_time 은 캐시 제외이므로
|
||||
* UX 를 저해하던 이슈 방지. server_time 은 캐시 제외이므로
|
||||
* 매 호출마다 갱신됨도 함께 검증한다.
|
||||
*/
|
||||
public function test_system_info_caches_hardware_payload_but_refreshes_server_time(): void
|
||||
@@ -1162,7 +1221,7 @@ class SettingsControllerTest extends TestCase
|
||||
* site_logo가 Attachment 객체 배열로 전송되어도 검증 통과
|
||||
*
|
||||
* initLocal로 복사된 Attachment 객체가 폼 데이터에 포함되어
|
||||
* 정수 검증 실패하는 버그 회귀 방지 (#225)
|
||||
* 정수 검증 실패하는 버그 회귀 방지
|
||||
*/
|
||||
public function test_store_general_accepts_site_logo_as_attachment_objects(): void
|
||||
{
|
||||
|
||||
@@ -8,8 +8,11 @@ use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\Template;
|
||||
use App\Models\User;
|
||||
use App\Services\TemplateService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
|
||||
@@ -540,6 +543,93 @@ class TemplateControllerTest extends TestCase
|
||||
$this->assertArrayNotHasKey('deleted_at', $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 상세 응답에 template.json 의 externals 가 정규화되어 포함된다.
|
||||
*/
|
||||
public function test_show_response_includes_normalized_externals(): void
|
||||
{
|
||||
// Arrange
|
||||
$template = Template::factory()->create();
|
||||
|
||||
// Mock 설정 — externals 에 정규화 대상(HTTP URL, 중복) 포함
|
||||
$mock = Mockery::mock(TemplateManagerInterface::class);
|
||||
$mock->shouldReceive('loadTemplates')->andReturnNull();
|
||||
$mock->shouldReceive('getTemplateInfo')->andReturn([
|
||||
'id' => $template->id,
|
||||
'identifier' => $template->identifier,
|
||||
'vendor' => $template->vendor,
|
||||
'name' => $template->name,
|
||||
'version' => $template->version,
|
||||
'type' => $template->type,
|
||||
'status' => $template->status,
|
||||
'externals' => [
|
||||
[
|
||||
'id' => 'fontawesome',
|
||||
'type' => 'style',
|
||||
'url' => 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css',
|
||||
],
|
||||
// 중복 — normalize 가 제거해야 함
|
||||
[
|
||||
'id' => 'fontawesome-dup',
|
||||
'type' => 'style',
|
||||
'url' => 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css',
|
||||
],
|
||||
// HTTP URL — normalize 가 탈락시켜야 함
|
||||
[
|
||||
'id' => 'insecure',
|
||||
'type' => 'style',
|
||||
'url' => 'http://insecure.example.com/style.css',
|
||||
],
|
||||
],
|
||||
]);
|
||||
$this->app->instance(TemplateManagerInterface::class, $mock);
|
||||
|
||||
// Act
|
||||
$response = $this->authRequest()->getJson("/api/admin/templates/{$template->identifier}");
|
||||
|
||||
// Assert
|
||||
$response->assertStatus(200);
|
||||
|
||||
$externals = $response->json('data.externals');
|
||||
$this->assertIsArray($externals);
|
||||
// 중복 1건 + HTTP 1건 탈락 → 1건만 남음
|
||||
$this->assertCount(1, $externals);
|
||||
$this->assertSame('style', $externals[0]['type']);
|
||||
$this->assertSame(
|
||||
'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css',
|
||||
$externals[0]['url'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* externals 가 없는 템플릿은 상세 응답에서 빈 배열로 노출된다.
|
||||
*/
|
||||
public function test_show_response_externals_defaults_to_empty_array(): void
|
||||
{
|
||||
// Arrange
|
||||
$template = Template::factory()->create();
|
||||
|
||||
$mock = Mockery::mock(TemplateManagerInterface::class);
|
||||
$mock->shouldReceive('loadTemplates')->andReturnNull();
|
||||
$mock->shouldReceive('getTemplateInfo')->andReturn([
|
||||
'id' => $template->id,
|
||||
'identifier' => $template->identifier,
|
||||
'vendor' => $template->vendor,
|
||||
'name' => $template->name,
|
||||
'version' => $template->version,
|
||||
'type' => $template->type,
|
||||
'status' => $template->status,
|
||||
]);
|
||||
$this->app->instance(TemplateManagerInterface::class, $mock);
|
||||
|
||||
// Act
|
||||
$response = $this->authRequest()->getJson("/api/admin/templates/{$template->identifier}");
|
||||
|
||||
// Assert
|
||||
$response->assertStatus(200);
|
||||
$this->assertSame([], $response->json('data.externals'));
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// activate() 테스트
|
||||
// ========================================
|
||||
@@ -623,7 +713,7 @@ class TemplateControllerTest extends TestCase
|
||||
$mock = Mockery::mock(TemplateManagerInterface::class);
|
||||
$mock->shouldReceive('loadTemplates')->andReturnNull();
|
||||
$mock->shouldReceive('activateTemplate')->andThrow(
|
||||
\Illuminate\Validation\ValidationException::withMessages([
|
||||
ValidationException::withMessages([
|
||||
'template' => ['No active template found'],
|
||||
])
|
||||
);
|
||||
@@ -734,7 +824,7 @@ class TemplateControllerTest extends TestCase
|
||||
$mock->shouldReceive('loadTemplates')->andReturnNull();
|
||||
$mock->shouldReceive('getTemplate')->andReturn(null);
|
||||
$mock->shouldReceive('installTemplate')->andThrow(
|
||||
\Illuminate\Validation\ValidationException::withMessages([
|
||||
ValidationException::withMessages([
|
||||
'identifier' => ['Failed to install template.: Template not found'],
|
||||
])
|
||||
);
|
||||
@@ -898,7 +988,7 @@ class TemplateControllerTest extends TestCase
|
||||
*/
|
||||
public function test_install_from_file_succeeds_with_valid_zip(): void
|
||||
{
|
||||
$templateServiceMock = \Mockery::mock(\App\Services\TemplateService::class);
|
||||
$templateServiceMock = Mockery::mock(TemplateService::class);
|
||||
$templateServiceMock->shouldReceive('installFromZipFile')
|
||||
->once()
|
||||
->andReturn([
|
||||
@@ -906,7 +996,7 @@ class TemplateControllerTest extends TestCase
|
||||
'name' => 'Test Template',
|
||||
'version' => '1.0.0',
|
||||
]);
|
||||
$this->app->instance(\App\Services\TemplateService::class, $templateServiceMock);
|
||||
$this->app->instance(TemplateService::class, $templateServiceMock);
|
||||
|
||||
$file = UploadedFile::fake()->create('template.zip', 100, 'application/zip');
|
||||
|
||||
@@ -924,11 +1014,11 @@ class TemplateControllerTest extends TestCase
|
||||
*/
|
||||
public function test_install_from_file_returns_422_on_runtime_exception(): void
|
||||
{
|
||||
$templateServiceMock = \Mockery::mock(\App\Services\TemplateService::class);
|
||||
$templateServiceMock = Mockery::mock(TemplateService::class);
|
||||
$templateServiceMock->shouldReceive('installFromZipFile')
|
||||
->once()
|
||||
->andThrow(new \RuntimeException('template.json을 찾을 수 없습니다.'));
|
||||
$this->app->instance(\App\Services\TemplateService::class, $templateServiceMock);
|
||||
$this->app->instance(TemplateService::class, $templateServiceMock);
|
||||
|
||||
$file = UploadedFile::fake()->create('template.zip', 100, 'application/zip');
|
||||
|
||||
@@ -945,11 +1035,11 @@ class TemplateControllerTest extends TestCase
|
||||
*/
|
||||
public function test_install_from_file_returns_500_on_general_exception(): void
|
||||
{
|
||||
$templateServiceMock = \Mockery::mock(\App\Services\TemplateService::class);
|
||||
$templateServiceMock = Mockery::mock(TemplateService::class);
|
||||
$templateServiceMock->shouldReceive('installFromZipFile')
|
||||
->once()
|
||||
->andThrow(new \Exception('예상치 못한 오류'));
|
||||
$this->app->instance(\App\Services\TemplateService::class, $templateServiceMock);
|
||||
$this->app->instance(TemplateService::class, $templateServiceMock);
|
||||
|
||||
$file = UploadedFile::fake()->create('template.zip', 100, 'application/zip');
|
||||
|
||||
@@ -969,7 +1059,7 @@ class TemplateControllerTest extends TestCase
|
||||
*/
|
||||
public function test_install_from_github_calls_service_with_valid_url(): void
|
||||
{
|
||||
$templateServiceMock = \Mockery::mock(\App\Services\TemplateService::class);
|
||||
$templateServiceMock = Mockery::mock(TemplateService::class);
|
||||
$templateServiceMock->shouldReceive('installFromGithub')
|
||||
->once()
|
||||
->with('https://github.com/sirsoft/sample-template')
|
||||
@@ -978,7 +1068,7 @@ class TemplateControllerTest extends TestCase
|
||||
'name' => 'Sample Template',
|
||||
'version' => '1.0.0',
|
||||
]);
|
||||
$this->app->instance(\App\Services\TemplateService::class, $templateServiceMock);
|
||||
$this->app->instance(TemplateService::class, $templateServiceMock);
|
||||
|
||||
$response = $this->authRequest()->postJson('/api/admin/templates/install-from-github', [
|
||||
'github_url' => 'https://github.com/sirsoft/sample-template',
|
||||
@@ -994,11 +1084,11 @@ class TemplateControllerTest extends TestCase
|
||||
*/
|
||||
public function test_install_from_github_returns_422_on_runtime_exception(): void
|
||||
{
|
||||
$templateServiceMock = \Mockery::mock(\App\Services\TemplateService::class);
|
||||
$templateServiceMock = Mockery::mock(TemplateService::class);
|
||||
$templateServiceMock->shouldReceive('installFromGithub')
|
||||
->once()
|
||||
->andThrow(new \RuntimeException('GitHub 저장소를 찾을 수 없습니다.'));
|
||||
$this->app->instance(\App\Services\TemplateService::class, $templateServiceMock);
|
||||
$this->app->instance(TemplateService::class, $templateServiceMock);
|
||||
|
||||
$response = $this->authRequest()->postJson('/api/admin/templates/install-from-github', [
|
||||
'github_url' => 'https://github.com/sirsoft/sample-template',
|
||||
@@ -1013,11 +1103,11 @@ class TemplateControllerTest extends TestCase
|
||||
*/
|
||||
public function test_install_from_github_returns_500_on_general_exception(): void
|
||||
{
|
||||
$templateServiceMock = \Mockery::mock(\App\Services\TemplateService::class);
|
||||
$templateServiceMock = Mockery::mock(TemplateService::class);
|
||||
$templateServiceMock->shouldReceive('installFromGithub')
|
||||
->once()
|
||||
->andThrow(new \Exception('예상치 못한 오류'));
|
||||
$this->app->instance(\App\Services\TemplateService::class, $templateServiceMock);
|
||||
$this->app->instance(TemplateService::class, $templateServiceMock);
|
||||
|
||||
$response = $this->authRequest()->postJson('/api/admin/templates/install-from-github', [
|
||||
'github_url' => 'https://github.com/sirsoft/sample-template',
|
||||
@@ -1210,7 +1300,7 @@ class TemplateControllerTest extends TestCase
|
||||
$mock = Mockery::mock(TemplateManagerInterface::class);
|
||||
$mock->shouldReceive('loadTemplates')->andReturnNull();
|
||||
$mock->shouldReceive('deactivateTemplate')->andThrow(
|
||||
\Illuminate\Validation\ValidationException::withMessages([
|
||||
ValidationException::withMessages([
|
||||
'template' => ['No active template found'],
|
||||
])
|
||||
);
|
||||
@@ -1448,8 +1538,8 @@ class TemplateControllerTest extends TestCase
|
||||
public function test_changelog_returns_parsed_entries(): void
|
||||
{
|
||||
$templatePath = base_path('templates/test-changelog-tpl');
|
||||
\Illuminate\Support\Facades\File::ensureDirectoryExists($templatePath);
|
||||
\Illuminate\Support\Facades\File::put($templatePath.'/CHANGELOG.md', "# Changelog\n\n## [0.1.1] - 2026-02-25\n\n### Changed\n- UI 개선\n");
|
||||
File::ensureDirectoryExists($templatePath);
|
||||
File::put($templatePath.'/CHANGELOG.md', "# Changelog\n\n## [0.1.1] - 2026-02-25\n\n### Changed\n- UI 개선\n");
|
||||
|
||||
try {
|
||||
$response = $this->authRequest()->getJson('/api/admin/templates/test-changelog-tpl/changelog');
|
||||
@@ -1458,7 +1548,7 @@ class TemplateControllerTest extends TestCase
|
||||
->assertJsonPath('data.changelog.0.version', '0.1.1')
|
||||
->assertJsonPath('data.changelog.0.categories.0.name', 'Changed');
|
||||
} finally {
|
||||
\Illuminate\Support\Facades\File::deleteDirectory($templatePath);
|
||||
File::deleteDirectory($templatePath);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\Template;
|
||||
use App\Models\TemplateCustomTranslation;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* TemplateCustomTranslationController API 테스트.
|
||||
*
|
||||
* 커스텀 다국어 키 CRUD / 권한 경계 / 키 자동 생성 / seq 충돌 / 낙관적 잠금(409)을
|
||||
* 검증합니다.
|
||||
*/
|
||||
class TemplateCustomTranslationControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 레이아웃/템플릿 요청 경로가 GDPR 정책 테이블을 조회하므로
|
||||
* 해당 플러그인 마이그레이션을 테스트 DB 에 포함시킨다.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
private User $adminUser;
|
||||
|
||||
private User $normalUser;
|
||||
|
||||
private Template $template;
|
||||
|
||||
private string $token;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->adminUser = $this->createAdminUser([
|
||||
'core.templates.read',
|
||||
'core.templates.layouts.edit',
|
||||
]);
|
||||
$this->token = $this->adminUser->createToken('test-token')->plainTextToken;
|
||||
|
||||
$this->normalUser = User::factory()->create();
|
||||
$this->template = Template::factory()->create();
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자 사용자 생성 (필요한 권한 포함)
|
||||
*
|
||||
* @param array<string> $permissions 부여할 권한 식별자 목록
|
||||
*/
|
||||
private function createAdminUser(array $permissions = []): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$permissionIds = [];
|
||||
foreach ($permissions as $permissionIdentifier) {
|
||||
$permission = Permission::firstOrCreate(
|
||||
['identifier' => $permissionIdentifier],
|
||||
[
|
||||
'name' => json_encode(['ko' => $permissionIdentifier, 'en' => $permissionIdentifier]),
|
||||
'description' => json_encode(['ko' => $permissionIdentifier, 'en' => $permissionIdentifier]),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'type' => 'admin',
|
||||
]
|
||||
);
|
||||
$permissionIds[] = $permission->id;
|
||||
}
|
||||
|
||||
$testRole = Role::create([
|
||||
'identifier' => 'admin_test_'.uniqid(),
|
||||
'name' => json_encode(['ko' => '테스트 관리자', 'en' => 'Test Administrator']),
|
||||
'description' => json_encode(['ko' => '테스트 관리자', 'en' => 'Test Administrator']),
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$adminRole = Role::firstOrCreate(
|
||||
['identifier' => 'admin'],
|
||||
[
|
||||
'name' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
|
||||
'description' => json_encode(['ko' => '시스템 관리자', 'en' => 'System Administrator']),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'type' => 'admin',
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
|
||||
$testRole->permissions()->sync($permissionIds);
|
||||
$user->roles()->attach($adminRole->id, ['assigned_at' => now(), 'assigned_by' => null]);
|
||||
$user->roles()->attach($testRole->id, ['assigned_at' => now(), 'assigned_by' => null]);
|
||||
|
||||
return $user->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* 인증된 요청 헬퍼
|
||||
*/
|
||||
private function authRequest(): static
|
||||
{
|
||||
return $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$this->token,
|
||||
'Accept' => 'application/json',
|
||||
]);
|
||||
}
|
||||
|
||||
private function endpoint(string $suffix = ''): string
|
||||
{
|
||||
return "/api/admin/templates/{$this->template->identifier}/custom-translations{$suffix}";
|
||||
}
|
||||
|
||||
// ---- store: 키 자동 생성 ----
|
||||
|
||||
public function test_store_creates_key_with_auto_generated_translation_key(): void
|
||||
{
|
||||
$response = $this->authRequest()->postJson($this->endpoint(), [
|
||||
'layout_name' => 'board/list',
|
||||
'locale' => 'ko',
|
||||
'value' => '안녕하세요',
|
||||
]);
|
||||
|
||||
$response->assertStatus(201);
|
||||
$response->assertJsonPath('data.translation_key', 'custom.board_list.1');
|
||||
$response->assertJsonPath('data.values.ko', '안녕하세요');
|
||||
// 모든 활성 로케일에 폴백 시드
|
||||
$response->assertJsonPath('data.values.en', '안녕하세요');
|
||||
$response->assertJsonPath('data.lock_version', 0);
|
||||
|
||||
$this->assertDatabaseHas('template_custom_translations', [
|
||||
'template_id' => $this->template->id,
|
||||
'translation_key' => 'custom.board_list.1',
|
||||
'status' => 'active',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_store_increments_seq_for_same_layout(): void
|
||||
{
|
||||
$this->authRequest()->postJson($this->endpoint(), [
|
||||
'layout_name' => 'home',
|
||||
'locale' => 'ko',
|
||||
'value' => '첫번째',
|
||||
])->assertStatus(201)->assertJsonPath('data.translation_key', 'custom.home.1');
|
||||
|
||||
$this->authRequest()->postJson($this->endpoint(), [
|
||||
'layout_name' => 'home',
|
||||
'locale' => 'ko',
|
||||
'value' => '두번째',
|
||||
])->assertStatus(201)->assertJsonPath('data.translation_key', 'custom.home.2');
|
||||
}
|
||||
|
||||
public function test_store_validation_fails_when_value_missing(): void
|
||||
{
|
||||
$response = $this->authRequest()->postJson($this->endpoint(), [
|
||||
'layout_name' => 'home',
|
||||
'locale' => 'ko',
|
||||
]);
|
||||
|
||||
$response->assertStatus(422);
|
||||
$response->assertJsonValidationErrors(['value']);
|
||||
}
|
||||
|
||||
// ---- index ----
|
||||
|
||||
public function test_index_returns_keys_filtered_by_layout(): void
|
||||
{
|
||||
TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => ['ko' => 'A', 'en' => 'A'],
|
||||
'status' => 'active',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'board/list',
|
||||
'translation_key' => 'custom.board_list.1',
|
||||
'values' => ['ko' => 'B', 'en' => 'B'],
|
||||
'status' => 'active',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->getJson($this->endpoint('?layout_name=home'));
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertJsonCount(1, 'data');
|
||||
$response->assertJsonPath('data.0.translation_key', 'custom.home.1');
|
||||
}
|
||||
|
||||
// ---- update: 낙관적 잠금 ----
|
||||
|
||||
public function test_update_changes_values_and_increments_lock_version(): void
|
||||
{
|
||||
$row = TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => ['ko' => '구', 'en' => 'old'],
|
||||
'status' => 'active',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->putJson($this->endpoint("/{$row->id}"), [
|
||||
'values' => ['ko' => '신', 'en' => 'new'],
|
||||
'expected_lock_version' => 0,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertJsonPath('data.values.ko', '신');
|
||||
$response->assertJsonPath('data.lock_version', 1);
|
||||
|
||||
$this->assertDatabaseHas('template_custom_translations', [
|
||||
'id' => $row->id,
|
||||
'lock_version' => 1,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_update_returns_409_on_lock_version_conflict(): void
|
||||
{
|
||||
$row = TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => ['ko' => 'A', 'en' => 'A'],
|
||||
'status' => 'active',
|
||||
'lock_version' => 3,
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->putJson($this->endpoint("/{$row->id}"), [
|
||||
'values' => ['ko' => 'B', 'en' => 'B'],
|
||||
'expected_lock_version' => 1, // stale
|
||||
]);
|
||||
|
||||
$response->assertStatus(409);
|
||||
$response->assertJsonPath('errors.error', 'concurrent_modification');
|
||||
$response->assertJsonPath('errors.current_version', 3);
|
||||
$response->assertJsonPath('errors.your_version', 1);
|
||||
|
||||
// 값이 변경되지 않았는지 확인
|
||||
$this->assertDatabaseHas('template_custom_translations', [
|
||||
'id' => $row->id,
|
||||
'lock_version' => 3,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_update_concurrent_edit_one_succeeds_one_conflicts(): void
|
||||
{
|
||||
$row = TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => ['ko' => 'A', 'en' => 'A'],
|
||||
'status' => 'active',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
// 두 클라이언트 모두 expected=0 보유
|
||||
$first = $this->authRequest()->putJson($this->endpoint("/{$row->id}"), [
|
||||
'values' => ['ko' => 'first', 'en' => 'first'],
|
||||
'expected_lock_version' => 0,
|
||||
]);
|
||||
$first->assertStatus(200);
|
||||
|
||||
$second = $this->authRequest()->putJson($this->endpoint("/{$row->id}"), [
|
||||
'values' => ['ko' => 'second', 'en' => 'second'],
|
||||
'expected_lock_version' => 0,
|
||||
]);
|
||||
$second->assertStatus(409);
|
||||
|
||||
$this->assertDatabaseHas('template_custom_translations', [
|
||||
'id' => $row->id,
|
||||
'lock_version' => 1,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_update_validation_fails_when_expected_lock_version_missing(): void
|
||||
{
|
||||
$row = TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => ['ko' => 'A', 'en' => 'A'],
|
||||
'status' => 'active',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->putJson($this->endpoint("/{$row->id}"), [
|
||||
'values' => ['ko' => 'B', 'en' => 'B'],
|
||||
]);
|
||||
|
||||
$response->assertStatus(422);
|
||||
$response->assertJsonValidationErrors(['expected_lock_version']);
|
||||
}
|
||||
|
||||
// ---- destroy ----
|
||||
|
||||
public function test_destroy_removes_key(): void
|
||||
{
|
||||
$row = TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => ['ko' => 'A', 'en' => 'A'],
|
||||
'status' => 'active',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->deleteJson($this->endpoint("/{$row->id}"));
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertDatabaseMissing('template_custom_translations', ['id' => $row->id]);
|
||||
}
|
||||
|
||||
public function test_update_rejects_key_from_other_template(): void
|
||||
{
|
||||
$otherTemplate = Template::factory()->create();
|
||||
$row = TemplateCustomTranslation::create([
|
||||
'template_id' => $otherTemplate->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => ['ko' => 'A', 'en' => 'A'],
|
||||
'status' => 'active',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->putJson($this->endpoint("/{$row->id}"), [
|
||||
'values' => ['ko' => 'B', 'en' => 'B'],
|
||||
'expected_lock_version' => 0,
|
||||
]);
|
||||
|
||||
$response->assertStatus(404);
|
||||
}
|
||||
|
||||
// ---- bulkDestroy: 일괄 삭제 ----
|
||||
|
||||
public function test_bulk_destroy_removes_multiple_keys(): void
|
||||
{
|
||||
$a = TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => ['ko' => 'A', 'en' => 'A'],
|
||||
'status' => 'orphaned',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
$b = TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.2',
|
||||
'values' => ['ko' => 'B', 'en' => 'B'],
|
||||
'status' => 'orphaned',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->deleteJson($this->endpoint(), [
|
||||
'ids' => [$a->id, $b->id],
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertJsonPath('data.deleted', 2);
|
||||
$this->assertDatabaseMissing('template_custom_translations', ['id' => $a->id]);
|
||||
$this->assertDatabaseMissing('template_custom_translations', ['id' => $b->id]);
|
||||
}
|
||||
|
||||
public function test_bulk_destroy_ignores_keys_from_other_template(): void
|
||||
{
|
||||
$otherTemplate = Template::factory()->create();
|
||||
$own = TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => ['ko' => 'A', 'en' => 'A'],
|
||||
'status' => 'active',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
$foreign = TemplateCustomTranslation::create([
|
||||
'template_id' => $otherTemplate->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => ['ko' => 'X', 'en' => 'X'],
|
||||
'status' => 'active',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
$response = $this->authRequest()->deleteJson($this->endpoint(), [
|
||||
'ids' => [$own->id, $foreign->id],
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
// 본 템플릿 소속만 삭제 — 교차 템플릿 행은 보존.
|
||||
$response->assertJsonPath('data.deleted', 1);
|
||||
$this->assertDatabaseMissing('template_custom_translations', ['id' => $own->id]);
|
||||
$this->assertDatabaseHas('template_custom_translations', ['id' => $foreign->id]);
|
||||
}
|
||||
|
||||
public function test_bulk_destroy_validation_fails_when_ids_missing(): void
|
||||
{
|
||||
$response = $this->authRequest()->deleteJson($this->endpoint(), []);
|
||||
|
||||
$response->assertStatus(422);
|
||||
$response->assertJsonValidationErrors(['ids']);
|
||||
}
|
||||
|
||||
public function test_bulk_destroy_forbidden_without_edit_permission(): void
|
||||
{
|
||||
$row = TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => ['ko' => 'A', 'en' => 'A'],
|
||||
'status' => 'orphaned',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
$token = $this->normalUser->createToken('t')->plainTextToken;
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$token,
|
||||
'Accept' => 'application/json',
|
||||
])->deleteJson($this->endpoint(), ['ids' => [$row->id]]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
$this->assertDatabaseHas('template_custom_translations', ['id' => $row->id]);
|
||||
}
|
||||
|
||||
// ---- 권한 경계 ----
|
||||
|
||||
public function test_store_forbidden_without_edit_permission(): void
|
||||
{
|
||||
$token = $this->normalUser->createToken('t')->plainTextToken;
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => 'Bearer '.$token,
|
||||
'Accept' => 'application/json',
|
||||
])->postJson($this->endpoint(), [
|
||||
'layout_name' => 'home',
|
||||
'locale' => 'ko',
|
||||
'value' => 'x',
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
public function test_index_unauthenticated_returns_401(): void
|
||||
{
|
||||
$response = $this->withHeaders(['Accept' => 'application/json'])
|
||||
->getJson($this->endpoint());
|
||||
|
||||
$response->assertStatus(401);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\Template;
|
||||
use App\Models\TemplateLayoutAttachment;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 템플릿 레이아웃 첨부 파일 컨트롤러 Feature 테스트
|
||||
*
|
||||
* golden path(업로드/조회/삭제) + 권한 경계 + 유효성 실패 + 스토리지 실삭제 검증.
|
||||
*/
|
||||
class TemplateLayoutAttachmentControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
// 같은 스위트의 다른 레이아웃 테스트(LayoutSourceMetaServingTest 등)가
|
||||
// GDPR 플러그인 미들웨어(CookieConsentMiddleware → g7_gdpr_policy_versions)를
|
||||
// 모든 요청에서 거치므로, 공유 migrate:fresh 가 실행 순서와 무관하게 GDPR 테이블을
|
||||
// 포함하도록 동일 확장을 선언한다 (migrate:fresh 1회 함정 회피).
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
private User $adminUser;
|
||||
|
||||
private string $adminToken;
|
||||
|
||||
private Template $template;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Storage::fake(config('attachment.disk', 'attachments'));
|
||||
|
||||
$editPermission = Permission::firstOrCreate(
|
||||
['identifier' => 'core.templates.layouts.edit'],
|
||||
['name' => '레이아웃 편집', 'display_name' => '레이아웃 편집', 'type' => 'admin'],
|
||||
);
|
||||
$role = Role::firstOrCreate(
|
||||
['identifier' => 'super-admin'],
|
||||
['name' => 'Super Admin', 'display_name' => 'Super Admin', 'is_default' => false],
|
||||
);
|
||||
$role->permissions()->syncWithoutDetaching([$editPermission->id]);
|
||||
|
||||
$this->adminUser = User::factory()->create();
|
||||
$this->adminUser->roles()->syncWithoutDetaching([$role->id]);
|
||||
$this->adminToken = $this->adminUser->createToken('admin')->plainTextToken;
|
||||
|
||||
$this->template = Template::create([
|
||||
'identifier' => 'sirsoft-basic',
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => ['ko' => '기본', 'en' => 'Basic'],
|
||||
'version' => '1.0.0',
|
||||
'type' => 'user',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
'description' => ['ko' => '기본', 'en' => 'Basic'],
|
||||
]);
|
||||
}
|
||||
|
||||
/** 인증 헤더 헬퍼 */
|
||||
private function authHeaders(): array
|
||||
{
|
||||
return ['Authorization' => "Bearer {$this->adminToken}", 'Accept' => 'application/json'];
|
||||
}
|
||||
|
||||
public function test_upload_creates_attachment_and_stores_file(): void
|
||||
{
|
||||
$file = UploadedFile::fake()->image('bg.png', 100, 100);
|
||||
|
||||
$response = $this->withHeaders($this->authHeaders())
|
||||
->postJson("/api/admin/templates/{$this->template->identifier}/layout-attachments", [
|
||||
'file' => $file,
|
||||
'layout_name' => 'home',
|
||||
]);
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJson(['success' => true])
|
||||
->assertJsonPath('data.original_name', 'bg.png')
|
||||
->assertJsonPath('data.layout_name', 'home');
|
||||
|
||||
// url 은 공개 서빙 라우트를 가리켜야 한다
|
||||
$url = $response->json('data.url');
|
||||
$this->assertNotNull($url);
|
||||
$this->assertStringContainsString('/layout-attachments/', (string) $url);
|
||||
$this->assertStringContainsString('/file', (string) $url);
|
||||
|
||||
$attachment = TemplateLayoutAttachment::first();
|
||||
$this->assertNotNull($attachment);
|
||||
$this->assertSame($this->template->id, $attachment->template_id);
|
||||
$this->assertSame($this->adminUser->id, $attachment->created_by);
|
||||
|
||||
// 스토리지에 실제 저장됐는지 (category/path)
|
||||
Storage::disk($attachment->disk)->assertExists('template-layout-attachments/'.$attachment->path);
|
||||
}
|
||||
|
||||
public function test_index_lists_template_attachments(): void
|
||||
{
|
||||
TemplateLayoutAttachment::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'disk' => config('attachment.disk', 'attachments'),
|
||||
'path' => 'sirsoft-basic/2026/05/29/a.png',
|
||||
'original_name' => 'a.png',
|
||||
'mime_type' => 'image/png',
|
||||
'size' => 123,
|
||||
'created_by' => $this->adminUser->id,
|
||||
]);
|
||||
|
||||
$response = $this->withHeaders($this->authHeaders())
|
||||
->getJson("/api/admin/templates/{$this->template->identifier}/layout-attachments");
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJson(['success' => true])
|
||||
->assertJsonPath('data.0.original_name', 'a.png');
|
||||
}
|
||||
|
||||
public function test_index_filters_by_layout_name(): void
|
||||
{
|
||||
foreach (['home', 'about'] as $layout) {
|
||||
TemplateLayoutAttachment::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => $layout,
|
||||
'disk' => 'attachments',
|
||||
'path' => "p/{$layout}.png",
|
||||
'original_name' => "{$layout}.png",
|
||||
'mime_type' => 'image/png',
|
||||
'size' => 1,
|
||||
'created_by' => $this->adminUser->id,
|
||||
]);
|
||||
}
|
||||
|
||||
$response = $this->withHeaders($this->authHeaders())
|
||||
->getJson("/api/admin/templates/{$this->template->identifier}/layout-attachments?layout_name=home");
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertCount(1, $response->json('data'));
|
||||
$this->assertSame('home.png', $response->json('data.0.original_name'));
|
||||
}
|
||||
|
||||
public function test_destroy_removes_row_and_storage_file(): void
|
||||
{
|
||||
$disk = config('attachment.disk', 'attachments');
|
||||
$path = 'sirsoft-basic/2026/05/29/del.png';
|
||||
Storage::disk($disk)->put('template-layout-attachments/'.$path, 'data');
|
||||
|
||||
$attachment = TemplateLayoutAttachment::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'disk' => $disk,
|
||||
'path' => $path,
|
||||
'original_name' => 'del.png',
|
||||
'mime_type' => 'image/png',
|
||||
'size' => 4,
|
||||
'created_by' => $this->adminUser->id,
|
||||
]);
|
||||
|
||||
$response = $this->withHeaders($this->authHeaders())
|
||||
->deleteJson("/api/admin/templates/layout-attachments/{$attachment->id}");
|
||||
|
||||
$response->assertStatus(200)->assertJson(['success' => true]);
|
||||
$this->assertNull(TemplateLayoutAttachment::find($attachment->id));
|
||||
// 스토리지 파일도 명시적으로 삭제됐는지 (CASCADE 미의존)
|
||||
Storage::disk($disk)->assertMissing('template-layout-attachments/'.$path);
|
||||
}
|
||||
|
||||
public function test_upload_rejects_non_image_file(): void
|
||||
{
|
||||
$file = UploadedFile::fake()->create('doc.pdf', 10, 'application/pdf');
|
||||
|
||||
$response = $this->withHeaders($this->authHeaders())
|
||||
->postJson("/api/admin/templates/{$this->template->identifier}/layout-attachments", [
|
||||
'file' => $file,
|
||||
]);
|
||||
|
||||
$response->assertStatus(422);
|
||||
$this->assertDatabaseCount('template_layout_attachments', 0);
|
||||
}
|
||||
|
||||
public function test_upload_requires_permission(): void
|
||||
{
|
||||
// 권한 없는 사용자
|
||||
$noPermUser = User::factory()->create();
|
||||
$token = $noPermUser->createToken('np')->plainTextToken;
|
||||
|
||||
$response = $this->withHeaders([
|
||||
'Authorization' => "Bearer {$token}",
|
||||
'Accept' => 'application/json',
|
||||
])->postJson("/api/admin/templates/{$this->template->identifier}/layout-attachments", [
|
||||
'file' => UploadedFile::fake()->image('x.png'),
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
public function test_upload_to_nonexistent_template_returns_404(): void
|
||||
{
|
||||
$response = $this->withHeaders($this->authHeaders())
|
||||
->postJson('/api/admin/templates/nope-nope/layout-attachments', [
|
||||
'file' => UploadedFile::fake()->image('x.png'),
|
||||
]);
|
||||
|
||||
$response->assertStatus(404);
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
// 공개 서빙 라우트 — 발행 배경 이미지 공개 로드
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** 업로드된 첨부를 생성하고 모델 반환 (서빙 테스트용 헬퍼) */
|
||||
private function makeStoredAttachment(?Template $template = null, string $path = 'sirsoft-basic/2026/05/29/served.png'): TemplateLayoutAttachment
|
||||
{
|
||||
$template ??= $this->template;
|
||||
$disk = config('attachment.disk', 'attachments');
|
||||
Storage::disk($disk)->put('template-layout-attachments/'.$path, 'PNGDATA');
|
||||
|
||||
return TemplateLayoutAttachment::create([
|
||||
'template_id' => $template->id,
|
||||
'layout_name' => 'home',
|
||||
'disk' => $disk,
|
||||
'path' => $path,
|
||||
'original_name' => 'served.png',
|
||||
'mime_type' => 'image/png',
|
||||
'size' => 7,
|
||||
'created_by' => $this->adminUser->id,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_serve_file_returns_image_publicly_without_auth(): void
|
||||
{
|
||||
$attachment = $this->makeStoredAttachment();
|
||||
|
||||
// 인증 헤더 없이(공개) 접근 — 발행 배경은 방문자에게 로드되어야 함
|
||||
$response = $this->get("/api/templates/{$this->template->identifier}/layout-attachments/{$attachment->id}/file");
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertStringStartsWith('image/', (string) $response->headers->get('Content-Type'));
|
||||
// 캐싱 헤더(ETag) 동반
|
||||
$this->assertNotNull($response->headers->get('ETag'));
|
||||
}
|
||||
|
||||
public function test_serve_file_cross_template_returns_404(): void
|
||||
{
|
||||
// 다른 템플릿 소속 첨부를 본 템플릿 경로로 요청 → 404 (교차 접근 차단)
|
||||
$other = Template::create([
|
||||
'identifier' => 'sirsoft-admin_basic',
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => ['ko' => '관리자', 'en' => 'Admin'],
|
||||
'version' => '1.0.0',
|
||||
'type' => 'admin',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
'description' => ['ko' => '관리자', 'en' => 'Admin'],
|
||||
]);
|
||||
$attachment = $this->makeStoredAttachment($other, 'sirsoft-admin_basic/x.png');
|
||||
|
||||
$response = $this->getJson("/api/templates/{$this->template->identifier}/layout-attachments/{$attachment->id}/file");
|
||||
|
||||
$response->assertStatus(404);
|
||||
}
|
||||
|
||||
public function test_serve_file_missing_storage_returns_404(): void
|
||||
{
|
||||
// DB 행은 있으나 스토리지 파일이 없는 경우 → 404
|
||||
$attachment = TemplateLayoutAttachment::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'disk' => config('attachment.disk', 'attachments'),
|
||||
'path' => 'sirsoft-basic/missing.png',
|
||||
'original_name' => 'missing.png',
|
||||
'mime_type' => 'image/png',
|
||||
'size' => 1,
|
||||
'created_by' => $this->adminUser->id,
|
||||
]);
|
||||
|
||||
$response = $this->getJson("/api/templates/{$this->template->identifier}/layout-attachments/{$attachment->id}/file");
|
||||
|
||||
$response->assertStatus(404);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ namespace Tests\Feature\Api\Admin;
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Enums\IdentityVerificationStatus;
|
||||
use App\Enums\PermissionType;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\IdentityPolicy;
|
||||
use App\Models\IdentityVerificationLog;
|
||||
use App\Models\Permission;
|
||||
@@ -13,6 +14,7 @@ use App\Models\User;
|
||||
use Database\Seeders\IdentityPolicySeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Str;
|
||||
use RuntimeException;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
@@ -238,4 +240,54 @@ class UserControllerDeleteTest extends TestCase
|
||||
$response->assertJsonPath('success', true);
|
||||
$response->assertJsonPath('message', __('user.delete_success'));
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// 삭제 실패 시 에러 상세 메시지 노출 (:error placeholder 치환)
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* 회귀 — 삭제 실패 시 토스트 message 에 `:error` placeholder 가 그대로 노출되지 않고,
|
||||
* 구체적 실패 사유가 치환되어 사용자에게 보여야 한다.
|
||||
*
|
||||
* 사례: 플러그인 FK 제약 등으로 UserService::deleteUser 가 ValidationException 을
|
||||
* 던질 때, UserController::destroy 의 422 경로가 message 용 치환값을 전달하지 않아
|
||||
* 토스트에 `사용자 삭제에 실패했습니다: :error` 가 그대로 노출됨 (#415).
|
||||
*
|
||||
* 검증: 응답 message 에 `:error` 가 남지 않고 구체 사유가 포함되며, errors.general 에도
|
||||
* 동일 상세가 담긴다 (에러 상세 표시 기능 유지 — 메시지를 숨기지 않음).
|
||||
*/
|
||||
public function test_delete_failure_message_substitutes_error_detail_not_raw_placeholder(): void
|
||||
{
|
||||
$target = User::factory()->create(['is_super' => false]);
|
||||
|
||||
$hookName = 'core.user.before_delete';
|
||||
$reason = '연결된 외부 데이터가 있어 삭제할 수 없습니다 (regression-marker)';
|
||||
|
||||
// UserService::deleteUser 의 before_delete 훅에서 예외를 던져 삭제 실패를 강제.
|
||||
// Service 가 이를 잡아 __('user.delete_failed', ['error' => ...]) ValidationException 으로 변환.
|
||||
HookManager::addAction($hookName, function () use ($reason) {
|
||||
throw new RuntimeException($reason);
|
||||
});
|
||||
|
||||
try {
|
||||
$response = $this->authRequest()
|
||||
->deleteJson("/api/admin/users/{$target->uuid}");
|
||||
} finally {
|
||||
HookManager::clearAction($hookName);
|
||||
}
|
||||
|
||||
$response->assertStatus(422);
|
||||
$response->assertJsonPath('success', false);
|
||||
|
||||
$message = (string) $response->json('message');
|
||||
|
||||
// 핵심: placeholder 가 그대로 노출되면 안 됨
|
||||
$this->assertStringNotContainsString(':error', $message, 'message 에 미치환 :error 가 남으면 안 된다');
|
||||
// 핵심: 실패 사유가 사용자에게 보여야 함 (기능 유지)
|
||||
$this->assertStringContainsString($reason, $message, '구체적 실패 사유가 message 에 노출되어야 한다');
|
||||
|
||||
// errors.general 에도 동일 상세가 담긴다
|
||||
$this->assertStringContainsString($reason, (string) $response->json('errors.general.0'));
|
||||
$this->assertStringNotContainsString(':error', (string) $response->json('errors.general.0'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Laravel\Sanctum\Sanctum;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* broadcasting/auth 채널 인증 토글 가드 테스트 (공개#50).
|
||||
*
|
||||
* 웹소켓 사용 OFF(broadcasting.default='null') 시 채널 인증이 거부되어,
|
||||
* 변경 1(reverb.key 무력화)을 우회한 직접 연결 시도까지 차단되는지 검증한다.
|
||||
*/
|
||||
class BroadcastingAuthTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 웹소켓 OFF 시 broadcasting/auth 가 403 을 반환하는지 테스트합니다.
|
||||
*/
|
||||
public function test_broadcasting_auth_returns_403_when_websocket_disabled(): void
|
||||
{
|
||||
Config::set('broadcasting.default', 'null');
|
||||
|
||||
$user = User::factory()->create();
|
||||
Sanctum::actingAs($user, ['*'], 'sanctum');
|
||||
|
||||
$response = $this->postJson('/api/broadcasting/auth', [
|
||||
'channel_name' => 'private-test',
|
||||
'socket_id' => '123.456',
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
/**
|
||||
* 비인증 요청은 401 을 반환하는지 테스트합니다 (회귀 방지).
|
||||
*/
|
||||
public function test_broadcasting_auth_returns_401_without_authentication(): void
|
||||
{
|
||||
Config::set('broadcasting.default', 'reverb');
|
||||
|
||||
$response = $this->postJson('/api/broadcasting/auth', [
|
||||
'channel_name' => 'private-test',
|
||||
'socket_id' => '123.456',
|
||||
]);
|
||||
|
||||
$response->assertStatus(401);
|
||||
}
|
||||
|
||||
/**
|
||||
* 웹소켓 ON + 인증 시 토글 가드를 통과해 Broadcast::auth 로 진입하는지 테스트합니다.
|
||||
*
|
||||
* 채널 인증 콜백이 없는 임의 채널이므로 403(인증 통과 후 채널 권한 거부)을 받는다.
|
||||
* 핵심은 토글 가드(broadcasting.default='null')에 의한 사전 403 이 아님을 구분하는 것 —
|
||||
* Broadcast::auth 단계까지 도달함을 검증한다.
|
||||
*/
|
||||
public function test_broadcasting_auth_passes_toggle_guard_when_enabled(): void
|
||||
{
|
||||
Config::set('broadcasting.default', 'reverb');
|
||||
|
||||
$user = User::factory()->create();
|
||||
Sanctum::actingAs($user, ['*'], 'sanctum');
|
||||
|
||||
$response = $this->postJson('/api/broadcasting/auth', [
|
||||
'channel_name' => 'private-nonexistent-channel',
|
||||
'socket_id' => '123.456',
|
||||
]);
|
||||
|
||||
// 토글 가드(403)에서 멈추지 않고 Broadcast::auth 로 진입 → 채널 권한 거부(403/200).
|
||||
// 토글 OFF 가 아님을 확인: 401(미인증) 이 아닌 것으로 인증 통과 입증.
|
||||
$this->assertNotSame(401, $response->getStatusCode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Public;
|
||||
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Models\Module;
|
||||
use App\Models\Plugin;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 모듈/플러그인 editor-spec.json / components.json 서빙 + 활성/비활성 가드
|
||||
*
|
||||
* 서빙 컨트롤러는 활성 디렉토리(modules/{id}/...)를 읽으므로, 테스트는 고유 식별자의
|
||||
* 임시 디렉토리에 파일을 작성하고 tearDown 에서 정리한다. _bundled 원본/실제 확장
|
||||
* 디렉토리를 건드리지 않는다.
|
||||
*/
|
||||
class EditorSpecServingTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private string $moduleId = 'testvendor-specmodule';
|
||||
|
||||
private string $pluginId = 'testvendor-specplugin';
|
||||
|
||||
private array $createdDirs = [];
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
foreach ($this->createdDirs as $dir) {
|
||||
$this->removeDir($dir);
|
||||
}
|
||||
$this->createdDirs = [];
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/** 임시 확장 디렉토리에 파일 작성 (정리 대상 등록) */
|
||||
private function writeExtensionFile(string $type, string $identifier, string $file, string $content): void
|
||||
{
|
||||
$dir = base_path("{$type}/{$identifier}");
|
||||
if (! is_dir($dir)) {
|
||||
mkdir($dir, 0777, true);
|
||||
$this->createdDirs[] = $dir;
|
||||
}
|
||||
// 분할 형식(editor-spec/{block}.json)은 하위 디렉토리가 필요하다.
|
||||
$filePath = "{$dir}/{$file}";
|
||||
$fileDir = \dirname($filePath);
|
||||
if (! is_dir($fileDir)) {
|
||||
mkdir($fileDir, 0777, true);
|
||||
}
|
||||
file_put_contents($filePath, $content);
|
||||
}
|
||||
|
||||
/** 디렉토리 재귀 삭제 */
|
||||
private function removeDir(string $dir): void
|
||||
{
|
||||
if (! is_dir($dir)) {
|
||||
return;
|
||||
}
|
||||
$items = scandir($dir);
|
||||
foreach ($items as $item) {
|
||||
if ($item === '.' || $item === '..') {
|
||||
continue;
|
||||
}
|
||||
$path = "{$dir}/{$item}";
|
||||
is_dir($path) ? $this->removeDir($path) : @unlink($path);
|
||||
}
|
||||
@rmdir($dir);
|
||||
}
|
||||
|
||||
public function test_active_module_editor_spec_returns_spec(): void
|
||||
{
|
||||
Module::create([
|
||||
'identifier' => $this->moduleId,
|
||||
'vendor' => 'testvendor',
|
||||
'name' => ['ko' => '테스트', 'en' => 'Test'],
|
||||
'version' => '1.0.0',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
$this->writeExtensionFile('modules', $this->moduleId, 'editor-spec.json', json_encode([
|
||||
'sampleGlobal' => ['cart' => ['count' => 0]],
|
||||
'actionRecipes' => ['pay' => []],
|
||||
]));
|
||||
|
||||
$response = $this->getJson("/api/modules/{$this->moduleId}/editor-spec");
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJson(['success' => true])
|
||||
->assertJsonPath('data.identifier', $this->moduleId)
|
||||
->assertJsonPath('data.spec.sampleGlobal.cart.count', 0)
|
||||
->assertJsonPath('data.spec.actionRecipes.pay', []);
|
||||
}
|
||||
|
||||
public function test_split_module_editor_spec_is_assembled(): void
|
||||
{
|
||||
// 분할 형식: manifest + `$include` → editor-spec/{block}.json.
|
||||
// 엔드포인트가 합본해 단일 spec 으로 응답하는지 검증한다.
|
||||
Module::create([
|
||||
'identifier' => $this->moduleId,
|
||||
'vendor' => 'testvendor',
|
||||
'name' => ['ko' => '테스트', 'en' => 'Test'],
|
||||
'version' => '1.0.0',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
$this->writeExtensionFile('modules', $this->moduleId, 'editor-spec.json', json_encode([
|
||||
'templateId' => $this->moduleId,
|
||||
'darkMode' => ['strategy' => 'ancestor-class'],
|
||||
'$include' => [
|
||||
'controls' => 'editor-spec/controls.json',
|
||||
'sampleData' => 'editor-spec/sampleData.json',
|
||||
],
|
||||
]));
|
||||
$this->writeExtensionFile('modules', $this->moduleId, 'editor-spec/controls.json', json_encode([
|
||||
'textAlign' => ['widget' => 'segmented'],
|
||||
]));
|
||||
$this->writeExtensionFile('modules', $this->moduleId, 'editor-spec/sampleData.json', json_encode([
|
||||
'byDataSourceId' => ['cart' => ['data' => ['count' => 3]]],
|
||||
]));
|
||||
|
||||
$this->getJson("/api/modules/{$this->moduleId}/editor-spec")
|
||||
->assertStatus(200)
|
||||
->assertJson(['success' => true])
|
||||
// include 블록이 top-level 키로 합본됨
|
||||
->assertJsonPath('data.spec.controls.textAlign.widget', 'segmented')
|
||||
->assertJsonPath('data.spec.sampleData.byDataSourceId.cart.data.count', 3)
|
||||
// 인라인 메타 보존
|
||||
->assertJsonPath('data.spec.darkMode.strategy', 'ancestor-class')
|
||||
// `$include` 키는 합본 결과에 남지 않음
|
||||
->assertJsonMissingPath('data.spec.$include');
|
||||
}
|
||||
|
||||
public function test_inactive_module_editor_spec_returns_404(): void
|
||||
{
|
||||
Module::create([
|
||||
'identifier' => $this->moduleId,
|
||||
'vendor' => 'testvendor',
|
||||
'name' => ['ko' => '테스트', 'en' => 'Test'],
|
||||
'version' => '1.0.0',
|
||||
'status' => ExtensionStatus::Inactive->value,
|
||||
]);
|
||||
$this->writeExtensionFile('modules', $this->moduleId, 'editor-spec.json', json_encode(['controls' => []]));
|
||||
|
||||
$this->getJson("/api/modules/{$this->moduleId}/editor-spec")
|
||||
->assertStatus(404)
|
||||
->assertJson(['success' => false]);
|
||||
}
|
||||
|
||||
public function test_active_module_without_spec_file_returns_null_spec(): void
|
||||
{
|
||||
Module::create([
|
||||
'identifier' => $this->moduleId,
|
||||
'vendor' => 'testvendor',
|
||||
'name' => ['ko' => '테스트', 'en' => 'Test'],
|
||||
'version' => '1.0.0',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
// editor-spec.json 미작성 — 정상 응답 + spec null
|
||||
$this->getJson("/api/modules/{$this->moduleId}/editor-spec")
|
||||
->assertStatus(200)
|
||||
->assertJsonPath('data.spec', null);
|
||||
}
|
||||
|
||||
public function test_active_module_components_returns_manifest(): void
|
||||
{
|
||||
Module::create([
|
||||
'identifier' => $this->moduleId,
|
||||
'vendor' => 'testvendor',
|
||||
'name' => ['ko' => '테스트', 'en' => 'Test'],
|
||||
'version' => '1.0.0',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
$this->writeExtensionFile('modules', $this->moduleId, 'components.json', json_encode([
|
||||
'identifier' => $this->moduleId,
|
||||
'components' => ['basic' => [], 'composite' => [['name' => 'ProductCard']], 'layout' => []],
|
||||
]));
|
||||
|
||||
$this->getJson("/api/modules/{$this->moduleId}/components.json")
|
||||
->assertStatus(200)
|
||||
->assertJsonPath('components.composite.0.name', 'ProductCard');
|
||||
}
|
||||
|
||||
public function test_inactive_module_components_returns_404(): void
|
||||
{
|
||||
Module::create([
|
||||
'identifier' => $this->moduleId,
|
||||
'vendor' => 'testvendor',
|
||||
'name' => ['ko' => '테스트', 'en' => 'Test'],
|
||||
'version' => '1.0.0',
|
||||
'status' => ExtensionStatus::Inactive->value,
|
||||
]);
|
||||
$this->getJson("/api/modules/{$this->moduleId}/components.json")->assertStatus(404);
|
||||
}
|
||||
|
||||
public function test_active_plugin_editor_spec_returns_spec(): void
|
||||
{
|
||||
Plugin::create([
|
||||
'identifier' => $this->pluginId,
|
||||
'vendor' => 'testvendor',
|
||||
'name' => ['ko' => '테스트', 'en' => 'Test'],
|
||||
'version' => '1.0.0',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
$this->writeExtensionFile('plugins', $this->pluginId, 'editor-spec.json', json_encode([
|
||||
'sampleGlobal' => ['notifications' => ['unread' => 3]],
|
||||
]));
|
||||
|
||||
$this->getJson("/api/plugins/{$this->pluginId}/editor-spec")
|
||||
->assertStatus(200)
|
||||
->assertJsonPath('data.spec.sampleGlobal.notifications.unread', 3);
|
||||
}
|
||||
|
||||
public function test_inactive_plugin_editor_spec_returns_404(): void
|
||||
{
|
||||
Plugin::create([
|
||||
'identifier' => $this->pluginId,
|
||||
'vendor' => 'testvendor',
|
||||
'name' => ['ko' => '테스트', 'en' => 'Test'],
|
||||
'version' => '1.0.0',
|
||||
'status' => ExtensionStatus::Inactive->value,
|
||||
]);
|
||||
$this->getJson("/api/plugins/{$this->pluginId}/editor-spec")->assertStatus(404);
|
||||
}
|
||||
|
||||
public function test_nonexistent_module_editor_spec_returns_404(): void
|
||||
{
|
||||
$this->getJson('/api/modules/nope-nope/editor-spec')->assertStatus(404);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,17 @@ class LayoutServingTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 같은 스위트의 DB 테스트(LayoutSourceMetaServingTest, PublicLayoutControllerTest)
|
||||
* 와 마이그레이션 정합성을 맞추기 위해 — 레이아웃 서빙 경로가 GDPR 미들웨어를
|
||||
* 거치므로 해당 플러그인 마이그레이션을 테스트 DB 에 포함시킨다.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
/**
|
||||
* 정상적인 레이아웃 서빙 전체 플로우 테스트
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,417 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Public;
|
||||
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Enums\LayoutSourceType;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\Template;
|
||||
use App\Models\TemplateLayout;
|
||||
use App\Models\User;
|
||||
use Database\Seeders\RolePermissionSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Laravel\Sanctum\Sanctum;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 레이아웃 출처 메타 옵션 서빙 검증
|
||||
*
|
||||
* `GET /api/layouts/{id}/{name}.json?with_source_meta=1` 가 응답의 각 노드에
|
||||
* `__source` 메타를 부여하고, 옵션 미사용 시 응답 형식이 종전과 100% 동일함을
|
||||
* 보장한다 (계획서).
|
||||
*
|
||||
* 동시에 권한 가드(편집 권한 필수) 와 비파괴 보장(일반 사이트 렌더 영향 0) 회귀
|
||||
* 가드도 함께 검증한다.
|
||||
*/
|
||||
class LayoutSourceMetaServingTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
// 권한 시더 명시 실행 — `core.templates.layouts.edit` 등 코어 권한 등록
|
||||
$this->seed(RolePermissionSeeder::class);
|
||||
}
|
||||
|
||||
private function createActiveTemplate(): Template
|
||||
{
|
||||
return Template::factory()->create([
|
||||
'identifier' => 'sirsoft-admin_basic',
|
||||
'type' => 'admin',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 편집 권한을 가진 사용자 생성 (`core.templates.layouts.edit`)
|
||||
*/
|
||||
private function makeEditor(): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$role = Role::query()->create([
|
||||
'identifier' => 'meta_test_role_'.uniqid(),
|
||||
'name' => ['ko' => '테스트 편집자', 'en' => 'Test Editor'],
|
||||
'description' => ['ko' => '', 'en' => ''],
|
||||
'is_active' => true,
|
||||
]);
|
||||
$permission = Permission::query()
|
||||
->where('identifier', 'core.templates.layouts.edit')
|
||||
->first();
|
||||
if ($permission !== null) {
|
||||
$role->permissions()->attach($permission->id);
|
||||
}
|
||||
$user->roles()->attach($role->id);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* extends + slots 구조의 부모/자식 레이아웃 쌍을 생성한다.
|
||||
*
|
||||
* 부모(`_admin_base`) 가 헤더 + 콘텐츠 슬롯을 정의하고, 자식(`dashboard`) 이
|
||||
* 콘텐츠 슬롯을 채운다. 메타 옵션 검증을 위해 의도적으로 단순한 구조 사용.
|
||||
*/
|
||||
private function createBaseAndChildLayouts(Template $template): array
|
||||
{
|
||||
$base = TemplateLayout::create([
|
||||
'template_id' => $template->id,
|
||||
'name' => '_admin_base',
|
||||
'content' => [
|
||||
'meta' => ['title' => 'Base'],
|
||||
'components' => [
|
||||
[
|
||||
'type' => 'basic',
|
||||
'name' => 'Div',
|
||||
'props' => ['className' => 'header'],
|
||||
'children' => [
|
||||
['type' => 'basic', 'name' => 'Span', 'text' => 'Header'],
|
||||
],
|
||||
],
|
||||
[
|
||||
'type' => 'basic',
|
||||
'name' => 'Div',
|
||||
'slot' => 'content',
|
||||
'props' => ['className' => 'content'],
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$child = TemplateLayout::create([
|
||||
'template_id' => $template->id,
|
||||
'name' => 'dashboard',
|
||||
'content' => [
|
||||
'extends' => '_admin_base',
|
||||
'meta' => ['title' => 'Dashboard'],
|
||||
'slots' => [
|
||||
'content' => [
|
||||
[
|
||||
'type' => 'basic',
|
||||
'name' => 'H1',
|
||||
'text' => 'Dashboard',
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
return ['base' => $base, 'child' => $child];
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function serve_without_option_returns_response_without_source_meta(): void
|
||||
{
|
||||
$template = $this->createActiveTemplate();
|
||||
$this->createBaseAndChildLayouts($template);
|
||||
|
||||
$response = $this->getJson("/api/layouts/{$template->identifier}/dashboard.json");
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
$components = $response->json('data.components');
|
||||
$this->assertIsArray($components);
|
||||
|
||||
// 옵션 미전달 — 어느 노드에도 __source 가 없어야 한다 (비파괴 보장)
|
||||
$hasSourceMeta = $this->treeHasKey($components, '__source');
|
||||
$this->assertFalse(
|
||||
$hasSourceMeta,
|
||||
'옵션 미전달 시 응답에 __source 메타가 포함되면 안 됨 (일반 사이트 렌더 영향 0)'
|
||||
);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function serve_with_option_returns_response_with_source_meta_on_every_node(): void
|
||||
{
|
||||
$template = $this->createActiveTemplate();
|
||||
$this->createBaseAndChildLayouts($template);
|
||||
|
||||
$admin = $this->makeEditor();
|
||||
Sanctum::actingAs($admin, ['*'], 'sanctum');
|
||||
|
||||
$response = $this->getJson("/api/layouts/{$template->identifier}/dashboard.json?with_source_meta=1");
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
$components = $response->json('data.components');
|
||||
$this->assertIsArray($components);
|
||||
|
||||
// 첫 번째 컴포넌트(헤더) 는 base 출처
|
||||
$this->assertEquals('base', $components[0]['__source']['kind'] ?? null);
|
||||
$this->assertEquals('_admin_base', $components[0]['__source']['layout'] ?? null);
|
||||
|
||||
// 헤더 children 도 base 출처 (부모로부터 상속)
|
||||
$this->assertEquals('base', $components[0]['children'][0]['__source']['kind'] ?? null);
|
||||
|
||||
// 두 번째 컴포넌트(콘텐츠 슬롯 래퍼) 는 base 출처 — slot 위치는 부모가 정의
|
||||
$this->assertEquals('base', $components[1]['__source']['kind'] ?? null);
|
||||
|
||||
// 콘텐츠 슬롯의 children(H1 Dashboard) 은 route 출처 — 자식 레이아웃의 slot 콘텐츠
|
||||
$contentChildren = $components[1]['children'] ?? [];
|
||||
$this->assertNotEmpty($contentChildren);
|
||||
$this->assertEquals('route', $contentChildren[0]['__source']['kind'] ?? null);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function serve_with_option_requires_authenticated_user(): void
|
||||
{
|
||||
$template = $this->createActiveTemplate();
|
||||
$this->createBaseAndChildLayouts($template);
|
||||
|
||||
// 비로그인 사용자의 메타 옵션 요청은 401
|
||||
$response = $this->getJson("/api/layouts/{$template->identifier}/dashboard.json?with_source_meta=1");
|
||||
|
||||
$response->assertStatus(401);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function serve_with_option_requires_edit_permission(): void
|
||||
{
|
||||
$template = $this->createActiveTemplate();
|
||||
$this->createBaseAndChildLayouts($template);
|
||||
|
||||
// 일반 사용자 (편집 권한 없음) 의 메타 옵션 요청은 403
|
||||
$user = User::factory()->create(['is_super' => false]);
|
||||
Sanctum::actingAs($user, ['*'], 'sanctum');
|
||||
|
||||
$response = $this->getJson("/api/layouts/{$template->identifier}/dashboard.json?with_source_meta=1");
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function meta_cache_is_separate_from_normal_response_cache(): void
|
||||
{
|
||||
$template = $this->createActiveTemplate();
|
||||
$this->createBaseAndChildLayouts($template);
|
||||
|
||||
$admin = $this->makeEditor();
|
||||
|
||||
// 일반 응답 먼저 캐시 적재 (비인증 사이트 렌더)
|
||||
$normal = $this->getJson("/api/layouts/{$template->identifier}/dashboard.json");
|
||||
$normal->assertStatus(200);
|
||||
$this->assertFalse($this->treeHasKey($normal->json('data.components'), '__source'));
|
||||
|
||||
// 메타 옵션 응답이 일반 캐시를 오염시키지 않아야 한다
|
||||
Sanctum::actingAs($admin, ['*'], 'sanctum');
|
||||
$meta = $this->getJson("/api/layouts/{$template->identifier}/dashboard.json?with_source_meta=1");
|
||||
$meta->assertStatus(200);
|
||||
$this->assertTrue($this->treeHasKey($meta->json('data.components'), '__source'));
|
||||
|
||||
// 일반 요청을 다시 호출 (비인증) → 여전히 메타 없음 (캐시 분리 확인)
|
||||
app('auth')->guard('sanctum')->forgetUser();
|
||||
$normalAgain = $this->getJson("/api/layouts/{$template->identifier}/dashboard.json");
|
||||
$normalAgain->assertStatus(200);
|
||||
$this->assertFalse($this->treeHasKey($normalAgain->json('data.components'), '__source'));
|
||||
}
|
||||
|
||||
/**
|
||||
* data_sources 항목을 가진 레이아웃을 생성한다 (방안 B 출처 메타 검증용).
|
||||
*/
|
||||
private function createLayoutWithDataSources(Template $template): TemplateLayout
|
||||
{
|
||||
return TemplateLayout::create([
|
||||
'template_id' => $template->id,
|
||||
'name' => 'with_sources',
|
||||
'content' => [
|
||||
'meta' => ['title' => 'With Sources'],
|
||||
'data_sources' => [
|
||||
['id' => 'settings', 'type' => 'api', 'endpoint' => '/api/admin/settings', 'method' => 'GET'],
|
||||
['id' => 'roles', 'type' => 'api', 'endpoint' => '/api/admin/roles', 'method' => 'GET'],
|
||||
],
|
||||
'components' => [
|
||||
['type' => 'basic', 'name' => 'Div', 'props' => ['className' => 'root']],
|
||||
],
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function data_source_source_meta_present_with_flag(): void
|
||||
{
|
||||
$template = $this->createActiveTemplate();
|
||||
$this->createLayoutWithDataSources($template);
|
||||
|
||||
$admin = $this->makeEditor();
|
||||
Sanctum::actingAs($admin, ['*'], 'sanctum');
|
||||
|
||||
$response = $this->getJson("/api/layouts/{$template->identifier}/with_sources.json?with_source_meta=1");
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
$dataSources = $response->json('data.data_sources');
|
||||
$this->assertIsArray($dataSources);
|
||||
$this->assertNotEmpty($dataSources);
|
||||
|
||||
// 템플릿 자체 레이아웃(prefix 없음) → kind=route / identifier=null (방안 B §deriveDataSourceSourceMeta)
|
||||
foreach ($dataSources as $ds) {
|
||||
$this->assertArrayHasKey('__source', $ds, "data_source '{$ds['id']}' 에 __source 메타가 부여되어야 함");
|
||||
$this->assertEquals('route', $ds['__source']['kind'] ?? null);
|
||||
$this->assertArrayHasKey('identifier', $ds['__source']);
|
||||
$this->assertNull($ds['__source']['identifier']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 소유 레이아웃(`source_type = Plugin`)을 prefix 이름으로 생성한다.
|
||||
*
|
||||
* 이름 패턴(`{ext}.{layout}`)만으로는 module/plugin 을 구분하지 못하므로,
|
||||
* 행의 `source_type` 을 명시해 `LayoutResolverService::resolve` 가 plugin 으로
|
||||
* 해석하게 한다.
|
||||
*/
|
||||
private function createPluginLayoutWithDataSources(Template $template): TemplateLayout
|
||||
{
|
||||
return TemplateLayout::create([
|
||||
'template_id' => $template->id,
|
||||
'name' => 'sirsoft-gdpr.plugin_settings',
|
||||
'source_type' => LayoutSourceType::Plugin->value,
|
||||
'source_identifier' => 'sirsoft-gdpr',
|
||||
'content' => [
|
||||
'meta' => ['title' => 'GDPR Settings'],
|
||||
'data_sources' => [
|
||||
['id' => 'settings', 'type' => 'api', 'endpoint' => '/api/plugins/sirsoft-gdpr/settings', 'method' => 'GET'],
|
||||
],
|
||||
'components' => [
|
||||
['type' => 'basic', 'name' => 'Div', 'props' => ['className' => 'root']],
|
||||
],
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function data_source_source_meta_classifies_plugin_layout_as_plugin_kind(): void
|
||||
{
|
||||
$template = $this->createActiveTemplate();
|
||||
$this->createPluginLayoutWithDataSources($template);
|
||||
|
||||
$admin = $this->makeEditor();
|
||||
Sanctum::actingAs($admin, ['*'], 'sanctum');
|
||||
|
||||
$response = $this->getJson("/api/layouts/{$template->identifier}/sirsoft-gdpr.plugin_settings.json?with_source_meta=1");
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
$dataSources = $response->json('data.data_sources');
|
||||
$this->assertIsArray($dataSources);
|
||||
$this->assertNotEmpty($dataSources);
|
||||
|
||||
// 플러그인 레이아웃 data_source → kind=plugin / identifier=sirsoft-gdpr.
|
||||
// 엔진 editorSpecLoader 가 plugin 스펙을 `plugin:{id}` 키로 보존하므로 kind 가
|
||||
// plugin 이어야 그 확장 샘플이 매칭된다. (module 오분류 시 `plugin:` 스펙을 빗나감)
|
||||
foreach ($dataSources as $ds) {
|
||||
$this->assertArrayHasKey('__source', $ds, "data_source '{$ds['id']}' 에 __source 메타가 부여되어야 함");
|
||||
$this->assertEquals('plugin', $ds['__source']['kind'] ?? null, "plugin 레이아웃 data_source '{$ds['id']}' 의 kind 는 plugin 이어야 함");
|
||||
$this->assertEquals('sirsoft-gdpr', $ds['__source']['identifier'] ?? null);
|
||||
}
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function data_source_source_meta_classifies_module_layout_as_module_kind(): void
|
||||
{
|
||||
$template = $this->createActiveTemplate();
|
||||
TemplateLayout::create([
|
||||
'template_id' => $template->id,
|
||||
'name' => 'sirsoft-ecommerce.admin_ecommerce_settings',
|
||||
'source_type' => LayoutSourceType::Module->value,
|
||||
'source_identifier' => 'sirsoft-ecommerce',
|
||||
'content' => [
|
||||
'meta' => ['title' => 'Shop Settings'],
|
||||
'data_sources' => [
|
||||
['id' => 'settings', 'type' => 'api', 'endpoint' => '/api/admin/ecommerce/settings', 'method' => 'GET'],
|
||||
],
|
||||
'components' => [
|
||||
['type' => 'basic', 'name' => 'Div', 'props' => ['className' => 'root']],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$admin = $this->makeEditor();
|
||||
Sanctum::actingAs($admin, ['*'], 'sanctum');
|
||||
|
||||
$response = $this->getJson("/api/layouts/{$template->identifier}/sirsoft-ecommerce.admin_ecommerce_settings.json?with_source_meta=1");
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
$dataSources = $response->json('data.data_sources');
|
||||
$this->assertIsArray($dataSources);
|
||||
$this->assertNotEmpty($dataSources);
|
||||
|
||||
foreach ($dataSources as $ds) {
|
||||
$this->assertArrayHasKey('__source', $ds);
|
||||
$this->assertEquals('module', $ds['__source']['kind'] ?? null, "module 레이아웃 data_source '{$ds['id']}' 의 kind 는 module 이어야 함");
|
||||
$this->assertEquals('sirsoft-ecommerce', $ds['__source']['identifier'] ?? null);
|
||||
}
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function data_source_source_meta_absent_without_flag(): void
|
||||
{
|
||||
$template = $this->createActiveTemplate();
|
||||
$this->createLayoutWithDataSources($template);
|
||||
|
||||
// 옵션 미전달 — 일반 사이트 렌더 경로에는 __source 가 없어야 한다 (비파괴 보장)
|
||||
$response = $this->getJson("/api/layouts/{$template->identifier}/with_sources.json");
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
$dataSources = $response->json('data.data_sources');
|
||||
$this->assertIsArray($dataSources);
|
||||
foreach ($dataSources as $ds) {
|
||||
$this->assertArrayNotHasKey('__source', $ds, '옵션 미전달 시 data_source 에 __source 가 포함되면 안 됨');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 컴포넌트 트리에서 특정 키가 존재하는지 재귀 탐색
|
||||
*/
|
||||
private function treeHasKey(array $components, string $key): bool
|
||||
{
|
||||
foreach ($components as $component) {
|
||||
if (! is_array($component)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (array_key_exists($key, $component)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isset($component['children']) && is_array($component['children'])) {
|
||||
if ($this->treeHasKey($component['children'], $key)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Public;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Models\Template;
|
||||
use App\Models\TemplateCustomTranslation;
|
||||
use App\Services\TemplateCustomTranslationService;
|
||||
use App\Services\TemplateService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* serveLanguage 공개 엔드포인트 커스텀 다국어 키 통합 테스트.
|
||||
*
|
||||
* `GET /api/templates/{identifier}/lang/{locale}.json` 응답이
|
||||
* MergeCustomTranslations 필터를 거쳐 커스텀 키를 실제로 포함하는지,
|
||||
* 캐시 무효화(?v= 파라미터)가 동작하는지를 end-to-end 로 검증합니다.
|
||||
*
|
||||
* (단위 합성 — 필터 직접 호출(MergeCustomTranslationsTest) + cache_version bump
|
||||
* (Controller/Service 테스트) — 의 통합 경로를 보강하는 테스트.)
|
||||
*/
|
||||
class PublicTemplateLanguageMergeTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 같은 스위트의 DB 테스트와 migrate:fresh 정합성을 위해 일관 선언.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
private TemplateService $templateService;
|
||||
|
||||
private Template $template;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->templateService = app(TemplateService::class);
|
||||
|
||||
// 실제 활성 템플릿 — serveLanguage 가 status=Active + template.json 을 요구한다.
|
||||
$this->templateService->installTemplate('sirsoft-admin_basic');
|
||||
$this->template = Template::where('identifier', 'sirsoft-admin_basic')->first();
|
||||
$this->templateService->activateTemplate($this->template->id);
|
||||
|
||||
Cache::flush();
|
||||
}
|
||||
|
||||
public function test_serve_language_response_includes_custom_translation_key(): void
|
||||
{
|
||||
TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => ['ko' => '커스텀안녕', 'en' => 'custom hello'],
|
||||
'status' => 'active',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
$response = $this->getJson('/api/templates/sirsoft-admin_basic/lang/ko.json');
|
||||
|
||||
$response->assertStatus(200);
|
||||
// 점 경로 custom.home.1 이 응답 트리에 병합되어 ko 값으로 해석됨
|
||||
$response->assertJsonPath('custom.home.1', '커스텀안녕');
|
||||
}
|
||||
|
||||
public function test_serve_language_resolves_locale_specific_value(): void
|
||||
{
|
||||
TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => ['ko' => '커스텀안녕', 'en' => 'custom hello'],
|
||||
'status' => 'active',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
$response = $this->getJson('/api/templates/sirsoft-admin_basic/lang/en.json');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertJsonPath('custom.home.1', 'custom hello');
|
||||
}
|
||||
|
||||
public function test_orphaned_custom_key_not_served(): void
|
||||
{
|
||||
TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => ['ko' => '고아', 'en' => 'orphan'],
|
||||
'status' => 'orphaned',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
$response = $this->getJson('/api/templates/sirsoft-admin_basic/lang/ko.json');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$this->assertNull(data_get($response->json(), 'custom.home.1'));
|
||||
}
|
||||
|
||||
public function test_cache_invalidation_serves_fresh_keys_on_new_cache_version(): void
|
||||
{
|
||||
// 초기 응답 (v0) — 커스텀 키 없음, 캐시에 저장됨
|
||||
$first = $this->getJson('/api/templates/sirsoft-admin_basic/lang/ko.json?v=0');
|
||||
$first->assertStatus(200);
|
||||
$this->assertNull(data_get($first->json(), 'custom.home.1'));
|
||||
|
||||
// 커스텀 키 생성 → Service 가 ext.cache_version 을 bump
|
||||
app(TemplateCustomTranslationService::class)->createKey(
|
||||
$this->template->id,
|
||||
'home',
|
||||
'ko',
|
||||
'신규키',
|
||||
);
|
||||
|
||||
$newVersion = (int) app(CacheInterface::class)->get('ext.cache_version', 0);
|
||||
$this->assertGreaterThan(0, $newVersion);
|
||||
|
||||
// 새 캐시 버전으로 재요청 → 캐시 미스 → 커스텀 키 포함된 신선한 응답
|
||||
$second = $this->getJson("/api/templates/sirsoft-admin_basic/lang/ko.json?v={$newVersion}");
|
||||
$second->assertStatus(200);
|
||||
$second->assertJsonPath('custom.home.1', '신규키');
|
||||
}
|
||||
|
||||
public function test_stale_cache_version_still_serves_old_snapshot(): void
|
||||
{
|
||||
// v0 응답을 먼저 캐시에 적재 (커스텀 키 없음)
|
||||
$this->getJson('/api/templates/sirsoft-admin_basic/lang/ko.json?v=0')->assertStatus(200);
|
||||
|
||||
TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => ['ko' => '나중', 'en' => 'later'],
|
||||
'status' => 'active',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
// 동일 v0 재요청 → 캐시 히트 → 옛 스냅샷(커스텀 키 부재)
|
||||
$cached = $this->getJson('/api/templates/sirsoft-admin_basic/lang/ko.json?v=0');
|
||||
$cached->assertStatus(200);
|
||||
$this->assertNull(data_get($cached->json(), 'custom.home.1'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Public;
|
||||
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Models\Template;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 라우트 트리 소스 태깅 Feature 테스트
|
||||
*
|
||||
* getRoutesDataWithModules 가 각 라우트에 source { kind, identifier } 메타를
|
||||
* 비파괴적으로 부여하는지 검증. 레이아웃 편집기 라우트 트리 그룹핑의 SSoT.
|
||||
*/
|
||||
class PublicTemplateRoutesSourceTaggingTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 같은 스위트의 GDPR 미들웨어 의존 테스트와 migrate:fresh 정합성을 맞추기 위해
|
||||
* GDPR 플러그인 마이그레이션을 일관 선언한다.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
#[Test]
|
||||
public function template_routes_response_attaches_source_kind_template_with_null_identifier(): void
|
||||
{
|
||||
$template = Template::create([
|
||||
'identifier' => 'sirsoft-admin_basic',
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
|
||||
'version' => '1.0.0',
|
||||
'type' => 'admin',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
'description' => ['ko' => '관리자 템플릿', 'en' => 'Admin Template'],
|
||||
]);
|
||||
|
||||
$response = $this->getJson("/api/templates/{$template->identifier}/routes.json");
|
||||
|
||||
$response->assertStatus(200)
|
||||
->assertJson(['success' => true]);
|
||||
|
||||
$routes = $response->json('data.routes');
|
||||
$this->assertIsArray($routes);
|
||||
$this->assertNotEmpty($routes);
|
||||
|
||||
// 최소 1건의 템플릿 자체 라우트가 source.kind = 'template' 으로 태깅되었는지
|
||||
$templateRoutes = array_filter(
|
||||
$routes,
|
||||
fn ($r) => isset($r['source']['kind']) && $r['source']['kind'] === 'template'
|
||||
);
|
||||
|
||||
$this->assertNotEmpty($templateRoutes, '템플릿 자체 라우트에 source.kind=template 이 부여되어야 함');
|
||||
|
||||
foreach ($templateRoutes as $route) {
|
||||
$this->assertSame('template', $route['source']['kind']);
|
||||
$this->assertNull(
|
||||
$route['source']['identifier'],
|
||||
'템플릿 자체 라우트의 source.identifier 는 null'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function template_routes_response_preserves_existing_meta_fields_non_destructively(): void
|
||||
{
|
||||
$template = Template::create([
|
||||
'identifier' => 'sirsoft-admin_basic',
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
|
||||
'version' => '1.0.0',
|
||||
'type' => 'admin',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
'description' => ['ko' => '관리자 템플릿', 'en' => 'Admin Template'],
|
||||
]);
|
||||
|
||||
$response = $this->getJson("/api/templates/{$template->identifier}/routes.json");
|
||||
$routes = $response->json('data.routes');
|
||||
|
||||
// path / layout 등 기존 필드가 source 추가로 인해 사라지지 않았는지
|
||||
foreach ($routes as $route) {
|
||||
$this->assertArrayHasKey('path', $route, '기존 path 필드는 보존되어야 함');
|
||||
$this->assertArrayHasKey('source', $route, '신규 source 필드는 모든 라우트에 부여');
|
||||
$this->assertArrayHasKey('kind', $route['source']);
|
||||
$this->assertArrayHasKey('identifier', $route['source']);
|
||||
}
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function nonexistent_template_returns_404_unchanged_by_source_tagging(): void
|
||||
{
|
||||
$response = $this->getJson('/api/templates/nonexistent-template/routes.json');
|
||||
|
||||
$response->assertStatus(404)
|
||||
->assertJson(['success' => false]);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,16 @@ class TemplateRouteTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 같은 스위트의 GDPR 미들웨어 의존 테스트와 migrate:fresh 정합성을 맞추기 위해
|
||||
* GDPR 플러그인 마이그레이션을 일관 선언한다.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
/**
|
||||
* 활성화된 템플릿의 라우트 조회 성공 테스트
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Seo\TemplateRouteResolver;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* catch-all 미등록 경로 HTTP 404 응답 테스트 (공개#47).
|
||||
*
|
||||
* routes/web.php 의 user/admin catch-all 이 TemplateRouteResolver::routeExists() 판별로
|
||||
* 미등록 경로에 SPA 셸 본문 + HTTP 404 를, 등록 경로에 200 을 반환하는지 검증한다.
|
||||
*
|
||||
* routeExists() 자체의 매칭 로직은 TemplateRouteResolverTest(Unit)가 커버하고,
|
||||
* 본 Feature 는 catch-all 라우트 ↔ routeExists 결과의 HTTP status 연결을 검증한다.
|
||||
*/
|
||||
class CatchAllNotFoundTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* routeExists 가 지정 값을 반환하도록 resolver 를 바인딩합니다.
|
||||
*
|
||||
* @param bool $exists routeExists 반환값
|
||||
*/
|
||||
private function bindResolver(bool $exists): void
|
||||
{
|
||||
$resolver = Mockery::mock(TemplateRouteResolver::class);
|
||||
$resolver->shouldReceive('routeExists')->andReturn($exists);
|
||||
$this->app->instance(TemplateRouteResolver::class, $resolver);
|
||||
}
|
||||
|
||||
/**
|
||||
* 미등록 user 경로는 404 + SPA 셸 본문을 반환합니다.
|
||||
*/
|
||||
public function test_unregistered_user_path_returns_404_with_shell(): void
|
||||
{
|
||||
$this->bindResolver(false);
|
||||
|
||||
$response = $this->get('/this-does-not-exist');
|
||||
|
||||
$response->assertStatus(404);
|
||||
$response->assertSee('id="app"', false); // SPA 셸 마커 (본문은 그대로)
|
||||
}
|
||||
|
||||
/**
|
||||
* 등록된 user 경로는 200 을 반환합니다.
|
||||
*/
|
||||
public function test_registered_user_path_returns_200(): void
|
||||
{
|
||||
$this->bindResolver(true);
|
||||
|
||||
$response = $this->get('/some-registered-route');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertSee('id="app"', false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 미등록 admin 경로는 404 + admin 셸 본문을 반환합니다.
|
||||
*/
|
||||
public function test_unregistered_admin_path_returns_404(): void
|
||||
{
|
||||
$this->bindResolver(false);
|
||||
|
||||
$response = $this->get('/admin/nonexistent');
|
||||
|
||||
$response->assertStatus(404);
|
||||
}
|
||||
|
||||
/**
|
||||
* 등록된 admin 경로는 200 을 반환합니다.
|
||||
*/
|
||||
public function test_registered_admin_path_returns_200(): void
|
||||
{
|
||||
$this->bindResolver(true);
|
||||
|
||||
$response = $this->get('/admin/users');
|
||||
|
||||
$response->assertStatus(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* 봇(Googlebot) 미등록 경로도 404 를 받습니다 (봇/비봇 일관).
|
||||
*/
|
||||
public function test_bot_unregistered_path_returns_404(): void
|
||||
{
|
||||
$this->bindResolver(false);
|
||||
|
||||
$response = $this->get('/this-does-not-exist', [
|
||||
'User-Agent' => 'Googlebot/2.1 (+http://www.google.com/bot.html)',
|
||||
]);
|
||||
|
||||
$response->assertStatus(404);
|
||||
}
|
||||
|
||||
/**
|
||||
* 정적 자산 확장자 경로는 catch-all 에 진입하지 않습니다 (where 정규식 제외).
|
||||
*/
|
||||
public function test_static_asset_path_not_handled_by_catchall(): void
|
||||
{
|
||||
$this->bindResolver(false);
|
||||
|
||||
// .js 확장자는 catch-all where 정규식에서 제외 → 404(라우트 미정의)이되
|
||||
// routeExists 호출 경로를 타지 않음. 상태만 확인(파일 미존재로 404).
|
||||
$response = $this->get('/assets/app.js');
|
||||
|
||||
$this->assertContains($response->getStatusCode(), [404]);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Tests\Feature\Console\Commands;
|
||||
|
||||
use App\Console\Commands\Core\CoreUpdateCommand;
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Extension\TemplateManager;
|
||||
@@ -10,6 +11,7 @@ use App\Services\LanguagePackService;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Mockery;
|
||||
use Mockery\MockInterface;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
@@ -272,11 +274,57 @@ class ExecuteUpgradeStepsStandaloneTest extends TestCase
|
||||
}
|
||||
}
|
||||
|
||||
public function test_steps_only_option_runs_only_upgrade_steps(): void
|
||||
{
|
||||
// --steps-only: 업그레이드 스텝만 실행. 권한 정상화·마이그레이션·resync·
|
||||
// 버전 갱신·캐시 정리·번들 업데이트 등 모든 보조 단계를 생략한다.
|
||||
[$service, $module, $plugin, $template, $langPack] = $this->bindMocks();
|
||||
|
||||
$service->shouldNotReceive('runMigrations');
|
||||
$service->shouldNotReceive('reloadCoreConfigAndResync');
|
||||
$service->shouldNotReceive('ensureWritableDirectories');
|
||||
$service->shouldReceive('runUpgradeSteps')->once();
|
||||
$service->shouldNotReceive('updateVersionInEnv');
|
||||
$service->shouldNotReceive('clearAllCaches');
|
||||
$service->shouldNotReceive('collectBundledExtensionUpdates');
|
||||
$langPack->shouldNotReceive('collectBundledLangPackUpdates');
|
||||
|
||||
$exitCode = $this->runCommand(['--steps-only' => true]);
|
||||
$this->assertSame(0, $exitCode);
|
||||
}
|
||||
|
||||
public function test_steps_only_skips_aux_steps_even_without_env_signal(): void
|
||||
{
|
||||
// env 미설정(운영자 단독 호출) + --steps-only → 단독 실행 시 자동 수행되던
|
||||
// 5단계도 모두 생략. --steps-only 가 단독 실행 계약보다 우선한다.
|
||||
[$service, $module, $plugin, $template, $langPack] = $this->bindMocks();
|
||||
|
||||
$service->shouldNotReceive('runMigrations');
|
||||
$service->shouldNotReceive('reloadCoreConfigAndResync');
|
||||
$service->shouldReceive('runUpgradeSteps')->once();
|
||||
$service->shouldNotReceive('updateVersionInEnv');
|
||||
$service->shouldNotReceive('clearAllCaches');
|
||||
$service->shouldNotReceive('collectBundledExtensionUpdates');
|
||||
$langPack->shouldNotReceive('collectBundledLangPackUpdates');
|
||||
|
||||
$originalEnv = getenv('G7_UPDATE_IN_PROGRESS');
|
||||
putenv('G7_UPDATE_IN_PROGRESS');
|
||||
|
||||
try {
|
||||
$exitCode = $this->runCommand(['--steps-only' => true]);
|
||||
$this->assertSame(0, $exitCode);
|
||||
} finally {
|
||||
if ($originalEnv !== false) {
|
||||
putenv('G7_UPDATE_IN_PROGRESS='.$originalEnv);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function test_spawn_passes_all_five_skip_options_to_child(): void
|
||||
{
|
||||
// 부모 CoreUpdateCommand::spawnUpgradeStepsProcess 가 자식 command 배열에
|
||||
// 5개 `--skip-*` 옵션을 추가하는지 검증 (escapeshellarg 후 commandLine 문자열에 포함).
|
||||
$reflection = new \ReflectionClass(\App\Console\Commands\Core\CoreUpdateCommand::class);
|
||||
$reflection = new \ReflectionClass(CoreUpdateCommand::class);
|
||||
$source = File::get($reflection->getFileName());
|
||||
|
||||
$this->assertStringContainsString("\$command[] = '--skip-migrations';", $source);
|
||||
@@ -289,7 +337,7 @@ class ExecuteUpgradeStepsStandaloneTest extends TestCase
|
||||
/**
|
||||
* CoreUpdateService + 3개 Manager + LanguagePackService 를 컨테이너에 mock 으로 swap.
|
||||
*
|
||||
* @return array{0: \Mockery\MockInterface, 1: \Mockery\MockInterface, 2: \Mockery\MockInterface, 3: \Mockery\MockInterface, 4: \Mockery\MockInterface}
|
||||
* @return array{0: MockInterface, 1: MockInterface, 2: MockInterface, 3: MockInterface, 4: MockInterface}
|
||||
*/
|
||||
private function bindMocks(): array
|
||||
{
|
||||
@@ -299,6 +347,13 @@ class ExecuteUpgradeStepsStandaloneTest extends TestCase
|
||||
$template = Mockery::mock(TemplateManager::class);
|
||||
$langPack = Mockery::mock(LanguagePackService::class);
|
||||
|
||||
// 콘솔 커맨드 resolve 시 Service 계층 생성자가 매니저의 스캔 메서드를
|
||||
// 호출할 수 있다 (예: TemplateService 가 TemplateManagerInterface::loadTemplates()
|
||||
// 를 생성자에서 호출). 스캔 메서드는 부수효과만 있으므로 무해하게 허용한다.
|
||||
$module->shouldReceive('loadModules')->andReturnNull()->byDefault();
|
||||
$plugin->shouldReceive('loadPlugins')->andReturnNull()->byDefault();
|
||||
$template->shouldReceive('loadTemplates')->andReturnNull()->byDefault();
|
||||
|
||||
$this->app->instance(CoreUpdateService::class, $service);
|
||||
$this->app->instance(ModuleManager::class, $module);
|
||||
$this->app->instance(PluginManager::class, $plugin);
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Dashboard;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Enums\NotificationLogStatus;
|
||||
use App\Models\NotificationLog;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 대시보드 최근 알림 API 테스트
|
||||
*
|
||||
* GET /api/admin/dashboard/recent-notifications
|
||||
* - 가드: admin 미들웨어 + permission:admin,core.notification-logs.read
|
||||
*/
|
||||
class RecentNotificationsApiTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private const URL = '/api/admin/dashboard/recent-notifications';
|
||||
|
||||
/**
|
||||
* 관리자 사용자를 생성하고 지정 권한을 부여합니다.
|
||||
*
|
||||
* @param array<int, string> $permissions 권한 식별자 목록
|
||||
* @return User 생성된 관리자 사용자
|
||||
*/
|
||||
private function makeAdmin(array $permissions = ['core.notification-logs.read']): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$permissionIds = [];
|
||||
foreach ($permissions as $identifier) {
|
||||
$permission = Permission::firstOrCreate(
|
||||
['identifier' => $identifier],
|
||||
[
|
||||
'name' => json_encode(['ko' => $identifier, 'en' => $identifier]),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'type' => 'admin',
|
||||
]
|
||||
);
|
||||
$permissionIds[] = $permission->id;
|
||||
}
|
||||
|
||||
$role = Role::create([
|
||||
'identifier' => 'admin_test_'.uniqid(),
|
||||
'name' => json_encode(['ko' => '테스트 관리자', 'en' => 'Test Admin']),
|
||||
'is_active' => true,
|
||||
]);
|
||||
$adminBaseRole = Role::firstOrCreate(
|
||||
['identifier' => 'admin'],
|
||||
[
|
||||
'name' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
|
||||
$sync = [];
|
||||
foreach ($permissionIds as $id) {
|
||||
$sync[$id] = ['scope_type' => null];
|
||||
}
|
||||
$role->permissions()->sync($sync);
|
||||
|
||||
$user->roles()->attach($adminBaseRole->id, ['assigned_at' => now()]);
|
||||
$user->roles()->attach($role->id, ['assigned_at' => now()]);
|
||||
|
||||
return $user->fresh();
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function test_requires_authentication(): void
|
||||
{
|
||||
$this->getJson(self::URL)->assertStatus(401);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function test_rejects_admin_without_permission(): void
|
||||
{
|
||||
$admin = $this->makeAdmin([]);
|
||||
|
||||
$this->actingAs($admin)->getJson(self::URL)->assertStatus(403);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function test_returns_recent_notifications_for_authorized_admin(): void
|
||||
{
|
||||
$admin = $this->makeAdmin();
|
||||
|
||||
NotificationLog::create([
|
||||
'channel' => 'mail',
|
||||
'notification_type' => 'order_confirmed',
|
||||
'extension_type' => 'module',
|
||||
'extension_identifier' => 'sirsoft-ecommerce',
|
||||
'recipient_name' => '홍길동',
|
||||
'recipient_identifier' => 'test@example.com',
|
||||
'subject' => '주문이 확인되었습니다',
|
||||
'status' => NotificationLogStatus::Sent,
|
||||
'sent_at' => now(),
|
||||
]);
|
||||
|
||||
$this->actingAs($admin)->getJson(self::URL)
|
||||
->assertStatus(200)
|
||||
->assertJsonStructure(['success', 'data' => [['id', 'type', 'channel', 'recipient', 'subject', 'status', 'time']]])
|
||||
->assertJsonPath('data.0.type', 'order_confirmed')
|
||||
->assertJsonPath('data.0.channel', 'mail')
|
||||
->assertJsonPath('data.0.status', 'sent');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Extension;
|
||||
|
||||
use App\Extension\Testing\ExtensionTestAllowlist;
|
||||
use Illuminate\Contracts\Http\Kernel as HttpKernelContract;
|
||||
use Illuminate\Foundation\Http\Kernel as HttpKernel;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Plugins\Sirsoft\Gdpr\Http\Middleware\CookieConsentMiddleware;
|
||||
use Plugins\Sirsoft\Gdpr\Providers\GdprServiceProvider;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 테스트 환경 확장 격리 회귀 테스트 — allowlist 포함 시나리오
|
||||
*
|
||||
* requiredExtensions 에 GDPR 플러그인을 명시하면 해당 플러그인의
|
||||
* ServiceProvider 와 미들웨어가 정상적으로 로드되어야 한다.
|
||||
*/
|
||||
class ExtensionTestIsolationGdprAllowedTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* GDPR 플러그인을 allowlist 에 명시.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
/**
|
||||
* @effects allowlisted_plugin_service_provider_is_registered
|
||||
*/
|
||||
public function test_allowlisted_plugin_service_provider_is_registered(): void
|
||||
{
|
||||
$this->assertTrue(ExtensionTestAllowlist::isAllowed('plugin', 'sirsoft-gdpr'));
|
||||
|
||||
$this->assertTrue(
|
||||
$this->app->providerIsLoaded(GdprServiceProvider::class),
|
||||
'allowlist 에 명시된 GdprServiceProvider 가 등록되지 않았습니다'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects allowlisted_plugin_middleware_is_registered_in_web_group
|
||||
*/
|
||||
public function test_allowlisted_plugin_middleware_is_registered_in_web_group(): void
|
||||
{
|
||||
$kernel = $this->app->make(HttpKernelContract::class);
|
||||
$this->assertInstanceOf(HttpKernel::class, $kernel);
|
||||
|
||||
$groups = $kernel->getMiddlewareGroups();
|
||||
|
||||
$this->assertContains(
|
||||
CookieConsentMiddleware::class,
|
||||
$groups['web'] ?? [],
|
||||
'allowlist 에 GDPR 을 명시했으나 web 그룹에 CookieConsentMiddleware 가 없습니다'
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Extension;
|
||||
|
||||
use App\Extension\Testing\ExtensionTestAllowlist;
|
||||
use Illuminate\Contracts\Http\Kernel as HttpKernelContract;
|
||||
use Illuminate\Foundation\Http\Kernel as HttpKernel;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Plugins\Sirsoft\Gdpr\Http\Middleware\CookieConsentMiddleware;
|
||||
use Plugins\Sirsoft\Gdpr\Providers\GdprServiceProvider;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 테스트 환경 확장 격리 회귀 테스트
|
||||
*
|
||||
* requiredExtensions allowlist 가 ServiceProvider / route / middleware 등록
|
||||
* 범위를 통제하는지 검증합니다.
|
||||
*
|
||||
* - core-only 테스트(requiredExtensions 미선언): GDPR 플러그인 미로드
|
||||
* - requiredExtensions = ['plugins/sirsoft-gdpr']: GDPR 플러그인 로드
|
||||
*
|
||||
* 본 클래스 자체는 requiredExtensions 를 선언하지 않으므로 core-only 시나리오다.
|
||||
*/
|
||||
class ExtensionTestIsolationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* @effects core_only_test_does_not_register_gdpr_service_provider
|
||||
*/
|
||||
public function test_core_only_test_does_not_register_gdpr_service_provider(): void
|
||||
{
|
||||
// allowlist 가 활성(testing + 명시적 set)이어야 격리가 동작
|
||||
$this->assertTrue(ExtensionTestAllowlist::isActive());
|
||||
$this->assertFalse(ExtensionTestAllowlist::isAllowed('plugin', 'sirsoft-gdpr'));
|
||||
|
||||
$this->assertFalse(
|
||||
$this->app->providerIsLoaded(GdprServiceProvider::class),
|
||||
'core-only 테스트에서 GdprServiceProvider 가 등록되었습니다 — 격리 실패'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects core_only_test_does_not_register_gdpr_middleware_in_web_group, core_only_test_does_not_register_gdpr_middleware_in_api_group
|
||||
*/
|
||||
public function test_core_only_test_does_not_register_gdpr_middleware_in_groups(): void
|
||||
{
|
||||
$kernel = $this->app->make(HttpKernelContract::class);
|
||||
$this->assertInstanceOf(HttpKernel::class, $kernel);
|
||||
|
||||
$groups = $kernel->getMiddlewareGroups();
|
||||
|
||||
$webGroup = $groups['web'] ?? [];
|
||||
$apiGroup = $groups['api'] ?? [];
|
||||
|
||||
$this->assertNotContains(
|
||||
CookieConsentMiddleware::class,
|
||||
$webGroup,
|
||||
'core-only 테스트의 web 미들웨어 그룹에 CookieConsentMiddleware 가 개입했습니다'
|
||||
);
|
||||
$this->assertNotContains(
|
||||
CookieConsentMiddleware::class,
|
||||
$apiGroup,
|
||||
'core-only 테스트의 api 미들웨어 그룹에 CookieConsentMiddleware 가 개입했습니다'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects core_only_test_does_not_register_gdpr_plugin_routes
|
||||
*/
|
||||
public function test_core_only_test_does_not_register_gdpr_plugin_routes(): void
|
||||
{
|
||||
$routes = collect($this->app['router']->getRoutes()->getRoutes())
|
||||
->map(fn ($route) => $route->uri())
|
||||
->filter(fn ($uri) => str_contains($uri, 'plugins/sirsoft-gdpr'));
|
||||
|
||||
$this->assertCount(
|
||||
0,
|
||||
$routes,
|
||||
'core-only 테스트에 GDPR 플러그인 라우트가 등록되었습니다 — 격리 실패'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects allowlist_inactive_when_never_configured
|
||||
*/
|
||||
public function test_allowlist_is_inactive_when_never_configured(): void
|
||||
{
|
||||
// 비-테스트 부팅(또는 set 호출 전)에는 가드가 비활성이어야
|
||||
// 운영/개발 환경의 확장 전수 로딩이 보존됨
|
||||
ExtensionTestAllowlist::reset();
|
||||
|
||||
$this->assertFalse(ExtensionTestAllowlist::isActive());
|
||||
|
||||
// 테스트 격리 보존을 위해 본 클래스의 core-only allowlist 복원
|
||||
ExtensionTestAllowlist::set($this->resolveAllowedExtensions());
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects selfExtension_returns_null_for_core_tests
|
||||
*/
|
||||
public function test_selfExtension_returns_null_for_core_tests(): void
|
||||
{
|
||||
// 본 테스트 클래스는 tests/Feature/ 하위 (코어 테스트) →
|
||||
// selfExtension() 의 modules/plugins 경로 패턴에 매칭되지 않아 null 반환
|
||||
$this->assertNull($this->selfExtension());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Extension;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Extension\StorageInterface;
|
||||
use App\Extension\Cache\CoreCacheDriver;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 코어 캐시·스토리지 글로벌 바인딩 무결성 회귀 가드.
|
||||
*
|
||||
* 이슈 #392 — 어떤 플러그인 ServiceProvider 도 `app(CacheInterface)` 글로벌 바인딩을
|
||||
* PluginCacheDriver 로 덮어쓰면 안 된다. 글로벌 바인딩이 덮어쓰여지면 코어
|
||||
* LayoutService 등의 `$this->cache->put('ext.cache_version', ...)` 가 플러그인
|
||||
* 도메인으로 누수되어 화면에 반영되지 않는 결함이 재발한다.
|
||||
*
|
||||
* 본 테스트는 코어 컨텍스트에서 모든 ServiceProvider 가 부팅된 직후의 상태를 검증한다.
|
||||
* 플러그인별 contextual binding 정확성 (식별자 prefix 매칭 등) 은 해당 플러그인의
|
||||
* Feature 테스트로 검증한다 (예: PluginCacheContextualBindingTest in
|
||||
* plugins/_bundled/sirsoft-verification_kginicis/tests/Feature/).
|
||||
*
|
||||
* @see tests/scenarios/extension-cache-binding-isolation.yaml
|
||||
*/
|
||||
class PluginCacheBindingIsolationTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* @scenario extension_kind=plugin,service_kind=cache_service,global_binding_state=installed_before_provider,manager_state=plugin_resolved,consumer_type=single_class
|
||||
* @effects global_cache_interface_binding_remains_core_cache_driver
|
||||
*/
|
||||
public function test_global_cache_interface_resolves_to_core_cache_driver(): void
|
||||
{
|
||||
$cache = $this->app->make(CacheInterface::class);
|
||||
|
||||
$this->assertInstanceOf(
|
||||
CoreCacheDriver::class,
|
||||
$cache,
|
||||
'app(CacheInterface) 는 항상 CoreCacheDriver 여야 한다. '
|
||||
.'PluginCacheDriver 가 반환되면 어떤 ServiceProvider 가 '
|
||||
.'$this->app->singleton(CacheInterface::class, ...) 로 글로벌 바인딩을 덮어쓰고 있다 (이슈 #392).'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario extension_kind=plugin,service_kind=storage_service,global_binding_state=absent,manager_state=plugin_resolved,consumer_type=no_registration
|
||||
* @effects global_storage_interface_binding_remains_core_storage_driver
|
||||
*/
|
||||
public function test_global_storage_interface_is_not_bound_to_extension_driver(): void
|
||||
{
|
||||
// 코어는 StorageInterface 를 글로벌 바인딩하지 않는다 — 확장은 contextual binding
|
||||
// 으로만 StorageInterface 를 주입해야 한다. 어떤 ServiceProvider 가 글로벌
|
||||
// 바인딩을 등록했다면 그 자체가 결함 후보 (특히 확장 도메인 드라이버로 바인딩 시
|
||||
// 코어/타 확장 도메인의 파일 접근이 누수됨).
|
||||
if (! $this->app->bound(StorageInterface::class)) {
|
||||
$this->assertTrue(true, 'StorageInterface 는 글로벌 바인딩이 없는 상태가 정상.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$storage = $this->app->make(StorageInterface::class);
|
||||
|
||||
$this->assertNotInstanceOf(
|
||||
\App\Extension\Storage\PluginStorageDriver::class,
|
||||
$storage,
|
||||
'app(StorageInterface) 는 PluginStorageDriver 가 아니어야 한다 — 확장 ServiceProvider 의 글로벌 재바인딩 의심.'
|
||||
);
|
||||
$this->assertNotInstanceOf(
|
||||
\App\Extension\Storage\ModuleStorageDriver::class,
|
||||
$storage,
|
||||
'app(StorageInterface) 는 ModuleStorageDriver 가 아니어야 한다 — 확장 ServiceProvider 의 글로벌 재바인딩 의심.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario extension_kind=plugin,service_kind=cache_service,global_binding_state=installed_before_provider,manager_state=plugin_resolved,consumer_type=single_class
|
||||
* @effects layout_service_ext_cache_version_key_written_to_core_namespace
|
||||
*/
|
||||
public function test_core_cache_writes_use_core_namespace_prefix(): void
|
||||
{
|
||||
$cache = $this->app->make(CacheInterface::class);
|
||||
$this->assertInstanceOf(CoreCacheDriver::class, $cache);
|
||||
|
||||
$resolvedKey = $cache->resolveKey('ext.cache_version');
|
||||
|
||||
$this->assertStringStartsWith(
|
||||
'g7:core:',
|
||||
$resolvedKey,
|
||||
'코어 LayoutService 의 ext.cache_version bump 가 플러그인 도메인 (g7:plugin.*:) 으로 누수되면 안 된다.'
|
||||
);
|
||||
|
||||
// 실제 put → has → forget 사이클로 코어 캐시 도메인이 정상 동작함을 검증
|
||||
$cache->put('isolation_probe_392', 'probe', 60);
|
||||
$this->assertTrue($cache->has('isolation_probe_392'));
|
||||
$cache->forget('isolation_probe_392');
|
||||
}
|
||||
}
|
||||
@@ -308,6 +308,11 @@ class IdentityProviderResolutionTest extends TestCase
|
||||
return ['email'];
|
||||
}
|
||||
|
||||
public function getChannelLabels(): array
|
||||
{
|
||||
return ['email' => 'Email'];
|
||||
}
|
||||
|
||||
public function getRenderHint(): string
|
||||
{
|
||||
return 'text_code';
|
||||
|
||||
@@ -2,12 +2,18 @@
|
||||
|
||||
namespace Tests\Feature\LanguagePack;
|
||||
|
||||
use App\Enums\LanguagePackStatus;
|
||||
use App\Extension\AbstractModule;
|
||||
use App\Extension\AbstractPlugin;
|
||||
use App\Extension\HookManager;
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Models\LanguagePack;
|
||||
use App\Providers\LanguagePackServiceProvider;
|
||||
use App\Services\LanguagePack\LanguagePackRegistry;
|
||||
use App\Services\LanguagePack\LanguagePackSeedInjector;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use ReflectionClass;
|
||||
use Tests\TestCase;
|
||||
|
||||
@@ -31,7 +37,6 @@ class ManagerSyncFilterTest extends TestCase
|
||||
* @param string $identifier 모듈 식별자
|
||||
* @param array $payload getter 가 반환할 페이로드
|
||||
* @param string $getter override 할 메서드 이름
|
||||
* @return AbstractModule
|
||||
*/
|
||||
private function fakeModule(string $identifier, array $payload, string $getter): AbstractModule
|
||||
{
|
||||
@@ -216,4 +221,70 @@ class ManagerSyncFilterTest extends TestCase
|
||||
$this->assertNotNull($captured, 'seed.{id}.identity_messages.translations 필터가 플러그인에서 발화되지 않음');
|
||||
$this->assertSame('sensitive_action', $captured[0]['scope_value'] ?? null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 언어팩(plugin/module/template scope)에 seed/manifest.json 이 있으면
|
||||
* ServiceProvider 가 `{scope}.{id}.manifest.translations` 필터를 자동 등록하고,
|
||||
* 그 필터가 manifest name/description 에 ja 를 주입함을 검증.
|
||||
*
|
||||
* Manager DB 저장 직전이 호출하는 `applyFilters("{scope}.{id}.manifest.translations", ...)`
|
||||
* 와 동일 경로 — Manager 결선이 끊기면 라벨이 영영 ko 폴백된다.
|
||||
*
|
||||
* @return iterable<string, array{string, string}>
|
||||
*/
|
||||
public static function manifestScopeProvider(): iterable
|
||||
{
|
||||
yield 'plugin' => ['plugin', 'sirsoft-gdpr'];
|
||||
yield 'module' => ['module', 'sirsoft-ecommerce'];
|
||||
yield 'template' => ['template', 'sirsoft-basic'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider manifestScopeProvider
|
||||
*/
|
||||
public function test_manifest_translations_filter_auto_registered_and_injects_ja(string $scope, string $target): void
|
||||
{
|
||||
$packRoot = base_path("lang-packs/g7-{$scope}-{$target}-ja");
|
||||
File::ensureDirectoryExists($packRoot.'/seed');
|
||||
File::put($packRoot.'/seed/manifest.json', json_encode([
|
||||
'name' => 'ジャパニーズ名',
|
||||
'description' => 'ジャパニーズ説明',
|
||||
]));
|
||||
|
||||
try {
|
||||
LanguagePack::query()->create([
|
||||
'identifier' => "g7-{$scope}-{$target}-ja",
|
||||
'vendor' => 'g7',
|
||||
'scope' => $scope,
|
||||
'target_identifier' => $target,
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'Japanese',
|
||||
'locale_native_name' => '日本語',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => LanguagePackStatus::Active->value,
|
||||
'is_protected' => false,
|
||||
'manifest' => [],
|
||||
'source_type' => 'bundled',
|
||||
]);
|
||||
$this->app->make(LanguagePackRegistry::class)->invalidate();
|
||||
|
||||
// ServiceProvider 의 동적 등록 재실행 (활성 팩 변경 반영)
|
||||
$provider = new LanguagePackServiceProvider($this->app);
|
||||
$provider->registerExtensionSeedFilters($this->app->make(LanguagePackSeedInjector::class));
|
||||
|
||||
// Manager DB 저장 직전과 동일한 필터 호출
|
||||
$result = HookManager::applyFilters("{$scope}.{$target}.manifest.translations", [
|
||||
'name' => ['ko' => '한국어명', 'en' => 'English'],
|
||||
'description' => ['ko' => '한국어설명', 'en' => 'English desc'],
|
||||
]);
|
||||
|
||||
$this->assertSame('ジャパニーズ名', $result['name']['ja'], "{$scope} manifest 필터가 ja name 미주입");
|
||||
$this->assertSame('ジャパニーズ説明', $result['description']['ja'], "{$scope} manifest 필터가 ja description 미주입");
|
||||
$this->assertSame('한국어명', $result['name']['ko'], 'ko 회귀');
|
||||
$this->assertSame('English', $result['name']['en'], 'en 회귀');
|
||||
} finally {
|
||||
File::deleteDirectory($packRoot);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Listeners;
|
||||
|
||||
use App\Listeners\LayoutEditor\MarkOrphanedCustomTranslations;
|
||||
use App\Models\Template;
|
||||
use App\Models\TemplateCustomTranslation;
|
||||
use App\Models\TemplateLayout;
|
||||
use App\Services\LayoutService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* MarkOrphanedCustomTranslations 리스너 Feature 테스트.
|
||||
*
|
||||
* 레이아웃 저장(`core.layout.after_update`) 시 좀비(고아) 커스텀 다국어 키
|
||||
* 자동 표시/복원, layout_name 격리, auto-discovery 등록, Repository 위임을 검증합니다.
|
||||
*/
|
||||
class MarkOrphanedCustomTranslationsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 레이아웃 저장 경로가 GDPR 정책 테이블을 조회하므로 포함.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
private Template $template;
|
||||
|
||||
private LayoutService $layoutService;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->template = Template::factory()->create([
|
||||
'type' => 'user',
|
||||
]);
|
||||
$this->layoutService = app(LayoutService::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 content 헬퍼 — components 안에 주어진 text 노드들을 둔다.
|
||||
*
|
||||
* @param array<int, array<string, mixed>> $components
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function content(array $components): array
|
||||
{
|
||||
return ['meta' => ['title' => 'T'], 'components' => $components];
|
||||
}
|
||||
|
||||
private function makeLayout(string $name, array $components): TemplateLayout
|
||||
{
|
||||
return TemplateLayout::create([
|
||||
'template_id' => $this->template->id,
|
||||
'name' => $name,
|
||||
'content' => $this->content($components),
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
private function makeKey(string $layoutName, string $key, string $status = 'active'): TemplateCustomTranslation
|
||||
{
|
||||
return TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => $layoutName,
|
||||
'translation_key' => $key,
|
||||
'values' => ['ko' => 'A', 'en' => 'A'],
|
||||
'status' => $status,
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_unreferenced_key_is_marked_orphaned_on_save(): void
|
||||
{
|
||||
$this->makeLayout('home', [['text' => '$t:custom.home.1']]);
|
||||
$key = $this->makeKey('home', 'custom.home.1');
|
||||
|
||||
// 키 참조 노드를 제거(평문으로 교체)한 채 저장.
|
||||
$this->layoutService->updateLayout($this->template->id, 'home', [
|
||||
'content' => $this->content([['text' => 'plain text now']]),
|
||||
'expected_lock_version' => 0,
|
||||
]);
|
||||
|
||||
$this->assertDatabaseHas('template_custom_translations', [
|
||||
'id' => $key->id,
|
||||
'status' => 'orphaned',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_referenced_key_stays_active(): void
|
||||
{
|
||||
$this->makeLayout('home', [['text' => '$t:custom.home.1']]);
|
||||
$key = $this->makeKey('home', 'custom.home.1');
|
||||
|
||||
$this->layoutService->updateLayout($this->template->id, 'home', [
|
||||
'content' => $this->content([['text' => '$t:custom.home.1'], ['text' => 'extra']]),
|
||||
'expected_lock_version' => 0,
|
||||
]);
|
||||
|
||||
$this->assertDatabaseHas('template_custom_translations', [
|
||||
'id' => $key->id,
|
||||
'status' => 'active',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_orphaned_key_is_restored_when_reference_returns(): void
|
||||
{
|
||||
$this->makeLayout('home', [['text' => 'plain']]);
|
||||
$key = $this->makeKey('home', 'custom.home.1', 'orphaned');
|
||||
|
||||
// 텍스트를 키 참조로 되돌린 채 저장 → active 복원.
|
||||
$this->layoutService->updateLayout($this->template->id, 'home', [
|
||||
'content' => $this->content([['text' => '$t:custom.home.1']]),
|
||||
'expected_lock_version' => 0,
|
||||
]);
|
||||
|
||||
$this->assertDatabaseHas('template_custom_translations', [
|
||||
'id' => $key->id,
|
||||
'status' => 'active',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_other_layout_keys_are_not_affected(): void
|
||||
{
|
||||
$this->makeLayout('home', [['text' => 'plain']]);
|
||||
// home 레이아웃 저장 시 board/list 의 키는 건드리지 않아야 한다(layout_name 격리).
|
||||
$homeKey = $this->makeKey('home', 'custom.home.1');
|
||||
$boardKey = $this->makeKey('board/list', 'custom.board_list.1');
|
||||
|
||||
$this->layoutService->updateLayout($this->template->id, 'home', [
|
||||
'content' => $this->content([['text' => 'plain']]),
|
||||
'expected_lock_version' => 0,
|
||||
]);
|
||||
|
||||
// home 키는 미참조 → orphaned, board/list 키는 무관 → active 유지.
|
||||
$this->assertDatabaseHas('template_custom_translations', ['id' => $homeKey->id, 'status' => 'orphaned']);
|
||||
$this->assertDatabaseHas('template_custom_translations', ['id' => $boardKey->id, 'status' => 'active']);
|
||||
}
|
||||
|
||||
public function test_listener_is_auto_discovered_and_subscribes_after_update(): void
|
||||
{
|
||||
$hooks = MarkOrphanedCustomTranslations::getSubscribedHooks();
|
||||
|
||||
$this->assertArrayHasKey('core.layout.after_update', $hooks);
|
||||
$this->assertSame('handleLayoutAfterUpdate', $hooks['core.layout.after_update']['method']);
|
||||
// 저장 직후 같은 요청에서 좀비 상태가 확정되어야 하므로 동기 실행.
|
||||
$this->assertTrue($hooks['core.layout.after_update']['sync'] ?? false);
|
||||
|
||||
// auto-discovery 대상 — HookListenerInterface 구현.
|
||||
$this->assertInstanceOf(
|
||||
\App\Contracts\Extension\HookListenerInterface::class,
|
||||
app(MarkOrphanedCustomTranslations::class),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Listeners;
|
||||
|
||||
use App\Contracts\Repositories\TemplateCustomTranslationRepositoryInterface;
|
||||
use App\Extension\HookManager;
|
||||
use App\Listeners\LanguagePack\MergeCustomTranslations;
|
||||
use App\Models\Template;
|
||||
use App\Models\TemplateCustomTranslation;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* MergeCustomTranslations 리스너 테스트.
|
||||
*
|
||||
* `template.language.merge` 필터 결과에 커스텀 키가 점 경로로 병합되며,
|
||||
* 언어팩 데이터보다 높은 우선순위(나중 실행)로 덮어쓰는지 검증합니다.
|
||||
*/
|
||||
class MergeCustomTranslationsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 같은 스위트의 DB 테스트와 migrate:fresh 정합성을 위해 일관 선언
|
||||
* (requiredExtensions 누락 시 migrate:fresh 1회 함정 — feedback_required_extensions_all_db_tests).
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
private Template $template;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->template = Template::factory()->create();
|
||||
}
|
||||
|
||||
private function applyMerge(array $base, string $locale = 'ko'): array
|
||||
{
|
||||
return HookManager::applyFilters(
|
||||
'template.language.merge',
|
||||
$base,
|
||||
$this->template->identifier,
|
||||
$locale,
|
||||
);
|
||||
}
|
||||
|
||||
public function test_custom_key_is_merged_into_language_tree_by_dot_path(): void
|
||||
{
|
||||
TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => ['ko' => '안녕', 'en' => 'hello'],
|
||||
'status' => 'active',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
$result = $this->applyMerge([], 'ko');
|
||||
|
||||
$this->assertSame('안녕', data_get($result, 'custom.home.1'));
|
||||
}
|
||||
|
||||
public function test_custom_key_resolves_locale_value(): void
|
||||
{
|
||||
TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => ['ko' => '안녕', 'en' => 'hello'],
|
||||
'status' => 'active',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
$result = $this->applyMerge([], 'en');
|
||||
|
||||
$this->assertSame('hello', data_get($result, 'custom.home.1'));
|
||||
}
|
||||
|
||||
public function test_custom_key_overrides_existing_language_pack_value(): void
|
||||
{
|
||||
TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => ['ko' => '커스텀', 'en' => 'custom'],
|
||||
'status' => 'active',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
// 언어팩이 먼저 채운 동일 경로를 커스텀 키가 덮어써야 한다 (priority 20 > 10).
|
||||
$base = ['custom' => ['home' => ['1' => '언어팩값']]];
|
||||
$result = $this->applyMerge($base, 'ko');
|
||||
|
||||
$this->assertSame('커스텀', data_get($result, 'custom.home.1'));
|
||||
}
|
||||
|
||||
public function test_orphaned_keys_are_not_merged(): void
|
||||
{
|
||||
TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => ['ko' => '고아', 'en' => 'orphan'],
|
||||
'status' => 'orphaned',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
$result = $this->applyMerge([], 'ko');
|
||||
|
||||
$this->assertNull(data_get($result, 'custom.home.1'));
|
||||
}
|
||||
|
||||
public function test_missing_locale_falls_back_to_fallback_locale(): void
|
||||
{
|
||||
TemplateCustomTranslation::create([
|
||||
'template_id' => $this->template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => ['ko' => '폴백'],
|
||||
'status' => 'active',
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
// en 값 부재 → fallback_locale(ko) 값으로 폴백
|
||||
$result = $this->applyMerge([], 'en');
|
||||
|
||||
$this->assertSame('폴백', data_get($result, 'custom.home.1'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀 — repository 조회가 실패해도(테이블 미적용·DB 장애) 전체 언어
|
||||
* 파이프라인이 무너지지 않고 입력 데이터를 그대로 반환한다(무손실 디그레이드).
|
||||
*
|
||||
* 배경: `template_custom_translations` 테이블이 없는 환경에서 본 리스너가 던진
|
||||
* QueryException 이 `serveLanguage` 전체를 500 으로 무너뜨려 모든 admin/user 화면의
|
||||
* 다국어 로드가 깨졌다. 리스너는 코어 언어 파이프라인의 후행 부가 단계이므로 자신의
|
||||
* 실패를 흡수해야 한다.
|
||||
*/
|
||||
public function test_repository_failure_degrades_to_input_data_without_throwing(): void
|
||||
{
|
||||
$base = ['nav' => ['home' => '홈']];
|
||||
|
||||
// repository 가 QueryException(테이블 부재 등)을 던지도록 모킹.
|
||||
$failingRepo = Mockery::mock(TemplateCustomTranslationRepositoryInterface::class);
|
||||
$failingRepo->shouldReceive('getActiveByTemplateId')
|
||||
->andThrow(new QueryException(
|
||||
'mysql',
|
||||
'select * from `g7_template_custom_translations`',
|
||||
[],
|
||||
new \PDOException("SQLSTATE[42S02]: Base table or view not found: 1146 Table 'g7.g7_template_custom_translations' doesn't exist"),
|
||||
));
|
||||
|
||||
$listener = new MergeCustomTranslations(
|
||||
app(\App\Contracts\Repositories\TemplateRepositoryInterface::class),
|
||||
$failingRepo,
|
||||
);
|
||||
|
||||
// 예외가 전파되지 않고 입력이 그대로 반환되어야 한다.
|
||||
$result = $listener($base, $this->template->identifier, 'ko');
|
||||
|
||||
$this->assertSame('홈', data_get($result, 'nav.home'));
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Mockery::close();
|
||||
parent::tearDown();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Mail;
|
||||
|
||||
use App\Models\NotificationDefinition;
|
||||
use App\Models\NotificationTemplate;
|
||||
use App\Models\User;
|
||||
use App\Notifications\BaseNotification;
|
||||
use App\Notifications\GenericNotification;
|
||||
use App\Services\NotificationDefinitionService;
|
||||
use App\Services\NotificationTemplateService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\App;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 알림 수신자 언어(locale) 결정 회귀 테스트 (A7)
|
||||
*
|
||||
* 알림 렌더는 요청자(app locale) 가 아닌 수신자 본인 언어(users.language)로
|
||||
* 결정되어야 합니다. User 가 HasLocalePreference 를 구현하고, 렌더 3지점
|
||||
* (toMail / toArray / Dispatcher) 이 BaseNotification::resolveNotifiableLocale()
|
||||
* 헬퍼로 수신자 선호 로케일을 우선 해석하는지 검증합니다.
|
||||
*/
|
||||
class NotificationRecipientLocaleTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Cache::flush();
|
||||
Config::set('app.name', 'G7 Test');
|
||||
Config::set('app.url', 'https://g7.test');
|
||||
Config::set('app.supported_locales', ['ko', 'en']);
|
||||
}
|
||||
|
||||
/**
|
||||
* User::preferredLocale() 이 users.language 를 SSoT 로 반환한다.
|
||||
*/
|
||||
public function test_preferred_locale_returns_user_language(): void
|
||||
{
|
||||
$user = User::factory()->create(['language' => 'en']);
|
||||
|
||||
$this->assertSame('en', $user->preferredLocale());
|
||||
}
|
||||
|
||||
/**
|
||||
* language 가 미지원/빈값이면 사이트 기본 로케일로 폴백한다.
|
||||
*/
|
||||
public function test_preferred_locale_falls_back_to_default(): void
|
||||
{
|
||||
Config::set('app.locale', 'ko');
|
||||
|
||||
$unsupported = User::factory()->create(['language' => 'fr']);
|
||||
$this->assertSame('ko', $unsupported->preferredLocale());
|
||||
|
||||
// language 가 빈값(null) 인 수신자 — language 컬럼은 NOT NULL 이므로 모델 객체로 검증
|
||||
$empty = new User(['language' => null]);
|
||||
$this->assertSame('ko', $empty->preferredLocale());
|
||||
}
|
||||
|
||||
/**
|
||||
* 헬퍼는 HasLocalePreference 수신자의 preferredLocale() 을 우선한다.
|
||||
*/
|
||||
public function test_helper_prefers_recipient_locale_over_app_locale(): void
|
||||
{
|
||||
App::setLocale('en'); // 요청자/관리자 컨텍스트 = en
|
||||
|
||||
$recipient = User::factory()->create(['language' => 'ko']);
|
||||
|
||||
$this->assertSame('ko', BaseNotification::resolveNotifiableLocale($recipient));
|
||||
}
|
||||
|
||||
/**
|
||||
* contract 미구현 수신자는 현재 app locale 로 폴백한다.
|
||||
*/
|
||||
public function test_helper_falls_back_for_non_contract_notifiable(): void
|
||||
{
|
||||
App::setLocale('en');
|
||||
|
||||
$anonymous = new \Illuminate\Notifications\AnonymousNotifiable;
|
||||
|
||||
$this->assertSame('en', BaseNotification::resolveNotifiableLocale($anonymous));
|
||||
}
|
||||
|
||||
/**
|
||||
* toMail: 요청자 locale=en 이어도 수신자 language=ko 면 ko 본문으로 렌더.
|
||||
*/
|
||||
public function test_to_mail_renders_in_recipient_language(): void
|
||||
{
|
||||
$this->createDefinitionWithMailChannel('order_test', 'sirsoft-ecommerce', 'module', 'sirsoft-ecommerce', [
|
||||
'subject' => ['ko' => '주문 안내', 'en' => 'Order notice'],
|
||||
'body' => ['ko' => '<p>한국어 본문</p>', 'en' => '<p>English body</p>'],
|
||||
]);
|
||||
|
||||
App::setLocale('en'); // 관리자(요청자) 컨텍스트
|
||||
|
||||
$recipient = User::factory()->create(['language' => 'ko', 'email' => 'ko@example.com']);
|
||||
|
||||
$notification = new GenericNotification('order_test', 'sirsoft-ecommerce', []);
|
||||
$mailable = $notification->toMail($recipient);
|
||||
|
||||
$this->assertSame('주문 안내', $mailable->envelope()->subject);
|
||||
$this->assertStringContainsString('한국어 본문', $mailable->content()->with['body']);
|
||||
}
|
||||
|
||||
/**
|
||||
* toArray(database): 수신자 language=ko 면 ko 본문으로 렌더.
|
||||
*/
|
||||
public function test_to_array_renders_in_recipient_language(): void
|
||||
{
|
||||
$this->createDefinitionWithDatabaseChannel('order_test_db', 'sirsoft-ecommerce', 'module', 'sirsoft-ecommerce', [
|
||||
'subject' => ['ko' => '주문 알림', 'en' => 'Order alert'],
|
||||
'body' => ['ko' => '한국어 알림 본문', 'en' => 'English alert body'],
|
||||
]);
|
||||
|
||||
App::setLocale('en');
|
||||
|
||||
$recipient = User::factory()->create(['language' => 'ko']);
|
||||
|
||||
$notification = new GenericNotification('order_test_db', 'sirsoft-ecommerce', []);
|
||||
$payload = $notification->toArray($recipient);
|
||||
|
||||
$this->assertSame('주문 알림', $payload['subject']);
|
||||
$this->assertStringContainsString('한국어 알림 본문', $payload['body']);
|
||||
}
|
||||
|
||||
private function createDefinitionWithMailChannel(
|
||||
string $type,
|
||||
string $hookPrefix,
|
||||
string $extensionType,
|
||||
string $extensionIdentifier,
|
||||
array $templateData,
|
||||
): NotificationDefinition {
|
||||
return $this->createDefinition($type, $hookPrefix, $extensionType, $extensionIdentifier, 'mail', $templateData);
|
||||
}
|
||||
|
||||
private function createDefinitionWithDatabaseChannel(
|
||||
string $type,
|
||||
string $hookPrefix,
|
||||
string $extensionType,
|
||||
string $extensionIdentifier,
|
||||
array $templateData,
|
||||
): NotificationDefinition {
|
||||
return $this->createDefinition($type, $hookPrefix, $extensionType, $extensionIdentifier, 'database', $templateData);
|
||||
}
|
||||
|
||||
private function createDefinition(
|
||||
string $type,
|
||||
string $hookPrefix,
|
||||
string $extensionType,
|
||||
string $extensionIdentifier,
|
||||
string $channel,
|
||||
array $templateData,
|
||||
): NotificationDefinition {
|
||||
$definition = NotificationDefinition::create([
|
||||
'type' => $type,
|
||||
'hook_prefix' => $hookPrefix,
|
||||
'extension_type' => $extensionType,
|
||||
'extension_identifier' => $extensionIdentifier,
|
||||
'name' => ['ko' => $type, 'en' => $type],
|
||||
'variables' => [],
|
||||
'channels' => [$channel],
|
||||
'hooks' => [],
|
||||
'is_active' => true,
|
||||
'is_default' => true,
|
||||
]);
|
||||
|
||||
NotificationTemplate::create([
|
||||
'definition_id' => $definition->id,
|
||||
'channel' => $channel,
|
||||
'subject' => $templateData['subject'],
|
||||
'body' => $templateData['body'],
|
||||
'is_active' => true,
|
||||
'is_default' => true,
|
||||
]);
|
||||
|
||||
app(NotificationDefinitionService::class)->invalidateCache($type);
|
||||
app(NotificationTemplateService::class)->invalidateCache($type, $channel);
|
||||
|
||||
return $definition;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Migrations;
|
||||
|
||||
use App\Models\Template;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* template_custom_translations 마이그레이션 테스트.
|
||||
*
|
||||
* 테이블 생성 + lock_version 컬럼 + up/down 라운드트립 안전성을 검증합니다.
|
||||
*/
|
||||
class TemplateCustomTranslationsMigrationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 같은 스위트의 DB 테스트와 migrate:fresh 정합성을 위해 일관 선언
|
||||
* (requiredExtensions 누락 시 migrate:fresh 1회 함정 — feedback_required_extensions_all_db_tests).
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
public function test_table_exists_with_expected_columns(): void
|
||||
{
|
||||
$this->assertTrue(Schema::hasTable('template_custom_translations'));
|
||||
|
||||
$this->assertTrue(Schema::hasColumns('template_custom_translations', [
|
||||
'id',
|
||||
'template_id',
|
||||
'layout_name',
|
||||
'translation_key',
|
||||
'values',
|
||||
'user_overrides',
|
||||
'status',
|
||||
'created_by',
|
||||
'updated_by',
|
||||
'lock_version',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
]));
|
||||
}
|
||||
|
||||
public function test_lock_version_column_defaults_to_zero(): void
|
||||
{
|
||||
$template = Template::factory()->create();
|
||||
|
||||
$id = DB::table('template_custom_translations')->insertGetId([
|
||||
'template_id' => $template->id,
|
||||
'layout_name' => 'home',
|
||||
'translation_key' => 'custom.home.1',
|
||||
'values' => json_encode(['ko' => 'a', 'en' => 'a']),
|
||||
'status' => 'active',
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
$row = DB::table('template_custom_translations')->find($id);
|
||||
|
||||
$this->assertSame(0, (int) $row->lock_version);
|
||||
}
|
||||
|
||||
public function test_lock_version_migration_down_then_up_roundtrip(): void
|
||||
{
|
||||
// down: lock_version 컬럼 제거
|
||||
Schema::table('template_custom_translations', function ($table) {
|
||||
$table->dropColumn('lock_version');
|
||||
});
|
||||
$this->assertFalse(Schema::hasColumn('template_custom_translations', 'lock_version'));
|
||||
|
||||
// up: 컬럼 재추가 (마이그레이션 up 본문과 동일)
|
||||
Schema::table('template_custom_translations', function ($table) {
|
||||
$table->unsignedBigInteger('lock_version')->default(0)->after('updated_by')->comment('낙관적 잠금 버전');
|
||||
});
|
||||
$this->assertTrue(Schema::hasColumn('template_custom_translations', 'lock_version'));
|
||||
}
|
||||
}
|
||||
@@ -100,17 +100,17 @@ class ModuleRolePermissionSyncTest extends TestCase
|
||||
{
|
||||
$this->moduleManager->installModule('sirsoft-board');
|
||||
|
||||
// 권한 생성 확인 (모듈 루트 1 + 카테고리 3 + 리프 8 = 12)
|
||||
// 권한 생성 확인 (모듈 루트 1 + 카테고리 4 + 리프 10 = 15)
|
||||
$permissions = Permission::where('extension_type', ExtensionOwnerType::Module)
|
||||
->where('extension_identifier', 'sirsoft-board')->get();
|
||||
$this->assertCount(12, $permissions);
|
||||
$this->assertCount(15, $permissions);
|
||||
|
||||
// admin 역할에 할당된 sirsoft-board 권한 확인 (리프 8개)
|
||||
// admin 역할에 할당된 sirsoft-board 권한 확인 (리프 10개)
|
||||
$adminRole = Role::where('identifier', 'admin')->first();
|
||||
$adminPermissions = $adminRole->permissions()->where('extension_identifier', 'sirsoft-board')->get();
|
||||
$this->assertCount(8, $adminPermissions);
|
||||
$this->assertCount(10, $adminPermissions);
|
||||
|
||||
// manager 역할에 할당된 sirsoft-board 권한 확인
|
||||
// manager 역할에 할당된 sirsoft-board 권한 확인 (리프 4개)
|
||||
$managerRole = Role::where('identifier', 'manager')->first();
|
||||
$managerPermissions = $managerRole->permissions()->where('extension_identifier', 'sirsoft-board')->get();
|
||||
$this->assertCount(4, $managerPermissions);
|
||||
@@ -171,14 +171,14 @@ class ModuleRolePermissionSyncTest extends TestCase
|
||||
{
|
||||
$this->moduleManager->installModule('sirsoft-board');
|
||||
|
||||
// 초기 상태 확인 (admin에 리프 8개 할당)
|
||||
// 초기 상태 확인 (admin에 리프 10개 할당)
|
||||
$adminRole = Role::where('identifier', 'admin')->first();
|
||||
$this->assertCount(8, $adminRole->permissions()->where('extension_identifier', 'sirsoft-board')->get());
|
||||
$this->assertCount(10, $adminRole->permissions()->where('extension_identifier', 'sirsoft-board')->get());
|
||||
|
||||
// 유저가 admin에서 boards.delete 권한 해제
|
||||
$deletePerm = Permission::where('identifier', 'sirsoft-board.boards.delete')->first();
|
||||
$adminRole->permissions()->detach($deletePerm->id);
|
||||
$this->assertCount(7, $adminRole->permissions()->where('extension_identifier', 'sirsoft-board')->get());
|
||||
$this->assertCount(9, $adminRole->permissions()->where('extension_identifier', 'sirsoft-board')->get());
|
||||
|
||||
// user_overrides에 개별 권한 식별자 기록 (실제로는 Listener가 수행)
|
||||
$adminRole->update(['user_overrides' => ['sirsoft-board.boards.delete']]);
|
||||
@@ -187,10 +187,10 @@ class ModuleRolePermissionSyncTest extends TestCase
|
||||
$module = $this->moduleManager->getModule('sirsoft-board');
|
||||
$this->callProtectedMethod('assignPermissionsToRoles', [$module]);
|
||||
|
||||
// sirsoft-board.boards.delete만 보호 → 해제 상태 유지 → 7개 유지
|
||||
// sirsoft-board.boards.delete만 보호 → 해제 상태 유지 → 9개 유지
|
||||
$adminRole->refresh();
|
||||
$this->assertCount(
|
||||
7,
|
||||
9,
|
||||
$adminRole->permissions()->where('extension_identifier', 'sirsoft-board')->get(),
|
||||
'user_overrides에 개별 권한 식별자가 있으면 해당 권한만 보호되어야 합니다'
|
||||
);
|
||||
@@ -226,7 +226,8 @@ class ModuleRolePermissionSyncTest extends TestCase
|
||||
$readPerm = Permission::where('identifier', 'sirsoft-board.boards.read')->first();
|
||||
$adminRole->permissions()->detach($readPerm->id);
|
||||
|
||||
$this->assertCount(6, $adminRole->permissions()->where('extension_identifier', 'sirsoft-board')->get());
|
||||
// 리프 10개 중 2개 해제 → 8개
|
||||
$this->assertCount(8, $adminRole->permissions()->where('extension_identifier', 'sirsoft-board')->get());
|
||||
|
||||
// 재설치
|
||||
$module = $this->moduleManager->getModule('sirsoft-board');
|
||||
@@ -234,7 +235,7 @@ class ModuleRolePermissionSyncTest extends TestCase
|
||||
|
||||
$adminRole->refresh();
|
||||
|
||||
// boards.read는 비보호 → 다시 attach → 7개
|
||||
// boards.read는 비보호 → 다시 attach → 9개
|
||||
$this->assertTrue(
|
||||
$adminRole->permissions()->where('identifier', 'sirsoft-board.boards.read')->exists(),
|
||||
'비보호 권한(boards.read)은 재설치 시 다시 attach되어야 합니다'
|
||||
@@ -247,7 +248,7 @@ class ModuleRolePermissionSyncTest extends TestCase
|
||||
);
|
||||
|
||||
$this->assertCount(
|
||||
7,
|
||||
9,
|
||||
$adminRole->permissions()->where('extension_identifier', 'sirsoft-board')->get(),
|
||||
'비보호 권한만 동기화되고 보호 권한은 유지되어야 합니다'
|
||||
);
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Notifications;
|
||||
|
||||
use App\Models\NotificationLog;
|
||||
use App\Notifications\GenericNotification;
|
||||
use App\Notifications\GuestNotifiable;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 비회원(게스트) 발송 로깅 end-to-end 테스트
|
||||
*
|
||||
* 비회원에게 실제로 발송이 일어날 때(mail driver=log) 알림 발송 시스템(notification_logs)에
|
||||
* 정상 기록되는지, 그리고 게스트의 합성 키(guest:...)가 정수 FK 컬럼에 들어가지 않고
|
||||
* recipient_user_id=null + recipient_identifier=email 로 분리 기록되는지 검증한다.
|
||||
*/
|
||||
class GuestNotificationLoggingTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private function sendGuestMail(string $email, ?string $name = '비회원'): void
|
||||
{
|
||||
// mail 채널 직접 지정 GenericNotification — definition/template 없이도
|
||||
// 발송 파이프라인(NotificationDispatcher::buildContext → after_channel_send 훅)을 탄다.
|
||||
$guest = new GuestNotifiable($email, $name, 'ko');
|
||||
$guest->notify(new GenericNotification(
|
||||
type: 'welcome',
|
||||
hookPrefix: 'core.auth',
|
||||
data: ['name' => $name],
|
||||
extensionType: 'core',
|
||||
extensionIdentifier: 'core',
|
||||
channel: 'mail',
|
||||
));
|
||||
}
|
||||
|
||||
public function test_guest_mail_send_is_logged_with_null_user_id_and_email_identifier(): void
|
||||
{
|
||||
$this->sendGuestMail('guest@example.com', '비회원주문자');
|
||||
|
||||
$log = NotificationLog::where('channel', 'mail')
|
||||
->where('recipient_identifier', 'guest@example.com')
|
||||
->first();
|
||||
|
||||
$this->assertNotNull($log, '비회원 mail 발송이 notification_logs 에 기록되어야 한다.');
|
||||
// 게스트는 users FK 가 없으므로 recipient_user_id 는 null 이어야 한다 (합성 키 문자열 미삽입).
|
||||
$this->assertNull($log->recipient_user_id);
|
||||
$this->assertSame('비회원주문자', $log->recipient_name);
|
||||
}
|
||||
|
||||
public function test_guest_database_channel_is_not_logged_as_sent(): void
|
||||
{
|
||||
// database 채널은 allow_guest=false 게이트로 via() 가 빈 배열을 반환 → 발송 안 됨.
|
||||
$guest = new GuestNotifiable('guest-db@example.com', '비회원', 'ko');
|
||||
$guest->notify(new GenericNotification(
|
||||
type: 'welcome',
|
||||
hookPrefix: 'core.auth',
|
||||
data: ['name' => '비회원'],
|
||||
extensionType: 'core',
|
||||
extensionIdentifier: 'core',
|
||||
channel: 'database',
|
||||
));
|
||||
|
||||
// database 채널로 발송 성공 기록이 없어야 한다 (게이트 차단).
|
||||
$sent = NotificationLog::where('channel', 'database')
|
||||
->where('recipient_identifier', 'guest-db@example.com')
|
||||
->where('status', '!=', 'skipped')
|
||||
->count();
|
||||
|
||||
$this->assertSame(0, $sent, '비회원 database 발송은 게이트로 차단되어 발송 기록이 없어야 한다.');
|
||||
|
||||
// 사이트내(database) 알림 morph 테이블에도 게스트 행이 생기지 않아야 한다.
|
||||
$this->assertDatabaseCount('notifications', 0);
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,12 @@
|
||||
|
||||
namespace Tests\Feature\Plugin;
|
||||
|
||||
use App\Contracts\Extension\PluginInterface;
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Enums\PermissionType;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use ReflectionMethod;
|
||||
use Tests\TestCase;
|
||||
|
||||
@@ -17,25 +16,31 @@ use Tests\TestCase;
|
||||
*
|
||||
* PluginManager.createPluginPermissions()가 모듈과 동일한
|
||||
* 3레벨 계층(플러그인 → 카테고리 → 개별 권한)을 생성하는지 검증합니다.
|
||||
*
|
||||
* 검증 대상 플러그인: sirsoft-gdpr
|
||||
* - 그룹 1 (sirsoft-gdpr)
|
||||
* - 카테고리 1 (privacy)
|
||||
* - 리프 2 (privacy.view, privacy.update)
|
||||
*/
|
||||
class PluginPermissionGroupTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private PluginManager $pluginManager;
|
||||
/**
|
||||
* GDPR 플러그인의 ServiceProvider/route/권한 정의를 테스트 앱에 로드.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
private bool $verificationExistedBefore = false;
|
||||
private PluginManager $pluginManager;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$activePath = base_path('plugins/sirsoft-verification');
|
||||
if (File::isDirectory($activePath) && ! File::exists($activePath.'/plugin.php')) {
|
||||
File::deleteDirectory($activePath);
|
||||
}
|
||||
|
||||
$this->verificationExistedBefore = File::isDirectory($activePath);
|
||||
$this->pluginManager = app(PluginManager::class);
|
||||
$this->pluginManager->loadPlugins();
|
||||
|
||||
@@ -50,14 +55,27 @@ class PluginPermissionGroupTest extends TestCase
|
||||
]);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
/**
|
||||
* 검증 대상 GDPR 플러그인 인스턴스를 반환합니다.
|
||||
*/
|
||||
private function gdprPlugin(): PluginInterface
|
||||
{
|
||||
$activePath = base_path('plugins/sirsoft-verification');
|
||||
if (! $this->verificationExistedBefore && File::isDirectory($activePath)) {
|
||||
File::deleteDirectory($activePath);
|
||||
}
|
||||
$plugin = $this->pluginManager->getPlugin('sirsoft-gdpr');
|
||||
$this->assertNotNull($plugin, 'GDPR 플러그인이 로드되어야 합니다');
|
||||
|
||||
parent::tearDown();
|
||||
return $plugin;
|
||||
}
|
||||
|
||||
/**
|
||||
* PluginManager의 protected 메서드를 호출하는 헬퍼
|
||||
*
|
||||
* @param string $methodName 메서드명
|
||||
* @param PluginInterface $plugin 대상 플러그인
|
||||
*/
|
||||
private function callProtectedMethod(string $methodName, PluginInterface $plugin): void
|
||||
{
|
||||
$method = new ReflectionMethod(PluginManager::class, $methodName);
|
||||
$method->invoke($this->pluginManager, $plugin);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -65,20 +83,16 @@ class PluginPermissionGroupTest extends TestCase
|
||||
*/
|
||||
public function test_creates_plugin_group_node(): void
|
||||
{
|
||||
$plugin = $this->pluginManager->getPlugin('sirsoft-verification');
|
||||
$this->assertNotNull($plugin, '본인인증 플러그인이 로드되어야 합니다');
|
||||
$this->callProtectedMethod('createPluginPermissions', $this->gdprPlugin());
|
||||
|
||||
$method = new ReflectionMethod(PluginManager::class, 'createPluginPermissions');
|
||||
$method->invoke($this->pluginManager, $plugin);
|
||||
|
||||
$groupNode = Permission::where('identifier', 'sirsoft-verification')
|
||||
$groupNode = Permission::where('identifier', 'sirsoft-gdpr')
|
||||
->whereNull('parent_id')
|
||||
->first();
|
||||
|
||||
$this->assertNotNull($groupNode, '플러그인 그룹 노드가 생성되어야 합니다');
|
||||
$this->assertEquals(ExtensionOwnerType::Plugin, $groupNode->extension_type);
|
||||
$this->assertEquals('sirsoft-verification', $groupNode->extension_identifier);
|
||||
$this->assertEquals('본인인증', $groupNode->getLocalizedName());
|
||||
$this->assertEquals('sirsoft-gdpr', $groupNode->extension_identifier);
|
||||
$this->assertEquals('GDPR (일반 데이터 보호 규정)', $groupNode->getLocalizedName());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -86,22 +100,16 @@ class PluginPermissionGroupTest extends TestCase
|
||||
*/
|
||||
public function test_creates_category_nodes_under_plugin(): void
|
||||
{
|
||||
$plugin = $this->pluginManager->getPlugin('sirsoft-verification');
|
||||
$this->callProtectedMethod('createPluginPermissions', $this->gdprPlugin());
|
||||
|
||||
$method = new ReflectionMethod(PluginManager::class, 'createPluginPermissions');
|
||||
$method->invoke($this->pluginManager, $plugin);
|
||||
|
||||
$groupNode = Permission::where('identifier', 'sirsoft-verification')->first();
|
||||
$groupNode = Permission::where('identifier', 'sirsoft-gdpr')->first();
|
||||
|
||||
// 카테고리 노드 확인
|
||||
$categories = Permission::where('parent_id', $groupNode->id)->orderBy('order')->get();
|
||||
$this->assertCount(2, $categories, '2개 카테고리가 있어야 합니다');
|
||||
$this->assertCount(1, $categories, '1개 카테고리가 있어야 합니다');
|
||||
|
||||
$this->assertEquals('sirsoft-verification.settings', $categories[0]->identifier);
|
||||
$this->assertEquals('설정 관리', $categories[0]->getLocalizedName());
|
||||
|
||||
$this->assertEquals('sirsoft-verification.user', $categories[1]->identifier);
|
||||
$this->assertEquals('사용자 인증 정보', $categories[1]->getLocalizedName());
|
||||
$this->assertEquals('sirsoft-gdpr.privacy', $categories[0]->identifier);
|
||||
$this->assertEquals('개인정보 보호', $categories[0]->getLocalizedName());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -109,24 +117,14 @@ class PluginPermissionGroupTest extends TestCase
|
||||
*/
|
||||
public function test_permissions_are_children_of_category_nodes(): void
|
||||
{
|
||||
$plugin = $this->pluginManager->getPlugin('sirsoft-verification');
|
||||
$this->callProtectedMethod('createPluginPermissions', $this->gdprPlugin());
|
||||
|
||||
$method = new ReflectionMethod(PluginManager::class, 'createPluginPermissions');
|
||||
$method->invoke($this->pluginManager, $plugin);
|
||||
|
||||
// settings 카테고리의 자식 권한
|
||||
$settingsCategory = Permission::where('identifier', 'sirsoft-verification.settings')->first();
|
||||
$settingsPerms = Permission::where('parent_id', $settingsCategory->id)->orderBy('order')->get();
|
||||
$this->assertCount(2, $settingsPerms);
|
||||
$this->assertEquals('sirsoft-verification.settings.view', $settingsPerms[0]->identifier);
|
||||
$this->assertEquals('sirsoft-verification.settings.update', $settingsPerms[1]->identifier);
|
||||
|
||||
// user 카테고리의 자식 권한
|
||||
$userCategory = Permission::where('identifier', 'sirsoft-verification.user')->first();
|
||||
$userPerms = Permission::where('parent_id', $userCategory->id)->orderBy('order')->get();
|
||||
$this->assertCount(2, $userPerms);
|
||||
$this->assertEquals('sirsoft-verification.user.view', $userPerms[0]->identifier);
|
||||
$this->assertEquals('sirsoft-verification.user.update', $userPerms[1]->identifier);
|
||||
// privacy 카테고리의 자식 권한
|
||||
$privacyCategory = Permission::where('identifier', 'sirsoft-gdpr.privacy')->first();
|
||||
$privacyPerms = Permission::where('parent_id', $privacyCategory->id)->orderBy('order')->get();
|
||||
$this->assertCount(2, $privacyPerms);
|
||||
$this->assertEquals('sirsoft-gdpr.privacy.view', $privacyPerms[0]->identifier);
|
||||
$this->assertEquals('sirsoft-gdpr.privacy.update', $privacyPerms[1]->identifier);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -134,36 +132,30 @@ class PluginPermissionGroupTest extends TestCase
|
||||
*/
|
||||
public function test_only_leaf_permissions_are_assignable(): void
|
||||
{
|
||||
$plugin = $this->pluginManager->getPlugin('sirsoft-verification');
|
||||
|
||||
$method = new ReflectionMethod(PluginManager::class, 'createPluginPermissions');
|
||||
$method->invoke($this->pluginManager, $plugin);
|
||||
$this->callProtectedMethod('createPluginPermissions', $this->gdprPlugin());
|
||||
|
||||
// 그룹 노드: 자식 있음 → 할당 불가
|
||||
$groupNode = Permission::where('identifier', 'sirsoft-verification')->first();
|
||||
$groupNode = Permission::where('identifier', 'sirsoft-gdpr')->first();
|
||||
$this->assertTrue($groupNode->children()->exists());
|
||||
|
||||
// 카테고리 노드: 자식 있음 → 할당 불가
|
||||
$settingsCategory = Permission::where('identifier', 'sirsoft-verification.settings')->first();
|
||||
$this->assertTrue($settingsCategory->children()->exists());
|
||||
$privacyCategory = Permission::where('identifier', 'sirsoft-gdpr.privacy')->first();
|
||||
$this->assertTrue($privacyCategory->children()->exists());
|
||||
|
||||
// 리프 권한: 자식 없음 → 할당 가능
|
||||
$leafPerm = Permission::where('identifier', 'sirsoft-verification.settings.view')->first();
|
||||
$leafPerm = Permission::where('identifier', 'sirsoft-gdpr.privacy.view')->first();
|
||||
$this->assertFalse($leafPerm->children()->exists());
|
||||
}
|
||||
|
||||
/**
|
||||
* 전체 권한 수 확인 (그룹 1 + 카테고리 2 + 개별 4 = 7)
|
||||
* 전체 권한 수 확인 (그룹 1 + 카테고리 1 + 개별 2 = 4)
|
||||
*/
|
||||
public function test_total_permission_count(): void
|
||||
{
|
||||
$plugin = $this->pluginManager->getPlugin('sirsoft-verification');
|
||||
$this->callProtectedMethod('createPluginPermissions', $this->gdprPlugin());
|
||||
|
||||
$method = new ReflectionMethod(PluginManager::class, 'createPluginPermissions');
|
||||
$method->invoke($this->pluginManager, $plugin);
|
||||
|
||||
$total = Permission::where('extension_identifier', 'sirsoft-verification')->count();
|
||||
$this->assertEquals(7, $total, '그룹 1개 + 카테고리 2개 + 개별 권한 4개 = 7개');
|
||||
$total = Permission::where('extension_identifier', 'sirsoft-gdpr')->count();
|
||||
$this->assertEquals(4, $total, '그룹 1개 + 카테고리 1개 + 개별 권한 2개 = 4개');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -171,7 +163,7 @@ class PluginPermissionGroupTest extends TestCase
|
||||
*/
|
||||
public function test_no_permissions_for_plugin_without_categories(): void
|
||||
{
|
||||
$mockPlugin = $this->createMock(\App\Contracts\Extension\PluginInterface::class);
|
||||
$mockPlugin = $this->createMock(PluginInterface::class);
|
||||
$mockPlugin->method('getPermissions')->willReturn([]);
|
||||
$mockPlugin->method('getIdentifier')->willReturn('test-no-permissions');
|
||||
|
||||
@@ -186,23 +178,21 @@ class PluginPermissionGroupTest extends TestCase
|
||||
*/
|
||||
public function test_sync_updates_without_duplication(): void
|
||||
{
|
||||
$plugin = $this->pluginManager->getPlugin('sirsoft-verification');
|
||||
|
||||
$method = new ReflectionMethod(PluginManager::class, 'createPluginPermissions');
|
||||
$plugin = $this->gdprPlugin();
|
||||
|
||||
// 1차 실행
|
||||
$method->invoke($this->pluginManager, $plugin);
|
||||
$firstCount = Permission::where('extension_identifier', 'sirsoft-verification')->count();
|
||||
$firstGroupId = Permission::where('identifier', 'sirsoft-verification')->first()->id;
|
||||
$this->callProtectedMethod('createPluginPermissions', $plugin);
|
||||
$firstCount = Permission::where('extension_identifier', 'sirsoft-gdpr')->count();
|
||||
$firstGroupId = Permission::where('identifier', 'sirsoft-gdpr')->first()->id;
|
||||
|
||||
// 2차 실행 (업데이트 시뮬레이션)
|
||||
$method->invoke($this->pluginManager, $plugin);
|
||||
$secondCount = Permission::where('extension_identifier', 'sirsoft-verification')->count();
|
||||
$secondGroupId = Permission::where('identifier', 'sirsoft-verification')->first()->id;
|
||||
$this->callProtectedMethod('createPluginPermissions', $plugin);
|
||||
$secondCount = Permission::where('extension_identifier', 'sirsoft-gdpr')->count();
|
||||
$secondGroupId = Permission::where('identifier', 'sirsoft-gdpr')->first()->id;
|
||||
|
||||
$this->assertEquals($firstCount, $secondCount, '중복 생성 없이 동일 수');
|
||||
$this->assertEquals($firstGroupId, $secondGroupId, '그룹 노드 ID 유지');
|
||||
$this->assertEquals(7, $secondCount);
|
||||
$this->assertEquals(4, $secondCount);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -210,17 +200,13 @@ class PluginPermissionGroupTest extends TestCase
|
||||
*/
|
||||
public function test_remove_deletes_all_permission_levels(): void
|
||||
{
|
||||
$plugin = $this->pluginManager->getPlugin('sirsoft-verification');
|
||||
$plugin = $this->gdprPlugin();
|
||||
|
||||
$createMethod = new ReflectionMethod(PluginManager::class, 'createPluginPermissions');
|
||||
$createMethod->invoke($this->pluginManager, $plugin);
|
||||
$this->callProtectedMethod('createPluginPermissions', $plugin);
|
||||
$this->assertEquals(4, Permission::where('extension_identifier', 'sirsoft-gdpr')->count());
|
||||
|
||||
$this->assertEquals(7, Permission::where('extension_identifier', 'sirsoft-verification')->count());
|
||||
|
||||
$removeMethod = new ReflectionMethod(PluginManager::class, 'removePluginPermissions');
|
||||
$removeMethod->invoke($this->pluginManager, $plugin);
|
||||
|
||||
$this->assertEquals(0, Permission::where('extension_identifier', 'sirsoft-verification')->count());
|
||||
$this->callProtectedMethod('removePluginPermissions', $plugin);
|
||||
$this->assertEquals(0, Permission::where('extension_identifier', 'sirsoft-gdpr')->count());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -228,35 +214,32 @@ class PluginPermissionGroupTest extends TestCase
|
||||
*/
|
||||
public function test_assign_permissions_to_roles_with_categories(): void
|
||||
{
|
||||
$plugin = $this->pluginManager->getPlugin('sirsoft-verification');
|
||||
$plugin = $this->gdprPlugin();
|
||||
|
||||
// 플러그인 역할 생성
|
||||
Role::create([
|
||||
'identifier' => 'sirsoft-verification.manager',
|
||||
'name' => ['ko' => '본인인증 관리자', 'en' => 'Verification Manager'],
|
||||
'description' => ['ko' => '본인인증 관리', 'en' => 'Verification management'],
|
||||
'identifier' => 'sirsoft-gdpr.privacy',
|
||||
'name' => ['ko' => '개인정보 운영자', 'en' => 'Privacy Operator'],
|
||||
'description' => ['ko' => '개인정보 운영', 'en' => 'Privacy operation'],
|
||||
'extension_type' => ExtensionOwnerType::Plugin,
|
||||
'extension_identifier' => 'sirsoft-verification',
|
||||
'extension_identifier' => 'sirsoft-gdpr',
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
// 권한 생성
|
||||
$createMethod = new ReflectionMethod(PluginManager::class, 'createPluginPermissions');
|
||||
$createMethod->invoke($this->pluginManager, $plugin);
|
||||
$this->callProtectedMethod('createPluginPermissions', $plugin);
|
||||
|
||||
// 역할 할당
|
||||
$assignMethod = new ReflectionMethod(PluginManager::class, 'assignPermissionsToRoles');
|
||||
$assignMethod->invoke($this->pluginManager, $plugin);
|
||||
$this->callProtectedMethod('assignPermissionsToRoles', $plugin);
|
||||
|
||||
// admin 역할에 4개 리프 권한 할당 확인
|
||||
// admin 역할에 2개 리프 권한 할당 확인
|
||||
$adminRole = Role::where('identifier', 'admin')->first();
|
||||
$assignedPerms = $adminRole->permissions()->where('extension_identifier', 'sirsoft-verification')->get();
|
||||
$this->assertCount(4, $assignedPerms, 'admin 역할에 4개 리프 권한이 할당되어야 합니다');
|
||||
$assignedPerms = $adminRole->permissions()->where('extension_identifier', 'sirsoft-gdpr')->get();
|
||||
$this->assertCount(2, $assignedPerms, 'admin 역할에 2개 리프 권한이 할당되어야 합니다');
|
||||
|
||||
// 그룹/카테고리 노드는 역할에 할당되지 않음
|
||||
$assignedIdentifiers = $assignedPerms->pluck('identifier')->toArray();
|
||||
$this->assertNotContains('sirsoft-verification', $assignedIdentifiers);
|
||||
$this->assertNotContains('sirsoft-verification.settings', $assignedIdentifiers);
|
||||
$this->assertNotContains('sirsoft-verification.user', $assignedIdentifiers);
|
||||
$this->assertNotContains('sirsoft-gdpr', $assignedIdentifiers);
|
||||
$this->assertNotContains('sirsoft-gdpr.privacy', $assignedIdentifiers);
|
||||
}
|
||||
}
|
||||
@@ -110,7 +110,11 @@ class UpdateLayoutRequestTest extends TestCase
|
||||
public function test_passes_with_valid_data(): void
|
||||
{
|
||||
// Arrange
|
||||
$data = ['content' => $this->getValidContentData()];
|
||||
// 낙관적 잠금 인프라 도입으로 expected_lock_version 이 required 가 됨
|
||||
$data = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => $this->getValidContentData(),
|
||||
];
|
||||
$request = new UpdateLayoutContentRequest;
|
||||
|
||||
// Act
|
||||
@@ -181,14 +185,92 @@ class UpdateLayoutRequestTest extends TestCase
|
||||
}
|
||||
|
||||
/**
|
||||
* content.endpoint 누락 시 실패
|
||||
* content.endpoint 누락 시에도 통과 (standalone endpoint-less 레이아웃)
|
||||
*
|
||||
* 최상위 content.endpoint 는 데이터를 주로 fetch 하는 화면에서만 쓰는 레거시 필드로,
|
||||
* 로그인/대시보드/정적 페이지처럼 주 데이터 fetch 가 없는 standalone 레이아웃은
|
||||
* 정당하게 endpoint 가 없다(번들 admin 103 + basic 39 = 전 142 레이아웃이 endpoint 부재
|
||||
* 상태로 정상 렌더). 구조 SSoT(ValidLayoutStructure) 도 endpoint 를 필수로 요구하지 않는다.
|
||||
* 따라서 endpoint 미존재는 저장을 막아서는 안 된다.
|
||||
*/
|
||||
public function test_fails_without_endpoint(): void
|
||||
public function test_passes_without_endpoint_for_standalone_layout(): void
|
||||
{
|
||||
// Arrange
|
||||
// Arrange — getValidContentData 는 endpoint 를 포함하므로 제거하여 endpoint-less 재현
|
||||
$content = $this->getValidContentData();
|
||||
unset($content['endpoint']);
|
||||
$data = ['content' => $content];
|
||||
$data = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => $content,
|
||||
];
|
||||
$request = new UpdateLayoutContentRequest;
|
||||
|
||||
// Act
|
||||
$validator = Validator::make($data, $request->rules());
|
||||
|
||||
// Assert
|
||||
if ($validator->fails()) {
|
||||
dump($validator->errors()->toArray());
|
||||
}
|
||||
$this->assertFalse($validator->fails());
|
||||
$this->assertArrayNotHasKey('content.endpoint', $validator->errors()->toArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* 실 admin_login 구조(endpoint·extends·slots 모두 없음 + meta/init_actions)로 저장 통과
|
||||
*
|
||||
* 번들 로그인 레이아웃과 동일한 shape 으로, 편집기에서 컴포넌트만 추가해도
|
||||
* 저장이 막히지 않아야 한다.
|
||||
*/
|
||||
public function test_passes_with_real_login_layout_shape(): void
|
||||
{
|
||||
// Arrange — admin_login 과 동형: endpoint/extends/slots 없음
|
||||
$content = [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'admin_login',
|
||||
'meta' => [
|
||||
'title' => '$t:auth.login.title',
|
||||
'description' => '관리자 로그인 페이지',
|
||||
'auth_required' => false,
|
||||
],
|
||||
'data_sources' => [],
|
||||
'init_actions' => [],
|
||||
'components' => [
|
||||
[
|
||||
'id' => 'logo',
|
||||
'type' => 'basic',
|
||||
'name' => 'H1',
|
||||
'text' => '$t:auth.login.title',
|
||||
],
|
||||
],
|
||||
];
|
||||
$data = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => $content,
|
||||
];
|
||||
$request = new UpdateLayoutContentRequest;
|
||||
|
||||
// Act
|
||||
$validator = Validator::make($data, $request->rules());
|
||||
|
||||
// Assert
|
||||
if ($validator->fails()) {
|
||||
dump($validator->errors()->toArray());
|
||||
}
|
||||
$this->assertFalse($validator->fails());
|
||||
}
|
||||
|
||||
/**
|
||||
* endpoint 가 명시되면 여전히 검증된다 (whitelist/외부URL 차단 유지 — 회귀 가드)
|
||||
*/
|
||||
public function test_still_validates_endpoint_when_present(): void
|
||||
{
|
||||
// Arrange — 외부 URL 은 endpoint 가 없어도 통과시키는 변경과 무관하게 차단되어야 함
|
||||
$content = $this->getValidContentData();
|
||||
$content['endpoint'] = 'https://external.com/api';
|
||||
$data = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => $content,
|
||||
];
|
||||
$request = new UpdateLayoutContentRequest;
|
||||
|
||||
// Act
|
||||
@@ -298,4 +380,88 @@ class UpdateLayoutRequestTest extends TestCase
|
||||
$errors = $validator->errors();
|
||||
$this->assertStringContainsString('레이아웃 content', $errors->first('content'));
|
||||
}
|
||||
|
||||
/**
|
||||
* data_sources 의 label_key 와 임의 신규 필드가 validated 에서 보존된다.
|
||||
*
|
||||
* content.data_sources 는 bare 'array' 규칙(하위 키 미명시)이므로 Laravel validated()
|
||||
* 가 배열 전체를 그대로 통과시킨다. 따라서 6-c 편집기가 추가하는 label_key 및
|
||||
* endpoint/method/auth_mode/params/auto_fetch/loading_strategy/fallback 등 모든 필드가
|
||||
* 백엔드 별도 동기 없이 저장 경로로 보존되어야 한다.
|
||||
*
|
||||
* 시나리오 매니페스트: tests/scenarios/layout-editor-data-sources.yaml
|
||||
*
|
||||
* @effects validated_preserves_label_key_and_all_data_source_fields,
|
||||
* all_bundled_layouts_data_sources_have_label_key_zero_missing,
|
||||
* audit_data_source_label_key_coverage_blocks_future_omission
|
||||
*/
|
||||
public function test_validated_preserves_data_source_label_key_and_fields(): void
|
||||
{
|
||||
// Arrange
|
||||
$content = $this->getValidContentData();
|
||||
$content['data_sources'] = [
|
||||
[
|
||||
'id' => 'products',
|
||||
'label_key' => '$t:editor.data_source.products',
|
||||
'type' => 'api',
|
||||
'endpoint' => '/api/products',
|
||||
'method' => 'GET',
|
||||
'auth_mode' => 'optional',
|
||||
'loading_strategy' => 'progressive',
|
||||
'auto_fetch' => true,
|
||||
'params' => ['page' => '{{query.page ?? 1}}'],
|
||||
'fallback' => ['data' => []],
|
||||
],
|
||||
];
|
||||
$data = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => $content,
|
||||
];
|
||||
$request = new UpdateLayoutContentRequest;
|
||||
|
||||
// Act
|
||||
$validator = Validator::make($data, $request->rules());
|
||||
if ($validator->fails()) {
|
||||
dump($validator->errors()->toArray());
|
||||
}
|
||||
$validated = $validator->validated();
|
||||
|
||||
// Assert — data_sources 항목의 모든 필드가 보존됨
|
||||
$this->assertFalse($validator->fails());
|
||||
$ds = $validated['content']['data_sources'][0];
|
||||
$this->assertSame('products', $ds['id']);
|
||||
$this->assertSame('$t:editor.data_source.products', $ds['label_key']);
|
||||
$this->assertSame('/api/products', $ds['endpoint']);
|
||||
$this->assertSame('optional', $ds['auth_mode']);
|
||||
$this->assertSame('progressive', $ds['loading_strategy']);
|
||||
$this->assertTrue($ds['auto_fetch']);
|
||||
$this->assertSame(['page' => '{{query.page ?? 1}}'], $ds['params']);
|
||||
$this->assertSame(['data' => []], $ds['fallback']);
|
||||
}
|
||||
|
||||
/**
|
||||
* data_sources 에 id 누락 시 ValidDataSourceMerge 가 실패시킨다.
|
||||
*
|
||||
* @effects missing_id_rejected_by_valid_data_source_merge
|
||||
*/
|
||||
public function test_fails_when_data_source_missing_id(): void
|
||||
{
|
||||
// Arrange
|
||||
$content = $this->getValidContentData();
|
||||
$content['data_sources'] = [
|
||||
['label_key' => '$t:editor.data_source.noid', 'type' => 'api'],
|
||||
];
|
||||
$data = [
|
||||
'expected_lock_version' => 0,
|
||||
'content' => $content,
|
||||
];
|
||||
$request = new UpdateLayoutContentRequest;
|
||||
|
||||
// Act
|
||||
$validator = Validator::make($data, $request->rules());
|
||||
|
||||
// Assert
|
||||
$this->assertTrue($validator->fails());
|
||||
$this->assertArrayHasKey('content.data_sources', $validator->errors()->toArray());
|
||||
}
|
||||
}
|
||||
@@ -477,6 +477,54 @@ class ValidLayoutStructureTest extends TestCase
|
||||
$this->assertTrue($failed, 'Expected invalid child component (missing type) to be blocked');
|
||||
}
|
||||
|
||||
/**
|
||||
* extension_point 타입 노드를 포함한 레이아웃 허용.
|
||||
*
|
||||
* `_user_base` 등 호스트 레이아웃은 확장 주입 지점을 `type:"extension_point"` 노드로
|
||||
* 선언한다(예: `user_global_overlay`, `identity_provider_ui:provider`). 종전엔 type
|
||||
* allow-list 가 basic/composite/layout 뿐이라 extension_point 를 거부 → extension_point 를
|
||||
* 포함한 레이아웃(또는 그 레이아웃의 모달)을 편집기에서 저장 시 422
|
||||
* (`components[N].children[0].type은 basic, composite, layout 중 하나여야 합니다`).
|
||||
* extension_point 는 정상 노드 타입이므로 허용해야 한다.
|
||||
*/
|
||||
public function test_allows_extension_point_type_node(): void
|
||||
{
|
||||
$layout = [
|
||||
'version' => '1.0',
|
||||
'layout_name' => '_user_base',
|
||||
'components' => [
|
||||
[
|
||||
'id' => 'user_layout_root',
|
||||
'type' => 'basic',
|
||||
'name' => 'Div',
|
||||
'props' => ['className' => 'min-h-screen'],
|
||||
'children' => [
|
||||
[
|
||||
// 확장 주입 지점 — type="extension_point" + name(슬롯명) + default/children.
|
||||
'id' => 'user_global_overlay_slot',
|
||||
'type' => 'extension_point',
|
||||
'name' => 'user_global_overlay',
|
||||
'default' => [],
|
||||
'children' => [],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$failed = false;
|
||||
$failMessage = null;
|
||||
$this->rule->validate('layout', $layout, function ($msg) use (&$failed, &$failMessage) {
|
||||
$failed = true;
|
||||
$failMessage = $msg;
|
||||
});
|
||||
|
||||
$this->assertFalse(
|
||||
$failed,
|
||||
'extension_point 타입 노드를 포함한 레이아웃은 허용돼야 한다: '.((string) $failMessage)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* actions 필드 검증 테스트
|
||||
*/
|
||||
|
||||
@@ -74,6 +74,55 @@ class WhitelistedEndpointTest extends TestCase
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈/플러그인 API 프리픽스 허용 테스트
|
||||
*
|
||||
* ModuleRouteServiceProvider/PluginRouteServiceProvider 가 등록하는
|
||||
* /api/(modules|plugins)/{vendor-id}/ 프리픽스는 코어 정식 라우트 네임스페이스다
|
||||
*
|
||||
*/
|
||||
public function test_allows_module_and_plugin_api_endpoints(): void
|
||||
{
|
||||
$validEndpoints = [
|
||||
'/api/modules/sirsoft-board/posts',
|
||||
'/api/modules/sirsoft-ecommerce/checkout',
|
||||
'/api/modules/gnuboard7-hello_module/memos',
|
||||
'/api/plugins/sirsoft-payment/methods',
|
||||
'/api/modules/sirsoft-board/users/1/posts/stats?page=1',
|
||||
];
|
||||
|
||||
foreach ($validEndpoints as $endpoint) {
|
||||
$failed = false;
|
||||
$this->rule->validate('endpoint', $endpoint, function () use (&$failed) {
|
||||
$failed = true;
|
||||
});
|
||||
|
||||
$this->assertFalse($failed, "Expected endpoint '{$endpoint}' to be allowed");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 식별자(vendor-name) 형식이 아닌 modules/plugins 세그먼트 차단 테스트
|
||||
*/
|
||||
public function test_blocks_non_extension_module_segments(): void
|
||||
{
|
||||
$invalidEndpoints = [
|
||||
'/api/modules/assets/sirsoft-board/app.js', // 에셋 서빙 경로 — data source 대상 아님
|
||||
'/api/modules/internal/secret', // 하이픈 없는 세그먼트
|
||||
'/api/modules/', // 식별자 없음
|
||||
'/api/plugins/system/config',
|
||||
];
|
||||
|
||||
foreach ($invalidEndpoints as $endpoint) {
|
||||
$failed = false;
|
||||
$this->rule->validate('endpoint', $endpoint, function () use (&$failed) {
|
||||
$failed = true;
|
||||
});
|
||||
|
||||
$this->assertTrue($failed, "Expected endpoint '{$endpoint}' to be blocked");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 허용되지 않은 API 엔드포인트 차단 테스트
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Seo;
|
||||
|
||||
use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
use App\Seo\Editor\SeoOgPreviewService;
|
||||
use App\Seo\SeoMetaResolver;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* SeoOgPreviewService base 상속 출처 구분 테스트.
|
||||
*
|
||||
* og/twitter 미리보기는 병합본(base+자식) meta.seo 를 받아 키별 출처를 계산한다. 종전엔
|
||||
* 병합본에 있는 키를 모두 source='layout'(자체 override) 으로 봐서, base 상속분과 자식이
|
||||
* 직접 입력한 값이 구분되지 않았다(검색엔진 탭에 "상속됨" 출처가 원천적으로 안 뜸).
|
||||
*
|
||||
* 본 테스트는 own_seo(자식 직접 선언분, base 병합 전)를 함께 넘기면 병합본에만 있는 키가
|
||||
* source='inherited' / inheritedFromBase=true 로 분류되는지, 자식이 직접 채운 키는 여전히
|
||||
* source='layout' 인지, 자식이 빈 값으로 비우면 다시 상속/코어로 돌아가는지를 검증한다.
|
||||
*/
|
||||
class SeoOgPreviewServiceInheritanceTest extends TestCase
|
||||
{
|
||||
private function service(): SeoOgPreviewService
|
||||
{
|
||||
// 모듈/플러그인 declaration 은 본 테스트 범위 밖 — 빈 매니저로 격리(코어/상속/자체만 검증).
|
||||
$moduleManager = $this->createMock(ModuleManagerInterface::class);
|
||||
$moduleManager->method('getModule')->willReturn(null);
|
||||
$pluginManager = $this->createMock(PluginManagerInterface::class);
|
||||
$pluginManager->method('getPlugin')->willReturn(null);
|
||||
|
||||
return new SeoOgPreviewService(
|
||||
app(SeoMetaResolver::class),
|
||||
$moduleManager,
|
||||
$pluginManager,
|
||||
);
|
||||
}
|
||||
|
||||
/** og 배열에서 특정 key 행을 찾는다. */
|
||||
private function ogRow(array $preview, string $key): ?array
|
||||
{
|
||||
foreach ($preview['og'] as $row) {
|
||||
if ($row['key'] === $key) {
|
||||
return $row;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function test_병합본에만_있고_own_에_없는_og_키는_상속_출처로_분류된다(): void
|
||||
{
|
||||
// 병합본 = base(type=website) + 자식(자체 og 없음). own = 자식 직접 선언분(og 비움).
|
||||
$merged = ['og' => ['type' => 'website']];
|
||||
$own = ['og' => []]; // 자식은 og.type 을 직접 선언하지 않음 → 상속.
|
||||
|
||||
$preview = $this->service()->preview($merged, [], [], $own);
|
||||
|
||||
$typeRow = $this->ogRow($preview, 'type');
|
||||
$this->assertNotNull($typeRow);
|
||||
$this->assertSame('inherited', $typeRow['source'], 'base 상속 키는 source=inherited');
|
||||
$this->assertTrue($typeRow['inheritedFromBase']);
|
||||
$this->assertFalse($typeRow['overriddenByLayout'], '상속은 자체 override 아님');
|
||||
}
|
||||
|
||||
public function test_자식이_직접_채운_og_키는_layout_출처로_분류된다(): void
|
||||
{
|
||||
// 병합본 = 자식이 type=product 로 덮음. own 에도 동일하게 존재 → 자체 override.
|
||||
$merged = ['og' => ['type' => 'product']];
|
||||
$own = ['og' => ['type' => 'product']];
|
||||
|
||||
$preview = $this->service()->preview($merged, [], [], $own);
|
||||
|
||||
$typeRow = $this->ogRow($preview, 'type');
|
||||
$this->assertNotNull($typeRow);
|
||||
$this->assertSame('layout', $typeRow['source'], '자식 직접 입력은 source=layout');
|
||||
$this->assertFalse($typeRow['inheritedFromBase']);
|
||||
$this->assertTrue($typeRow['overriddenByLayout']);
|
||||
}
|
||||
|
||||
public function test_own_미전달이면_상속_구분_없이_종전대로_layout(): void
|
||||
{
|
||||
// own_seo 미전달(null) → 상속/자체 구분 안 함(하위호환).
|
||||
$merged = ['og' => ['type' => 'website']];
|
||||
|
||||
$preview = $this->service()->preview($merged, [], []);
|
||||
|
||||
$typeRow = $this->ogRow($preview, 'type');
|
||||
$this->assertNotNull($typeRow);
|
||||
$this->assertSame('layout', $typeRow['source']);
|
||||
$this->assertFalse($typeRow['inheritedFromBase']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Seo;
|
||||
|
||||
use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
use App\Extension\AbstractModule;
|
||||
use App\Seo\Editor\SeoOgPreviewService;
|
||||
use App\Seo\SeoMetaResolver;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* SeoOgPreviewService 모듈 자동값 → 연결 칩 메타 동반 테스트.
|
||||
*
|
||||
* 모듈 seoOgDefaults()/seoStructuredData() 는 resolve 된 평문을 반환하므로 데이터 경로가 소실된다.
|
||||
* 편집기가 자동값을 "상품 이름" 연결 칩으로 보여주려면 키별 데이터 경로(expr)+라벨이 필요하다.
|
||||
* 본 테스트는 미리보기 응답이:
|
||||
* - 출처가 module 인 og 행에 seoOgDefaultMeta() 의 sourceExpr/label 을 (현재 로케일로 해석해) 동반하는지
|
||||
* - structured autoMeta 가 점 경로 키별 expr/label 을 동반하는지
|
||||
* - 메타 미선언(평문 폴백) 시 sourceExpr/label 미동반(하위호환)인지
|
||||
* - 레이아웃이 직접 override 한 키엔 메타 미동반인지
|
||||
* 를 격리된 fake 모듈로 검증한다.
|
||||
*/
|
||||
class SeoOgPreviewServiceModuleMetaTest extends TestCase
|
||||
{
|
||||
/** seoOgDefaults(평문) + seoOgDefaultMeta(expr/label) 를 동시에 제공하는 fake 모듈을 만든다. */
|
||||
private function fakeModule(): AbstractModule
|
||||
{
|
||||
return new class extends AbstractModule
|
||||
{
|
||||
public function seoOgDefaults(string $pageType, array $context, array $routeParams = []): array
|
||||
{
|
||||
return ['image' => 'https://cdn/p.jpg', 'image_alt' => '베이직 오버핏 티셔츠'];
|
||||
}
|
||||
|
||||
public function seoOgDefaultMeta(string $pageType): array
|
||||
{
|
||||
return [
|
||||
'image' => ['expr' => '{{product.data.thumbnail_url}}', 'label' => ['ko' => '상품 대표 이미지', 'en' => 'Product image']],
|
||||
'image_alt' => ['expr' => '{{product.data.name}}', 'label' => ['ko' => '상품 이름', 'en' => 'Product name']],
|
||||
];
|
||||
}
|
||||
|
||||
public function seoTwitterDefaults(string $pageType, array $context, array $routeParams = []): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function seoTwitterDefaultMeta(string $pageType): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function seoStructuredData(string $pageType, array $context, array $routeParams = []): array
|
||||
{
|
||||
return ['@type' => 'Product', 'name' => '베이직 오버핏 티셔츠', 'offers' => ['price' => '23200']];
|
||||
}
|
||||
|
||||
public function seoStructuredDataMeta(string $pageType): array
|
||||
{
|
||||
return [
|
||||
'name' => ['expr' => '{{product.data.name}}', 'label' => ['ko' => '상품 이름', 'en' => 'Product name']],
|
||||
'offers.price' => ['expr' => '{{product.data.selling_price}}', 'label' => ['ko' => '판매가', 'en' => 'Selling price']],
|
||||
];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private function service(?AbstractModule $module): SeoOgPreviewService
|
||||
{
|
||||
$moduleManager = $this->createMock(ModuleManagerInterface::class);
|
||||
$moduleManager->method('getModule')->willReturn($module);
|
||||
$pluginManager = $this->createMock(PluginManagerInterface::class);
|
||||
$pluginManager->method('getPlugin')->willReturn(null);
|
||||
|
||||
return new SeoOgPreviewService(
|
||||
app(SeoMetaResolver::class),
|
||||
$moduleManager,
|
||||
$pluginManager,
|
||||
);
|
||||
}
|
||||
|
||||
/** og 배열에서 특정 key 행을 찾는다. */
|
||||
private function ogRow(array $preview, string $key): ?array
|
||||
{
|
||||
foreach ($preview['og'] as $row) {
|
||||
if ($row['key'] === $key) {
|
||||
return $row;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 자동값 cascade 가 일어나도록 extensions ∧ page_type 충족 + 레이아웃 og 비움. */
|
||||
private function seoConfig(array $overrides = []): array
|
||||
{
|
||||
return array_merge([
|
||||
'page_type' => 'product',
|
||||
'extensions' => [['type' => 'module', 'id' => 'sirsoft-ecommerce']],
|
||||
], $overrides);
|
||||
}
|
||||
|
||||
public function test_모듈_출처_og_행에_sourceExpr_와_라벨이_동반된다(): void
|
||||
{
|
||||
app()->setLocale('ko');
|
||||
$preview = $this->service($this->fakeModule())->preview($this->seoConfig(), [], []);
|
||||
|
||||
$imageRow = $this->ogRow($preview, 'image');
|
||||
$this->assertNotNull($imageRow);
|
||||
$this->assertStringStartsWith('module:', $imageRow['source']);
|
||||
$this->assertSame('{{product.data.thumbnail_url}}', $imageRow['sourceExpr']);
|
||||
$this->assertSame('상품 대표 이미지', $imageRow['label'], '라벨은 현재 로케일(ko)로 해석');
|
||||
|
||||
$altRow = $this->ogRow($preview, 'image_alt');
|
||||
$this->assertSame('{{product.data.name}}', $altRow['sourceExpr']);
|
||||
$this->assertSame('상품 이름', $altRow['label']);
|
||||
}
|
||||
|
||||
public function test_라벨은_요청_로케일로_해석된다(): void
|
||||
{
|
||||
app()->setLocale('en');
|
||||
$preview = $this->service($this->fakeModule())->preview($this->seoConfig(), [], [], null, 'en');
|
||||
|
||||
$imageRow = $this->ogRow($preview, 'image');
|
||||
$this->assertSame('Product image', $imageRow['label']);
|
||||
}
|
||||
|
||||
/** label 이 번역 키 문자열이면 __() 로 해석된다 — 언어팩 대응(추가 언어 자동). */
|
||||
private function translationKeyLabelModule(): AbstractModule
|
||||
{
|
||||
return new class extends AbstractModule
|
||||
{
|
||||
public function seoOgDefaults(string $pageType, array $context, array $routeParams = []): array
|
||||
{
|
||||
return ['image' => 'https://cdn/p.jpg'];
|
||||
}
|
||||
|
||||
public function seoOgDefaultMeta(string $pageType): array
|
||||
{
|
||||
// 인라인 ko/en 맵이 아니라 **번역 키 문자열** — 언어팩(ja 등)이 그 키를 번역하면 자동 대응.
|
||||
return ['image' => ['expr' => '{{product.data.thumbnail_url}}', 'label' => 'demo-pkg::seo.product_image']];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public function test_label_번역키_문자열은_언어팩으로_해석된다(): void
|
||||
{
|
||||
// 언어팩이 키를 번역한 상태를 모사 — 번역기에 키 등록(ja 로케일).
|
||||
app('translator')->addLines(['seo.product_image' => '商品画像'], 'ja', 'demo-pkg');
|
||||
app()->setLocale('ja');
|
||||
|
||||
$preview = $this->service($this->translationKeyLabelModule())->preview($this->seoConfig(), [], [], null, 'ja');
|
||||
|
||||
$imageRow = $this->ogRow($preview, 'image');
|
||||
// 번역 키가 그대로 노출되면(=__() 미해석) 실패. 언어팩 번역값으로 해석돼야 통과.
|
||||
$this->assertSame('商品画像', $imageRow['label'], 'label 번역 키는 __() 로 해석돼 언어팩에 대응해야 한다');
|
||||
}
|
||||
|
||||
public function test_label_번역키_미등록_로케일은_다른_언어로_폴백되지_원문키_노출_안함(): void
|
||||
{
|
||||
// ko/en 만 등록된 키를 미등록 로케일(ja)로 요청 — 번역기 폴백(기본 로케일)로 사람이 읽을
|
||||
// 문자열이 나오되, raw 키(demo-pkg::seo.x)가 그대로 노출되지는 않아야 한다.
|
||||
app('translator')->addLines(['seo.product_image' => '상품 이미지'], 'ko', 'demo-pkg');
|
||||
app('translator')->addLines(['seo.product_image' => 'Product image'], 'en', 'demo-pkg');
|
||||
|
||||
$preview = $this->service($this->translationKeyLabelModule())->preview($this->seoConfig(), [], [], null, 'ja');
|
||||
|
||||
$imageRow = $this->ogRow($preview, 'image');
|
||||
$this->assertStringNotContainsString('demo-pkg::', $imageRow['label'], 'raw 번역 키가 노출되면 안 된다');
|
||||
}
|
||||
|
||||
public function test_레이아웃이_직접_채운_키엔_메타_미동반(): void
|
||||
{
|
||||
// 레이아웃이 og.image 를 직접 입력 → 출처 layout → 연결 칩 메타 미동반(자기 값이므로).
|
||||
$config = $this->seoConfig(['og' => ['image' => '{{custom.path}}']]);
|
||||
$preview = $this->service($this->fakeModule())->preview($config, [], []);
|
||||
|
||||
$imageRow = $this->ogRow($preview, 'image');
|
||||
$this->assertSame('layout', $imageRow['source']);
|
||||
$this->assertArrayNotHasKey('sourceExpr', $imageRow);
|
||||
$this->assertArrayNotHasKey('label', $imageRow);
|
||||
}
|
||||
|
||||
public function test_메타_미선언_모듈은_평문_폴백_메타_미동반(): void
|
||||
{
|
||||
// seoOgDefaultMeta 가 빈 배열(부모 기본)인 모듈 → effectiveValue(평문)만, 연결 칩 메타 없음(하위호환).
|
||||
$plain = new class extends AbstractModule
|
||||
{
|
||||
public function seoOgDefaults(string $pageType, array $context, array $routeParams = []): array
|
||||
{
|
||||
return ['image' => 'https://cdn/p.jpg'];
|
||||
}
|
||||
};
|
||||
$preview = $this->service($plain)->preview($this->seoConfig(), [], []);
|
||||
|
||||
$imageRow = $this->ogRow($preview, 'image');
|
||||
$this->assertNotNull($imageRow);
|
||||
$this->assertStringStartsWith('module:', $imageRow['source']);
|
||||
$this->assertSame('https://cdn/p.jpg', $imageRow['effectiveValue'], '평문 폴백 유지');
|
||||
$this->assertArrayNotHasKey('sourceExpr', $imageRow);
|
||||
}
|
||||
|
||||
public function test_structured_autoMeta_가_점경로_키별_데이터경로를_동반한다(): void
|
||||
{
|
||||
app()->setLocale('ko');
|
||||
$preview = $this->service($this->fakeModule())->preview($this->seoConfig(), [], []);
|
||||
|
||||
$autoMeta = $preview['structured']['autoMeta'];
|
||||
$this->assertArrayHasKey('name', $autoMeta);
|
||||
$this->assertSame('{{product.data.name}}', $autoMeta['name']['expr']);
|
||||
$this->assertSame('상품 이름', $autoMeta['name']['label']);
|
||||
$this->assertArrayHasKey('offers.price', $autoMeta);
|
||||
$this->assertSame('{{product.data.selling_price}}', $autoMeta['offers.price']['expr']);
|
||||
// 자동 블록 자체는 종전대로 평문(하위호환).
|
||||
$this->assertSame('베이직 오버핏 티셔츠', $preview['structured']['autoBlock']['name']);
|
||||
}
|
||||
|
||||
public function test_레이아웃_구조화_선언이_있으면_autoMeta_는_여전히_모듈_기준(): void
|
||||
{
|
||||
// 레이아웃이 structured_data 를 통 override 해도 autoBlock/autoMeta(모듈 자동)는 OFF 미리보기용으로 유지.
|
||||
$config = $this->seoConfig(['structured_data' => ['@type' => 'WebPage']]);
|
||||
$preview = $this->service($this->fakeModule())->preview($config, [], []);
|
||||
|
||||
$this->assertTrue($preview['structured']['hasLayoutBlock']);
|
||||
$this->assertArrayHasKey('name', $preview['structured']['autoMeta']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Seo;
|
||||
|
||||
use Illuminate\Support\Facades\View;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* seo-preview.blade.php 테스트.
|
||||
*
|
||||
* 봇 미리보기는 검색엔진 탭·레이아웃·모듈/코어 SEO 설정이 산출한 데이터만 보여준다.
|
||||
* 본 블레이드는 그 산출물(title/description/keywords/canonical/hreflang/og/twitter/JSON-LD/
|
||||
* 소유권 확인 메타)만 렌더하고, SEO 설정 산출물이 아닌 것(body 컴포넌트 마크업·CSS·charset/
|
||||
* viewport/generator 시스템 메타·Google Analytics 추적 스크립트)은 포함하지 않는다.
|
||||
*/
|
||||
class SeoPreviewBladeTest extends TestCase
|
||||
{
|
||||
/** 운영 seo.blade.php / seo-preview.blade.php 가 공유하는 $viewData 형태(대표 값) */
|
||||
private function viewData(array $overrides = []): array
|
||||
{
|
||||
return array_merge([
|
||||
'locale' => 'ko',
|
||||
'title' => '베이직 오버핏 코튼 티셔츠',
|
||||
'titleSuffix' => ' | 코지홈',
|
||||
'description' => '사계절 입기 좋은 오버핏 기본 티셔츠',
|
||||
'keywords' => '티셔츠,오버핏',
|
||||
'canonicalUrl' => 'https://example.com/shop/products/1',
|
||||
'hreflangTags' => '<link rel="alternate" hreflang="en" href="https://example.com/shop/products/1?locale=en">',
|
||||
'ogTags' => '<meta property="og:type" content="product"><meta property="og:title" content="베이직 오버핏 코튼 티셔츠">',
|
||||
'twitterTags' => '<meta name="twitter:card" content="summary_large_image">',
|
||||
'jsonLd' => '{"@type":"Product","name":"베이직 오버핏 코튼 티셔츠"}',
|
||||
'bodyHtml' => '<div class="app-chrome"><button>장바구니</button><nav><a href="/login">로그인</a></nav></div>',
|
||||
'googleAnalyticsId' => 'G-XXXX',
|
||||
'googleVerification' => 'gverify123',
|
||||
'naverVerification' => 'nverify456',
|
||||
'cssPath' => '/build/assets/app.css',
|
||||
'stylesheets' => ['/api/templates/assets/sirsoft-basic/css/components.css', 'https://cdnjs.cloudflare.com/font-awesome.css'],
|
||||
'extraHeadTags' => '',
|
||||
'extraBodyEnd' => '',
|
||||
'generatorTag' => '<meta name="generator" content="GnuBoard7">',
|
||||
], $overrides);
|
||||
}
|
||||
|
||||
private function renderPreview(array $overrides = []): string
|
||||
{
|
||||
return View::make('seo-preview', $this->viewData($overrides))->render();
|
||||
}
|
||||
|
||||
public function test_seo_설정_산출물은_포함된다(): void
|
||||
{
|
||||
$out = $this->renderPreview();
|
||||
|
||||
$this->assertStringContainsString('<title>베이직 오버핏 코튼 티셔츠 | 코지홈</title>', $out);
|
||||
$this->assertStringContainsString('name="description"', $out);
|
||||
$this->assertStringContainsString('name="keywords"', $out);
|
||||
$this->assertStringContainsString('rel="canonical"', $out);
|
||||
$this->assertStringContainsString('hreflang="en"', $out);
|
||||
$this->assertStringContainsString('property="og:title"', $out);
|
||||
$this->assertStringContainsString('name="twitter:card"', $out);
|
||||
$this->assertStringContainsString('application/ld+json', $out);
|
||||
$this->assertStringContainsString('"@type":"Product"', $out);
|
||||
// 사이트 소유권 확인 메타 = 검색엔진 SEO 설정 산출물.
|
||||
$this->assertStringContainsString('google-site-verification', $out);
|
||||
$this->assertStringContainsString('naver-site-verification', $out);
|
||||
}
|
||||
|
||||
public function test_seo_설정_산출물이_아닌_것은_제외된다(): void
|
||||
{
|
||||
$out = $this->renderPreview();
|
||||
|
||||
// body 컴포넌트 마크업 — 페이지 본문(검색엔진 탭과 무관).
|
||||
$this->assertStringNotContainsString('app-chrome', $out);
|
||||
$this->assertStringNotContainsString('장바구니', $out);
|
||||
$this->assertStringNotContainsString('<button', $out);
|
||||
// CSS 에셋.
|
||||
$this->assertStringNotContainsString('app.css', $out);
|
||||
$this->assertStringNotContainsString('components.css', $out);
|
||||
$this->assertStringNotContainsString('font-awesome', $out);
|
||||
// 시스템 기본 메타(charset/viewport/generator).
|
||||
$this->assertStringNotContainsString('charset', $out);
|
||||
$this->assertStringNotContainsString('viewport', $out);
|
||||
$this->assertStringNotContainsString('generator', $out);
|
||||
// Google Analytics 추적 스크립트(검색 노출 산출물 아님).
|
||||
$this->assertStringNotContainsString('googletagmanager', $out);
|
||||
// body 영역 자체 미포함.
|
||||
$this->assertStringNotContainsString('<body', $out);
|
||||
}
|
||||
|
||||
public function test_keywords_없으면_keywords_메타_미출력(): void
|
||||
{
|
||||
$out = $this->renderPreview(['keywords' => '']);
|
||||
$this->assertStringNotContainsString('name="keywords"', $out);
|
||||
}
|
||||
|
||||
public function test_json_ld_없으면_구조화_스크립트_미출력(): void
|
||||
{
|
||||
$out = $this->renderPreview(['jsonLd' => '']);
|
||||
$this->assertStringNotContainsString('application/ld+json', $out);
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,16 @@ class LayoutExtensionIntegrationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 같은 스위트의 레이아웃/GDPR 미들웨어 의존 테스트와 migrate:fresh 정합성을
|
||||
* 맞추기 위해 GDPR 플러그인 마이그레이션을 일관 선언한다.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
private LayoutExtensionService $service;
|
||||
|
||||
private LayoutExtensionRepositoryInterface $repository;
|
||||
@@ -918,6 +928,199 @@ class LayoutExtensionIntegrationTest extends TestCase
|
||||
$this->assertContains('ov_modal', $modalIds);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// extends 체인 base-타겟 overlay 전파 (E1 ~ E4)
|
||||
//
|
||||
// 배경: home(extends _user_base) 같은 자식 레이아웃을 서빙할 때, base(_user_base)
|
||||
// 를 target_layout 으로 하는 overlay(예: 헤더 통화 슬롯 주입)가 적용되지 않던 결함.
|
||||
// applyExtensions 가 $layout['layout_name'](="home") 으로만 overlay 를 매칭했기 때문.
|
||||
// loadAndMergeLayout 가 부여하는 $layout['__extends_chain'] 을 매칭 대상에 포함시켜 해소.
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* E1: base(_user_base) 를 타겟한 overlay 가 자식(home) 서빙 시 적용된다
|
||||
*/
|
||||
public function test_base_targeted_overlay_applies_to_child_via_extends_chain(): void
|
||||
{
|
||||
$this->mockActiveExtensions(['sirsoft-ecommerce'], []);
|
||||
|
||||
// base 레이아웃(_user_base)을 타겟하는 overlay — 헤더 통화 슬롯 주입과 동형
|
||||
$this->service->registerExtension(
|
||||
[
|
||||
'target_layout' => '_user_base',
|
||||
'injections' => [
|
||||
[
|
||||
'target_id' => 'header_currency_inject_anchor',
|
||||
'position' => 'append_child',
|
||||
'components' => [
|
||||
['id' => 'ext_header_currency_selector', 'type' => 'basic', 'name' => 'Div', 'slot' => 'header_currency'],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
LayoutSourceType::Module,
|
||||
'sirsoft-ecommerce',
|
||||
$this->template->id
|
||||
);
|
||||
|
||||
// 자식(home) 서빙 시 loadAndMergeLayout 가 부여한 __extends_chain 을 가진 병합 결과
|
||||
$layout = [
|
||||
'layout_name' => 'home',
|
||||
'__extends_chain' => ['_user_base'],
|
||||
'components' => [
|
||||
[
|
||||
'id' => 'header_currency_inject_anchor',
|
||||
'type' => 'basic',
|
||||
'name' => 'Div',
|
||||
'children' => [],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$result = $this->service->applyExtensions($layout, $this->template->id);
|
||||
|
||||
// base-타겟 overlay 가 자식 서빙 결과에 주입됨
|
||||
$anchorChildren = $result['components'][0]['children'] ?? [];
|
||||
$this->assertCount(1, $anchorChildren, 'base(_user_base) overlay 가 자식(home)에 전파되어야 한다');
|
||||
$this->assertEquals('ext_header_currency_selector', $anchorChildren[0]['id']);
|
||||
$this->assertEquals('header_currency', $anchorChildren[0]['slot']);
|
||||
|
||||
// 내부 메타(__extends_chain)는 최종 응답에서 제거되어야 한다 (일반/편집 응답 노출 0)
|
||||
$this->assertArrayNotHasKey('__extends_chain', $result, '__extends_chain 은 응답에서 제거되어야 한다');
|
||||
}
|
||||
|
||||
/**
|
||||
* E2: base overlay 의 init_actions 가 자식 서빙 시 호스트 init_actions 뒤에 병합된다
|
||||
*/
|
||||
public function test_base_overlay_init_actions_merge_into_child_via_extends_chain(): void
|
||||
{
|
||||
$this->mockActiveExtensions(['sirsoft-ecommerce'], []);
|
||||
|
||||
$this->service->registerExtension(
|
||||
[
|
||||
'target_layout' => '_user_base',
|
||||
'injections' => [
|
||||
[
|
||||
'target_id' => 'header_currency_inject_anchor',
|
||||
'position' => 'append_child',
|
||||
'components' => [
|
||||
['id' => 'ext_currency', 'type' => 'basic', 'name' => 'Div'],
|
||||
],
|
||||
],
|
||||
],
|
||||
'init_actions' => [
|
||||
['handler' => 'sirsoft-ecommerce.initPreferredCurrency'],
|
||||
],
|
||||
],
|
||||
LayoutSourceType::Module,
|
||||
'sirsoft-ecommerce',
|
||||
$this->template->id
|
||||
);
|
||||
|
||||
$layout = [
|
||||
'layout_name' => 'home',
|
||||
'__extends_chain' => ['_user_base'],
|
||||
'init_actions' => [
|
||||
['handler' => 'hostInit'],
|
||||
],
|
||||
'components' => [
|
||||
['id' => 'header_currency_inject_anchor', 'type' => 'basic', 'name' => 'Div', 'children' => []],
|
||||
],
|
||||
];
|
||||
|
||||
$result = $this->service->applyExtensions($layout, $this->template->id);
|
||||
|
||||
$handlers = array_column($result['init_actions'] ?? [], 'handler');
|
||||
$this->assertSame(['hostInit', 'sirsoft-ecommerce.initPreferredCurrency'], $handlers, '호스트 init_actions 뒤에 확장 init_actions 가 병합되어야 한다');
|
||||
}
|
||||
|
||||
/**
|
||||
* E3: 다단계 extends 체인 — 자식의 자식까지 base overlay 전파
|
||||
*/
|
||||
public function test_base_overlay_propagates_through_multi_level_extends_chain(): void
|
||||
{
|
||||
$this->mockActiveExtensions(['sirsoft-ecommerce'], []);
|
||||
|
||||
$this->service->registerExtension(
|
||||
[
|
||||
'target_layout' => '_user_base',
|
||||
'injections' => [
|
||||
[
|
||||
'target_id' => 'anchor',
|
||||
'position' => 'append_child',
|
||||
'components' => [['id' => 'ext_node', 'type' => 'basic', 'name' => 'Div']],
|
||||
],
|
||||
],
|
||||
],
|
||||
LayoutSourceType::Module,
|
||||
'sirsoft-ecommerce',
|
||||
$this->template->id
|
||||
);
|
||||
|
||||
// shop_detail extends shop_base extends _user_base
|
||||
$layout = [
|
||||
'layout_name' => 'shop_detail',
|
||||
'__extends_chain' => ['shop_base', '_user_base'],
|
||||
'components' => [
|
||||
['id' => 'anchor', 'type' => 'basic', 'name' => 'Div', 'children' => []],
|
||||
],
|
||||
];
|
||||
|
||||
$result = $this->service->applyExtensions($layout, $this->template->id);
|
||||
|
||||
$children = $result['components'][0]['children'] ?? [];
|
||||
$this->assertCount(1, $children, '다단계 체인 끝의 base overlay 도 전파되어야 한다');
|
||||
$this->assertEquals('ext_node', $children[0]['id']);
|
||||
}
|
||||
|
||||
/**
|
||||
* E4: 자식 자신을 타겟한 overlay 와 base 타겟 overlay 가 한 번씩만 적용된다(중복 방지)
|
||||
*/
|
||||
public function test_child_and_base_overlays_apply_once_each_without_duplication(): void
|
||||
{
|
||||
$this->mockActiveExtensions(['sirsoft-ecommerce'], []);
|
||||
|
||||
// base(_user_base) 타겟 overlay
|
||||
$this->service->registerExtension(
|
||||
[
|
||||
'target_layout' => '_user_base',
|
||||
'injections' => [
|
||||
['target_id' => 'anchor', 'position' => 'append_child', 'components' => [['id' => 'base_node', 'type' => 'basic', 'name' => 'Div']]],
|
||||
],
|
||||
],
|
||||
LayoutSourceType::Module,
|
||||
'sirsoft-ecommerce',
|
||||
$this->template->id
|
||||
);
|
||||
|
||||
// 자식(home) 자신을 타겟한 overlay
|
||||
$this->service->registerExtension(
|
||||
[
|
||||
'target_layout' => 'home',
|
||||
'injections' => [
|
||||
['target_id' => 'anchor', 'position' => 'append_child', 'components' => [['id' => 'child_node', 'type' => 'basic', 'name' => 'Div']]],
|
||||
],
|
||||
],
|
||||
LayoutSourceType::Module,
|
||||
'sirsoft-ecommerce',
|
||||
$this->template->id
|
||||
);
|
||||
|
||||
$layout = [
|
||||
'layout_name' => 'home',
|
||||
'__extends_chain' => ['_user_base'],
|
||||
'components' => [
|
||||
['id' => 'anchor', 'type' => 'basic', 'name' => 'Div', 'children' => []],
|
||||
],
|
||||
];
|
||||
|
||||
$result = $this->service->applyExtensions($layout, $this->template->id);
|
||||
|
||||
$childIds = array_column($result['components'][0]['children'] ?? [], 'id');
|
||||
sort($childIds);
|
||||
$this->assertEquals(['base_node', 'child_node'], $childIds, '자식·base overlay 가 각각 한 번씩만 적용되어야 한다(중복 없음)');
|
||||
}
|
||||
|
||||
/**
|
||||
* C-7: inject_props + overlay state/computed 종합 시나리오
|
||||
*/
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace Tests\Feature\Services;
|
||||
use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
use App\Contracts\Extension\TemplateManagerInterface;
|
||||
use App\Contracts\Repositories\LayoutVersionRepositoryInterface;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Models\Template;
|
||||
use App\Repositories\TemplateRepository;
|
||||
@@ -54,7 +55,8 @@ class TemplateServiceInstallationTest extends TestCase
|
||||
$this->templateRepository,
|
||||
$this->templateManager,
|
||||
$this->moduleManager,
|
||||
$this->pluginManager
|
||||
$this->pluginManager,
|
||||
app(LayoutVersionRepositoryInterface::class)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,9 @@ use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Extension\PluginInterface;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
use App\Contracts\Extension\TemplateManagerInterface;
|
||||
use App\Contracts\Repositories\LayoutVersionRepositoryInterface;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\Template;
|
||||
use App\Repositories\TemplateRepository;
|
||||
use App\Services\TemplateService;
|
||||
@@ -65,7 +67,8 @@ class TemplateServiceLanguageMergeTest extends TestCase
|
||||
$this->templateRepository,
|
||||
$this->templateManager,
|
||||
$this->moduleManager,
|
||||
$this->pluginManager
|
||||
$this->pluginManager,
|
||||
app(LayoutVersionRepositoryInterface::class)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -342,4 +345,192 @@ class TemplateServiceLanguageMergeTest extends TestCase
|
||||
$result['data']['sirsoft-board']['messages']['boards']['menu_added_success']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 코어 프론트엔드 다국어 자원(`lang/{locale}.json`)이 베이스 레이어로 병합되어
|
||||
* 어떤 템플릿이 부팅되든 `core.*` 키가 응답에 포함되는지 검증.
|
||||
*/
|
||||
public function test_core_frontend_lang_data_is_loaded_as_base_layer(): void
|
||||
{
|
||||
$identifier = 'sirsoft-admin_basic';
|
||||
$locale = 'ko';
|
||||
|
||||
Template::create([
|
||||
'identifier' => $identifier,
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => 'Admin Basic',
|
||||
'type' => 'admin',
|
||||
'version' => '1.0.0',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
|
||||
$this->templateManager
|
||||
->shouldReceive('getTemplateInfo')
|
||||
->with($identifier)
|
||||
->andReturn([
|
||||
'identifier' => $identifier,
|
||||
'locales' => ['ko', 'en'],
|
||||
]);
|
||||
|
||||
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([]);
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([]);
|
||||
|
||||
$result = $this->templateService->getLanguageDataWithModules($identifier, $locale);
|
||||
|
||||
$this->assertTrue($result['success']);
|
||||
$this->assertIsArray($result['data']);
|
||||
// 코어 프론트엔드 키가 베이스로 병합됨
|
||||
$this->assertArrayHasKey('core', $result['data']);
|
||||
$this->assertArrayHasKey('errors', $result['data']['core']);
|
||||
// 한국어 번역 확인
|
||||
$this->assertEquals(
|
||||
'활성화된 템플릿이 없습니다',
|
||||
$result['data']['core']['errors']['template_not_found']
|
||||
);
|
||||
// 템플릿 키도 동시에 존재
|
||||
$this->assertArrayHasKey('auth', $result['data']);
|
||||
}
|
||||
|
||||
/**
|
||||
* en 로케일에서도 코어 프론트엔드 키가 영어로 해석되는지 검증.
|
||||
*/
|
||||
public function test_core_frontend_lang_data_resolved_in_english_locale(): void
|
||||
{
|
||||
$identifier = 'sirsoft-admin_basic';
|
||||
$locale = 'en';
|
||||
|
||||
Template::create([
|
||||
'identifier' => $identifier,
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => 'Admin Basic',
|
||||
'type' => 'admin',
|
||||
'version' => '1.0.0',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
|
||||
$this->templateManager
|
||||
->shouldReceive('getTemplateInfo')
|
||||
->with($identifier)
|
||||
->andReturn([
|
||||
'identifier' => $identifier,
|
||||
'locales' => ['ko', 'en'],
|
||||
]);
|
||||
|
||||
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([]);
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([]);
|
||||
|
||||
$result = $this->templateService->getLanguageDataWithModules($identifier, $locale);
|
||||
|
||||
$this->assertTrue($result['success']);
|
||||
$this->assertEquals(
|
||||
'No active template found',
|
||||
$result['data']['core']['errors']['template_not_found']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 결함 A 회귀 테스트.
|
||||
*
|
||||
* 코어의 `layout_editor.chrome.*` 가 살아남으면서 sirsoft-basic 템플릿이 자체
|
||||
* 정의한 `layout_editor.palette.*` 도 동시에 노출되어야 한다. 과거 array_merge
|
||||
* shallow 는 템플릿 partial 의 `layout_editor` 가 코어 `layout_editor` 를 통째
|
||||
* 덮어써서 chrome/device/zoom/save 키가 누락되었다.
|
||||
*/
|
||||
public function test_deep_merge_preserves_core_layout_editor_chrome_when_template_defines_palette(): void
|
||||
{
|
||||
$identifier = 'sirsoft-basic';
|
||||
$locale = 'ko';
|
||||
|
||||
Template::create([
|
||||
'identifier' => $identifier,
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => 'Basic',
|
||||
'type' => 'user',
|
||||
'version' => '1.0.0',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
|
||||
$this->templateManager
|
||||
->shouldReceive('getTemplateInfo')
|
||||
->with($identifier)
|
||||
->andReturn([
|
||||
'identifier' => $identifier,
|
||||
'locales' => ['ko', 'en'],
|
||||
]);
|
||||
|
||||
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([]);
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([]);
|
||||
|
||||
$result = $this->templateService->getLanguageDataWithModules($identifier, $locale);
|
||||
|
||||
$this->assertTrue($result['success']);
|
||||
$this->assertIsArray($result['data']);
|
||||
$this->assertArrayHasKey('layout_editor', $result['data']);
|
||||
|
||||
// 코어의 chrome / device / zoom / preview / save 키가 모두 살아남아야 함
|
||||
$layoutEditor = $result['data']['layout_editor'];
|
||||
$this->assertArrayHasKey('chrome', $layoutEditor, 'core layout_editor.chrome 누락');
|
||||
$this->assertArrayHasKey('device', $layoutEditor, 'core layout_editor.device 누락');
|
||||
$this->assertArrayHasKey('zoom', $layoutEditor, 'core layout_editor.zoom 누락');
|
||||
$this->assertArrayHasKey('preview', $layoutEditor, 'core layout_editor.preview 누락');
|
||||
$this->assertArrayHasKey('save', $layoutEditor, 'core layout_editor.save 누락');
|
||||
|
||||
// 동시에 템플릿이 정의한 palette 트리도 그대로 노출
|
||||
$this->assertArrayHasKey('palette', $layoutEditor, 'template layout_editor.palette 누락');
|
||||
$this->assertIsArray($layoutEditor['palette']);
|
||||
}
|
||||
|
||||
/**
|
||||
* deep merge — 양쪽이 assoc 일 때 leaf 병합 + 충돌 leaf 는 뒤가 우선.
|
||||
*/
|
||||
public function test_deep_merge_recursive_leaf_resolution(): void
|
||||
{
|
||||
$identifier = 'sirsoft-admin_basic';
|
||||
$locale = 'ko';
|
||||
|
||||
Template::create([
|
||||
'identifier' => $identifier,
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => 'Admin Basic',
|
||||
'type' => 'admin',
|
||||
'version' => '1.0.0',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
|
||||
$this->templateManager
|
||||
->shouldReceive('getTemplateInfo')
|
||||
->with($identifier)
|
||||
->andReturn([
|
||||
'identifier' => $identifier,
|
||||
'locales' => ['ko', 'en'],
|
||||
]);
|
||||
|
||||
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([]);
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([]);
|
||||
|
||||
// template.language.merge 훅으로 인공적인 deep merge 검증 입력 합류
|
||||
$overrideCallback = function ($data) {
|
||||
return array_replace_recursive($data, [
|
||||
'core' => [
|
||||
'errors' => [
|
||||
'template_not_found' => '<<HOOK_OVERRIDE>>',
|
||||
],
|
||||
],
|
||||
]);
|
||||
};
|
||||
HookManager::addFilter('template.language.merge', $overrideCallback);
|
||||
|
||||
$result = $this->templateService->getLanguageDataWithModules($identifier, $locale);
|
||||
|
||||
HookManager::removeFilter('template.language.merge', $overrideCallback);
|
||||
|
||||
$this->assertTrue($result['success']);
|
||||
$this->assertEquals(
|
||||
'<<HOOK_OVERRIDE>>',
|
||||
$result['data']['core']['errors']['template_not_found']
|
||||
);
|
||||
// 동시에 같은 core.errors 트리의 다른 leaf 는 코어 값이 살아남아야 함
|
||||
// (deep merge 검증 — 충돌 leaf 만 override, 동기 트리의 다른 형제는 보존)
|
||||
$this->assertArrayHasKey('layout_load_failed', $result['data']['core']['errors']);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Extension\PluginInterface;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
use App\Contracts\Extension\TemplateManagerInterface;
|
||||
use App\Contracts\Repositories\LayoutVersionRepositoryInterface;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Models\Template;
|
||||
use App\Repositories\TemplateRepository;
|
||||
@@ -60,7 +61,8 @@ class TemplateServiceRoutesFilterTest extends TestCase
|
||||
$templateRepository,
|
||||
$this->templateManager,
|
||||
$this->moduleManager,
|
||||
$this->pluginManager
|
||||
$this->pluginManager,
|
||||
app(LayoutVersionRepositoryInterface::class)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -497,4 +499,96 @@ class TemplateServiceRoutesFilterTest extends TestCase
|
||||
$termsRoutes = array_filter($routes, fn ($r) => $r['path'] === '*/shop/terms');
|
||||
$this->assertEmpty($termsRoutes, 'User 라우트(쇼핑몰 이용약관)는 admin 템플릿에 포함되지 않아야 함');
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// 편집기 모달 수집 — 모듈/플러그인 레이아웃 디렉토리(admin/ vs user/) 타입 필터링
|
||||
//
|
||||
// 라우트는 routes/{admin|user}.json 으로 분기되지만, 편집기 트리의 모달은
|
||||
// collectEditorBaseAndModals 가 모듈 layouts/ 를 순회해 수집한다. 이 수집도
|
||||
// 템플릿 타입에 맞는 layouts/{admin|user}/ 서브디렉토리만 대상으로 해야
|
||||
// user 템플릿 편집 모드에 admin 모달이, admin 편집 모드에 user 모달이 새지 않는다.
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* 테스트용 모듈에 admin/user 레이아웃(모달 포함)을 생성합니다.
|
||||
*
|
||||
* - layouts/admin/admin_screen.json : 모달 `admin_only_modal` 보유
|
||||
* - layouts/user/user_screen.json : 모달 `user_only_modal` 보유
|
||||
*
|
||||
* @return string 테스트용 모듈 식별자
|
||||
*/
|
||||
private function setupModuleWithTypedModalLayouts(): string
|
||||
{
|
||||
$identifier = 'test-routes-module';
|
||||
$layoutsBase = base_path("modules/{$identifier}/resources/layouts");
|
||||
|
||||
File::ensureDirectoryExists($layoutsBase.'/admin');
|
||||
File::ensureDirectoryExists($layoutsBase.'/user');
|
||||
|
||||
File::put($layoutsBase.'/admin/admin_screen.json', json_encode([
|
||||
'modals' => [
|
||||
['id' => 'admin_only_modal', 'title' => '관리자 전용 모달'],
|
||||
],
|
||||
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
|
||||
|
||||
File::put($layoutsBase.'/user/user_screen.json', json_encode([
|
||||
'modals' => [
|
||||
['id' => 'user_only_modal', 'title' => '사용자 전용 모달'],
|
||||
],
|
||||
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
|
||||
|
||||
return $identifier;
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function user_template_editor_excludes_admin_module_modals(): void
|
||||
{
|
||||
// Given: admin/user 레이아웃에 각각 모달을 가진 모듈
|
||||
$identifier = $this->setupModuleWithTypedModalLayouts();
|
||||
|
||||
$this->setupUserTemplate();
|
||||
|
||||
$mockModule = $this->createMockModule($identifier);
|
||||
$this->moduleManager->method('getActiveModules')->willReturn([$identifier => $mockModule]);
|
||||
$this->pluginManager->method('getActivePlugins')->willReturn([]);
|
||||
|
||||
// When: user 템플릿 편집기 라우트/모달 조회
|
||||
$result = $this->templateService->getEditorRoutesDataWithModules('test-user_template');
|
||||
|
||||
// Then: user 레이아웃 모달은 포함, admin 레이아웃 모달은 제외
|
||||
$this->assertTrue($result['success']);
|
||||
$modals = $result['data']['modals'];
|
||||
|
||||
$adminModals = array_filter($modals, fn ($m) => $m['modal_id'] === 'admin_only_modal');
|
||||
$userModals = array_filter($modals, fn ($m) => $m['modal_id'] === 'user_only_modal');
|
||||
|
||||
$this->assertEmpty($adminModals, 'Admin 레이아웃 모달은 user 템플릿 편집기에 노출되지 않아야 함');
|
||||
$this->assertNotEmpty($userModals, 'User 레이아웃 모달은 user 템플릿 편집기에 노출되어야 함');
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function admin_template_editor_excludes_user_module_modals(): void
|
||||
{
|
||||
// Given: admin/user 레이아웃에 각각 모달을 가진 모듈
|
||||
$identifier = $this->setupModuleWithTypedModalLayouts();
|
||||
|
||||
$this->setupAdminTemplate();
|
||||
|
||||
$mockModule = $this->createMockModule($identifier);
|
||||
$this->moduleManager->method('getActiveModules')->willReturn([$identifier => $mockModule]);
|
||||
$this->pluginManager->method('getActivePlugins')->willReturn([]);
|
||||
|
||||
// When: admin 템플릿 편집기 라우트/모달 조회
|
||||
$result = $this->templateService->getEditorRoutesDataWithModules('sirsoft-admin_basic');
|
||||
|
||||
// Then: admin 레이아웃 모달은 포함, user 레이아웃 모달은 제외
|
||||
$this->assertTrue($result['success']);
|
||||
$modals = $result['data']['modals'];
|
||||
|
||||
$adminModals = array_filter($modals, fn ($m) => $m['modal_id'] === 'admin_only_modal');
|
||||
$userModals = array_filter($modals, fn ($m) => $m['modal_id'] === 'user_only_modal');
|
||||
|
||||
$this->assertNotEmpty($adminModals, 'Admin 레이아웃 모달은 admin 템플릿 편집기에 노출되어야 함');
|
||||
$this->assertEmpty($userModals, 'User 레이아웃 모달은 admin 템플릿 편집기에 노출되지 않아야 함');
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,12 @@
|
||||
|
||||
namespace Tests\Feature\Services;
|
||||
|
||||
use App\Contracts\Extension\ModuleInterface;
|
||||
use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Extension\PluginInterface;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
use App\Contracts\Extension\TemplateManagerInterface;
|
||||
use App\Contracts\Repositories\LayoutVersionRepositoryInterface;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Models\Template;
|
||||
use App\Repositories\TemplateRepository;
|
||||
@@ -57,7 +60,8 @@ class TemplateServiceRoutesMergeTest extends TestCase
|
||||
$this->templateRepository,
|
||||
$this->templateManager,
|
||||
$this->moduleManager,
|
||||
$this->pluginManager
|
||||
$this->pluginManager,
|
||||
app(LayoutVersionRepositoryInterface::class)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -104,6 +108,51 @@ class TemplateServiceRoutesMergeTest extends TestCase
|
||||
$this->assertIsArray($result['data']['routes']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function get_layout_route_path_map_maps_layout_name_to_route_path(): void
|
||||
{
|
||||
// Given: 활성화된 user 템플릿 (실제 routes.json 보유)
|
||||
Template::factory()->create([
|
||||
'identifier' => 'sirsoft-basic',
|
||||
'type' => 'user',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
$this->templateManager->method('getTemplateInfo')->willReturn([
|
||||
'identifier' => 'sirsoft-basic',
|
||||
'type' => 'user',
|
||||
]);
|
||||
$this->moduleManager->method('getActiveModules')->willReturn([]);
|
||||
|
||||
// When: 레이아웃 → path 매핑 조회
|
||||
$map = $this->templateService->getLayoutRoutePathMap('sirsoft-basic');
|
||||
|
||||
// Then: 정적 라우트는 path 로 매핑, base/partial(라우트 없음)은 제외
|
||||
$this->assertSame('/', $map['home'] ?? null);
|
||||
$this->assertSame('/login', $map['auth/login'] ?? null);
|
||||
$this->assertArrayNotHasKey('_user_base', $map, 'base 레이아웃은 라우트가 없어 매핑에서 제외');
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function get_layout_route_path_map_returns_empty_for_template_without_routes(): void
|
||||
{
|
||||
// Given: routes.json 없는 템플릿
|
||||
Template::factory()->create([
|
||||
'identifier' => 'no-routes-template',
|
||||
'type' => 'admin',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
$this->templateManager->method('getTemplateInfo')->willReturn([
|
||||
'identifier' => 'no-routes-template',
|
||||
'type' => 'admin',
|
||||
]);
|
||||
|
||||
// When: 매핑 조회
|
||||
$map = $this->templateService->getLayoutRoutePathMap('no-routes-template');
|
||||
|
||||
// Then: 빈 배열 (route_path 는 모두 null 로 직렬화됨)
|
||||
$this->assertSame([], $map);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function module_routes_data_is_merged_with_template_routes(): void
|
||||
{
|
||||
@@ -121,7 +170,7 @@ class TemplateServiceRoutesMergeTest extends TestCase
|
||||
]);
|
||||
|
||||
// Module Manager Mock 설정
|
||||
$mockModule = $this->createMock(\App\Contracts\Extension\ModuleInterface::class);
|
||||
$mockModule = $this->createMock(ModuleInterface::class);
|
||||
$mockModule->method('getIdentifier')->willReturn('sirsoft-board');
|
||||
$this->moduleManager->method('getActiveModules')->willReturn([
|
||||
'sirsoft-board' => $mockModule,
|
||||
@@ -195,7 +244,7 @@ class TemplateServiceRoutesMergeTest extends TestCase
|
||||
]);
|
||||
|
||||
// Module Manager Mock
|
||||
$mockModule = $this->createMock(\App\Contracts\Extension\ModuleInterface::class);
|
||||
$mockModule = $this->createMock(ModuleInterface::class);
|
||||
$mockModule->method('getIdentifier')->willReturn('sirsoft-board');
|
||||
$this->moduleManager->method('getActiveModules')->willReturn([
|
||||
'sirsoft-board' => $mockModule,
|
||||
@@ -256,11 +305,11 @@ class TemplateServiceRoutesMergeTest extends TestCase
|
||||
$this->moduleManager->method('getActiveModules')->willReturn([]);
|
||||
|
||||
// Plugin Mock: 설정이 있는 플러그인 2개
|
||||
$pluginA = $this->createMock(\App\Contracts\Extension\PluginInterface::class);
|
||||
$pluginA = $this->createMock(PluginInterface::class);
|
||||
$pluginA->method('getIdentifier')->willReturn('sirsoft-tosspayments');
|
||||
$pluginA->method('hasSettings')->willReturn(true);
|
||||
|
||||
$pluginB = $this->createMock(\App\Contracts\Extension\PluginInterface::class);
|
||||
$pluginB = $this->createMock(PluginInterface::class);
|
||||
$pluginB->method('getIdentifier')->willReturn('sirsoft-daum_postcode');
|
||||
$pluginB->method('hasSettings')->willReturn(true);
|
||||
|
||||
@@ -318,7 +367,7 @@ class TemplateServiceRoutesMergeTest extends TestCase
|
||||
$this->moduleManager->method('getActiveModules')->willReturn([]);
|
||||
|
||||
// Plugin Mock: 설정이 없는 플러그인
|
||||
$plugin = $this->createMock(\App\Contracts\Extension\PluginInterface::class);
|
||||
$plugin = $this->createMock(PluginInterface::class);
|
||||
$plugin->method('getIdentifier')->willReturn('sirsoft-no-settings');
|
||||
$plugin->method('hasSettings')->willReturn(false);
|
||||
|
||||
@@ -357,11 +406,11 @@ class TemplateServiceRoutesMergeTest extends TestCase
|
||||
$this->moduleManager->method('getActiveModules')->willReturn([]);
|
||||
|
||||
// Plugin Mock: 설정이 있는 플러그인 2개
|
||||
$pluginA = $this->createMock(\App\Contracts\Extension\PluginInterface::class);
|
||||
$pluginA = $this->createMock(PluginInterface::class);
|
||||
$pluginA->method('getIdentifier')->willReturn('sirsoft-tosspayments');
|
||||
$pluginA->method('hasSettings')->willReturn(true);
|
||||
|
||||
$pluginB = $this->createMock(\App\Contracts\Extension\PluginInterface::class);
|
||||
$pluginB = $this->createMock(PluginInterface::class);
|
||||
$pluginB->method('getIdentifier')->willReturn('sirsoft-daum_postcode');
|
||||
$pluginB->method('hasSettings')->willReturn(true);
|
||||
|
||||
@@ -377,12 +426,12 @@ class TemplateServiceRoutesMergeTest extends TestCase
|
||||
$this->assertTrue($result['success']);
|
||||
$routes = $result['data']['routes'];
|
||||
|
||||
// layout 을 가진 settings 페이지만 대상 — `/settings/language-packs` 같은
|
||||
// redirect 라우트(layout 키 없음)는 플러그인 레이아웃 격리 검증 대상이 아니다.
|
||||
$settingsRoutes = array_filter($routes, function ($route) {
|
||||
return str_contains($route['path'], '/settings');
|
||||
return str_contains($route['path'], '/settings') && isset($route['layout']);
|
||||
});
|
||||
|
||||
$layouts = array_map(fn ($route) => $route['layout'], array_values($settingsRoutes));
|
||||
|
||||
// 토스페이먼츠 경로에 토스페이먼츠 레이아웃이 매핑되어야 함
|
||||
foreach ($settingsRoutes as $route) {
|
||||
if (str_contains($route['path'], 'sirsoft-tosspayments')) {
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace Tests\Feature\Services;
|
||||
use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
use App\Contracts\Extension\TemplateManagerInterface;
|
||||
use App\Contracts\Repositories\LayoutVersionRepositoryInterface;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Exceptions\TemplateFileCopyException;
|
||||
use App\Extension\HookManager;
|
||||
@@ -21,9 +22,13 @@ class TemplateServiceTest extends TestCase
|
||||
use RefreshDatabase;
|
||||
|
||||
private TemplateService $templateService;
|
||||
|
||||
private TemplateRepository $templateRepository;
|
||||
|
||||
private TemplateManagerInterface $templateManager;
|
||||
|
||||
private ModuleManagerInterface $moduleManager;
|
||||
|
||||
private PluginManagerInterface $pluginManager;
|
||||
|
||||
protected function setUp(): void
|
||||
@@ -43,14 +48,15 @@ class TemplateServiceTest extends TestCase
|
||||
$this->pluginManager = Mockery::mock(PluginManagerInterface::class);
|
||||
|
||||
// TemplateRepository 인스턴스 생성
|
||||
$this->templateRepository = new TemplateRepository();
|
||||
$this->templateRepository = new TemplateRepository;
|
||||
|
||||
// TemplateService 인스턴스 생성 (Mock Manager 주입)
|
||||
$this->templateService = new TemplateService(
|
||||
$this->templateRepository,
|
||||
$this->templateManager,
|
||||
$this->moduleManager,
|
||||
$this->pluginManager
|
||||
$this->pluginManager,
|
||||
app(LayoutVersionRepositoryInterface::class)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -66,7 +72,7 @@ class TemplateServiceTest extends TestCase
|
||||
public function test_activates_template_with_hook_system(): void
|
||||
{
|
||||
// Arrange - 고유 identifier 사용하여 트랜잭션 락 충돌 방지
|
||||
$identifier = 'test-template-' . uniqid();
|
||||
$identifier = 'test-template-'.uniqid();
|
||||
$template = Template::create([
|
||||
'identifier' => $identifier,
|
||||
'vendor' => 'test-vendor',
|
||||
@@ -104,6 +110,7 @@ class TemplateServiceTest extends TestCase
|
||||
->andReturnUsing(function () use ($template, $templateInfo) {
|
||||
// Manager가 DB 업데이트 시뮬레이션
|
||||
$template->update(['status' => ExtensionStatus::Active->value]);
|
||||
|
||||
return $templateInfo; // 배열 반환 (인터페이스 요구사항)
|
||||
});
|
||||
|
||||
@@ -122,13 +129,13 @@ class TemplateServiceTest extends TestCase
|
||||
$this->assertGreaterThanOrEqual(2, count($hookCalls));
|
||||
|
||||
// before_activate가 호출되었는지 확인
|
||||
$beforeActivateCalls = array_filter($hookCalls, fn($call) => $call['hook'] === 'before_activate');
|
||||
$beforeActivateCalls = array_filter($hookCalls, fn ($call) => $call['hook'] === 'before_activate');
|
||||
$this->assertNotEmpty($beforeActivateCalls);
|
||||
$firstBeforeActivate = array_values($beforeActivateCalls)[0];
|
||||
$this->assertEquals($template->identifier, $firstBeforeActivate['identifier']);
|
||||
|
||||
// after_activate가 호출되었는지 확인
|
||||
$afterActivateCalls = array_filter($hookCalls, fn($call) => $call['hook'] === 'after_activate');
|
||||
$afterActivateCalls = array_filter($hookCalls, fn ($call) => $call['hook'] === 'after_activate');
|
||||
$this->assertNotEmpty($afterActivateCalls);
|
||||
$firstAfterActivate = array_values($afterActivateCalls)[0];
|
||||
$this->assertEquals($template->id, $firstAfterActivate['template_id']);
|
||||
@@ -145,7 +152,7 @@ class TemplateServiceTest extends TestCase
|
||||
public function test_delegates_file_copy_to_manager(): void
|
||||
{
|
||||
// Arrange - 고유 identifier 사용하여 트랜잭션 락 충돌 방지
|
||||
$identifier = 'test-template-' . uniqid();
|
||||
$identifier = 'test-template-'.uniqid();
|
||||
$template = Template::create([
|
||||
'identifier' => $identifier,
|
||||
'vendor' => 'test-vendor',
|
||||
@@ -170,6 +177,7 @@ class TemplateServiceTest extends TestCase
|
||||
->with($identifier, false)
|
||||
->andReturnUsing(function () use ($template, $templateInfo) {
|
||||
$template->update(['status' => ExtensionStatus::Active->value]);
|
||||
|
||||
return $templateInfo; // 배열 반환 (인터페이스 요구사항)
|
||||
});
|
||||
|
||||
@@ -194,7 +202,7 @@ class TemplateServiceTest extends TestCase
|
||||
public function test_applies_filter_hook_before_manager_call(): void
|
||||
{
|
||||
// Arrange - 고유 identifier 사용하여 트랜잭션 락 충돌 방지
|
||||
$identifier = 'test-template-' . uniqid();
|
||||
$identifier = 'test-template-'.uniqid();
|
||||
$template = Template::create([
|
||||
'identifier' => $identifier,
|
||||
'vendor' => 'test-vendor',
|
||||
@@ -217,6 +225,7 @@ class TemplateServiceTest extends TestCase
|
||||
HookManager::addFilter('core.templates.filter_activate_data', function ($data, $template) use (&$filterApplied) {
|
||||
$filterApplied = true;
|
||||
$data['custom_field'] = 'filtered_value';
|
||||
|
||||
return $data;
|
||||
}, 10, 2);
|
||||
|
||||
@@ -227,6 +236,7 @@ class TemplateServiceTest extends TestCase
|
||||
->with($identifier, false)
|
||||
->andReturnUsing(function () use ($template, $templateInfo) {
|
||||
$template->update(['status' => ExtensionStatus::Active->value]);
|
||||
|
||||
return $templateInfo; // 배열 반환 (인터페이스 요구사항)
|
||||
});
|
||||
|
||||
@@ -250,7 +260,7 @@ class TemplateServiceTest extends TestCase
|
||||
public function test_throws_exception_on_manager_failure(): void
|
||||
{
|
||||
// Arrange - 고유 identifier 사용하여 트랜잭션 락 충돌 방지
|
||||
$identifier = 'test-template-' . uniqid();
|
||||
$identifier = 'test-template-'.uniqid();
|
||||
$template = Template::create([
|
||||
'identifier' => $identifier,
|
||||
'vendor' => 'test-vendor',
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* /storage/{path} 자동 서빙 라우트 미노출 회귀 테스트 (공개#52).
|
||||
*
|
||||
* local/modules/plugins 디스크의 serve => false 로 Laravel 이 자동 생성하던
|
||||
* GET/PUT /storage/{path}(storage.local/modules/plugins(.upload)) 라우트가
|
||||
* 더 이상 등록되지 않는지 검증한다. 첨부(attachments)·확장 에셋은 이 라우트를
|
||||
* 사용하지 않으므로 무손상.
|
||||
*/
|
||||
class StorageServeRouteTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* storage serve 라우트(GET/PUT)가 라우트 목록에 등록되지 않았는지 테스트합니다.
|
||||
*/
|
||||
public function test_storage_serve_routes_are_not_registered(): void
|
||||
{
|
||||
$names = collect(Route::getRoutes()->getRoutes())
|
||||
->map(fn ($route) => $route->getName())
|
||||
->filter()
|
||||
->values()
|
||||
->all();
|
||||
|
||||
foreach ($names as $name) {
|
||||
$this->assertStringNotContainsString(
|
||||
'storage.',
|
||||
(string) $name,
|
||||
"serve 자동 라우트가 여전히 등록됨: {$name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PUT /storage/{path}(업로드 입구)가 더 이상 처리되지 않는지 테스트합니다.
|
||||
*
|
||||
* serve 라우트가 살아 있으면 PUT 이 ReceiveFile 로 라우팅되지만, 제거 후에는
|
||||
* PUT 을 처리하는 라우트가 없어 405(Method Not Allowed) 또는 404 가 된다.
|
||||
* (GET-only SPA catch-all 만 남으므로 PUT 은 메서드 미허용.)
|
||||
*/
|
||||
public function test_storage_put_upload_route_is_not_handled(): void
|
||||
{
|
||||
$response = $this->put('/storage/foo.txt?upload=1', [], [
|
||||
'Content-Type' => 'text/plain',
|
||||
]);
|
||||
|
||||
$this->assertContains(
|
||||
$response->getStatusCode(),
|
||||
[404, 405],
|
||||
'PUT /storage 업로드 입구가 여전히 처리됨 (serve 라우트 잔존)'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* GET storage serve 라우트 이름이 라우트 컬렉션에 존재하지 않는지 테스트합니다.
|
||||
*
|
||||
* (GET /storage/foo 는 SPA catch-all 이 흡수하므로 HTTP status 가 아닌
|
||||
* 라우트 이름 부재로 serve 라우트 제거를 검증한다.)
|
||||
*/
|
||||
public function test_storage_serve_route_names_absent(): void
|
||||
{
|
||||
foreach (['storage.local', 'storage.modules', 'storage.plugins'] as $name) {
|
||||
$this->assertNull(
|
||||
Route::getRoutes()->getByName($name),
|
||||
"serve 라우트 {$name} 이 여전히 등록됨"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Template;
|
||||
|
||||
use App\Contracts\Repositories\LayoutRepositoryInterface;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Extension\Cache\CoreCacheDriver;
|
||||
use App\Extension\Traits\InvalidatesLayoutCache;
|
||||
use App\Models\Template;
|
||||
use App\Models\TemplateLayout;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 레이아웃 편집기(`with_source_meta=1`) 캐시 무효화 회귀
|
||||
*
|
||||
* 배경: `PublicLayoutController::serve()` 는 일반 응답과 레이아웃 편집기 응답
|
||||
* (`with_source_meta=1`)을 **별도 캐시 키**(`.meta` 접미사)로 저장한다. 템플릿/
|
||||
* 레이아웃 상태 변화(refresh-layout / activate / deactivate / uninstall 등) 시
|
||||
* 공통으로 거치는 `InvalidatesLayoutCache::forgetLayoutCacheKeys()` 가 일반 키만
|
||||
* 삭제하고 `.meta` 키를 누락하면, 사용자 페이지는 갱신되지만 **편집기 캔버스만
|
||||
* stale 캐시**(옛 레이아웃)를 받는다( 재현 — 사용자는 복원, 편집기는
|
||||
* 미복원). 레이아웃 저장 경로(`LayoutService::clearPublicServingCache`)는 이미 두
|
||||
* 키를 지우므로, 본 테스트는 상태 변화 공통 지점이 두 키를 모두 무효화함을 잠근다.
|
||||
*/
|
||||
class LayoutEditorCacheInvalidationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/** trait 를 노출하는 익명 테스트 더블 */
|
||||
private function makeInvalidator(): object
|
||||
{
|
||||
return new class
|
||||
{
|
||||
use InvalidatesLayoutCache;
|
||||
|
||||
public LayoutRepositoryInterface $layoutRepository;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->layoutRepository = app(LayoutRepositoryInterface::class);
|
||||
}
|
||||
|
||||
/** protected 메서드 노출 */
|
||||
public function invalidate(int $templateId, string $identifier): void
|
||||
{
|
||||
$this->invalidateTemplateLayoutCache($templateId, $identifier);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private function coreCache(): CoreCacheDriver
|
||||
{
|
||||
return new CoreCacheDriver(config('cache.default', 'array'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 레이아웃_캐시_무효화는_일반키와_편집기meta키를_모두_삭제한다(): void
|
||||
{
|
||||
$template = Template::factory()->create([
|
||||
'identifier' => 'sirsoft-basic',
|
||||
'type' => 'user',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
TemplateLayout::create([
|
||||
'template_id' => $template->id,
|
||||
'name' => 'home',
|
||||
'content' => ['meta' => ['title' => 'Home'], 'components' => []],
|
||||
]);
|
||||
|
||||
$cache = $this->coreCache();
|
||||
$version = (int) $cache->get('ext.cache_version', 0);
|
||||
|
||||
// PublicLayoutController::serve() 가 쓰는 두 캐시 키 — 일반 + 편집기(.meta)
|
||||
$generalKey = "layout.sirsoft-basic.home.v{$version}";
|
||||
$metaKey = "layout.sirsoft-basic.home.v{$version}.meta";
|
||||
$cache->put($generalKey, ['cached' => 'general'], 3600);
|
||||
$cache->put($metaKey, ['cached' => 'meta'], 3600);
|
||||
|
||||
// 사전 조건: 두 키 모두 캐시에 존재
|
||||
$this->assertNotNull($cache->get($generalKey), '사전: 일반 키 캐시 존재');
|
||||
$this->assertNotNull($cache->get($metaKey), '사전: 편집기 .meta 키 캐시 존재');
|
||||
|
||||
// 상태 변화 공통 지점 — 레이아웃 캐시 무효화
|
||||
$this->makeInvalidator()->invalidate($template->id, 'sirsoft-basic');
|
||||
|
||||
// 두 키 모두 무효화되어야 함 (.meta 누락이면 편집기 stale 회귀)
|
||||
$this->assertNull($cache->get($generalKey), '일반 키가 무효화됨');
|
||||
$this->assertNull($cache->get($metaKey), '편집기.meta 키도 무효화됨');
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 템플릿_레이아웃_refresh_후_편집기meta_캐시가_stale로_남지_않는다(): void
|
||||
{
|
||||
$template = Template::factory()->create([
|
||||
'identifier' => 'sirsoft-basic',
|
||||
'type' => 'user',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
TemplateLayout::create([
|
||||
'template_id' => $template->id,
|
||||
'name' => 'home',
|
||||
'content' => ['meta' => ['title' => 'Home'], 'components' => []],
|
||||
]);
|
||||
|
||||
$cache = $this->coreCache();
|
||||
$version = (int) $cache->get('ext.cache_version', 0);
|
||||
$metaKey = "layout.sirsoft-basic.home.v{$version}.meta";
|
||||
$cache->put($metaKey, ['stale' => 'editor-old-content'], 3600);
|
||||
|
||||
// 상태 변화 공통 지점 호출 → 편집기 .meta 키가 stale 로 남으면 실패
|
||||
$this->makeInvalidator()->invalidate($template->id, 'sirsoft-basic');
|
||||
|
||||
$this->assertNull(
|
||||
$cache->get($metaKey),
|
||||
'refresh/상태변화 후 편집기 .meta 캐시가 stale 로 잔존하면 편집기 캔버스가 옛 레이아웃을 표시한다',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,16 @@ class PublicLayoutControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 레이아웃 서빙 경로가 GDPR 쿠키 동의 미들웨어를 거치므로
|
||||
* 해당 플러그인 마이그레이션을 테스트 DB 에 포함시킨다.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
/**
|
||||
* 유효한 레이아웃 서빙 성공 테스트
|
||||
*/
|
||||
@@ -191,16 +201,22 @@ class PublicLayoutControllerTest extends TestCase
|
||||
],
|
||||
]);
|
||||
|
||||
// 캐시 초기화
|
||||
Cache::forget("g7:core:layout.{$template->identifier}.{$layout->name}.v0");
|
||||
Cache::forget("g7:core:template.{$template->id}.layout.{$layout->name}");
|
||||
// 캐시 초기화 — CacheInterface 를 통해 코어 캐시 prefix 일관 사용
|
||||
// (Laravel Cache facade 의 global `CACHE_PREFIX` 와 CoreCacheDriver 의
|
||||
// `g7:core` prefix 가 합쳐진 실제 키와 동등하게 조회/삭제하기 위함)
|
||||
$coreCache = app(\App\Contracts\Extension\CacheInterface::class);
|
||||
$coreCache->forget("layout.{$template->identifier}.{$layout->name}.v0");
|
||||
$coreCache->forget("template.{$template->id}.layout.{$layout->name}");
|
||||
|
||||
// Act: 첫 번째 요청 (캐시 생성)
|
||||
$response1 = $this->getJson("/api/layouts/{$template->identifier}/{$layout->name}.json");
|
||||
$response1->assertStatus(200);
|
||||
|
||||
// 캐시가 생성되었는지 확인
|
||||
$this->assertTrue(Cache::has("g7:core:layout.{$template->identifier}.{$layout->name}.v0"));
|
||||
// 캐시가 생성되었는지 CacheInterface 로 확인 (컨트롤러가 사용하는 동일 경로)
|
||||
$this->assertTrue(
|
||||
$coreCache->has("layout.{$template->identifier}.{$layout->name}.v0"),
|
||||
'레이아웃 응답이 CoreCacheDriver(g7:core 접두사) 에 캐시되어야 함',
|
||||
);
|
||||
|
||||
// Act: 두 번째 요청 (캐시에서 조회)
|
||||
$response2 = $this->getJson("/api/layouts/{$template->identifier}/{$layout->name}.json");
|
||||
@@ -210,6 +226,71 @@ class PublicLayoutControllerTest extends TestCase
|
||||
$this->assertEquals($response1->json('data'), $response2->json('data'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 편집기 캐시-버스트 nonce(`?v={version}.{nonce}`) 요청 시 서버 캐시 키는 **정수 버전**만 쓴다.
|
||||
*
|
||||
* 레이아웃 편집기는 같은 세션 저장/복원 후 브라우저 HTTP 캐시를 우회하려고 `?v={cacheVersion}.{nonce}`
|
||||
* 형식으로 요청한다. 종전엔 `serve` 가 이 문자열을 그대로 캐시 키에 써(`v{ver}.{nonce}.meta`),
|
||||
* 저장 경로 `LayoutService::clearPublicServingCache` 가 `(int) ext.cache_version` 으로 nonce 없는 키만
|
||||
* forget 하므로 무효화가 빗나가 편집기가 stale 응답을 받았다. 본 테스트는 nonce 가 붙은 요청도
|
||||
* **정수 버전 키**(`v{ver}.meta`)로만 캐싱돼, 저장 경로 무효화 키와 정합함을 잠근다.
|
||||
*/
|
||||
public function test_editor_nonce_versioned_request_uses_integer_cache_key(): void
|
||||
{
|
||||
$template = Template::create([
|
||||
'identifier' => 'sirsoft-admin_basic',
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
|
||||
'version' => '1.0.0',
|
||||
'type' => 'admin',
|
||||
'status' => 'active',
|
||||
'description' => ['ko' => '기본 관리자 템플릿', 'en' => 'Basic Admin Template'],
|
||||
]);
|
||||
$layout = TemplateLayout::create([
|
||||
'template_id' => $template->id,
|
||||
'name' => 'dashboard',
|
||||
'content' => ['meta' => ['title' => 'Dashboard'], 'data_sources' => [], 'components' => []],
|
||||
]);
|
||||
|
||||
$coreCache = app(\App\Contracts\Extension\CacheInterface::class);
|
||||
$version = 1781151505;
|
||||
$nonce = 7;
|
||||
// 편집 모드(.meta) — `core.templates.layouts.edit` 권한 보유 사용자로 인증.
|
||||
$admin = User::factory()->create();
|
||||
$role = Role::create([
|
||||
'identifier' => 'editor',
|
||||
'name' => ['ko' => '편집자', 'en' => 'Editor'],
|
||||
'description' => ['ko' => '편집자', 'en' => 'Editor'],
|
||||
]);
|
||||
$perm = Permission::create([
|
||||
'identifier' => 'core.templates.layouts.edit',
|
||||
'name' => ['ko' => '레이아웃 편집', 'en' => 'Edit Layouts'],
|
||||
'description' => ['ko' => '레이아웃 편집', 'en' => 'Edit Layouts'],
|
||||
'type' => 'admin',
|
||||
]);
|
||||
$role->permissions()->attach($perm->id);
|
||||
$admin->roles()->attach($role->id);
|
||||
// 정수 버전 키(저장 경로가 forget 하는 키)와 nonce 부착 키를 모두 비워 둔다.
|
||||
$coreCache->forget("layout.{$template->identifier}.{$layout->name}.v{$version}.meta");
|
||||
$coreCache->forget("layout.{$template->identifier}.{$layout->name}.v{$version}.{$nonce}.meta");
|
||||
|
||||
// Act: 편집기 형식 요청 (`?v={version}.{nonce}&with_source_meta=1`).
|
||||
$this->actingAs($admin)
|
||||
->getJson("/api/layouts/{$template->identifier}/{$layout->name}.json?with_source_meta=1&v={$version}.{$nonce}")
|
||||
->assertStatus(200);
|
||||
|
||||
// 서버 캐시 키는 **정수 버전**(nonce 없는 키)에 생성돼야 한다 — 저장 경로 무효화 키와 일치.
|
||||
$this->assertTrue(
|
||||
$coreCache->has("layout.{$template->identifier}.{$layout->name}.v{$version}.meta"),
|
||||
'nonce 부착 요청도 정수 버전 캐시 키(`v{ver}.meta`)로 캐싱돼야 저장 경로 무효화와 정합함',
|
||||
);
|
||||
// nonce 가 박힌 키(`v{ver}.{nonce}.meta`)는 생성되지 않아야 한다(무효화 빗나감 회귀 차단).
|
||||
$this->assertFalse(
|
||||
$coreCache->has("layout.{$template->identifier}.{$layout->name}.v{$version}.{$nonce}.meta"),
|
||||
'nonce 가 박힌 캐시 키가 생성되면 저장 경로(정수 키 forget)가 무효화하지 못해 stale 회귀',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 상속 병합 테스트
|
||||
*/
|
||||
@@ -646,7 +727,7 @@ class PublicLayoutControllerTest extends TestCase
|
||||
'description' => ['ko' => '관리자', 'en' => 'Administrator'],
|
||||
'is_active' => true,
|
||||
]);
|
||||
$perm = \App\Models\Permission::firstOrCreate(
|
||||
$perm = Permission::firstOrCreate(
|
||||
['identifier' => 'core.dashboard.read'],
|
||||
[
|
||||
'name' => ['ko' => '대시보드', 'en' => 'Dashboard'],
|
||||
@@ -1005,7 +1086,7 @@ class PublicLayoutControllerTest extends TestCase
|
||||
'description' => ['ko' => '관리자', 'en' => 'Administrator'],
|
||||
'is_active' => true,
|
||||
]);
|
||||
$perm = \App\Models\Permission::firstOrCreate(
|
||||
$perm = Permission::firstOrCreate(
|
||||
['identifier' => 'core.dashboard.read'],
|
||||
[
|
||||
'name' => ['ko' => '대시보드', 'en' => 'Dashboard'],
|
||||
|
||||
@@ -2,12 +2,13 @@
|
||||
|
||||
namespace Tests\Feature\Template;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Extension\Cache\CoreCacheDriver;
|
||||
use App\Extension\TemplateManager;
|
||||
use App\Extension\Traits\ClearsTemplateCaches;
|
||||
use App\Models\Template;
|
||||
use App\Models\TemplateLayout;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\Helpers\ProtectsExtensionDirectories;
|
||||
@@ -49,6 +50,20 @@ class TemplateCacheManagementTest extends TestCase
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 코어 캐시 드라이버를 반환합니다.
|
||||
*
|
||||
* 검증 대상 키(`template.*`, `layout.*`)는 모두 코어 소유이며
|
||||
* TemplateManager 가 CoreCacheDriver(`g7:core:` 네임스페이스)로 기록한다.
|
||||
* 컨테이너의 CacheInterface 바인딩은 선행 모듈/플러그인 테스트가
|
||||
* PluginCacheDriver 로 재바인딩할 수 있어 네임스페이스가 어긋날 수 있으므로,
|
||||
* 테스트도 프로덕션과 동일하게 CoreCacheDriver 로 조회한다.
|
||||
*/
|
||||
private function coreCache(): CacheInterface
|
||||
{
|
||||
return new CoreCacheDriver(config('cache.default', 'array'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 활성화 시 캐시 워밍 테스트
|
||||
*/
|
||||
@@ -77,7 +92,7 @@ class TemplateCacheManagementTest extends TestCase
|
||||
if ($layoutExists) {
|
||||
$cacheKey = "layout.sirsoft-admin_basic.{$layoutName}.v{$cacheVersion}";
|
||||
$this->assertTrue(
|
||||
app(CacheInterface::class)->get($cacheKey) !== null,
|
||||
$this->coreCache()->get($cacheKey) !== null,
|
||||
"활성화 후 {$layoutName} 레이아웃 캐시가 생성되어야 합니다."
|
||||
);
|
||||
}
|
||||
@@ -87,7 +102,7 @@ class TemplateCacheManagementTest extends TestCase
|
||||
$routesFile = base_path('templates/sirsoft-admin_basic/routes.json');
|
||||
if (file_exists($routesFile)) {
|
||||
$this->assertTrue(
|
||||
app(CacheInterface::class)->get("template.routes.sirsoft-admin_basic.v{$cacheVersion}") !== null,
|
||||
$this->coreCache()->get("template.routes.sirsoft-admin_basic.v{$cacheVersion}") !== null,
|
||||
'활성화 후 routes 캐시가 생성되어야 합니다.'
|
||||
);
|
||||
}
|
||||
@@ -98,7 +113,7 @@ class TemplateCacheManagementTest extends TestCase
|
||||
$langFile = base_path("templates/sirsoft-admin_basic/lang/{$locale}.json");
|
||||
if (file_exists($langFile)) {
|
||||
$this->assertTrue(
|
||||
app(CacheInterface::class)->get("template.language.sirsoft-admin_basic.{$locale}.v{$cacheVersion}") !== null,
|
||||
$this->coreCache()->get("template.language.sirsoft-admin_basic.{$locale}.v{$cacheVersion}") !== null,
|
||||
"활성화 후 {$locale} 다국어 캐시가 생성되어야 합니다."
|
||||
);
|
||||
}
|
||||
@@ -120,7 +135,7 @@ class TemplateCacheManagementTest extends TestCase
|
||||
|
||||
// 캐시가 존재하는지 확인 (버전 포함 키)
|
||||
$this->assertTrue(
|
||||
app(CacheInterface::class)->get("template.routes.sirsoft-admin_basic.v{$activateVersion}") !== null,
|
||||
$this->coreCache()->get("template.routes.sirsoft-admin_basic.v{$activateVersion}") !== null,
|
||||
'활성화 후 캐시가 존재해야 합니다.'
|
||||
);
|
||||
|
||||
@@ -152,7 +167,7 @@ class TemplateCacheManagementTest extends TestCase
|
||||
|
||||
// 캐시가 존재하는지 확인 (버전 포함 키)
|
||||
$this->assertTrue(
|
||||
app(CacheInterface::class)->get("template.routes.sirsoft-admin_basic.v{$firstVersion}") !== null,
|
||||
$this->coreCache()->get("template.routes.sirsoft-admin_basic.v{$firstVersion}") !== null,
|
||||
'첫 번째 템플릿 활성화 후 캐시가 존재해야 합니다.'
|
||||
);
|
||||
|
||||
@@ -165,7 +180,7 @@ class TemplateCacheManagementTest extends TestCase
|
||||
// deactivate → activate 시 캐시 버전이 증가하므로 새 버전으로 확인
|
||||
$newVersion = ClearsTemplateCaches::getExtensionCacheVersion();
|
||||
$this->assertTrue(
|
||||
app(CacheInterface::class)->get("template.routes.sirsoft-admin_basic.v{$newVersion}") !== null,
|
||||
$this->coreCache()->get("template.routes.sirsoft-admin_basic.v{$newVersion}") !== null,
|
||||
'재활성화 후 캐시가 다시 생성되어야 합니다.'
|
||||
);
|
||||
}
|
||||
@@ -185,7 +200,7 @@ class TemplateCacheManagementTest extends TestCase
|
||||
|
||||
// 캐시가 존재하는지 확인 (버전 포함 키)
|
||||
$this->assertTrue(
|
||||
app(CacheInterface::class)->get("template.routes.sirsoft-admin_basic.v{$activateVersion}") !== null,
|
||||
$this->coreCache()->get("template.routes.sirsoft-admin_basic.v{$activateVersion}") !== null,
|
||||
'활성화 후 캐시가 존재해야 합니다.'
|
||||
);
|
||||
|
||||
@@ -223,14 +238,14 @@ class TemplateCacheManagementTest extends TestCase
|
||||
|
||||
// 설치 시에는 캐시가 생성되지 않아야 함 (비활성 상태로 설치됨)
|
||||
$this->assertFalse(
|
||||
app(CacheInterface::class)->get("template.routes.sirsoft-admin_basic.v{$cacheVersion}") !== null,
|
||||
$this->coreCache()->get("template.routes.sirsoft-admin_basic.v{$cacheVersion}") !== null,
|
||||
'설치 시에는 routes 캐시가 생성되지 않아야 합니다 (비활성 상태).'
|
||||
);
|
||||
|
||||
$supportedLocales = config('app.supported_locales', ['ko', 'en']);
|
||||
foreach ($supportedLocales as $locale) {
|
||||
$this->assertFalse(
|
||||
app(CacheInterface::class)->get("template.language.sirsoft-admin_basic.{$locale}.v{$cacheVersion}") !== null,
|
||||
$this->coreCache()->get("template.language.sirsoft-admin_basic.{$locale}.v{$cacheVersion}") !== null,
|
||||
"설치 시에는 {$locale} 다국어 캐시가 생성되지 않아야 합니다."
|
||||
);
|
||||
}
|
||||
@@ -263,7 +278,7 @@ class TemplateCacheManagementTest extends TestCase
|
||||
foreach ($layouts as $layout) {
|
||||
$cacheKey = "g7:core:template.{$template->id}.layout.{$layout->name}";
|
||||
$this->assertFalse(
|
||||
app(CacheInterface::class)->get($cacheKey) !== null,
|
||||
$this->coreCache()->get($cacheKey) !== null,
|
||||
"비활성화 후 {$layout->name} 내부 레이아웃 캐시가 삭제되어야 합니다."
|
||||
);
|
||||
}
|
||||
|
||||
@@ -137,6 +137,48 @@ class TemplateLayoutRegistrationTest extends TestCase
|
||||
$this->assertEquals($templateLayoutsBefore, $templateLayoutsAfterDeactivate, '비활성화 시 템플릿 자체 레이아웃 수는 변경되지 않아야 합니다.');
|
||||
}
|
||||
|
||||
/**
|
||||
* (S4'') / 카테고리 D — errors/* layout_name 식별자 통일 회귀
|
||||
*
|
||||
* errors/{code}.json 파일의 layout_name 필드가 다른 카테고리(auth/login,
|
||||
* board/show, mypage/profile) 와 동일하게 디렉토리 접두사를 포함한 "errors/{code}"
|
||||
* 형식이어야 하며, DB 에도 동일 형식으로 시드되어야 routes.json 의
|
||||
* `"layout": "errors/404"` 참조와 정합한다. 이전 결함: layout_name="404" 만
|
||||
* 저장되어 라우트 35/36 (404/403 페이지) 가 Layout not found 로 떨어졌음.
|
||||
*/
|
||||
public function test_install_template_seeds_errors_layouts_with_directory_prefix(): void
|
||||
{
|
||||
// Act
|
||||
$result = $this->templateManager->installTemplate('sirsoft-admin_basic');
|
||||
$this->assertTrue($result);
|
||||
|
||||
$template = Template::where('identifier', 'sirsoft-admin_basic')->first();
|
||||
$this->assertNotNull($template);
|
||||
|
||||
// Assert — errors/{code} 형식으로 시드되어야 함
|
||||
foreach (['errors/401', 'errors/403', 'errors/404', 'errors/500', 'errors/503', 'errors/maintenance'] as $expectedName) {
|
||||
$layout = TemplateLayout::where('template_id', $template->id)
|
||||
->where('name', $expectedName)
|
||||
->first();
|
||||
$this->assertNotNull(
|
||||
$layout,
|
||||
"{$expectedName} 레이아웃이 errors/ 접두사를 포함한 식별자로 시드되어야 합니다."
|
||||
);
|
||||
$this->assertSame($expectedName, $layout->content['layout_name'] ?? null);
|
||||
}
|
||||
|
||||
// Assert — 접두사 없는 "404"/"403" 등은 시드되지 않아야 함
|
||||
foreach (['401', '403', '404', '500', '503', 'maintenance'] as $bareName) {
|
||||
$stale = TemplateLayout::where('template_id', $template->id)
|
||||
->where('name', $bareName)
|
||||
->first();
|
||||
$this->assertNull(
|
||||
$stale,
|
||||
"디렉토리 접두사 없는 {$bareName} 식별자는 시드되지 않아야 합니다 (다른 카테고리 비대칭 회귀)."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 멱등성 테스트: 같은 템플릿 2번 설치 시 레이아웃 중복 생성 방지
|
||||
*/
|
||||
|
||||
@@ -564,9 +564,9 @@ class TemplateSystemIntegrationTest extends TestCase
|
||||
'dependencies' => $dependencies,
|
||||
'error_config' => [
|
||||
'layouts' => [
|
||||
'404' => 'error_404',
|
||||
'403' => 'error_403',
|
||||
'500' => 'error_500',
|
||||
'404' => 'errors/error_404',
|
||||
'403' => 'errors/error_403',
|
||||
'500' => 'errors/error_500',
|
||||
],
|
||||
],
|
||||
];
|
||||
@@ -631,9 +631,9 @@ class TemplateSystemIntegrationTest extends TestCase
|
||||
],
|
||||
'error_config' => [
|
||||
'layouts' => [
|
||||
'404' => 'error_404',
|
||||
'403' => 'error_403',
|
||||
'500' => 'error_500',
|
||||
'404' => 'errors/error_404',
|
||||
'403' => 'errors/error_403',
|
||||
'500' => 'errors/error_500',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
@@ -0,0 +1,556 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Upgrade;
|
||||
|
||||
use App\Enums\LayoutExtensionType;
|
||||
use App\Enums\LayoutSourceType;
|
||||
use App\Extension\UpgradeContext;
|
||||
use App\Models\LayoutExtension;
|
||||
use App\Models\Template;
|
||||
use App\Models\TemplateLayout;
|
||||
use App\Upgrades\Data\V7_0_0\Migrations\CleanupMisregisteredLayoutExtensions;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* beta.8 오등록 레이아웃 확장 정리 업그레이드 스텝 회귀 가드.
|
||||
*
|
||||
* beta.8 이전 refreshLayoutExtensions 가 모듈/플러그인 확장을 모든 활성 템플릿에
|
||||
* 무차별 등록하여, admin 레이아웃 대상 확장이 user 템플릿에(또는 그 반대로)
|
||||
* 잘못 등록된 행을 정리하는지 검증한다.
|
||||
*
|
||||
* axis 전수:
|
||||
* 1. overlay — 대상 레이아웃이 그 템플릿에 존재 → 보존
|
||||
* 2. overlay — 대상 레이아웃이 그 템플릿에 부재 → soft delete
|
||||
* 3. extension_point — 확장점이 그 템플릿 레이아웃에 정의됨 → 보존
|
||||
* 4. extension_point — 확장점 정의 부재 → soft delete
|
||||
* 5. 이미 soft delete 된 행 → 재처리 안 함 (멱등)
|
||||
* 6. 두 번 실행 → 동일 결과 (멱등)
|
||||
*/
|
||||
class Beta8CleanupMisregisteredLayoutExtensionsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private Template $adminTemplate;
|
||||
|
||||
private Template $userTemplate;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
require_once base_path('upgrades/data/7.0.0/migrations/01_CleanupMisregisteredLayoutExtensions.php');
|
||||
|
||||
$this->adminTemplate = Template::factory()->create(['type' => 'admin']);
|
||||
$this->userTemplate = Template::factory()->create(['type' => 'user']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 업그레이드 컨텍스트 생성 (beta.7 → beta.8 transition).
|
||||
*/
|
||||
private function context(): UpgradeContext
|
||||
{
|
||||
return new UpgradeContext('7.0.0-beta.7', '7.0.0', '7.0.0');
|
||||
}
|
||||
|
||||
/**
|
||||
* 마이그레이션 1회 실행.
|
||||
*/
|
||||
private function runMigration(): void
|
||||
{
|
||||
(new CleanupMisregisteredLayoutExtensions)->run($this->context());
|
||||
}
|
||||
|
||||
/**
|
||||
* overlay — 대상 레이아웃이 존재하는 템플릿의 확장은 보존
|
||||
*/
|
||||
public function test_overlay_with_existing_target_layout_is_preserved(): void
|
||||
{
|
||||
TemplateLayout::factory()->create([
|
||||
'template_id' => $this->adminTemplate->id,
|
||||
'name' => 'admin_user_detail',
|
||||
]);
|
||||
|
||||
$ext = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->adminTemplate->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'admin_user_detail',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-board',
|
||||
]);
|
||||
|
||||
$this->runMigration();
|
||||
|
||||
$this->assertNotSoftDeleted('template_layout_extensions', ['id' => $ext->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* overlay — 대상 레이아웃이 없는 템플릿의 확장은, 동일 4키가 다른 템플릿엔
|
||||
* 적용 가능할 때만 soft delete (cross-template 판정).
|
||||
*
|
||||
* cross-template 전환 후 의미 변화: 단순 "이 템플릿에 부재 → 삭제" 가 아니라
|
||||
* "이 템플릿엔 부재 ∧ 동일 확장이 다른 템플릿엔 적용 가능 = 오등록" 일 때만 삭제한다.
|
||||
* admin 템플릿엔 admin_user_detail 레이아웃이 존재하므로, user 행은 오등록으로 판정.
|
||||
*/
|
||||
public function test_overlay_without_target_layout_is_soft_deleted(): void
|
||||
{
|
||||
// admin 템플릿엔 대상 레이아웃 존재 + admin overlay 행 (= "다른 템플릿엔 적용 가능")
|
||||
TemplateLayout::factory()->create([
|
||||
'template_id' => $this->adminTemplate->id,
|
||||
'name' => 'admin_user_detail',
|
||||
]);
|
||||
$valid = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->adminTemplate->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'admin_user_detail',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-board',
|
||||
]);
|
||||
|
||||
// user 템플릿에는 admin_user_detail 레이아웃이 없음 → 오등록
|
||||
$orphan = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->userTemplate->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'admin_user_detail',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-board',
|
||||
]);
|
||||
|
||||
$this->runMigration();
|
||||
|
||||
$this->assertNotSoftDeleted('template_layout_extensions', ['id' => $valid->id]);
|
||||
$this->assertSoftDeleted('template_layout_extensions', ['id' => $orphan->id]);
|
||||
// soft delete 시 is_active=0 동반 (모순 상태 방지)
|
||||
$this->assertDatabaseHas('template_layout_extensions', [
|
||||
'id' => $orphan->id,
|
||||
'is_active' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* extension_point — 확장점이 정의된 템플릿의 확장은 보존
|
||||
*/
|
||||
public function test_extension_point_with_definition_is_preserved(): void
|
||||
{
|
||||
TemplateLayout::factory()->create([
|
||||
'template_id' => $this->adminTemplate->id,
|
||||
'name' => 'dashboard',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'dashboard',
|
||||
'components' => [
|
||||
[
|
||||
'type' => 'basic',
|
||||
'name' => 'Div',
|
||||
'children' => [
|
||||
['type' => 'extension_point', 'name' => 'admin.dashboard.widgets'],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$ext = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->adminTemplate->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'admin.dashboard.widgets',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-board',
|
||||
]);
|
||||
|
||||
$this->runMigration();
|
||||
|
||||
$this->assertNotSoftDeleted('template_layout_extensions', ['id' => $ext->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* extension_point — 확장점 정의가 없는 템플릿의 확장은, 동일 확장점이 다른
|
||||
* 템플릿엔 정의돼 있을 때만 soft delete (cross-template 판정).
|
||||
*
|
||||
* admin 템플릿엔 admin.dashboard.widgets 확장점이 정의돼 있으므로,
|
||||
* 확장점이 없는 user 행은 오등록으로 판정되어 삭제된다.
|
||||
*/
|
||||
public function test_extension_point_without_definition_is_soft_deleted(): void
|
||||
{
|
||||
// admin 템플릿엔 확장점 정의 + admin 확장점 행 (= "다른 템플릿엔 적용 가능")
|
||||
TemplateLayout::factory()->create([
|
||||
'template_id' => $this->adminTemplate->id,
|
||||
'name' => 'dashboard',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'dashboard',
|
||||
'components' => [
|
||||
[
|
||||
'type' => 'basic',
|
||||
'name' => 'Div',
|
||||
'children' => [
|
||||
['type' => 'extension_point', 'name' => 'admin.dashboard.widgets'],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
$valid = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->adminTemplate->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'admin.dashboard.widgets',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-board',
|
||||
]);
|
||||
|
||||
// user 템플릿엔 확장점 정의 없음 → 오등록
|
||||
TemplateLayout::factory()->create([
|
||||
'template_id' => $this->userTemplate->id,
|
||||
'name' => 'home',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'home',
|
||||
'components' => [['type' => 'basic', 'name' => 'Div']],
|
||||
],
|
||||
]);
|
||||
|
||||
$orphan = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->userTemplate->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'admin.dashboard.widgets',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-board',
|
||||
]);
|
||||
|
||||
$this->runMigration();
|
||||
|
||||
$this->assertNotSoftDeleted('template_layout_extensions', ['id' => $valid->id]);
|
||||
$this->assertSoftDeleted('template_layout_extensions', ['id' => $orphan->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 이미 soft delete 된 행은 재처리 대상이 아님
|
||||
*/
|
||||
public function test_already_soft_deleted_rows_are_not_reprocessed(): void
|
||||
{
|
||||
$ext = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->userTemplate->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'admin_user_detail',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-board',
|
||||
]);
|
||||
$ext->delete();
|
||||
$deletedAt = $ext->fresh()->deleted_at;
|
||||
|
||||
$this->runMigration();
|
||||
|
||||
// deleted_at 이 변경되지 않음 (재처리 안 함)
|
||||
$this->assertEquals(
|
||||
$deletedAt->toDateTimeString(),
|
||||
$ext->fresh()->deleted_at->toDateTimeString()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 멱등성 — 두 번 실행해도 결과 동일
|
||||
*/
|
||||
public function test_migration_is_idempotent(): void
|
||||
{
|
||||
TemplateLayout::factory()->create([
|
||||
'template_id' => $this->adminTemplate->id,
|
||||
'name' => 'admin_user_detail',
|
||||
]);
|
||||
|
||||
$valid = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->adminTemplate->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'admin_user_detail',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-board',
|
||||
]);
|
||||
$orphan = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->userTemplate->id,
|
||||
'extension_type' => LayoutExtensionType::Overlay,
|
||||
'target_name' => 'admin_user_detail',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-board',
|
||||
]);
|
||||
|
||||
$this->runMigration();
|
||||
$this->runMigration();
|
||||
|
||||
$this->assertNotSoftDeleted('template_layout_extensions', ['id' => $valid->id]);
|
||||
$this->assertSoftDeleted('template_layout_extensions', ['id' => $orphan->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 원격 전멸 재현 (가장 가혹) — admin_dashboard 호스트 레이아웃이 *모든* 템플릿에서
|
||||
* 구버전(슬롯 부재)이고, 그 확장점이 admin·user 양쪽에 등록된 상태.
|
||||
*
|
||||
* 이것이 원격에서 admin_dashboard_commerce/community/quick_menu 가 전멸한 실제 상황이다
|
||||
* (cleanup 실행 시점 16:42:42 < admin_dashboard 레이아웃 갱신 16:42:56 — 스텝 시점엔
|
||||
* 호스트가 아직 구버전). 어느 템플릿에서도 슬롯이 안 박혀 호스트명을 content 로 알 수
|
||||
* 없으므로, 호스트명 식별에 의존하면 admin 정상 행도 죽는다.
|
||||
*
|
||||
* 무결 원리: "모든 등록 템플릿에서 부재(전부 stale)" 면 그건 오등록이 아니라 content
|
||||
* 가 아직 stale 인 것이므로 **전부 보존**해야 한다. 한쪽만 부재일 때만 그 한쪽이 오등록.
|
||||
*
|
||||
* 올바른 결과: admin·user 4건(board×{admin,user} + ecommerce×{admin,user}) 전부 보존.
|
||||
*/
|
||||
public function test_all_templates_stale_host_preserves_every_registration(): void
|
||||
{
|
||||
// admin·user 양쪽에 admin_dashboard 레이아웃이 있으나 모두 구버전(슬롯 없음)
|
||||
foreach ([$this->adminTemplate->id, $this->userTemplate->id] as $tid) {
|
||||
TemplateLayout::factory()->create([
|
||||
'template_id' => $tid,
|
||||
'name' => 'admin_dashboard',
|
||||
'content' => [
|
||||
'version' => '0.9.0',
|
||||
'layout_name' => 'admin_dashboard',
|
||||
'components' => [['type' => 'basic', 'name' => 'Div']],
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
// 두 source(board, ecommerce)가 각각 admin·user 양쪽에 quick_menu 확장점 등록 (원격 동일)
|
||||
$ids = [];
|
||||
foreach (['sirsoft-board', 'sirsoft-ecommerce'] as $source) {
|
||||
foreach ([$this->adminTemplate->id, $this->userTemplate->id] as $tid) {
|
||||
$ids[] = LayoutExtension::factory()->create([
|
||||
'template_id' => $tid,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'admin_dashboard_quick_menu',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => $source,
|
||||
])->id;
|
||||
}
|
||||
}
|
||||
|
||||
$this->runMigration();
|
||||
|
||||
// 전부 stale → 4건 모두 보존 (전멸 차단)
|
||||
foreach ($ids as $id) {
|
||||
$this->assertNotSoftDeleted('template_layout_extensions', ['id' => $id]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 원격 재현 (#대시보드 미주입) 핵심 — admin 호스트 레이아웃(admin_dashboard)의 content 가
|
||||
* 구버전(슬롯 부재)이지만, 호스트 레이아웃 *행 자체*는 admin 에 존재하는 상태.
|
||||
*
|
||||
* 코어 업데이트 흐름에서 cleanup 이 도는 시점엔 호스트 레이아웃 content 가 아직
|
||||
* 구버전이라 슬롯이 안 박혔다. content 슬롯만으로 판정하면 admin 정상 행이 "부재" 로
|
||||
* 오판되어 삭제된다(관리자 대시보드 위젯 소실 회귀). 그러나 admin_dashboard 레이아웃
|
||||
* 행은 admin 에 존재하므로(content 만 구버전), 호스트 레이아웃 존재 신호로 보존해야 한다.
|
||||
*
|
||||
* user 에는 admin_dashboard 호스트 레이아웃 자체가 없으므로 user 행은 오등록 → 삭제.
|
||||
*
|
||||
* 호스트명은 "어느 템플릿이든 신버전이라 슬롯이 박힌 레이아웃" 에서 식별한다(여기선
|
||||
* 별도 admin2 템플릿이 신버전 admin_dashboard 를 가져 호스트명을 제공).
|
||||
*
|
||||
* 올바른 결과: admin 행 보존, user 행 삭제.
|
||||
*/
|
||||
public function test_admin_host_stale_content_but_layout_row_exists_preserves_admin(): void
|
||||
{
|
||||
// 신버전 admin 템플릿 — admin_dashboard 에 슬롯이 박혀 호스트명을 식별 가능하게 함
|
||||
$admin2 = Template::factory()->create(['type' => 'admin']);
|
||||
TemplateLayout::factory()->create([
|
||||
'template_id' => $admin2->id,
|
||||
'name' => 'admin_dashboard',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'admin_dashboard',
|
||||
'components' => [
|
||||
['type' => 'extension_point', 'name' => 'admin_dashboard_quick_menu'],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
// 대상 admin 템플릿: admin_dashboard 행은 존재하나 content 는 구버전(슬롯 부재)
|
||||
TemplateLayout::factory()->create([
|
||||
'template_id' => $this->adminTemplate->id,
|
||||
'name' => 'admin_dashboard',
|
||||
'content' => [
|
||||
'version' => '0.9.0',
|
||||
'layout_name' => 'admin_dashboard',
|
||||
'components' => [['type' => 'basic', 'name' => 'Div']],
|
||||
],
|
||||
]);
|
||||
// user 템플릿엔 admin_dashboard 호스트 레이아웃 자체가 없음
|
||||
|
||||
$adminExt = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->adminTemplate->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'admin_dashboard_quick_menu',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-board',
|
||||
]);
|
||||
$userExt = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->userTemplate->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'admin_dashboard_quick_menu',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-board',
|
||||
]);
|
||||
|
||||
$this->runMigration();
|
||||
|
||||
// admin 정상 행 보존 (구버전 content 라도 호스트 레이아웃 행이 존재 → 보존)
|
||||
$this->assertNotSoftDeleted('template_layout_extensions', ['id' => $adminExt->id]);
|
||||
// user 행은 호스트 레이아웃 부재 → 오등록 삭제
|
||||
$this->assertSoftDeleted('template_layout_extensions', ['id' => $userExt->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 원격 재현 (#대시보드 미주입) — 스텝 시점에 확장 레이아웃이 구버전이고,
|
||||
* 대상 확장점이 admin 템플릿 전용 레이아웃(admin_dashboard)에만 정의되는 케이스.
|
||||
*
|
||||
* 스텝 실행 시점:
|
||||
* - admin 템플릿: admin_dashboard 레이아웃 존재하나 content 는 구버전(슬롯 부재)
|
||||
* - user 템플릿: admin_dashboard 레이아웃 자체가 없음
|
||||
* - 양쪽에 admin_dashboard_commerce extension_point 행 등록됨
|
||||
*
|
||||
* 올바른 결과: admin 행은 admin 전용 확장의 정상 등록이므로 **보존**되어야 한다.
|
||||
* (구버전이라 슬롯 판정이 불가하면, 최소한 정상 확장을 죽여선 안 됨)
|
||||
*/
|
||||
public function test_admin_only_extension_point_preserved_when_step_runs_before_layout_sync(): void
|
||||
{
|
||||
// admin 템플릿: admin_dashboard 레이아웃 존재하나 구버전(슬롯 부재)
|
||||
TemplateLayout::factory()->create([
|
||||
'template_id' => $this->adminTemplate->id,
|
||||
'name' => 'admin_dashboard',
|
||||
'content' => [
|
||||
'version' => '0.9.0',
|
||||
'layout_name' => 'admin_dashboard',
|
||||
'components' => [['type' => 'basic', 'name' => 'Div']], // 슬롯 없음
|
||||
],
|
||||
]);
|
||||
// user 템플릿엔 admin_dashboard 레이아웃 자체가 없음 (생성 안 함)
|
||||
|
||||
$adminExt = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->adminTemplate->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'admin_dashboard_commerce',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-ecommerce',
|
||||
]);
|
||||
$userExt = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->userTemplate->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'admin_dashboard_commerce',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-ecommerce',
|
||||
]);
|
||||
|
||||
$this->runMigration();
|
||||
|
||||
// admin 정상 행은 반드시 보존 (이게 원격에서 깨진 회귀)
|
||||
$this->assertNotSoftDeleted('template_layout_extensions', ['id' => $adminExt->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* cross-template 회귀 가드 핵심 — 모든 템플릿의 레이아웃이 stale(슬롯 미포함)이면
|
||||
* 정상 확장도 전부 보존한다.
|
||||
*
|
||||
* 결함 재현: 코어 업데이트 흐름에서 cleanup 이 레이아웃 content 갱신 *전* 시점에
|
||||
* 돌면, admin·user 양쪽 레이아웃이 아직 슬롯을 갖지 못해 모든 행이 "대상 부재" 로
|
||||
* 오판된다. 기존(절대 부재) 로직이면 정상 확장(commerce) 이 admin·user 양쪽에서
|
||||
* 모두 soft delete 되어 대시보드 UI 가 사라진다.
|
||||
*
|
||||
* cross-template 로직: "이 템플릿엔 부재 ∧ 동일 4키가 *다른* 템플릿엔 적용 가능"
|
||||
* 일 때만 삭제하므로, 어느 템플릿에서도 적용 불가(전부 stale)면 전부 보존 → 전멸 차단.
|
||||
*/
|
||||
public function test_cleanup_preserves_valid_extension_when_all_layouts_are_stale(): void
|
||||
{
|
||||
// admin·user 양쪽 레이아웃 모두 확장점 슬롯 미포함 (stale 재현)
|
||||
TemplateLayout::factory()->create([
|
||||
'template_id' => $this->adminTemplate->id,
|
||||
'name' => 'admin_dashboard',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'admin_dashboard',
|
||||
'components' => [['type' => 'basic', 'name' => 'Div']],
|
||||
],
|
||||
]);
|
||||
TemplateLayout::factory()->create([
|
||||
'template_id' => $this->userTemplate->id,
|
||||
'name' => 'admin_dashboard',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'admin_dashboard',
|
||||
'components' => [['type' => 'basic', 'name' => 'Div']],
|
||||
],
|
||||
]);
|
||||
|
||||
// 동일 확장점 commerce 가 admin·user 양쪽에 등록됨
|
||||
$adminExt = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->adminTemplate->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'admin_dashboard_commerce',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-ecommerce',
|
||||
]);
|
||||
$userExt = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->userTemplate->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'admin_dashboard_commerce',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-ecommerce',
|
||||
]);
|
||||
|
||||
$this->runMigration();
|
||||
|
||||
// 전부 stale → 둘 다 보존 (정상 확장 전멸 차단 — 이 가드가 버그 ① 핵심)
|
||||
$this->assertNotSoftDeleted('template_layout_extensions', ['id' => $adminExt->id]);
|
||||
$this->assertNotSoftDeleted('template_layout_extensions', ['id' => $userExt->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* cross-template — admin 레이아웃엔 확장점이 정의됐고 user 엔 없을 때, user 행만
|
||||
* soft delete(+is_active=0) 되고 admin 행은 보존된다 (오등록 정확 제거).
|
||||
*/
|
||||
public function test_cleanup_removes_only_misregistered_when_layout_current(): void
|
||||
{
|
||||
// admin 레이아웃엔 commerce 확장점 정의 (= current/신버전)
|
||||
TemplateLayout::factory()->create([
|
||||
'template_id' => $this->adminTemplate->id,
|
||||
'name' => 'admin_dashboard',
|
||||
'content' => [
|
||||
'version' => '1.0.0',
|
||||
'layout_name' => 'admin_dashboard',
|
||||
'components' => [
|
||||
[
|
||||
'type' => 'basic',
|
||||
'name' => 'Div',
|
||||
'children' => [
|
||||
['type' => 'extension_point', 'name' => 'admin_dashboard_commerce'],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
// user 템플릿엔 admin_dashboard 레이아웃 자체가 없음 (admin_dashboard 는 admin 전용)
|
||||
|
||||
$adminExt = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->adminTemplate->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'admin_dashboard_commerce',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-ecommerce',
|
||||
]);
|
||||
$userExt = LayoutExtension::factory()->create([
|
||||
'template_id' => $this->userTemplate->id,
|
||||
'extension_type' => LayoutExtensionType::ExtensionPoint,
|
||||
'target_name' => 'admin_dashboard_commerce',
|
||||
'source_type' => LayoutSourceType::Module,
|
||||
'source_identifier' => 'sirsoft-ecommerce',
|
||||
]);
|
||||
|
||||
$this->runMigration();
|
||||
|
||||
// admin 보존(호스트 admin_dashboard 존재), user 만 soft delete + is_active=0
|
||||
// (user 엔 admin_dashboard 호스트 레이아웃 자체가 없으므로 오등록 확정)
|
||||
$this->assertNotSoftDeleted('template_layout_extensions', ['id' => $adminExt->id]);
|
||||
$this->assertSoftDeleted('template_layout_extensions', ['id' => $userExt->id]);
|
||||
$this->assertDatabaseHas('template_layout_extensions', [
|
||||
'id' => $userExt->id,
|
||||
'is_active' => 0,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Upgrades;
|
||||
|
||||
use App\Extension\UpgradeContext;
|
||||
use App\Upgrades\Data\V7_0_0\Migrations\MigrateCoreFrontendLangDirectory;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* `MigrateCoreFrontendLangDirectory` 회귀 가드.
|
||||
*
|
||||
* 본 마이그레이션은 `resources/js/core/lang/{ko,en}.json` 을 `lang/{ko,en}.json` 으로
|
||||
* 이동하고 빈 레거시 디렉토리를 정리한다. base_path() 기반이므로 테스트에서
|
||||
* `app()->setBasePath()` 로 sandbox 루트를 일시 교체한다.
|
||||
*
|
||||
* 검증 시나리오:
|
||||
* - 레거시 파일 양쪽 존재 + 신 위치 부재 → 양쪽 이동 + 디렉토리 정리
|
||||
* - 레거시 + 신 위치 모두 존재 → 신 위치 보존, 레거시 정리만
|
||||
* - 부분 마이그레이션 (ko 만) → 안전 처리
|
||||
* - 레거시 디렉토리 부재 → 즉시 skip (에러 없음)
|
||||
* - 두 번 실행 → idempotent (동일 결과)
|
||||
*/
|
||||
class MigrateCoreFrontendLangDirectoryTest extends TestCase
|
||||
{
|
||||
private MigrateCoreFrontendLangDirectory $migration;
|
||||
|
||||
private UpgradeContext $context;
|
||||
|
||||
private string $sandboxBasePath;
|
||||
|
||||
private string $originalBasePath;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
require_once base_path('upgrades/data/7.0.0/migrations/02_MigrateCoreFrontendLangDirectory.php');
|
||||
|
||||
$this->migration = new MigrateCoreFrontendLangDirectory;
|
||||
$this->context = new UpgradeContext(
|
||||
fromVersion: '7.0.0-beta.7',
|
||||
toVersion: '7.0.0',
|
||||
currentStep: '7.0.0',
|
||||
);
|
||||
|
||||
$this->sandboxBasePath = storage_path('framework/testing/core-lang-migration-'.uniqid());
|
||||
File::ensureDirectoryExists($this->sandboxBasePath);
|
||||
File::ensureDirectoryExists($this->sandboxBasePath.'/lang');
|
||||
|
||||
$this->originalBasePath = base_path();
|
||||
app()->setBasePath($this->sandboxBasePath);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
app()->setBasePath($this->originalBasePath);
|
||||
|
||||
if (File::isDirectory($this->sandboxBasePath)) {
|
||||
File::deleteDirectory($this->sandboxBasePath);
|
||||
}
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_name_returns_identifier(): void
|
||||
{
|
||||
$this->assertSame('MigrateCoreFrontendLangDirectory', $this->migration->name());
|
||||
}
|
||||
|
||||
public function test_skips_when_legacy_directory_absent(): void
|
||||
{
|
||||
// 레거시 디렉토리 미생성 — 즉시 return
|
||||
$this->migration->run($this->context);
|
||||
|
||||
// 신 위치도 그대로 (생성/삭제 없음)
|
||||
$this->assertFalse(file_exists($this->sandboxBasePath.'/lang/ko.json'));
|
||||
}
|
||||
|
||||
public function test_moves_both_legacy_files_to_new_location(): void
|
||||
{
|
||||
$legacyDir = $this->sandboxBasePath.'/resources/js/core/lang';
|
||||
File::ensureDirectoryExists($legacyDir);
|
||||
file_put_contents($legacyDir.'/ko.json', '{"core":{"errors":{"x":"한글"}}}');
|
||||
file_put_contents($legacyDir.'/en.json', '{"core":{"errors":{"x":"English"}}}');
|
||||
|
||||
$this->migration->run($this->context);
|
||||
|
||||
$this->assertFileExists($this->sandboxBasePath.'/lang/ko.json');
|
||||
$this->assertFileExists($this->sandboxBasePath.'/lang/en.json');
|
||||
$this->assertSame('{"core":{"errors":{"x":"한글"}}}', file_get_contents($this->sandboxBasePath.'/lang/ko.json'));
|
||||
// 레거시 파일은 사라짐
|
||||
$this->assertFileDoesNotExist($legacyDir.'/ko.json');
|
||||
$this->assertFileDoesNotExist($legacyDir.'/en.json');
|
||||
// 빈 레거시 디렉토리도 정리
|
||||
$this->assertDirectoryDoesNotExist($legacyDir);
|
||||
}
|
||||
|
||||
public function test_preserves_new_location_when_already_migrated(): void
|
||||
{
|
||||
$legacyDir = $this->sandboxBasePath.'/resources/js/core/lang';
|
||||
File::ensureDirectoryExists($legacyDir);
|
||||
file_put_contents($legacyDir.'/ko.json', '{"core":{"errors":{"x":"OLD"}}}');
|
||||
// 신 위치에 이미 새 내용이 있음
|
||||
file_put_contents($this->sandboxBasePath.'/lang/ko.json', '{"core":{"errors":{"x":"NEW"}}}');
|
||||
|
||||
$this->migration->run($this->context);
|
||||
|
||||
// 신 위치 보존 (덮어쓰기 금지)
|
||||
$this->assertSame('{"core":{"errors":{"x":"NEW"}}}', file_get_contents($this->sandboxBasePath.'/lang/ko.json'));
|
||||
// 레거시는 정리됨
|
||||
$this->assertFileDoesNotExist($legacyDir.'/ko.json');
|
||||
}
|
||||
|
||||
public function test_handles_partial_ko_only_migration(): void
|
||||
{
|
||||
$legacyDir = $this->sandboxBasePath.'/resources/js/core/lang';
|
||||
File::ensureDirectoryExists($legacyDir);
|
||||
// ko 만 존재, en 부재
|
||||
file_put_contents($legacyDir.'/ko.json', '{"core":{"a":1}}');
|
||||
|
||||
$this->migration->run($this->context);
|
||||
|
||||
$this->assertFileExists($this->sandboxBasePath.'/lang/ko.json');
|
||||
$this->assertFileDoesNotExist($this->sandboxBasePath.'/lang/en.json');
|
||||
$this->assertDirectoryDoesNotExist($legacyDir);
|
||||
}
|
||||
|
||||
public function test_is_idempotent_on_repeated_execution(): void
|
||||
{
|
||||
$legacyDir = $this->sandboxBasePath.'/resources/js/core/lang';
|
||||
File::ensureDirectoryExists($legacyDir);
|
||||
file_put_contents($legacyDir.'/ko.json', '{"core":{"a":1}}');
|
||||
|
||||
$this->migration->run($this->context);
|
||||
// 두 번째 실행 — 레거시 부재 상태에서 안전하게 skip
|
||||
$this->migration->run($this->context);
|
||||
|
||||
$this->assertFileExists($this->sandboxBasePath.'/lang/ko.json');
|
||||
$this->assertSame('{"core":{"a":1}}', file_get_contents($this->sandboxBasePath.'/lang/ko.json'));
|
||||
}
|
||||
|
||||
public function test_preserves_legacy_directory_when_unrelated_files_remain(): void
|
||||
{
|
||||
$legacyDir = $this->sandboxBasePath.'/resources/js/core/lang';
|
||||
File::ensureDirectoryExists($legacyDir);
|
||||
file_put_contents($legacyDir.'/ko.json', '{"core":{"a":1}}');
|
||||
// 사용자가 추가한 무관한 파일
|
||||
file_put_contents($legacyDir.'/custom.json', '{"keep":true}');
|
||||
|
||||
$this->migration->run($this->context);
|
||||
|
||||
$this->assertFileExists($this->sandboxBasePath.'/lang/ko.json');
|
||||
$this->assertFileExists($legacyDir.'/custom.json');
|
||||
// 디렉토리는 무관 파일 때문에 보존됨
|
||||
$this->assertDirectoryExists($legacyDir);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Tests\Feature\View;
|
||||
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Models\Template;
|
||||
use App\Services\TemplateService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
@@ -117,7 +118,7 @@ class AdminBladeTemplateLoadingTest extends TestCase
|
||||
public function test_admin_blade_renders_without_any_template(): void
|
||||
{
|
||||
// Arrange: 모든 템플릿 비활성화
|
||||
Template::query()->update(['status' => \App\Enums\ExtensionStatus::Inactive->value]);
|
||||
Template::query()->update(['status' => ExtensionStatus::Inactive->value]);
|
||||
|
||||
// Act: admin view 렌더링
|
||||
$response = $this->get('/admin');
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\View;
|
||||
|
||||
use App\Http\View\Composers\TemplateComposer;
|
||||
use App\Models\Template;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\View\View;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* G7Config 활성 확장 메타 노출 검증
|
||||
*
|
||||
* TemplateComposer 가 window.G7Config.activeModules / activePlugins 로
|
||||
* 노출할 활성 모듈/플러그인 메타({identifier, display_name, version})를
|
||||
* 정확히 뷰에 전달하는지 검증한다.
|
||||
*
|
||||
* 기존 modules/plugins(설정 데이터) 키와 분리된 신규 키이므로
|
||||
* 비파괴적 보강을 보장한다.
|
||||
*/
|
||||
class TemplateComposerActiveExtensionMetaTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 같은 스위트의 GDPR 미들웨어 의존 테스트와 migrate:fresh 정합성을 맞추기 위해.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
#[Test]
|
||||
public function template_composer_emits_active_modules_meta_view_variable(): void
|
||||
{
|
||||
Template::factory()->create([
|
||||
'identifier' => 'sirsoft-admin_basic',
|
||||
'type' => 'admin',
|
||||
'status' => 'active',
|
||||
]);
|
||||
|
||||
$capturedActiveModules = null;
|
||||
$capturedActivePlugins = null;
|
||||
|
||||
$view = $this->mock(View::class);
|
||||
$view->shouldReceive('with')
|
||||
->withArgs(function ($key, $value = null) use (&$capturedActiveModules, &$capturedActivePlugins) {
|
||||
if ($key === 'activeModulesMeta') {
|
||||
$capturedActiveModules = $value;
|
||||
}
|
||||
if ($key === 'activePluginsMeta') {
|
||||
$capturedActivePlugins = $value;
|
||||
}
|
||||
|
||||
return true; // 모든 with() 호출 허용
|
||||
});
|
||||
|
||||
$composer = app(TemplateComposer::class);
|
||||
$composer->compose($view);
|
||||
|
||||
$this->assertIsArray($capturedActiveModules, 'activeModulesMeta 가 배열로 전달되어야 함');
|
||||
$this->assertIsArray($capturedActivePlugins, 'activePluginsMeta 가 배열로 전달되어야 함');
|
||||
|
||||
// 각 항목 shape 검증: identifier / display_name / version
|
||||
foreach ($capturedActiveModules as $module) {
|
||||
$this->assertIsArray($module);
|
||||
$this->assertArrayHasKey('identifier', $module);
|
||||
$this->assertArrayHasKey('display_name', $module);
|
||||
$this->assertArrayHasKey('version', $module);
|
||||
$this->assertIsString($module['identifier']);
|
||||
$this->assertIsString($module['version']);
|
||||
}
|
||||
foreach ($capturedActivePlugins as $plugin) {
|
||||
$this->assertIsArray($plugin);
|
||||
$this->assertArrayHasKey('identifier', $plugin);
|
||||
$this->assertArrayHasKey('display_name', $plugin);
|
||||
$this->assertArrayHasKey('version', $plugin);
|
||||
$this->assertIsString($plugin['identifier']);
|
||||
$this->assertIsString($plugin['version']);
|
||||
}
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function legacy_modules_and_plugins_keys_remain_present_for_backward_compat(): void
|
||||
{
|
||||
Template::factory()->create([
|
||||
'identifier' => 'sirsoft-admin_basic',
|
||||
'type' => 'admin',
|
||||
'status' => 'active',
|
||||
]);
|
||||
|
||||
$sawModulesKey = false;
|
||||
$sawPluginsKey = false;
|
||||
$sawModuleAssetsKey = false;
|
||||
$sawPluginAssetsKey = false;
|
||||
|
||||
$view = $this->mock(View::class);
|
||||
$view->shouldReceive('with')
|
||||
->withArgs(function ($key, $value = null) use (&$sawModulesKey, &$sawPluginsKey, &$sawModuleAssetsKey, &$sawPluginAssetsKey) {
|
||||
if ($key === 'moduleSettings') {
|
||||
$sawModulesKey = true;
|
||||
}
|
||||
if ($key === 'pluginSettings') {
|
||||
$sawPluginsKey = true;
|
||||
}
|
||||
if ($key === 'moduleAssets') {
|
||||
$sawModuleAssetsKey = true;
|
||||
}
|
||||
if ($key === 'pluginAssets') {
|
||||
$sawPluginAssetsKey = true;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
$composer = app(TemplateComposer::class);
|
||||
$composer->compose($view);
|
||||
|
||||
$this->assertTrue($sawModulesKey, '기존 moduleSettings 키 보존');
|
||||
$this->assertTrue($sawPluginsKey, '기존 pluginSettings 키 보존');
|
||||
$this->assertTrue($sawModuleAssetsKey, '기존 moduleAssets 키 보존');
|
||||
$this->assertTrue($sawPluginAssetsKey, '기존 pluginAssets 키 보존');
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,16 @@ class TemplateComposerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 같은 스위트의 GDPR 미들웨어 의존 테스트와 migrate:fresh 정합성을 맞추기 위해
|
||||
* GDPR 플러그인 마이그레이션을 일관 선언한다.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $requiredExtensions = [
|
||||
'plugins/sirsoft-gdpr',
|
||||
];
|
||||
|
||||
/**
|
||||
* TemplateComposer가 활성화된 템플릿 ID를 뷰에 전달하는지 테스트
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
<?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' => []],
|
||||
'error_config' => [
|
||||
'layouts' => [
|
||||
'404' => 'error_404',
|
||||
'403' => 'error_403',
|
||||
'500' => 'error_500',
|
||||
],
|
||||
],
|
||||
'externals' => $externals,
|
||||
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
|
||||
|
||||
File::put($this->fixtureTemplatePath.'/components.json', json_encode(['components' => []], JSON_PRETTY_PRINT));
|
||||
File::put($this->fixtureTemplatePath.'/routes.json', json_encode(['routes' => []], JSON_PRETTY_PRINT));
|
||||
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/error_404.json', $errorLayout);
|
||||
File::put($this->fixtureTemplatePath.'/layouts/errors/error_403.json', $errorLayout);
|
||||
File::put($this->fixtureTemplatePath.'/layouts/errors/error_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}].");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user