fix(core,engine): OFFSET 순회 중 필터 컬럼 변경으로 인한 처리 누락 수정

Laravel chunk/each 는 OFFSET 기반이라, 콜백이 행의 필터 소속을 바꾸면
(필터 컬럼을 채우거나 매칭 행을 삭제하면) 다음 조회가 그만큼 앞으로 밀려
미처리 행을 조용히 건너뛴다. 250건/청크 100 이면 정확히 100건이 남는다.
코어·번들 확장 전수 조사로 확정한 6곳을 chunkById(키셋 순회)로 통일했다.

브라우저 검수(28축)에서 계획에 없던 결함 12건이 드러나 같은 사슬에서
수정했다. 이 중 layout_strategy=keep 무효화와 수정 감지 실패 시 "수정 없음"
오보는 사용자 작업 소실에 직결된다.

재발 방지로 audit 룰을 추가했고, 수정 6곳을 원복해 red 6건 / 복원 후 green
0건으로 판별력을 검증했다.
This commit is contained in:
HeuJung committed 2026-07-31 21:50:45 +09:00
1 parent 1866f0d566
commit 1eedbbdda1
55 files changed
+2764 -198

No files matched your search

@@ -0,0 +1,213 @@
<?php
namespace Tests\Feature\Api\Admin;
use App\Enums\ExtensionOwnerType;
use App\Enums\PermissionType;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use App\Services\ModuleService;
use App\Services\PluginService;
use App\Services\TemplateService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* `check-modified-layouts` 및 확장 업데이트 응답의 계약 회귀 테스트.
*
* 배경(Chrome MCP 정밀 점검에서 실측):
* - 미존재 식별자에 대해 형제 엔드포인트(show/uninstall-info)는 404 를 주는데
* check-modified-layouts 만 200 + "수정된 레이아웃 없음" 을 반환했다. 오타·제거된
* 확장이 "수정 없음" 으로 조용히 통과해, 레이아웃 보존 판단을 그르친다.
* - 업데이트 성공 메시지가 치환 파라미터 없이 반환되어 `:module` / `:version`
* 플레이스홀더가 그대로 사용자에게 노출됐다.
*
* 컨트롤러 소스의 철자가 아니라 **실제 HTTP 응답**(상태코드·메시지 본문)으로 계약을
* 고정한다. 확장 서비스는 컨테이너에서 대역으로 바꿔 파일시스템/네트워크 의존을 제거한다.
*/
class CheckModifiedLayoutsContractTest extends TestCase
{
use RefreshDatabase;
private string $token;
/** 확장 종류별 검증 축: [서비스, 조회 메서드, URL 세그먼트, 업데이트 메서드, 치환 키] */
private const EXTENSIONS = [
['service' => ModuleService::class, 'lookup' => 'getModuleInfo', 'segment' => 'modules', 'update' => 'updateModule', 'name' => 'zz-audit-module'],
['service' => PluginService::class, 'lookup' => 'getPluginInfo', 'segment' => 'plugins', 'update' => 'updatePlugin', 'name' => 'zz-audit-plugin'],
['service' => TemplateService::class, 'lookup' => 'getTemplateInfo', 'segment' => 'templates', 'update' => 'performVersionUpdate', 'name' => 'zz-audit-template'],
];
protected function setUp(): void
{
parent::setUp();
$admin = $this->createAdminUser([
'core.modules.read', 'core.modules.install',
'core.plugins.read', 'core.plugins.install',
'core.templates.read', 'core.templates.install',
]);
$this->token = $admin->createToken('test-token')->plainTextToken;
}
/**
* admin 역할 + 지정 권한을 가진 사용자를 생성합니다.
*
* AdminMiddleware 가 hasRole('admin') 을 확인하므로 admin 역할 부여가 필수입니다.
*
* @param array<int, string> $permissions 부여할 권한 식별자 목록
* @return User 생성된 관리자
*/
private function createAdminUser(array $permissions): User
{
$user = User::factory()->create();
$permissionIds = [];
foreach ($permissions as $identifier) {
$permissionIds[] = Permission::firstOrCreate(
['identifier' => $identifier],
[
'name' => ['ko' => $identifier, 'en' => $identifier],
'description' => ['ko' => $identifier, 'en' => $identifier],
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => PermissionType::Admin,
]
)->id;
}
$testRole = Role::create([
'identifier' => 'admin_test_'.uniqid(),
'name' => ['ko' => '테스트 관리자', 'en' => 'Test Administrator'],
'description' => ['ko' => '테스트 관리자', 'en' => 'Test Administrator'],
'is_active' => true,
]);
$testRole->permissions()->sync($permissionIds);
$adminRole = Role::firstOrCreate(
['identifier' => 'admin'],
[
'name' => ['ko' => '관리자', 'en' => 'Administrator'],
'description' => ['ko' => '시스템 관리자', 'en' => 'System Administrator'],
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'is_active' => true,
]
);
foreach ([$adminRole->id, $testRole->id] as $roleId) {
$user->roles()->attach($roleId, ['assigned_at' => now(), 'assigned_by' => null]);
}
return $user->fresh();
}
/**
* 인증 헤더가 붙은 요청 헬퍼.
*/
private function authRequest(): static
{
return $this->withHeaders([
'Authorization' => 'Bearer '.$this->token,
'Accept' => 'application/json',
]);
}
/**
* 미존재 식별자는 200 "수정 없음" 이 아니라 404 여야 한다 (D4).
*/
public function test_check_modified_layouts_returns_404_for_missing_identifier(): void
{
foreach (self::EXTENSIONS as $ext) {
$this->mock($ext['service'], function ($mock) use ($ext) {
$mock->shouldReceive($ext['lookup'])->andReturn(null);
$mock->shouldNotReceive('checkModifiedLayouts');
});
$response = $this->authRequest()
->getJson("/api/admin/{$ext['segment']}/{$ext['name']}/check-modified-layouts");
$response->assertStatus(404);
$this->assertFalse(
$response->json('success'),
"{$ext['segment']}: 미존재 식별자가 성공 응답으로 통과했습니다."
);
$this->assertStringNotContainsString(
'modified',
(string) $response->json('message'),
"{$ext['segment']}: 미존재인데 수정 감지 결과 메시지가 반환되었습니다."
);
}
}
/**
* 존재하는 식별자는 종전대로 200 + 감지 결과를 반환한다 (비회귀).
*/
public function test_check_modified_layouts_returns_200_for_existing_identifier(): void
{
foreach (self::EXTENSIONS as $ext) {
$this->mock($ext['service'], function ($mock) use ($ext) {
$mock->shouldReceive($ext['lookup'])->andReturn(['identifier' => $ext['name']]);
$mock->shouldReceive('checkModifiedLayouts')->andReturn([
'has_modified_layouts' => true,
'modified_count' => 2,
'modified_layouts' => [
['name' => 'a', 'size_diff' => 10],
['name' => 'b', 'size_diff' => -4],
],
]);
});
$response = $this->authRequest()
->getJson("/api/admin/{$ext['segment']}/{$ext['name']}/check-modified-layouts");
$response->assertStatus(200);
$this->assertSame(2, $response->json('data.modified_count'), $ext['segment']);
}
}
/**
* 업데이트 성공 메시지에 식별자·버전이 실제로 채워져야 한다 (D7).
*/
public function test_update_success_message_has_substituted_placeholders(): void
{
foreach (self::EXTENSIONS as $ext) {
$this->mock($ext['service'], function ($mock) use ($ext) {
// module_info/plugin_info/template_info 를 비워 success() 경로를 통과시킨다.
$mock->shouldReceive($ext['update'])->andReturn([
'success' => true,
'from_version' => '1.0.0',
'to_version' => '1.2.3',
]);
});
$response = $this->authRequest()
->postJson("/api/admin/{$ext['segment']}/{$ext['name']}/update", [
'layout_strategy' => 'keep',
]);
$response->assertStatus(200);
$message = (string) $response->json('message');
$this->assertStringContainsString($ext['name'], $message, "{$ext['segment']}: 식별자가 메시지에 치환되지 않았습니다.");
$this->assertStringContainsString('1.2.3', $message, "{$ext['segment']}: 버전이 메시지에 치환되지 않았습니다.");
$this->assertDoesNotMatchRegularExpression(
'/:(module|plugin|template|version)\b/',
$message,
"{$ext['segment']}: 치환되지 않은 플레이스홀더가 사용자에게 노출됩니다 — {$message}"
);
}
}
/**
* 인증 없이 호출하면 401 (라우트 가드 비회귀).
*/
public function test_check_modified_layouts_requires_authentication(): void
{
foreach (self::EXTENSIONS as $ext) {
$this->getJson("/api/admin/{$ext['segment']}/{$ext['name']}/check-modified-layouts")
->assertStatus(401);
}
}
}
@@ -0,0 +1,115 @@
<?php
namespace Tests\Feature\Console;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
/**
* json:convert-unicode 커맨드의 변환 누락 회귀 테스트.
*
* 재현 대상 결함: `WHERE name LIKE '%\u%'` 로 필터한 결과를 `chunk()`(OFFSET
* 페이지네이션)로 순회하면서 콜백이 그 컬럼을 UTF-8 로 다시 써 필터 조건에서
* 이탈시킨다. 처리된 행이 다음 페이지 조회 결과에서 빠지므로 OFFSET 이 아직
* 변환되지 않은 행을 건너뛴다.
*
* 250건 / 청크 100 기준으로 100건이 변환되지 않은 채 남는다.
*/
class ConvertJsonUnicodeEscapesTest extends TestCase
{
use RefreshDatabase;
/**
* 시드 건수 (청크 크기 100 보다 충분히 커야 skip 이 드러남)
*/
private const SEED_COUNT = 250;
/**
* `\uXXXX` 이스케이프가 포함된 boards 행을 시드합니다.
*
* @return void
*/
private function seedEscapedBoards(): void
{
$rows = [];
for ($i = 0; $i < self::SEED_COUNT; $i++) {
$rows[] = [
// 기본 json_encode 는 멀티바이트를 \uXXXX 로 인코딩한다 (변환 대상 상태)
'name' => json_encode(['ko' => '게시판 '.$i, 'en' => 'Board '.$i]),
'slug' => 'chunkskip-'.$i,
'created_at' => now(),
'updated_at' => now(),
];
}
foreach (array_chunk($rows, 100) as $batch) {
DB::table('boards')->insert($batch);
}
}
/**
* `\uXXXX` 이스케이프가 남아 있는 boards 건수를 반환합니다.
*
* @return int 잔여 건수
*/
private function remainingEscapedCount(): int
{
return DB::table('boards')->where('name', 'LIKE', '%\\\\u%')->count();
}
public function test_conversion_leaves_no_escaped_rows_when_filter_column_is_mutated_during_iteration(): void
{
$this->seedEscapedBoards();
$this->assertSame(
self::SEED_COUNT,
$this->remainingEscapedCount(),
'시드 직후에는 \\uXXXX 이스케이프 행이 시드 건수만큼 존재해야 합니다.'
);
$this->artisan('json:convert-unicode', ['--table' => 'boards', '--chunk' => 100])
->assertExitCode(0);
$this->assertSame(
0,
$this->remainingEscapedCount(),
'OFFSET 순회로 인해 변환되지 않고 남은 행이 있습니다 (chunk → chunkById 필요).'
);
}
public function test_converted_values_preserve_original_payload(): void
{
$this->seedEscapedBoards();
$this->artisan('json:convert-unicode', ['--table' => 'boards', '--chunk' => 100])
->assertExitCode(0);
$rows = DB::table('boards')->orderBy('id')->get(['slug', 'name']);
foreach ($rows as $row) {
$index = (int) str_replace('chunkskip-', '', $row->slug);
$this->assertSame(
['ko' => '게시판 '.$index, 'en' => 'Board '.$index],
json_decode($row->name, true),
'변환 후에도 원본 값이 그대로 보존되어야 합니다.'
);
}
}
public function test_dry_run_does_not_modify_rows(): void
{
$this->seedEscapedBoards();
$this->artisan('json:convert-unicode', ['--table' => 'boards', '--chunk' => 100, '--dry-run' => true])
->assertExitCode(0);
$this->assertSame(
self::SEED_COUNT,
$this->remainingEscapedCount(),
'dry-run 은 실제 데이터를 변경하지 않아야 합니다.'
);
}
}
@@ -0,0 +1,256 @@
<?php
namespace Tests\Feature\Console;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
/**
* `playwright:issue-token` 커맨드의 회귀 테스트.
*
* 배경(Chrome MCP 정밀 점검에서 실측):
* - D10: `Role`/`Permission` 의 `name`·`description` 은 모델에서 `array` 로 캐스팅되는데
* 커맨드가 `json_encode(...)` 문자열을 넣어 Eloquent 가 한 번 더 인코딩했다. 그 결과
* 관리자 회원 수정 화면의 역할 선택 목록에 `{"ko":"Playwright \uXXXX…"}` JSON 원문이
* 그대로 노출됐다.
* - D11: 커맨드가 호출마다 유저 1명 + 역할 1개를 만들고 회수하지 않아 역할·유저가
* 각각 2974건 누적됐다(전체의 99%). `--gc-hours` 정리가 추가됐고, 그 정리는
* 콜백이 순회 대상을 삭제하므로 `chunkById`(키셋) 여야 한다 — OFFSET 기반이면
* 청크 크기(100)를 넘는 순간부터 조용히 건너뛴다.
*
* 소스 철자가 아니라 **DB 에 실제로 저장/삭제된 결과**로 계약을 고정한다.
*/
class PlaywrightIssueTokenTest extends TestCase
{
use RefreshDatabase;
/** 정리 대상 시드 규모 — GC 의 청크 크기(100)를 넘겨야 OFFSET 누락이 재현된다 */
private const STALE_COUNT = 250;
/** 커맨드가 붙이는 테스트 역할 접두사 */
private const TEST_ROLE_PREFIX = 'playwright_test_';
protected function setUp(): void
{
parent::setUp();
// 커맨드의 옵트인 가드(② G7_PLAYWRIGHT_BYPASS) 통과. CLI 가드(①)는 PHPUnit 이 이미 cli.
putenv('G7_PLAYWRIGHT_BYPASS=1');
$_ENV['G7_PLAYWRIGHT_BYPASS'] = '1';
$_SERVER['G7_PLAYWRIGHT_BYPASS'] = '1';
}
protected function tearDown(): void
{
putenv('G7_PLAYWRIGHT_BYPASS');
unset($_ENV['G7_PLAYWRIGHT_BYPASS'], $_SERVER['G7_PLAYWRIGHT_BYPASS']);
parent::tearDown();
}
/**
* 테스트 역할 1건과 그 역할을 가진 유저를 생성합니다.
*
* @param string $identifier 역할 식별자
* @param Carbon|null $createdAt 생성 시각 (GC 임계값 판정용)
* @param int $userCount 이 역할에 붙일 유저 수
* @return Role 생성된 역할
*/
private function seedRoleWithUsers(string $identifier, $createdAt = null, int $userCount = 1): Role
{
$role = Role::create([
'identifier' => $identifier,
'name' => ['ko' => '시드 역할', 'en' => 'Seeded Role'],
'description' => ['ko' => '테스트용', 'en' => 'For testing'],
'is_active' => true,
]);
if ($createdAt) {
Role::where('id', $role->id)->update(['created_at' => $createdAt]);
}
for ($i = 0; $i < $userCount; $i++) {
$user = User::factory()->create();
$user->roles()->attach($role->id, ['assigned_at' => now(), 'assigned_by' => null]);
}
return $role;
}
// ========================================================================
// D10 — array 캐스팅 컬럼 이중 인코딩
// ========================================================================
/**
* 커맨드가 만든 역할/권한의 name·description 이 이중 인코딩되지 않아야 한다.
*/
public function test_created_role_and_permission_are_not_double_encoded(): void
{
$this->artisan('playwright:issue-token', [
'--permissions' => ['core.audit.doubleencode'],
'--gc-hours' => 0,
])->assertSuccessful();
$permission = Permission::where('identifier', 'core.audit.doubleencode')->firstOrFail();
$role = Role::where('identifier', 'like', self::TEST_ROLE_PREFIX.'%')->firstOrFail();
foreach ([
['permissions', $permission->id, $permission],
['roles', $role->id, $role],
] as [$table, $id, $model]) {
foreach (['name', 'description'] as $column) {
// 모델 캐스팅을 거친 값은 배열이어야 한다
$this->assertIsArray(
$model->{$column},
"{$table}.{$column} 이 배열로 캐스팅되지 않았습니다 (이중 인코딩 의심)."
);
$this->assertArrayHasKey('ko', $model->{$column});
// 원시 저장값을 1회 디코딩하면 배열이어야 한다.
// 이중 인코딩이면 1회 디코딩 결과가 문자열(JSON) 이 된다.
$raw = DB::table($table)->where('id', $id)->value($column);
$decoded = json_decode((string) $raw, true);
$this->assertIsArray(
$decoded,
"{$table}.{$column} 원시값이 이중 인코딩되었습니다 — 화면에 JSON 원문이 노출됩니다: {$raw}"
);
$this->assertArrayHasKey('ko', $decoded);
}
}
}
/**
* 저장된 한글 값이 화면에서 그대로 읽히는지 (유니코드 이스케이프 원문 미노출).
*/
public function test_created_role_name_reads_back_as_plain_text(): void
{
$this->artisan('playwright:issue-token', ['--gc-hours' => 0])->assertSuccessful();
$role = Role::where('identifier', 'like', self::TEST_ROLE_PREFIX.'%')->firstOrFail();
$this->assertSame('Playwright 테스트 관리자', $role->name['ko']);
$this->assertStringNotContainsString('\\u', json_encode($role->name, JSON_UNESCAPED_UNICODE));
}
// ========================================================================
// D11 — 오래된 테스트 아티팩트 정리 (--gc-hours)
// ========================================================================
/**
* 청크 크기를 넘는 규모에서도 오래된 테스트 역할/유저가 하나도 남지 않아야 한다.
*
* 250건 시드 → OFFSET 기반 순회면 100건이 남는다(키셋 순회 필요).
*/
public function test_gc_removes_all_stale_artifacts_beyond_chunk_size(): void
{
$stale = now()->subHours(24);
for ($i = 0; $i < self::STALE_COUNT; $i++) {
$this->seedRoleWithUsers(self::TEST_ROLE_PREFIX.'stale'.$i, $stale);
}
$this->assertSame(
self::STALE_COUNT,
Role::where('identifier', 'like', self::TEST_ROLE_PREFIX.'%')->count(),
'시드 직후에는 정리 대상이 시드 건수만큼 존재해야 합니다.'
);
$seededUsers = User::count();
$this->artisan('playwright:issue-token', ['--gc-hours' => 6])->assertSuccessful();
// 커맨드가 방금 만든 역할 1건(발급용) 외에는 남으면 안 된다
$remaining = Role::where('identifier', 'like', self::TEST_ROLE_PREFIX.'%')
->where('created_at', '<', now()->subHours(6))
->count();
$this->assertSame(
0,
$remaining,
'OFFSET 순회로 인해 정리되지 않고 남은 테스트 역할이 있습니다 (chunk → chunkById 필요).'
);
// 유저도 함께 회수되어야 한다 (시드 유저 250명 제거 + 커맨드가 만든 1명 추가)
$this->assertSame(
$seededUsers - self::STALE_COUNT + 1,
User::count(),
'오래된 테스트 유저가 회수되지 않았습니다.'
);
}
/**
* 임계 시간 이내의 아티팩트는 건드리면 안 된다 (동시 실행 중인 다른 워커 보호).
*/
public function test_gc_preserves_recent_artifacts(): void
{
$recent = $this->seedRoleWithUsers(self::TEST_ROLE_PREFIX.'recent', now()->subHour());
$this->artisan('playwright:issue-token', ['--gc-hours' => 6])->assertSuccessful();
$this->assertDatabaseHas('roles', ['id' => $recent->id]);
$this->assertSame(1, $recent->users()->count(), '동시 실행 중인 워커의 계정이 삭제되었습니다.');
}
/**
* playwright 테스트 역할이 아닌 역할과 그 소속 회원은 절대 삭제되지 않아야 한다.
*/
public function test_gc_never_touches_real_roles_and_members(): void
{
$realRole = $this->seedRoleWithUsers('shop_manager', now()->subYear());
$realUserId = $realRole->users()->first()->id;
$this->artisan('playwright:issue-token', ['--gc-hours' => 6])->assertSuccessful();
$this->assertDatabaseHas('roles', ['id' => $realRole->id]);
$this->assertDatabaseHas('users', ['id' => $realUserId]);
}
/**
* 오래된 역할을 지우더라도, 아직 유효한 다른 테스트 역할을 가진 계정은 남겨야 한다.
*
* 병렬 워커가 같은 계정을 쓰는 상황에서 세션이 끊기는 것을 막는 분기다.
*/
public function test_gc_keeps_user_that_still_holds_a_recent_test_role(): void
{
$staleRole = Role::create([
'identifier' => self::TEST_ROLE_PREFIX.'stale_shared',
'name' => ['ko' => '오래된 역할', 'en' => 'Stale Role'],
'description' => ['ko' => '테스트용', 'en' => 'For testing'],
'is_active' => true,
]);
Role::where('id', $staleRole->id)->update(['created_at' => now()->subHours(24)]);
$recentRole = Role::create([
'identifier' => self::TEST_ROLE_PREFIX.'recent_shared',
'name' => ['ko' => '최근 역할', 'en' => 'Recent Role'],
'description' => ['ko' => '테스트용', 'en' => 'For testing'],
'is_active' => true,
]);
$user = User::factory()->create();
$user->roles()->attach($staleRole->id, ['assigned_at' => now(), 'assigned_by' => null]);
$user->roles()->attach($recentRole->id, ['assigned_at' => now(), 'assigned_by' => null]);
$this->artisan('playwright:issue-token', ['--gc-hours' => 6])->assertSuccessful();
$this->assertDatabaseMissing('roles', ['id' => $staleRole->id]);
$this->assertDatabaseHas('roles', ['id' => $recentRole->id]);
$this->assertDatabaseHas('users', ['id' => $user->id]);
}
/**
* `--gc-hours=0` 이면 정리를 수행하지 않는다 (옵트아웃).
*/
public function test_gc_is_skipped_when_disabled(): void
{
$stale = $this->seedRoleWithUsers(self::TEST_ROLE_PREFIX.'stale_disabled', now()->subHours(24));
$this->artisan('playwright:issue-token', ['--gc-hours' => 0])->assertSuccessful();
$this->assertDatabaseHas('roles', ['id' => $stale->id]);
}
}
@@ -0,0 +1,259 @@
<?php
namespace Tests\Feature\Extension;
use App\Enums\ExtensionStatus;
use App\Extension\ModuleManager;
use App\Extension\PluginManager;
use App\Models\Module;
use App\Models\Template;
use App\Models\TemplateLayout;
use Illuminate\Foundation\Testing\RefreshDatabase;
use ReflectionMethod;
use Tests\TestCase;
/**
* 확장 업데이트의 `layout_strategy=keep` 이 실제로 사용자 수정 레이아웃을 보존하는지
* 보장하는 회귀 테스트.
*
* 배경: `updateModule()` / `updatePlugin()` 의 레이아웃 갱신 단계가 전략을 모르는
* `registerModuleLayouts()` / `registerPluginLayouts()` 를 전략 인지 refresh **앞에서**
* 호출했다. 그 메서드는 모든 레이아웃의 content 와 `original_content_hash` 를 파일 기준으로
* 덮어쓰므로, 뒤이어 실행되는 `refresh*Layouts($preserveModified)` 가 비교할 "수정본" 이
* 이미 사라져 keep 전략이 언제나 no-op 이 되었다 — 사용자는 '수정 유지' 를 골랐는데도
* 커스터마이징이 소실됐다.
*
* 실제 파일 교체·다운로드를 동반하는 전체 업데이트 경로는 네트워크/디스크에 의존하므로,
* 여기서는 그 경로가 호출하는 두 단계를 **실제로 실행해** 다음을 고정한다:
* 1. keep 전략의 보존/덮어쓰기 동작 자체 (§keep/overwrite)
* 2. 선행 register 가 수정 마커를 파괴한다는 회귀의 인과 (§선행 register 금지)
* 3. register 를 빼도 신규 레이아웃이 누락되지 않는다는 것 (§created 분기)
* 4. 업데이트 경로에 그 선행 호출이 남아 있지 않다는 호출 순서 계약 (§호출 계약)
*/
class UpdateLayoutStrategyKeepTest extends TestCase
{
use RefreshDatabase;
/** 레이아웃 파일이 실제로 존재하는 설치본 모듈 */
private const MODULE = 'sirsoft-board';
private ModuleManager $moduleManager;
private Template $adminTemplate;
protected function setUp(): void
{
parent::setUp();
$this->moduleManager = app(ModuleManager::class);
$this->adminTemplate = Template::create([
'identifier' => 'test-keep-admin',
'vendor' => 'test',
'name' => ['ko' => '보존 테스트 관리자', 'en' => 'Keep Test Admin'],
'version' => '1.0.0',
'type' => 'admin',
'status' => ExtensionStatus::Active->value,
'description' => ['ko' => '테스트용', 'en' => 'For testing'],
]);
Module::create([
'identifier' => self::MODULE,
'vendor' => 'sirsoft',
'name' => ['ko' => '게시판', 'en' => 'Board'],
'version' => '1.0.3',
'status' => ExtensionStatus::Active->value,
'description' => ['ko' => '테스트용', 'en' => 'For testing'],
]);
$this->moduleManager->loadModules();
if (! $this->moduleManager->getModule(self::MODULE)) {
$this->markTestSkipped(self::MODULE.' 설치본이 없어 레이아웃 보존 동작을 실행할 수 없습니다.');
}
}
/**
* 배포 상태(파일 기준)로 레이아웃을 DB 에 등록합니다.
*
* `registerModuleLayouts()` 는 protected 이므로 리플렉션으로 호출합니다.
* 이 메서드가 곧 D6 의 원인이 된 "전략 미인지 선덮어쓰기" 단계입니다.
*
* @return int 등록된 레이아웃 수
*/
private function registerFromFiles(): int
{
$method = new ReflectionMethod(ModuleManager::class, 'registerModuleLayouts');
$method->setAccessible(true);
return (int) $method->invoke($this->moduleManager, self::MODULE);
}
/**
* 사용자가 UI 에서 레이아웃 1건을 수정한 상태를 만듭니다.
*
* content 만 바꾸고 original_content_hash 는 배포 원본 그대로 두어야
* "수정됨" 으로 판정됩니다.
*
* @return TemplateLayout 수정된 레이아웃
*/
private function markOneLayoutAsUserModified(): TemplateLayout
{
$layout = TemplateLayout::where('source_type', 'module')
->where('source_identifier', self::MODULE)
->orderBy('id')
->firstOrFail();
$content = $layout->content;
$content['__user_marker'] = 'keep-me';
$layout->content = $content;
$layout->saveQuietly();
return $layout->fresh();
}
// ========================================================================
// keep / overwrite 동작
// ========================================================================
/**
* keep 전략은 사용자 수정 레이아웃을 덮어쓰지 않는다.
*/
public function test_keep_strategy_preserves_user_modified_layout(): void
{
$this->assertGreaterThan(0, $this->registerFromFiles(), '레이아웃이 등록되지 않았습니다.');
$modified = $this->markOneLayoutAsUserModified();
$this->moduleManager->refreshModuleLayouts(self::MODULE, true);
$this->assertArrayHasKey(
'__user_marker',
$modified->fresh()->content,
'keep 전략인데 사용자 수정본이 파일 내용으로 덮어써졌습니다.'
);
}
/**
* overwrite 전략은 사용자 수정 레이아웃을 파일 내용으로 되돌린다 (비회귀).
*/
public function test_overwrite_strategy_replaces_user_modified_layout(): void
{
$this->registerFromFiles();
$modified = $this->markOneLayoutAsUserModified();
$this->moduleManager->refreshModuleLayouts(self::MODULE, false);
$this->assertArrayNotHasKey(
'__user_marker',
$modified->fresh()->content,
'overwrite 전략인데 수정본이 그대로 남았습니다.'
);
}
// ========================================================================
// 선행 register 금지 (D6 의 인과)
// ========================================================================
/**
* 전략 인지 refresh **앞에서** register 를 호출하면 keep 이 무효가 된다.
*
* 이 테스트는 결함 재현을 고정한다 — 여기서 보존이 되어버리면 오히려 전제가 바뀐
* 것이므로, updateModule 의 호출 계약(아래)과 함께 읽어야 한다.
*/
public function test_pre_registering_before_refresh_destroys_the_modification_marker(): void
{
$this->registerFromFiles();
$modified = $this->markOneLayoutAsUserModified();
// 결함 당시 updateModule 이 하던 순서를 그대로 재현
$this->registerFromFiles();
$this->moduleManager->refreshModuleLayouts(self::MODULE, true);
$this->assertArrayNotHasKey(
'__user_marker',
$modified->fresh()->content,
'선행 register 가 수정 마커를 파괴하지 않는다면 이 회귀의 전제가 달라진 것입니다 — 계약을 재검토하세요.'
);
}
/**
* register 를 빼도 DB 에 없는 레이아웃은 refresh 가 생성한다.
*/
public function test_refresh_creates_layouts_missing_from_database(): void
{
$registered = $this->registerFromFiles();
TemplateLayout::where('source_type', 'module')
->where('source_identifier', self::MODULE)
->forceDelete();
$this->assertSame(0, $this->countModuleLayouts());
$this->moduleManager->refreshModuleLayouts(self::MODULE, true);
$this->assertSame(
$registered,
$this->countModuleLayouts(),
'registerModuleLayouts 제거 후 신규 레이아웃이 누락되었습니다 (refresh 의 created 분기 확인 필요).'
);
}
/**
* 현재 템플릿에 등록된 모듈 레이아웃 수.
*/
private function countModuleLayouts(): int
{
return TemplateLayout::where('template_id', $this->adminTemplate->id)
->where('source_type', 'module')
->where('source_identifier', self::MODULE)
->count();
}
// ========================================================================
// 호출 계약 — 전체 업데이트 경로는 실행 불가하므로 순서만 고정
// ========================================================================
/**
* updateModule / updatePlugin 의 레이아웃 단계에 전략 미인지 선덮어쓰기가 없어야 한다.
*/
public function test_update_path_does_not_pre_register_layouts(): void
{
foreach ([
[ModuleManager::class, 'updateModule', 'refreshModuleLayouts', 'registerModuleLayouts'],
[PluginManager::class, 'updatePlugin', 'refreshPluginLayouts', 'registerPluginLayouts'],
] as [$class, $method, $refresh, $register]) {
$source = $this->methodSource($class, $method);
$this->assertMatchesRegularExpression(
'/'.preg_quote($refresh, '/').'\(\s*\$identifier\s*,\s*\$preserveModified\s*\)/',
$source,
"{$class}::{$method} 는 전략 인지 {$refresh} 를 호출해야 한다"
);
$this->assertDoesNotMatchRegularExpression(
'/\$this->'.preg_quote($register, '/').'\(\s*\$identifier\s*\)/',
$source,
"{$class}::{$method} 가 {$register} 를 호출하면 keep 전략이 무효화된다 "
.'(content/original_content_hash 를 파일 기준으로 선덮어쓰기)'
);
}
}
/**
* 지정 메서드의 소스 본문을 반환합니다.
*
* @param string $class 대상 클래스 FQCN
* @param string $method 대상 메서드명
* @return string 메서드 본문 소스
*/
private function methodSource(string $class, string $method): string
{
$ref = new ReflectionMethod($class, $method);
$lines = file($ref->getFileName());
return implode('', array_slice(
$lines,
$ref->getStartLine() - 1,
$ref->getEndLine() - $ref->getStartLine() + 1
));
}
}
@@ -0,0 +1,153 @@
<?php
namespace Tests\Feature\Upgrades;
use App\Extension\UpgradeContext;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;
/**
* 코어 7.0.0-alpha.15 업그레이드 스텝의 UUID 백필 누락 회귀 테스트.
*
* 재현 대상 결함: `whereNull('uuid')` 로 필터한 결과를 `chunk()`(OFFSET 페이지네이션)로
* 순회하면서 콜백이 그 필터 컬럼(uuid)을 채운다. 처리된 행이 다음 페이지 조회의 결과
* 집합에서 이탈하므로 OFFSET 이 아직 처리되지 않은 행을 건너뛴다.
*
* 250건(청크 100) 기준: 1페이지 100건 처리 → 남은 150건에 OFFSET 100 적용 → 50건만
* 조회 → 3페이지는 OFFSET 200 이라 0건 → 총 150건만 처리되고 100건이 누락된다.
* `chunkById()`(키셋 순회)로 바꾸면 누락이 0건이 된다.
*/
class Alpha15UuidBackfillTest extends TestCase
{
use RefreshDatabase;
/**
* 시드 건수 (스텝의 청크 크기 100 보다 충분히 커야 skip 이 드러남)
*/
private const SEED_COUNT = 250;
/**
* 시드 사용자 이메일 프리픽스 (tearDown 정리 대상 식별용)
*/
private const EMAIL_PREFIX = 'alpha15-chunkskip-';
private object $upgrade;
private UpgradeContext $context;
protected function setUp(): void
{
parent::setUp();
require_once base_path('upgrades/Upgrade_7_0_0_alpha_15.php');
$class = 'App\\Upgrades\\Upgrade_7_0_0_alpha_15';
$this->upgrade = new $class;
$this->context = new UpgradeContext(
fromVersion: '7.0.0-alpha.14',
toVersion: '7.0.0-alpha.15',
currentStep: '7.0.0-alpha.15',
);
}
/**
* 스텝의 ALTER TABLE 은 MySQL 에서 암묵적 커밋을 유발하므로 RefreshDatabase 의
* 트랜잭션 롤백으로 되돌아가지 않는다. 시드 행과 컬럼 제약을 명시적으로 원복한다.
*/
protected function tearDown(): void
{
try {
DB::table('users')->where('email', 'LIKE', self::EMAIL_PREFIX.'%')->delete();
if ($this->uuidColumnIsNotNull()) {
Schema::table('users', function ($table) {
$table->uuid('uuid')->nullable()->change();
});
}
} catch (\Throwable) {
// 정리 실패는 테스트 결과에 영향을 주지 않도록 무시 (RefreshDatabase 가 다음 실행에서 재생성)
}
parent::tearDown();
}
/**
* uuid 컬럼이 NOT NULL 인지 확인합니다.
*
* @return bool NOT NULL 이면 true
*/
private function uuidColumnIsNotNull(): bool
{
$column = DB::selectOne("SHOW COLUMNS FROM {$this->context->table('users')} WHERE Field = 'uuid'");
return $column !== null && $column->Null === 'NO';
}
/**
* uuid 가 NULL 인 사용자 레코드를 시드합니다.
*
* @return void
*/
private function seedUsersWithoutUuid(): void
{
$rows = [];
for ($i = 0; $i < self::SEED_COUNT; $i++) {
$rows[] = [
'uuid' => null,
'name' => 'chunk skip user '.$i,
'email' => self::EMAIL_PREFIX.$i.'@g7.test',
'password' => bcrypt('password'),
'created_at' => now(),
'updated_at' => now(),
];
}
foreach (array_chunk($rows, 100) as $batch) {
DB::table('users')->insert($batch);
}
}
public function test_uuid_backfill_leaves_no_null_rows_when_filter_column_is_mutated_during_iteration(): void
{
$this->seedUsersWithoutUuid();
$this->assertSame(
self::SEED_COUNT,
DB::table('users')->whereNull('uuid')->count(),
'시드 직후에는 uuid NULL 레코드가 시드 건수만큼 존재해야 합니다.'
);
$this->upgrade->run($this->context);
$this->assertSame(
0,
DB::table('users')->whereNull('uuid')->count(),
'OFFSET 순회로 인해 백필되지 않고 남은 레코드가 있습니다 (chunk → chunkById 필요).'
);
// 백필이 끝나야 컬럼을 NOT NULL 로 조일 수 있다 — 한 건이라도 남으면
// 스텝의 ALTER TABLE 이 실패하거나 제약이 적용되지 않은 채 넘어간다.
$this->assertTrue(
$this->uuidColumnIsNotNull(),
'백필 후 uuid 컬럼이 NOT NULL 로 전환되지 않았습니다.'
);
}
public function test_backfilled_uuids_are_unique(): void
{
$this->seedUsersWithoutUuid();
$this->upgrade->run($this->context);
$uuids = DB::table('users')
->where('email', 'LIKE', self::EMAIL_PREFIX.'%')
->pluck('uuid')
->all();
$this->assertCount(self::SEED_COUNT, $uuids);
$this->assertCount(self::SEED_COUNT, array_unique($uuids), '백필된 UUID 는 모두 고유해야 합니다.');
}
}
@@ -0,0 +1,185 @@
<?php
namespace Tests\Feature\Upgrades;
use App\Extension\UpgradeContext;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use ReflectionClass;
use Tests\TestCase;
/**
* 코어 7.0.0-beta.2 업그레이드 스텝의 레이아웃 hash 백필 누락 회귀 테스트.
*
* 재현 대상 결함: `whereNull('original_content_hash')` 로 필터한 결과를 `chunk()`
* (OFFSET 페이지네이션)로 순회하면서 콜백이 그 필터 컬럼을 채운다. 처리된 행이
* 다음 페이지 조회 결과에서 이탈하므로 OFFSET 이 미처리 행을 건너뛴다.
*
* 이 테스트는 동일 백필 코드를 공유하는 마이그레이션 2건
* (`add_original_content_hash_to_template_layouts_table`,
* `add_original_content_hash_to_template_layout_extensions_table`) 의 정본 증명이기도 하다.
*/
class Beta2LayoutHashBackfillTest extends TestCase
{
use RefreshDatabase;
/**
* 시드 건수 (스텝의 청크 크기 100 보다 충분히 커야 skip 이 드러남)
*/
private const SEED_COUNT = 250;
private object $upgrade;
private UpgradeContext $context;
protected function setUp(): void
{
parent::setUp();
require_once base_path('upgrades/Upgrade_7_0_0_beta_2.php');
$class = 'App\\Upgrades\\Upgrade_7_0_0_beta_2';
$this->upgrade = new $class;
$this->context = new UpgradeContext(
fromVersion: '7.0.0-beta.1',
toVersion: '7.0.0-beta.2',
currentStep: '7.0.0-beta.2',
);
}
/**
* 백필 private 메서드만 호출합니다.
*
* (전체 run() 은 알림 시스템 이관 등 무관한 단계를 함께 실행하므로 검증 대상인
* 백필 로직만 reflection 으로 직접 실행합니다 — 기존 업그레이드 테스트와 동일 방식)
*
* @return void
*/
private function runBackfill(): void
{
$reflection = new ReflectionClass($this->upgrade);
$method = $reflection->getMethod('backfillModuleAndPluginLayoutHashes');
$method->setAccessible(true);
$method->invoke($this->upgrade, $this->context);
}
/**
* 테스트용 템플릿 1건을 생성합니다.
*
* @return int 생성된 템플릿 ID
*/
private function seedTemplate(): int
{
return DB::table('templates')->insertGetId([
'identifier' => 'test-chunkskip_template',
'vendor' => 'test',
'name' => json_encode(['ko' => '청크 테스트 템플릿', 'en' => 'Chunk Test Template']),
'version' => '1.0.0',
'type' => 'admin',
'status' => 'active',
'created_at' => now(),
'updated_at' => now(),
]);
}
/**
* hash 가 NULL 인 모듈/플러그인 레이아웃을 시드합니다.
*
* @param int $templateId 템플릿 ID
* @return void
*/
private function seedLayoutsWithoutHash(int $templateId): void
{
$rows = [];
for ($i = 0; $i < self::SEED_COUNT; $i++) {
$sourceType = $i % 2 === 0 ? 'module' : 'plugin';
$rows[] = [
'template_id' => $templateId,
'name' => 'chunkskip/layout_'.$i,
'content' => json_encode(['type' => 'page', 'index' => $i]),
'source_type' => $sourceType,
'source_identifier' => $sourceType === 'module' ? 'test-module' : 'test-plugin',
'original_content_hash' => null,
'original_content_size' => null,
'created_at' => now(),
'updated_at' => now(),
];
}
foreach (array_chunk($rows, 100) as $batch) {
DB::table('template_layouts')->insert($batch);
}
}
public function test_layout_hash_backfill_leaves_no_null_rows_when_filter_column_is_mutated_during_iteration(): void
{
$templateId = $this->seedTemplate();
$this->seedLayoutsWithoutHash($templateId);
$this->assertSame(
self::SEED_COUNT,
DB::table('template_layouts')->whereNull('original_content_hash')->count(),
'시드 직후에는 hash NULL 레이아웃이 시드 건수만큼 존재해야 합니다.'
);
$this->runBackfill();
$this->assertSame(
0,
DB::table('template_layouts')
->whereIn('source_type', ['module', 'plugin'])
->whereNull('original_content_hash')
->count(),
'OFFSET 순회로 인해 백필되지 않고 남은 레이아웃이 있습니다 (chunk → chunkById 필요).'
);
}
public function test_backfilled_hash_and_size_match_normalized_content(): void
{
$templateId = $this->seedTemplate();
$this->seedLayoutsWithoutHash($templateId);
$this->runBackfill();
$rows = DB::table('template_layouts')
->where('template_id', $templateId)
->get(['content', 'original_content_hash', 'original_content_size']);
foreach ($rows as $row) {
$normalized = json_encode(
json_decode($row->content, true),
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
);
$this->assertSame(hash('sha256', $normalized), $row->original_content_hash);
$this->assertSame(strlen($normalized), (int) $row->original_content_size);
}
}
public function test_template_source_layouts_are_not_touched(): void
{
$templateId = $this->seedTemplate();
$this->seedLayoutsWithoutHash($templateId);
DB::table('template_layouts')->insert([
'template_id' => $templateId,
'name' => 'chunkskip/template_owned',
'content' => json_encode(['type' => 'page']),
'source_type' => 'template',
'original_content_hash' => null,
'created_at' => now(),
'updated_at' => now(),
]);
$this->runBackfill();
$row = DB::table('template_layouts')
->where('template_id', $templateId)
->where('source_type', 'template')
->first(['original_content_hash']);
$this->assertNull($row->original_content_hash, '템플릿 소유 레이아웃은 백필 대상이 아닙니다.');
}
}
@@ -0,0 +1,227 @@
/**
* 확장(모듈/플러그인/템플릿) 관리 화면의 업데이트 계약 회귀 검증
*
* Chrome MCP 정밀 점검(2026-07-31)에서 실측된 결함을 브라우저 경로로 고정한다.
*
* - 목록 요약이 `data.total` 을 읽어 항상 "총 0개 중 1-0개 표시" 로 고정 표기됐다.
* 실제 응답은 `data.pagination.total` 이다.
* - `check-updates` 응답 필드는 `updated_count` 인데 레이아웃이 `update_count` 를
* 읽어, 업데이트가 감지돼도 항상 "모두 최신 상태입니다" 토스트가 떴다.
* - 업데이트 모달의 수정 감지 조회가 실패해도 "수정된 레이아웃이 없습니다" 라고
* 단언해, 그대로 '모두 교체' 를 진행하면 사용자가 고친 화면이 소실됐다.
*
* @scenario extension-update-modal
* @effects pagination-summary, check-updates-toast, modified-layouts-warning
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
import type { Locator, Page } from '@playwright/test';
// 이 파일의 테스트는 매번 관리자 SPA 를 냉시동해 목록 화면을 완전히 렌더한 뒤 조작한다.
// 전역 기본 30s 는 워커가 여럿 붙어 서로 PHP-FPM 을 나눠 쓰는 병렬 실행에서 부족하다
// (실측: 6워커 동시 실행 시 테스트당 22~35s). 회귀 감지는 개별 단언 타임아웃이 맡고,
// 이 값은 하네스 예산일 뿐이므로 파일 단위로 늘린다.
test.describe.configure({ timeout: 60_000 });
const LIST_ROUTES: Array<{ path: string; label: string; api: string; permission: string }> = [
{ path: '/admin/modules', label: '모듈', api: '**/api/admin/modules?*', permission: 'core.modules.read' },
{ path: '/admin/plugins', label: '플러그인', api: '**/api/admin/plugins?*', permission: 'core.plugins.read' },
];
/**
* 목록 화면이 함께 부르는 부수 데이터소스를 고정한다.
*
* `admin_module_list` / `admin_plugin_list` 는 목록 외에 `auto_deactivated_banner`
* (`/api/admin/extensions/auto-deactivated`) 도 페이지 데이터소스로 선언한다. 카드 그리드에는
* `blur_until_loaded: true` 가 걸려 있어 **모든** 데이터소스가 끝나기 전까지 래퍼에
* `pointer-events-none` 이 붙고(DynamicRenderer), 툴바 버튼은 목록 응답의 abilities 로
* `disabled` 가 결정된다. 이 요청 하나를 실서버에 남겨두면 병렬 워커 경합에서 응답이 늦어져
* 클릭이 로딩 가드에 막힌다 — 실측: 6워커에서 카드 버튼 클릭이 `#content_area` 로 흘러 20s 타임아웃.
* 이 spec 이 검증하는 것은 바인딩 계약이지 서버 지연이 아니므로 빈 응답으로 고정한다.
*/
async function stubSupportingSources(page: Page): Promise<void> {
await page.route('**/api/admin/extensions/auto-deactivated*', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
success: true,
message: 'ok',
data: {
items: { plugins: [], modules: [], templates: [] },
current_core_version: '7.0.6',
},
}),
});
});
}
/**
* 카드 그리드 안의 대상이 실제로 클릭 가능해질 때까지 기다린다.
*
* `blur_until_loaded` 래퍼는 로딩 중 `opacity-50 blur-sm … pointer-events-none` 을 달아
* 카드 안 버튼 클릭을 부모(`#content_area`)로 흘려보낸다. `domcontentloaded` 는 SPA 가
* 데이터를 받기 전에 끝나므로, 이 대기 없이 카드 버튼을 누르면 클릭이 가로채인다.
*
* 순서가 중요하다 — blur 부재(`toHaveCount(0)`)만 먼저 단언하면 그리드가 **아직 렌더되기
* 전이라** 즉시 통과하고, 그 뒤에 blur 가 붙어 대기가 무효가 된다. 대상이 보이는 것을
* 먼저 확인해 그리드 렌더를 확정한 뒤 blur 해제를 기다린다.
*/
async function waitForGridInteractive(page: Page, target: Locator): Promise<void> {
await expect(target).toBeVisible({ timeout: 20_000 });
await expect(page.locator('#content_area .blur-sm')).toHaveCount(0, { timeout: 20_000 });
}
for (const { path, label, api, permission } of LIST_ROUTES) {
test(`${label} 목록의 페이지네이션 요약이 응답의 총건수를 표시한다`, async ({ page }) => {
const token = issueToken(permission);
await authenticatePage(page, token);
await stubSupportingSources(page);
// 응답을 고정해 "환경에 몇 건 있는지" 가 아니라 바인딩 경로를 검증한다.
// (회귀 시 응답이 무엇이든 화면은 "총 0개 중 1-0개 표시" 로 고정된다)
await page.route(api, async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
success: true,
message: 'ok',
data: {
data: [],
pagination: { total: 37, current_page: 1, last_page: 4, per_page: 12 },
meta: {},
abilities: {},
},
}),
});
});
await page.goto(path);
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
const summary = page.locator('#pagination_info');
await expect(summary).toBeVisible({ timeout: 20_000 });
// "총 0개 중 1-0개 표시" 는 data.pagination 경로 회귀의 지문이다.
await expect(summary).toContainText('총 37개', { timeout: 20_000 });
await expect(summary).not.toContainText('총 0개');
});
}
test('업데이트 확인은 감지 건수를 토스트에 반영한다', async ({ page }) => {
const token = issueToken('core.modules.read', 'core.modules.install');
await authenticatePage(page, token);
await stubSupportingSources(page);
// 툴바의 '업데이트 확인' 은 `disabled: "{{… modules?.data?.abilities?.can_install !== true}}"` 이라
// 목록 응답이 도착하기 전까지 비활성이다. 목록도 고정해 버튼 활성 시점을 서버 지연에서 분리한다.
// (route 는 나중에 등록한 것이 먼저 매칭되므로 check-updates 보다 앞서 등록한다 —
// `**/api/admin/modules?*` 의 `?` 는 임의 1문자라 check-updates 경로에도 매칭될 수 있다)
await page.route('**/api/admin/modules?*', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
success: true,
message: 'ok',
data: {
data: [],
pagination: { total: 0, current_page: 1, last_page: 1, per_page: 12 },
meta: {},
abilities: { can_install: true, can_activate: true, can_uninstall: true },
},
}),
});
});
// check-updates 응답을 감지 1건으로 고정 — 레이아웃이 updated_count 를 읽는지 검증
await page.route('**/api/admin/modules/check-updates', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
success: true,
message: '업데이트 확인이 완료되었습니다.',
data: {
updated_count: 1,
details: [
{
identifier: 'sirsoft-board',
current_version: '1.0.1',
latest_version: '1.0.2',
update_source: 'bundled',
},
],
},
}),
});
});
await page.goto('/admin/modules');
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
const checkButton = page.getByRole('button', { name: /업데이트 확인/ });
await expect(checkButton).toBeEnabled({ timeout: 20_000 });
await checkButton.click();
const toast = page.getByRole('alert');
await expect(toast).toContainText(/업데이트 확인 완료/, { timeout: 20_000 });
await expect(toast).not.toContainText(/최신 상태입니다/);
});
test('수정 감지 조회가 실패하면 "수정 없음" 대신 확인 실패를 알린다', async ({ page }) => {
const token = issueToken('core.modules.read', 'core.modules.install');
await authenticatePage(page, token);
await stubSupportingSources(page);
// 업데이트 가용 상태를 고정하고, 수정 감지 조회만 실패시킨다
await page.route('**/api/admin/modules?*', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
success: true,
message: 'ok',
data: {
data: [
{
identifier: 'sirsoft-board',
vendor: 'sirsoft',
name: '게시판',
description: '검수용 고정 응답',
version: '1.0.1',
status: 'active',
dependencies: [],
update_available: true,
update_source: 'bundled',
latest_version: '1.0.2',
is_compatible: true,
is_pending: false,
is_bundled: true,
abilities: { can_install: true, can_activate: true, can_uninstall: true },
},
],
pagination: { total: 1, current_page: 1, last_page: 1, per_page: 12 },
meta: {},
abilities: { can_install: true, can_activate: true, can_uninstall: true },
},
}),
});
});
await page.route('**/check-modified-layouts', (route) => route.abort('failed'));
await page.route('**/changelog*', (route) => route.abort('failed'));
await page.goto('/admin/modules');
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
// 접근성 이름은 아이콘 글리프를 포함한다 ("refresh 업데이트") — '업데이트 확인' 과 구분한다.
const updateButton = page
.getByRole('button', { name: 'refresh 업데이트', exact: true })
.first();
await waitForGridInteractive(page, updateButton);
await updateButton.click({ timeout: 20_000 });
const dialog = page.getByRole('dialog');
await expect(dialog).toBeVisible({ timeout: 20_000 });
await expect(dialog).toContainText(/확인하지 못했습니다/, { timeout: 20_000 });
await expect(dialog).not.toContainText(/수정된 레이아웃이 없습니다/);
});
@@ -0,0 +1,159 @@
<?php
namespace Tests\Unit\Extension;
use App\Enums\ExtensionStatus;
use App\Extension\TemplateManager;
use App\Extension\Traits\ComputesLayoutContentHash;
use App\Models\Template;
use App\Models\TemplateLayout;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* 템플릿 수정 레이아웃 감지의 소유 범위 회귀 테스트.
*
* 배경(Chrome MCP 정밀 점검에서 실측): `hasModifiedLayouts()` 가
* `getByTemplateId()` 로 해당 template_id 의 **모든** 레이아웃을 세어,
* 같은 템플릿에 등록된 모듈/플러그인 소유 레이아웃의 수정본까지 템플릿 자신의
* 수정으로 집계했다(실측: 모달 4건 중 3건이 board/gdpr/sample 소유).
* 실제 갱신 범위인 `refreshTemplateLayouts()` 는 source_type='template' +
* source_identifier=null 만 다루므로 표시와 동작이 어긋난다.
*
* 조회 소스의 철자가 아니라 **실제 집계 결과**로 범위를 고정한다.
*/
class TemplateModifiedLayoutScopeTest extends TestCase
{
use ComputesLayoutContentHash, RefreshDatabase;
private TemplateManager $templateManager;
private Template $template;
/** 배포 원본 콘텐츠 */
private const ORIGINAL = ['layout_name' => 'home', 'slots' => ['content' => []]];
/** 사용자가 UI 에서 수정한 콘텐츠 */
private const MODIFIED = ['layout_name' => 'home', 'slots' => ['content' => [['component' => 'Div']]]];
protected function setUp(): void
{
parent::setUp();
$this->templateManager = app(TemplateManager::class);
$this->template = Template::create([
'identifier' => 'test-scope-admin',
'vendor' => 'test',
'name' => ['ko' => '범위 테스트 관리자', 'en' => 'Scope Test Admin'],
'version' => '1.0.0',
'type' => 'admin',
'status' => ExtensionStatus::Active->value,
'description' => ['ko' => '테스트용', 'en' => 'For testing'],
]);
}
/**
* 레이아웃 1건을 시드합니다.
*
* original_content_hash 는 항상 배포 원본 기준으로 기록하고, content 만 수정본으로
* 바꿔 "사용자가 UI 에서 고친 상태" 를 재현합니다.
*
* @param int $templateId 소속 템플릿 ID
* @param string $name 레이아웃 이름
* @param string $sourceType 소유 구분 (template/module/plugin)
* @param string|null $sourceIdentifier 소유 확장 식별자 (템플릿 소유는 null)
* @param bool $modified true 면 수정된 상태로 시드
* @return TemplateLayout 생성된 레이아웃
*/
private function seedLayout(
int $templateId,
string $name,
string $sourceType,
?string $sourceIdentifier,
bool $modified
): TemplateLayout {
return TemplateLayout::create([
'template_id' => $templateId,
'name' => $name,
'content' => $modified ? self::MODIFIED : self::ORIGINAL,
'source_type' => $sourceType,
'source_identifier' => $sourceIdentifier,
'original_content_hash' => $this->computeContentHash(self::ORIGINAL),
'original_content_size' => $this->computeContentSize(self::ORIGINAL),
]);
}
/**
* 템플릿 소유 수정본만 집계하고 남의 확장 소유는 제외해야 한다.
*/
public function test_has_modified_layouts_counts_only_template_owned_layouts(): void
{
$this->seedLayout($this->template->id, 'admin_home', 'template', null, true);
// 같은 template_id 에 얹힌 남의 확장 소유 수정본 3건
$this->seedLayout($this->template->id, 'sirsoft-board.admin_index', 'module', 'sirsoft-board', true);
$this->seedLayout($this->template->id, 'sirsoft-page.admin_index', 'module', 'sirsoft-page', true);
$this->seedLayout($this->template->id, 'sirsoft-gdpr.admin_index', 'plugin', 'sirsoft-gdpr', true);
$result = $this->templateManager->hasModifiedLayouts('test-scope-admin');
$this->assertTrue($result['has_modified_layouts']);
$this->assertSame(
1,
$result['modified_count'],
'템플릿 업데이트가 실제로 갱신하지 않는 모듈/플러그인 소유 레이아웃이 수정 건수에 합산되었습니다.'
);
$this->assertSame(['admin_home'], array_column($result['modified_layouts'], 'name'));
}
/**
* 남의 확장만 수정된 상태에서는 경고가 뜨면 안 된다.
*/
public function test_has_modified_layouts_returns_zero_when_only_other_extensions_are_modified(): void
{
$this->seedLayout($this->template->id, 'admin_home', 'template', null, false);
$this->seedLayout($this->template->id, 'sirsoft-board.admin_index', 'module', 'sirsoft-board', true);
$result = $this->templateManager->hasModifiedLayouts('test-scope-admin');
$this->assertFalse($result['has_modified_layouts']);
$this->assertSame(0, $result['modified_count']);
$this->assertEmpty($result['modified_layouts']);
}
/**
* 다른 템플릿의 수정본은 집계 대상이 아니다.
*/
public function test_has_modified_layouts_ignores_layouts_of_other_templates(): void
{
$other = Template::create([
'identifier' => 'test-scope-user',
'vendor' => 'test',
'name' => ['ko' => '범위 테스트 사용자', 'en' => 'Scope Test User'],
'version' => '1.0.0',
'type' => 'user',
'status' => ExtensionStatus::Active->value,
'description' => ['ko' => '테스트용', 'en' => 'For testing'],
]);
$this->seedLayout($other->id, 'user_home', 'template', null, true);
$this->seedLayout($this->template->id, 'admin_home', 'template', null, false);
$result = $this->templateManager->hasModifiedLayouts('test-scope-admin');
$this->assertSame(0, $result['modified_count'], '다른 템플릿의 수정본까지 집계되었습니다.');
}
/**
* 미존재 템플릿은 빈 결과를 반환한다.
*/
public function test_has_modified_layouts_returns_empty_for_unknown_template(): void
{
$result = $this->templateManager->hasModifiedLayouts('no-such-template');
$this->assertFalse($result['has_modified_layouts']);
$this->assertSame(0, $result['modified_count']);
$this->assertEmpty($result['modified_layouts']);
}
}
@@ -0,0 +1,69 @@
<?php
namespace Tests\Unit\Seo;
use App\Seo\ExpressionEvaluator;
use Tests\TestCase;
/**
* SEO(봇) 렌더러의 `{{raw:...}}` 번역 면제 바인딩 패리티 회귀 테스트.
*
* 배경: React 쪽 노드 `text` 처리에서 `raw:` 접두사를 벗기지 않아 표현식 평가가
* 예외로 끊기던 결함(engine-v1.54.4)을 고치면서, 봇 렌더러에는 접두사 처리 자체가
* 아예 없다는 사실이 드러났다. 같은 표현식이 화면에서는 값이 나오고 봇 화면에서만
* 사라지는 패리티 붕괴가 잠재해 있었다.
*/
class ExpressionEvaluatorRawPrefixTest extends TestCase
{
private function evaluator(): ExpressionEvaluator
{
$e = new ExpressionEvaluator;
$e->setTranslations(['common' => ['save' => '저장']]);
return $e;
}
public function test_raw_prefix_is_stripped_before_evaluation(): void
{
$context = ['file' => ['description' => '', 'name' => 'admin_module_list.json']];
$this->assertSame(
'admin_module_list.json',
$this->evaluator()->evaluate('{{raw:file.description || file.name}}', $context),
'raw: 접두사를 벗기지 않으면 콜론이 식으로 파싱돼 평가가 실패한다'
);
}
public function test_raw_prefix_result_is_translation_exempt(): void
{
$context = ['post' => ['title' => '$t:common.save']];
$this->assertSame(
'$t:common.save',
$this->evaluator()->evaluate('{{raw:post.title}}', $context),
'raw: 결과의 $t: 토큰은 번역하지 않아야 한다 (React rawMarkers 와 동일)'
);
}
public function test_non_raw_binding_still_resolves_translation_tokens(): void
{
$context = ['post' => ['title' => '$t:common.save']];
$this->assertSame(
'저장',
$this->evaluator()->evaluate('{{post.title}}', $context),
'raw: 가 없으면 종전대로 번역되어야 한다 (비회귀)'
);
}
public function test_evaluate_raw_strips_prefix(): void
{
$context = ['items' => [1, 2, 3]];
$this->assertSame(
[1, 2, 3],
$this->evaluator()->evaluateRaw('{{raw:items}}', $context),
'evaluateRaw 도 접두사를 벗기고 원본 타입을 유지해야 한다'
);
}
}