fix(core,admin_basic): 정적 게시 재게시 누락 3건 수정 + 관리자 수동 복구 UI + sudo core:update 소유권 정합
- 템플릿 update 는 레이아웃 변경 여부와 무관하게 캐시 버전을 올리고(실패 복원 뒤에도), 자산 주소 방식 전환 3경로도 bump 한다 - config:cache 가 컨테이너 인스턴스를 덮어 이후 terminating 재게시가 사라지던 결함을 복원 헬퍼로 차단 - custom/ 변경 감지와 게시가 같은 열거자(재귀·크기 포함)를 쓰고, 서명은 호스트별로 저장 - 캐시 버전·서명 키를 만료시키지 않는다(기본 TTL 24h 로 매일 전체 재생성되던 문제) - 관리자 > 환경설정 > 일반 「초기 화면 정적 파일」 카드: 상태 조회 + 지금 다시 만들기(확인 모달), 대시보드 알림 버튼 연결, CLI 와 같은 statusReport 소비 - sudo core:update 경로의 root 소유 잔존(설정 디렉토리·임시 폴더·로그·업그레이드 마이그레이션 산출물) 상속·정합화, ext-static 명령 root 경고와 sudo -u 힌트 - 안내·문서·트러블슈팅 4건·audit 룰 ext-cache-version-raw-read·ja 언어팩 동기
This commit is contained in:
1 parent
d263f74cae
commit
de18159986
105 files changed
+4055
-208
No files matched your search
@@ -0,0 +1,233 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Extension\Traits\ClearsTemplateCaches;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use App\Services\ExtensionStaticCacheService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 초기 화면 정적 파일(정적 게시) 상태 조회 + 관리자 수동 복구 API 테스트 (#651 U1·U2·U6).
|
||||
*
|
||||
* 캐시 버전이 만료로 재생성되지 않으므로(영구 번호) 재게시 누락은 무기한 stale 이 된다 —
|
||||
* 관리자 화면의 [지금 다시 만들기] 가 그 안전망이다. 이 테스트는 그 통로(권한 경계 · 진단 결과
|
||||
* 200 규약 · 버전 증가 + 게시)를 잠근다.
|
||||
*/
|
||||
class SettingsStaticCacheTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private const VERSION = 987650000;
|
||||
|
||||
private string $isolatedPublicPath;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
// 실 게시 트리(public/build/ext) 격리 — 운영 중 사이트의 게시본을 건드리지 않는다
|
||||
$this->isolatedPublicPath = storage_path('framework/testing/public-api-'.getmypid());
|
||||
File::ensureDirectoryExists($this->isolatedPublicPath);
|
||||
$this->app->usePublicPath($this->isolatedPublicPath);
|
||||
|
||||
ClearsTemplateCaches::resetExtensionCacheStoreMemo();
|
||||
Cache::put('g7:core:ext.cache_version', self::VERSION);
|
||||
Cache::forget('g7:core:ext.static.publish_failure');
|
||||
Cache::lock('ext-static.publish.'.self::VERSION, 300)->forceRelease();
|
||||
|
||||
ExtensionStaticCacheService::resetPublishScheduleForTesting();
|
||||
File::deleteDirectory(public_path('build/ext'));
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
File::deleteDirectory(public_path('build/ext'));
|
||||
File::deleteDirectory($this->isolatedPublicPath);
|
||||
ExtensionStaticCacheService::resetPublishScheduleForTesting();
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 권한을 가진 관리자를 만들고 Bearer 토큰을 돌려줍니다.
|
||||
*
|
||||
* @param array<int, string> $permissions 권한 식별자 목록
|
||||
* @return string plainText 토큰
|
||||
*/
|
||||
private function tokenWith(array $permissions): string
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$permissionIds = [];
|
||||
foreach ($permissions as $identifier) {
|
||||
$permissionIds[] = Permission::firstOrCreate(
|
||||
['identifier' => $identifier],
|
||||
[
|
||||
'name' => json_encode(['ko' => $identifier, 'en' => $identifier]),
|
||||
'description' => json_encode(['ko' => $identifier, 'en' => $identifier]),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'type' => 'admin',
|
||||
]
|
||||
)->id;
|
||||
}
|
||||
|
||||
$role = Role::create([
|
||||
'identifier' => 'static_cache_test_'.uniqid(),
|
||||
'name' => json_encode(['ko' => '테스트', 'en' => 'Test']),
|
||||
'description' => json_encode(['ko' => '테스트', 'en' => 'Test']),
|
||||
'is_active' => true,
|
||||
]);
|
||||
$role->permissions()->sync($permissionIds);
|
||||
|
||||
$adminRole = Role::firstOrCreate(
|
||||
['identifier' => 'admin'],
|
||||
[
|
||||
'name' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
|
||||
'description' => json_encode(['ko' => '관리자', 'en' => 'Administrator']),
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
|
||||
$user->roles()->attach($adminRole->id, ['assigned_at' => now(), 'assigned_by' => null]);
|
||||
$user->roles()->attach($role->id, ['assigned_at' => now(), 'assigned_by' => null]);
|
||||
|
||||
return $user->fresh()->createToken('test')->plainTextToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* 상태 조회는 CLI 와 같은 보고서 필드를 돌려준다.
|
||||
*
|
||||
* @scenario permission=granted, publishable=non_production, outcome=success
|
||||
*
|
||||
* @effects status_endpoint_returns_report_fields
|
||||
*/
|
||||
public function test_status_returns_report_fields(): void
|
||||
{
|
||||
$response = $this->withToken($this->tokenWith(['core.settings.read']))
|
||||
->getJson('/api/admin/settings/static-cache');
|
||||
|
||||
$response->assertOk()
|
||||
->assertJsonPath('success', true)
|
||||
->assertJsonPath('data.version', self::VERSION)
|
||||
->assertJsonPath('data.published', false)
|
||||
->assertJsonPath('data.publishable', false)
|
||||
->assertJsonStructure(['data' => [
|
||||
'enabled', 'publishable', 'environment', 'version', 'published', 'files',
|
||||
'published_at', 'tree_writable', 'process_user', 'failure', 'retained_versions',
|
||||
]]);
|
||||
|
||||
// 응답 메시지가 키 그대로 새어 나가지 않는다
|
||||
$this->assertStringNotContainsString('settings.', (string) $response->json('message'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 프로덕션에서 재게시하면 버전이 오르고 새 버전이 게시된다.
|
||||
*
|
||||
* @scenario permission=granted, publishable=production_enabled, outcome=success
|
||||
*
|
||||
* @effects republish_bumps_version_and_publishes
|
||||
*/
|
||||
public function test_republish_bumps_version_and_publishes_in_production(): void
|
||||
{
|
||||
$this->app['env'] = 'production';
|
||||
ExtensionStaticCacheService::fakeRootProcessForTesting(false);
|
||||
|
||||
$response = $this->withToken($this->tokenWith(['core.settings.read', 'core.settings.update']))
|
||||
->postJson('/api/admin/settings/static-cache/republish');
|
||||
|
||||
$response->assertOk()
|
||||
->assertJsonPath('success', true)
|
||||
->assertJsonPath('data.republished', true)
|
||||
->assertJsonPath('data.published', true)
|
||||
->assertJsonPath('data.publishable', true)
|
||||
->assertJsonPath('data.previous_version', self::VERSION);
|
||||
|
||||
$newVersion = (int) $response->json('data.version');
|
||||
$this->assertGreaterThan(self::VERSION, $newVersion, '재게시가 캐시 버전을 올리지 않았다');
|
||||
$this->assertTrue((bool) $response->json('data.version_changed'));
|
||||
$this->assertFileExists(public_path('build/ext/'.$newVersion.'/manifest.json'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 비프로덕션에서는 bump 하지 않고 200 + `republished=false` 로 사유를 돌려준다 (진단 결과 규약).
|
||||
*
|
||||
* @scenario permission=granted, publishable=non_production, outcome=publish_failed_marker
|
||||
*
|
||||
* @effects republish_disabled_when_not_publishable
|
||||
*/
|
||||
public function test_republish_outside_production_is_a_diagnostic_result_not_an_error(): void
|
||||
{
|
||||
$response = $this->withToken($this->tokenWith(['core.settings.read', 'core.settings.update']))
|
||||
->postJson('/api/admin/settings/static-cache/republish');
|
||||
|
||||
$response->assertOk()
|
||||
->assertJsonPath('data.republished', false)
|
||||
->assertJsonPath('data.publishable', false)
|
||||
->assertJsonPath('data.reason', 'not_production')
|
||||
->assertJsonPath('data.version', self::VERSION);
|
||||
|
||||
$this->assertSame(self::VERSION, (int) Cache::get('g7:core:ext.cache_version'), '게시가 쓰이지 않는 환경에서 버전을 올렸다');
|
||||
}
|
||||
|
||||
/**
|
||||
* kill-switch 가 꺼져 있으면 `enabled=false` 이고 재게시는 `disabled` 사유로 거절된다.
|
||||
*
|
||||
* @scenario permission=granted, publishable=kill_switch_off, outcome=publish_failed_marker
|
||||
*
|
||||
* @effects republish_disabled_when_not_publishable
|
||||
*/
|
||||
public function test_kill_switch_off_reports_disabled(): void
|
||||
{
|
||||
config(['core.static_cache.enabled' => false]);
|
||||
$this->app['env'] = 'production';
|
||||
|
||||
$token = $this->tokenWith(['core.settings.read', 'core.settings.update']);
|
||||
|
||||
$this->withToken($token)->getJson('/api/admin/settings/static-cache')
|
||||
->assertOk()
|
||||
->assertJsonPath('data.enabled', false)
|
||||
->assertJsonPath('data.publishable', false);
|
||||
|
||||
$this->withToken($token)->postJson('/api/admin/settings/static-cache/republish')
|
||||
->assertOk()
|
||||
->assertJsonPath('data.republished', false)
|
||||
->assertJsonPath('data.reason', 'disabled');
|
||||
}
|
||||
|
||||
/**
|
||||
* 읽기 권한만으로는 재게시할 수 없다.
|
||||
*
|
||||
* @scenario permission=denied, publishable=production_enabled, outcome=success
|
||||
*
|
||||
* @effects republish_denied_without_settings_update_permission
|
||||
*/
|
||||
public function test_republish_requires_settings_update_permission(): void
|
||||
{
|
||||
$this->withToken($this->tokenWith(['core.settings.read']))
|
||||
->postJson('/api/admin/settings/static-cache/republish')
|
||||
->assertStatus(403);
|
||||
}
|
||||
|
||||
/**
|
||||
* 비인증 요청은 401 이다.
|
||||
*
|
||||
* @scenario permission=denied, publishable=non_production, outcome=success
|
||||
*
|
||||
* @effects republish_denied_without_settings_update_permission
|
||||
*/
|
||||
public function test_unauthenticated_requests_are_rejected(): void
|
||||
{
|
||||
$this->getJson('/api/admin/settings/static-cache')->assertStatus(401);
|
||||
$this->postJson('/api/admin/settings/static-cache/republish')->assertStatus(401);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Console;
|
||||
|
||||
use App\Extension\Helpers\FilePermissionHelper;
|
||||
use App\Extension\Traits\ClearsTemplateCaches;
|
||||
use App\Services\ExtensionStaticCacheService;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* `ext-static:status` / `ext-static:publish` 의 root 실행 안내 + 상태 보고서 소비 테스트 (#651 C1·D3).
|
||||
*
|
||||
* 상태 명령은 종전에 "즉시 게시하려면 `php artisan ext-static:publish`" 를 실행 계정과 무관하게
|
||||
* 권했다. 운영자가 그 안내를 sudo 셸에서 그대로 따르면 캐시 락 샤드가 root 소유가 되어 이후 웹
|
||||
* 요청이 500 이 된다. 이제 root 이면 경고와 `sudo -u {웹계정}` 형태의 힌트를 함께 낸다 — 중단은
|
||||
* 하지 않는다(D3).
|
||||
*/
|
||||
class ExtStaticStatusCommandTest extends TestCase
|
||||
{
|
||||
private string $isolatedPublicPath;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->isolatedPublicPath = storage_path('framework/testing/public-cmd-'.getmypid());
|
||||
File::ensureDirectoryExists($this->isolatedPublicPath);
|
||||
$this->app->usePublicPath($this->isolatedPublicPath);
|
||||
|
||||
ClearsTemplateCaches::resetExtensionCacheStoreMemo();
|
||||
Cache::put('g7:core:ext.cache_version', 987600000);
|
||||
Cache::forget('g7:core:ext.static.publish_failure');
|
||||
ExtensionStaticCacheService::resetPublishScheduleForTesting();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
FilePermissionHelper::fakeWebServerAccountForTesting(null);
|
||||
File::deleteDirectory($this->isolatedPublicPath);
|
||||
ExtensionStaticCacheService::resetPublishScheduleForTesting();
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* root 가 아니면 경고 없이 종전 문구 그대로다 (미게시 → 비-0 종료).
|
||||
*
|
||||
* @effects status_command_warns_root_and_hints_web_account
|
||||
*/
|
||||
public function test_non_root_status_prints_plain_publish_hint_without_root_warning(): void
|
||||
{
|
||||
FilePermissionHelper::fakeWebServerAccountForTesting(['mode' => 'non_root', 'name' => null]);
|
||||
|
||||
$this->artisan('ext-static:status')
|
||||
->expectsOutputToContain('부트스트랩 리소스 정적 게시 상태')
|
||||
->expectsOutputToContain('현재 캐시 버전 : 987600000')
|
||||
->expectsOutputToContain('게시 상태 : 미게시')
|
||||
->expectsOutputToContain('php artisan ext-static:publish')
|
||||
->doesntExpectOutputToContain('root 로 실행 중')
|
||||
->doesntExpectOutputToContain('sudo -u')
|
||||
->assertExitCode(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* root + 웹 계정 식별 → 경고 + `sudo -u {계정}` 힌트. 종료 코드는 종전과 같다.
|
||||
*
|
||||
* @effects status_command_warns_root_and_hints_web_account
|
||||
*/
|
||||
public function test_root_status_warns_and_hints_sudo_with_web_account(): void
|
||||
{
|
||||
FilePermissionHelper::fakeWebServerAccountForTesting(['mode' => 'root_web_known', 'name' => 'www-data']);
|
||||
|
||||
$this->artisan('ext-static:status')
|
||||
->expectsOutputToContain('root 로 실행 중')
|
||||
->expectsOutputToContain('sudo -u www-data php artisan ext-static:publish')
|
||||
->assertExitCode(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* root + 웹 계정 미상 → placeholder 와 확인 방법.
|
||||
*
|
||||
* @effects status_command_warns_root_and_hints_web_account
|
||||
*/
|
||||
public function test_root_status_with_unknown_web_account_uses_placeholder(): void
|
||||
{
|
||||
FilePermissionHelper::fakeWebServerAccountForTesting(['mode' => 'root_web_unknown', 'name' => null]);
|
||||
|
||||
// 한 줄에 두 부분 문자열을 따로 기대하면 Mockery 가 첫 기대만 소비한다 — 한 문자열로 잠근다
|
||||
$this->artisan('ext-static:status')
|
||||
->expectsOutputToContain('sudo -u <웹서버계정> php artisan ext-static:publish (웹서버 계정은 storage 디렉토리 소유자로 확인)')
|
||||
->assertExitCode(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* root 서비스 구성(웹 계정도 root)은 sudo 접두 없이 안내한다 — 재실행도 root 로 무해.
|
||||
*
|
||||
* @effects status_command_warns_root_and_hints_web_account
|
||||
*/
|
||||
public function test_root_symmetric_hint_has_no_sudo_prefix(): void
|
||||
{
|
||||
FilePermissionHelper::fakeWebServerAccountForTesting(['mode' => 'root_web_symmetric', 'name' => null]);
|
||||
|
||||
$this->artisan('ext-static:status')
|
||||
->expectsOutputToContain('root 로 실행 중')
|
||||
->doesntExpectOutputToContain('sudo -u')
|
||||
->assertExitCode(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시 명령은 root 여도 **중단하지 않고** 경고 뒤 계속 실행한다 (D3 — 명시적 명령은 운영자 책임).
|
||||
*
|
||||
* @effects publish_command_warns_root_but_continues
|
||||
*/
|
||||
public function test_publish_warns_root_but_still_publishes(): void
|
||||
{
|
||||
FilePermissionHelper::fakeWebServerAccountForTesting(['mode' => 'root_web_known', 'name' => 'www-data']);
|
||||
Cache::lock('ext-static.publish.987600000', 300)->forceRelease();
|
||||
|
||||
$this->artisan('ext-static:publish')
|
||||
->expectsOutputToContain('root 로 실행 중')
|
||||
->expectsOutputToContain('sudo -u www-data php artisan ext-static:publish')
|
||||
->expectsOutputToContain('정적 게시가 완료되었습니다')
|
||||
->assertExitCode(0);
|
||||
|
||||
$this->assertFileExists(public_path('build/ext/987600000/manifest.json'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 상태 명령은 서비스 보고서를 소비한다 — 게시 뒤에는 완료·파일 수·게시 시각을 그대로 보인다.
|
||||
*
|
||||
* @effects status_command_consumes_service_report
|
||||
*/
|
||||
public function test_status_reflects_published_report(): void
|
||||
{
|
||||
FilePermissionHelper::fakeWebServerAccountForTesting(['mode' => 'non_root', 'name' => null]);
|
||||
Cache::lock('ext-static.publish.987600000', 300)->forceRelease();
|
||||
|
||||
$this->assertTrue(app(ExtensionStaticCacheService::class)->publishCurrent());
|
||||
|
||||
$this->artisan('ext-static:status')
|
||||
->expectsOutputToContain('게시 상태 : 완료')
|
||||
->expectsOutputToContain('manifest 파일 : 1건')
|
||||
->expectsOutputToContain('이상 없음.')
|
||||
->assertExitCode(0);
|
||||
}
|
||||
}
|
||||
@@ -98,6 +98,29 @@ class StaticPublishAlertTest extends TestCase
|
||||
$this->assertStringNotContainsString(':count', $alerts[0]['message']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 알림에서 바로 복구한다 — 관리자 수동 복구 엔드포인트와 버튼 라벨·성공 문구를 싣는다 (#651 D11).
|
||||
*
|
||||
* 대시보드 렌더러는 `recover_endpoint` 가 있는 알림에 [다시 만들기] 버튼을 그리고 그 주소로
|
||||
* POST 한다. 운영자가 결함을 처음 만나는 곳이 알림이므로 그 자리에서 복구가 끝나야 한다.
|
||||
*
|
||||
* @effects dashboard_alert_points_to_admin_republish
|
||||
*/
|
||||
public function test_alert_carries_admin_republish_recover_wiring(): void
|
||||
{
|
||||
$this->seedMarker(2);
|
||||
|
||||
$alerts = $this->listener()->addStaticPublishAlert([]);
|
||||
|
||||
$this->assertSame('/api/admin/settings/static-cache/republish', $alerts[0]['recover_endpoint']);
|
||||
$this->assertNotSame('', $alerts[0]['recover_label']);
|
||||
$this->assertStringNotContainsString('extensions.alerts.', $alerts[0]['recover_label']);
|
||||
$this->assertStringNotContainsString('extensions.alerts.', $alerts[0]['recover_success_message']);
|
||||
|
||||
// 문구도 관리자 화면 경로를 안내한다 — CLI 만 안내하면 수동 복구 UI 가 있어도 운영자가 모른다
|
||||
$this->assertStringContainsString('환경설정', $alerts[0]['message']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 사유별로 subtype 과 문구가 갈린다 — 조치할 곳이 다르기 때문이다.
|
||||
*
|
||||
|
||||
@@ -14,6 +14,7 @@ use App\Services\ExtensionBundleService;
|
||||
use App\Services\ExtensionStaticCacheService;
|
||||
use App\Services\LanguagePackService;
|
||||
use App\Services\TemplateService;
|
||||
use App\Support\CustomAssets;
|
||||
use Illuminate\Cache\ArrayStore;
|
||||
use Illuminate\Cache\Repository;
|
||||
use Illuminate\Filesystem\Filesystem;
|
||||
@@ -288,6 +289,132 @@ class ExtensionStaticCacheServiceTest extends TestCase
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시된 custom 파일 집합 == `CustomAssets::publishableFiles()` 집합 (#651 F7 패리티).
|
||||
*
|
||||
* 변경 감지가 이 열거자로 서명을 만들므로, 게시가 다른 집합을 복사하면 "감지됐는데 게시본에
|
||||
* 없다" 또는 "게시본에 있는데 바꿔도 감지되지 않는다" 가 된다. 두 소비자가 같은 열거자를
|
||||
* 쓰는지를 산출물로 잠근다.
|
||||
*
|
||||
* @effects custom_signature_covers_publishable_tree
|
||||
*/
|
||||
public function test_published_custom_set_matches_publishable_files(): void
|
||||
{
|
||||
$template = $this->createActiveTemplate();
|
||||
$identifier = (string) $template->identifier;
|
||||
$dir = base_path("templates/{$identifier}/custom");
|
||||
|
||||
File::ensureDirectoryExists($dir.'/img/deep');
|
||||
File::put($dir.'/custom.css', "body { background-image: url('./img/deep/m.svg'); }");
|
||||
File::put($dir.'/img/deep/m.svg', '<svg/>');
|
||||
File::put($dir.'/fonts.woff2', 'font');
|
||||
File::put($dir.'/notes.txt', 'not an asset');
|
||||
|
||||
try {
|
||||
CustomAssets::flushCache();
|
||||
$service = $this->service();
|
||||
$this->assertTrue($service->publishCurrent(), $this->publishDiagnostics($service));
|
||||
|
||||
$customRoot = $service->versionDir(self::VERSION)."/templates/{$identifier}/assets/custom";
|
||||
$published = [];
|
||||
foreach (File::allFiles($customRoot) as $file) {
|
||||
$published[] = str_replace('\\', '/', $file->getRelativePathname());
|
||||
}
|
||||
sort($published, SORT_STRING);
|
||||
|
||||
$enumerated = array_column(CustomAssets::publishableFiles('templates', $identifier), 'relative');
|
||||
|
||||
$this->assertSame($enumerated, $published, '게시된 custom 집합이 공유 열거자 집합과 다르다 — 감지와 게시 범위가 어긋난다');
|
||||
$this->assertSame(['custom.css', 'fonts.woff2', 'img/deep/m.svg'], $published);
|
||||
} finally {
|
||||
File::deleteDirectory($dir);
|
||||
// 요청 스코프 메모가 지운 파일을 가리키지 않도록 비운다 (같은 프로세스의 다음 테스트가 게시한다)
|
||||
CustomAssets::flushCache();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 상태 보고서는 미게시/게시 상태를 필드로 구분해 돌려준다 — CLI·API·화면이 같은 판정을 소비한다.
|
||||
*
|
||||
* @effects status_endpoint_returns_report_fields
|
||||
*/
|
||||
public function test_status_report_reflects_publish_state(): void
|
||||
{
|
||||
$service = $this->service();
|
||||
|
||||
$before = $service->statusReport();
|
||||
$this->assertSame(self::VERSION, $before['version']);
|
||||
$this->assertFalse($before['published']);
|
||||
$this->assertSame(0, $before['files']);
|
||||
$this->assertNull($before['published_at']);
|
||||
$this->assertFalse($before['publishable'], 'testing 환경은 publishable 이 아니다');
|
||||
$this->assertTrue($before['enabled']);
|
||||
$this->assertNull($before['failure']);
|
||||
$this->assertSame([], $before['retained_versions']);
|
||||
|
||||
$this->assertTrue($service->publishCurrent(), $this->publishDiagnostics($service));
|
||||
|
||||
$after = $service->statusReport();
|
||||
$this->assertTrue($after['published']);
|
||||
$this->assertGreaterThan(0, $after['files']);
|
||||
$this->assertNotNull($after['published_at']);
|
||||
$this->assertSame([self::VERSION], $after['retained_versions']);
|
||||
$this->assertTrue($after['tree_writable']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 수동 복구는 버전을 올리고 새 버전을 강제 게시한다 (`force` 없으면 같은 초 재게시가 skip 된다).
|
||||
*
|
||||
* @effects republish_bumps_version_and_publishes
|
||||
*/
|
||||
public function test_republish_bumps_version_and_force_publishes(): void
|
||||
{
|
||||
$this->app['env'] = 'production';
|
||||
ExtensionStaticCacheService::fakeRootProcessForTesting(false);
|
||||
|
||||
$service = $this->service();
|
||||
$result = $service->republish();
|
||||
|
||||
$this->assertTrue($result['republished'], json_encode($result));
|
||||
$this->assertSame(self::VERSION, $result['previous_version']);
|
||||
$this->assertGreaterThan(self::VERSION, $result['version']);
|
||||
$this->assertTrue($result['version_changed']);
|
||||
$this->assertTrue($result['published']);
|
||||
$this->assertNull($result['reason']);
|
||||
$this->assertFileExists($service->versionDir($result['version']).'/manifest.json');
|
||||
|
||||
// 같은 초의 연속 복구도 **내용을 다시 만든다** — manifest 시각이 갱신된다
|
||||
$firstManifest = (string) file_get_contents($service->versionDir($result['version']).'/manifest.json');
|
||||
sleep(1);
|
||||
$second = $service->republish();
|
||||
$this->assertTrue($second['republished']);
|
||||
$this->assertNotSame($firstManifest, (string) file_get_contents($service->versionDir($second['version']).'/manifest.json'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시가 쓰이지 않는 환경(비프로덕션 / kill-switch)에서는 bump 하지 않고 사유를 돌려준다.
|
||||
*
|
||||
* @effects republish_disabled_when_not_publishable
|
||||
*/
|
||||
public function test_republish_refuses_without_bump_when_not_publishable(): void
|
||||
{
|
||||
$service = $this->service();
|
||||
|
||||
$result = $service->republish();
|
||||
$this->assertFalse($result['republished']);
|
||||
$this->assertSame('not_production', $result['reason']);
|
||||
$this->assertSame(self::VERSION, $result['version']);
|
||||
$this->assertFalse($result['version_changed']);
|
||||
|
||||
config(['core.static_cache.enabled' => false]);
|
||||
$this->app['env'] = 'production';
|
||||
|
||||
$result = $service->republish();
|
||||
$this->assertFalse($result['republished']);
|
||||
$this->assertSame('disabled', $result['reason']);
|
||||
$this->assertSame(self::VERSION, ExtensionStaticCacheService::getExtensionCacheVersion());
|
||||
}
|
||||
|
||||
/**
|
||||
* 비활성 확장의 custom 은 게시하지 않는다.
|
||||
*
|
||||
|
||||
@@ -9,6 +9,7 @@ use App\Extension\PluginManager;
|
||||
use App\Http\View\Composers\TemplateComposer;
|
||||
use App\Support\CustomAssets;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use ReflectionMethod;
|
||||
@@ -285,9 +286,9 @@ class CustomAssetInjectionTest extends TestCase
|
||||
* `?custom=off` 진동은 `customAssetsDisabledByRequest` 가 이미 막고 있다 — 같은
|
||||
* 진동의 다른 원인인 admin/user 템플릿 비대칭만 열려 있었다.
|
||||
*
|
||||
* @scenario custom_source=convention_scan, custom_ext_type=template
|
||||
* @scenario custom_source=convention_scan, custom_asset=css, custom_change_detection=top_level_asset
|
||||
*
|
||||
* @effects custom_asset_signature_is_scoped_per_render
|
||||
* @effects custom_asset_signature_is_scoped_per_render, custom_signature_scoped_per_host
|
||||
*/
|
||||
#[Test]
|
||||
public function 관리자_사용자_렌더가_서명_키를_서로_덮어쓰지_않는다(): void
|
||||
@@ -322,21 +323,23 @@ class CustomAssetInjectionTest extends TestCase
|
||||
$collect->invoke($composer, $identifier);
|
||||
}
|
||||
|
||||
// 두 렌더의 서명이 **각자** 기억된다 — 하나의 자리를 서로 덮어쓰지 않는다
|
||||
// 두 렌더의 서명이 **각자** 기억된다 — 하나의 자리를 서로 덮어쓰지 않는다.
|
||||
// 스코프 키는 `{템플릿}@{호스트명}` — 다중 서버 공유 캐시에서 서버별로 기억한다(#651 F9).
|
||||
$host = gethostname() ?: 'host';
|
||||
$stored = $cache->get(CustomAssets::SIGNATURE_CACHE_KEY);
|
||||
|
||||
$this->assertIsArray($stored, '서명이 스코프별로 기억되지 않는다 (단일 값으로 덮어쓰기)');
|
||||
$this->assertArrayHasKey($adminTemplate, $stored);
|
||||
$this->assertArrayHasKey($userTemplate, $stored);
|
||||
$this->assertNotSame($stored[$adminTemplate], $stored[$userTemplate]);
|
||||
$this->assertArrayHasKey($adminTemplate.'@'.$host, $stored);
|
||||
$this->assertArrayHasKey($userTemplate.'@'.$host, $stored);
|
||||
$this->assertNotSame($stored[$adminTemplate.'@'.$host], $stored[$userTemplate.'@'.$host]);
|
||||
|
||||
// 파일은 그대로다 — 렌더를 오간다고 버전이 올라서는 안 된다
|
||||
$this->assertFalse(
|
||||
$sync->invoke($composer, $adminAssets, $adminTemplate),
|
||||
$sync->invoke($composer, $adminTemplate),
|
||||
'관리자 렌더가 사용자 렌더의 서명을 덮어써 파일 변경으로 오독했다'
|
||||
);
|
||||
$this->assertFalse(
|
||||
$sync->invoke($composer, $userAssets, $userTemplate),
|
||||
$sync->invoke($composer, $userTemplate),
|
||||
'사용자 렌더가 관리자 렌더의 서명을 덮어써 파일 변경으로 오독했다'
|
||||
);
|
||||
|
||||
@@ -346,7 +349,7 @@ class CustomAssetInjectionTest extends TestCase
|
||||
CustomAssets::flushCache();
|
||||
|
||||
$this->assertTrue(
|
||||
$sync->invoke($composer, $resolve->invoke($composer, $userTemplate), $userTemplate),
|
||||
$sync->invoke($composer, $userTemplate),
|
||||
'파일을 고쳤는데 변경 감지가 발화하지 않았다'
|
||||
);
|
||||
} finally {
|
||||
@@ -356,4 +359,92 @@ class CustomAssetInjectionTest extends TestCase
|
||||
CustomAssets::flushCache();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `custom/` **하위 디렉토리**의 글꼴·이미지 변경도 감지한다 — 게시와 같은 범위 (#651 F7).
|
||||
*
|
||||
* 종전 서명은 로드 목록(최상위 css/js)의 mtime 만 봤다. 게시는 `custom/**` 를 재귀로
|
||||
* 복사하므로, 문서가 권장하는 `url('./img/marker.svg')` 의 대상 파일만 교체하면 게시본이
|
||||
* 영영 갱신되지 않았다 — 실측(g7_2.dev): svg 62B→78B 교체 뒤 버전 불변, 게시본 62B.
|
||||
* mtime 이 같은 재작성도 크기로 잡는다.
|
||||
*
|
||||
* @scenario custom_source=convention_scan, custom_asset=static_file, custom_change_detection=nested_static_file
|
||||
*
|
||||
* @effects custom_signature_covers_publishable_tree
|
||||
*/
|
||||
#[Test]
|
||||
public function custom_하위_파일_크기_변경은_버전을_올린다(): void
|
||||
{
|
||||
$template = 'g7test-nested_tpl';
|
||||
$dir = base_path('templates/'.$template.'/custom');
|
||||
|
||||
File::ensureDirectoryExists($dir.'/img');
|
||||
File::put($dir.'/custom.css', ".x{background:url('./img/marker.svg')}");
|
||||
File::put($dir.'/img/marker.svg', '<svg/>');
|
||||
|
||||
try {
|
||||
$composer = app(TemplateComposer::class);
|
||||
$sync = new ReflectionMethod(TemplateComposer::class, 'syncCustomAssetCacheVersion');
|
||||
$cache = app(CacheInterface::class);
|
||||
|
||||
$cache->forget(CustomAssets::SIGNATURE_CACHE_KEY);
|
||||
$cache->put('ext.cache_version', 1000);
|
||||
|
||||
CustomAssets::flushCache();
|
||||
$this->assertFalse($sync->invoke($composer, $template), '첫 관측은 기록만 해야 한다');
|
||||
$this->assertFalse($sync->invoke($composer, $template), '변경이 없으면 올리지 않는다');
|
||||
|
||||
// 최상위 css 는 그대로, 하위 svg 만 내용(크기)이 바뀐다 — mtime 은 그대로 둔다
|
||||
$mtime = filemtime($dir.'/img/marker.svg');
|
||||
File::put($dir.'/img/marker.svg', '<svg><!-- v2 --></svg>');
|
||||
touch($dir.'/img/marker.svg', $mtime);
|
||||
CustomAssets::flushCache();
|
||||
|
||||
$this->assertTrue(
|
||||
$sync->invoke($composer, $template),
|
||||
'하위 디렉토리 파일의 크기 변경이 감지되지 않았다 — 게시본의 글꼴·이미지가 영영 갱신되지 않는다'
|
||||
);
|
||||
$this->assertGreaterThan(1000, (int) $cache->get('ext.cache_version'));
|
||||
} finally {
|
||||
File::deleteDirectory(base_path('templates/'.$template));
|
||||
CustomAssets::flushCache();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 서명 키는 만료되지 않는다 — 기본 TTL 로 만료되면 그 경계의 첫 관측이 "기록만" 이라 변경 1회를 놓친다 (#651 F11).
|
||||
*
|
||||
* @scenario custom_source=convention_scan, custom_asset=css, custom_change_detection=no_change
|
||||
*
|
||||
* @effects cache_version_key_does_not_expire
|
||||
*/
|
||||
#[Test]
|
||||
public function 서명_키는_이틀_뒤에도_남아_있다(): void
|
||||
{
|
||||
$this->mock(PluginManager::class, function ($mock) {
|
||||
$mock->shouldReceive('getActivePlugins')->andReturn([self::FAKE_PLUGIN => []]);
|
||||
$mock->shouldReceive('loadPlugins')->andReturnNull();
|
||||
});
|
||||
|
||||
$composer = app(TemplateComposer::class);
|
||||
$collect = new ReflectionMethod(TemplateComposer::class, 'collectCustomAssets');
|
||||
$cache = app(CacheInterface::class);
|
||||
|
||||
$cache->forget(CustomAssets::SIGNATURE_CACHE_KEY);
|
||||
CustomAssets::flushCache();
|
||||
$collect->invoke($composer, null);
|
||||
|
||||
$this->assertIsArray($cache->get(CustomAssets::SIGNATURE_CACHE_KEY));
|
||||
|
||||
try {
|
||||
Carbon::setTestNow(now()->addDays(2));
|
||||
|
||||
$this->assertIsArray(
|
||||
$cache->get(CustomAssets::SIGNATURE_CACHE_KEY),
|
||||
'서명 키가 기본 TTL 로 만료됐다 — 만료 경계의 실제 변경 1회가 조용히 삼켜진다'
|
||||
);
|
||||
} finally {
|
||||
Carbon::setTestNow();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* E2E: 환경설정 > 일반 — 초기 화면 정적 파일 상태 카드 + 지금 다시 만들기 (#651 D4·D7)
|
||||
*
|
||||
* 시나리오 매니페스트: tests/scenarios/static-cache-admin-rebuild.yaml — 마킹은 각 테스트의
|
||||
* scenario(k=v 조합)·effects 주석이 담당한다.
|
||||
*
|
||||
* 배경: 확장 캐시 버전이 만료로 재생성되지 않으므로(영구 번호) 재게시 누락은 무기한 stale 이 된다.
|
||||
* 관리자 화면의 [지금 다시 만들기] 가 그 안전망이다 — 상태를 보고, 확인 모달을 거쳐, POST 하고,
|
||||
* 토스트와 카드 재조회로 결과를 확인한다.
|
||||
*
|
||||
* 환경 가드: 대상 사이트가 운영 모드(production)가 아니면 카드는 「개발 모드」 배지와 비활성 버튼을
|
||||
* 보인다 — 그 경우 재게시 케이스는 skip 하고 비활성 계약만 잠근다.
|
||||
*/
|
||||
import { test, expect, issueToken, issueScopedToken, authenticatePage } from '../../fixtures/auth';
|
||||
|
||||
/** 관리자 환경설정 일반 탭 진입 + 상태 카드 도착 대기 */
|
||||
async function gotoGeneralTab(page: import('@playwright/test').Page): Promise<void> {
|
||||
// 배지 문구는 데이터소스 도착 전에는 비어 있다 — 상태 GET 응답을 기다려야 publishable 판정이 실제 값이 된다
|
||||
const statusArrived = page.waitForResponse(
|
||||
(r) => r.request().method() === 'GET' && /\/api\/admin\/settings\/static-cache$/.test(new URL(r.url()).pathname),
|
||||
{ timeout: 30_000 }
|
||||
);
|
||||
await page.goto('/admin/settings');
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
|
||||
await expect(page.locator('#card_static_cache')).toBeAttached({ timeout: 20_000 });
|
||||
await statusArrived;
|
||||
await expect(page.locator('#static_cache_status_badge')).not.toHaveText('', { timeout: 20_000 });
|
||||
}
|
||||
|
||||
/** 카드가 「게시됨/미게시」(publishable) 상태인지 — 운영 모드 + kill-switch 켜짐 */
|
||||
async function isPublishable(page: import('@playwright/test').Page): Promise<boolean> {
|
||||
const text = (await page.locator('#static_cache_status_badge').textContent()) ?? '';
|
||||
return /게시됨|미게시|Published|Not published/.test(text);
|
||||
}
|
||||
|
||||
// @scenario permission=granted, publishable=production_enabled, outcome=success
|
||||
// @effects card_renders_status_rows
|
||||
test('@smoke #651 - 일반 탭에 초기 화면 정적 파일 카드가 상태 행과 함께 렌더된다', async ({ page }) => {
|
||||
const token = issueToken('core.settings.read', 'core.settings.update');
|
||||
await authenticatePage(page, token);
|
||||
|
||||
const statusResponse = page.waitForResponse(
|
||||
(r) => r.request().method() === 'GET' && /\/api\/admin\/settings\/static-cache$/.test(new URL(r.url()).pathname),
|
||||
{ timeout: 20_000 }
|
||||
);
|
||||
|
||||
await gotoGeneralTab(page);
|
||||
|
||||
const response = await statusResponse;
|
||||
expect(response.status()).toBe(200);
|
||||
const body = await response.json();
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data).toHaveProperty('publishable');
|
||||
expect(body.data).toHaveProperty('version');
|
||||
|
||||
// 카드는 에셋 서빙 카드 다음에 있고, 행 텍스트에 다국어 키가 노출되지 않는다
|
||||
await expect(page.locator('#card_asset_serving')).toBeAttached();
|
||||
const cardText = (await page.locator('#card_static_cache').textContent()) ?? '';
|
||||
expect(cardText).not.toContain('$t:');
|
||||
expect(cardText).not.toContain('admin.settings');
|
||||
|
||||
await expect(page.locator('#static_cache_version_row')).toBeAttached();
|
||||
await expect(page.locator('#static_cache_files_row')).toBeAttached();
|
||||
await expect(page.locator('#static_cache_published_at_row')).toBeAttached();
|
||||
await expect(page.locator('#static_cache_process_user_row')).toBeAttached();
|
||||
});
|
||||
|
||||
// @scenario permission=granted, publishable=non_production, outcome=success
|
||||
// @effects republish_button_disabled_when_not_publishable
|
||||
test('#651 - 게시가 쓰이지 않는 환경이면 버튼이 비활성이고 사유 힌트가 있다', async ({ page }) => {
|
||||
const token = issueToken('core.settings.read', 'core.settings.update');
|
||||
await authenticatePage(page, token);
|
||||
|
||||
await gotoGeneralTab(page);
|
||||
|
||||
const button = page.locator('#static_cache_republish_button');
|
||||
await expect(button).toBeAttached();
|
||||
|
||||
if (await isPublishable(page)) {
|
||||
// 운영 모드 사이트 — 버튼은 활성이어야 하고 힌트는 없다 (비활성 분기는 단위 테스트가 덮는다)
|
||||
await expect(button).toBeEnabled();
|
||||
await expect(page.locator('#static_cache_not_publishable_hint')).toHaveCount(0);
|
||||
return;
|
||||
}
|
||||
|
||||
await expect(button).toBeDisabled();
|
||||
await expect(button).toHaveAttribute('aria-disabled', 'true');
|
||||
await expect(page.locator('#static_cache_not_publishable_hint')).toBeAttached();
|
||||
});
|
||||
|
||||
// @scenario permission=granted, publishable=production_enabled, outcome=success
|
||||
// @effects confirm_modal_then_toast_and_refetch
|
||||
test('#651 - 지금 다시 만들기 → 확인 모달 → POST 200 → 토스트 + 카드 재조회', async ({ page }) => {
|
||||
const token = issueToken('core.settings.read', 'core.settings.update');
|
||||
await authenticatePage(page, token);
|
||||
|
||||
await gotoGeneralTab(page);
|
||||
test.skip(!(await isPublishable(page)), '대상 사이트가 운영 모드가 아니어서 재게시를 수행할 수 없다 (비활성 계약은 별도 케이스가 잠근다)');
|
||||
|
||||
const versionBefore = ((await page.locator('#static_cache_version_row').textContent()) ?? '').replace(/\D/g, '');
|
||||
|
||||
await page.locator('#static_cache_republish_button').click();
|
||||
await expect(page.locator('#static_cache_republish_confirm_button')).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
const republish = page.waitForResponse(
|
||||
(r) => r.request().method() === 'POST' && /\/api\/admin\/settings\/static-cache\/republish$/.test(new URL(r.url()).pathname),
|
||||
{ timeout: 300_000 }
|
||||
);
|
||||
const refetch = page.waitForResponse(
|
||||
(r) => r.request().method() === 'GET' && /\/api\/admin\/settings\/static-cache$/.test(new URL(r.url()).pathname),
|
||||
{ timeout: 300_000 }
|
||||
);
|
||||
|
||||
await page.locator('#static_cache_republish_confirm_button').click();
|
||||
|
||||
const response = await republish;
|
||||
expect(response.status()).toBe(200);
|
||||
const body = await response.json();
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data.republished).toBe(true);
|
||||
expect(Number(body.data.version)).toBeGreaterThan(Number(versionBefore));
|
||||
|
||||
// 상태 재조회가 뒤따르고 모달이 닫힌다
|
||||
expect((await refetch).status()).toBe(200);
|
||||
await expect(page.locator('#static_cache_republish_confirm_button')).toBeHidden({ timeout: 10_000 });
|
||||
|
||||
// 카드에 새 버전이 반영된다
|
||||
await expect
|
||||
.poll(async () => ((await page.locator('#static_cache_version_row').textContent()) ?? '').replace(/\D/g, ''), { timeout: 20_000 })
|
||||
.toBe(String(body.data.version));
|
||||
|
||||
// 토스트 문구가 키 그대로 새어 나가지 않는다
|
||||
const toast = page.locator('[role="alert"], [role="status"], .toast').filter({ hasText: /다시 만들|rebuilt/ }).first();
|
||||
await expect(toast).toBeVisible({ timeout: 10_000 });
|
||||
});
|
||||
|
||||
// @scenario permission=denied, publishable=production_enabled, outcome=success
|
||||
// @effects republish_denied_without_settings_update_permission
|
||||
test('#651 - 읽기 권한만 있으면 상태는 보이지만 재게시 POST 는 403 이다', async ({ page }) => {
|
||||
const token = issueScopedToken('core.settings.read');
|
||||
await authenticatePage(page, token);
|
||||
|
||||
await gotoGeneralTab(page);
|
||||
|
||||
// 읽기 전용 계정에는 버튼이 비활성으로 렌더된다 (isReadOnly)
|
||||
await expect(page.locator('#static_cache_republish_button')).toBeDisabled();
|
||||
|
||||
// 서버 경계 — 화면 비활성과 무관하게 API 자체가 거부한다
|
||||
const status = await page.evaluate(async (t) => {
|
||||
const r = await fetch('/api/admin/settings/static-cache/republish', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${t}`, Accept: 'application/json' },
|
||||
});
|
||||
return { status: r.status, body: await r.json().catch(() => null) };
|
||||
}, token);
|
||||
|
||||
expect(status.status).toBe(403);
|
||||
expect(status.body?.success).toBe(false);
|
||||
expect(JSON.stringify(status.body)).not.toContain('settings.');
|
||||
});
|
||||
@@ -26,6 +26,19 @@ class BackupDirectoryRestoreOwnershipConfigTest extends TestCase
|
||||
$this->assertContains('storage/app/core_backups', $paths);
|
||||
}
|
||||
|
||||
/**
|
||||
* 정적 게시 트리(`public/build/ext`)가 두 목록에 포함된다 (#651 F22).
|
||||
*
|
||||
* root 프로세스는 자동 게시를 예약하지 않으므로 이 항목의 목적은 "terminating 게시가 만든 root
|
||||
* 디렉토리" 가 아니라 **실존하는** 게시 트리(웹 계정이 게시한 사이트)의 소유권을 코어 업데이트
|
||||
* 뒤 되돌리는 것이다 — 빠지면 재게시·GC 가 영구 실패해 정적 fast path 가 꺼진다.
|
||||
*/
|
||||
public function test_restore_ownership_includes_static_publish_tree(): void
|
||||
{
|
||||
$this->assertContains('public/build/ext', config('app.update.restore_ownership'));
|
||||
$this->assertContains('public/build/ext', config('app.update.restore_ownership_group_writable'));
|
||||
}
|
||||
|
||||
/**
|
||||
* restore_ownership_group_writable 목록에 백업 2경로가 포함됨.
|
||||
*/
|
||||
|
||||
@@ -9,6 +9,7 @@ use App\Extension\Traits\ClearsTemplateCaches;
|
||||
use App\Models\Template;
|
||||
use App\Services\ExtensionStaticCacheService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Tests\TestCase;
|
||||
|
||||
@@ -287,6 +288,49 @@ class ClearsTemplateCachesTest extends TestCase
|
||||
$this->assertLessThanOrEqual(time(), $newVersion);
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시 버전 키는 만료되지 않는다 (#651 F11).
|
||||
*
|
||||
* 종전에는 `put()` 에 TTL 을 넘기지 않아 `cache.default_ttl`(86400) 로 **매일 만료**됐고,
|
||||
* 다음 독자가 `regenerateExtensionCacheVersion()` 으로 새 버전을 만들어 정적 게시본 전체
|
||||
* (715파일·40MB)를 재생성하고 전 방문자의 자산 URL 을 바꿨다. 재생성은 `cache:clear` 나
|
||||
* 스토어 소실 때만 일어나야 한다.
|
||||
*
|
||||
* @effects cache_version_key_does_not_expire
|
||||
*/
|
||||
public function test_version_key_survives_two_days(): void
|
||||
{
|
||||
$this->traitUser->callIncrementExtensionCacheVersion();
|
||||
$version = ClearsTemplateCaches::getExtensionCacheVersion();
|
||||
$this->assertGreaterThan(0, $version);
|
||||
|
||||
try {
|
||||
Carbon::setTestNow(now()->addDays(2));
|
||||
|
||||
$this->assertSame(
|
||||
$version,
|
||||
(int) Cache::get('g7:core:ext.cache_version'),
|
||||
'캐시 버전 키가 이틀 뒤 만료됐다 — 매일 정적 게시본 전체가 재생성되고 전 방문자의 자산 URL 이 바뀐다'
|
||||
);
|
||||
$this->assertSame($version, ClearsTemplateCaches::getExtensionCacheVersion());
|
||||
} finally {
|
||||
Carbon::setTestNow();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 영구 TTL 상수는 `put(…, 0)`(forget) 도, 기본 TTL 도 아닌 명시 양수여야 한다.
|
||||
*
|
||||
* @effects cache_version_key_does_not_expire
|
||||
*/
|
||||
public function test_persistent_ttl_constant_is_positive_and_longer_than_default(): void
|
||||
{
|
||||
$this->assertGreaterThan(
|
||||
(int) config('cache.default_ttl', 86400) * 365,
|
||||
ExtensionStaticCacheService::PERSISTENT_TTL_SECONDS
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 버전 **재생성** 경로도 정적 게시를 예약한다 (D1).
|
||||
*
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Extension;
|
||||
|
||||
use App\Extension\Helpers\ExtensionPendingHelper;
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Extension\TemplateManager;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 확장 설정 시드·업데이트 임시 폴더의 소유권 상속 회귀 테스트 (#651 B2·B4).
|
||||
*
|
||||
* sudo 코어 업데이트(번들 확장 업데이트 프롬프트)가 root 로 `storage/app/{modules,plugins}/{id}/settings/`
|
||||
* 를 만들면 그 서브트리는 restore_ownership 의도적 제외 경로라 코어 업데이트로도 되돌려지지 않고,
|
||||
* 이후 웹 프로세스의 설정 저장이 영구 실패한다. 임시 폴더의 부모 `storage/app/temp` 도 최초 생성자가
|
||||
* root 면 같은 결말이다(자식만 삭제된다). 소유권 축은 Windows 에서 실측할 수 없으므로 저장소 관례
|
||||
* (소스 훑기)로 상속 호출의 존재를 잠근다.
|
||||
*/
|
||||
class ExtensionSettingsDirectoryOwnershipTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* 클래스 소스에서 주석을 제거한 본문을 돌려줍니다.
|
||||
*/
|
||||
private function strippedSource(string $class): string
|
||||
{
|
||||
$path = (new \ReflectionClass($class))->getFileName();
|
||||
$stripped = '';
|
||||
|
||||
foreach (token_get_all((string) file_get_contents($path)) as $token) {
|
||||
if (is_array($token) && in_array($token[0], [T_COMMENT, T_DOC_COMMENT], true)) {
|
||||
continue;
|
||||
}
|
||||
$stripped .= is_array($token) ? $token[1] : $token;
|
||||
}
|
||||
|
||||
return $stripped;
|
||||
}
|
||||
|
||||
/**
|
||||
* `makeDirectory($settingsDir …)` 뒤 5줄 안에 상속 호출이 있는지 판정합니다.
|
||||
*/
|
||||
private function assertMakeDirectoryInheritsOwnership(string $class): void
|
||||
{
|
||||
$source = $this->strippedSource($class);
|
||||
$offset = 0;
|
||||
$found = 0;
|
||||
|
||||
while (($pos = strpos($source, 'File::makeDirectory($settingsDir', $offset)) !== false) {
|
||||
$window = substr($source, $pos, 400);
|
||||
$lines = array_slice(explode("\n", $window), 0, 6);
|
||||
|
||||
$this->assertStringContainsString(
|
||||
'FilePermissionHelper::inheritOwnershipFromParent($settingsDir)',
|
||||
implode("\n", $lines),
|
||||
$class.': settings 디렉토리 생성 뒤 부모 소유권 상속이 없다 — sudo 코어 업데이트 뒤 그 확장의 설정 저장이 영구 실패한다'
|
||||
);
|
||||
|
||||
$found++;
|
||||
$offset = $pos + 1;
|
||||
}
|
||||
|
||||
$this->assertGreaterThan(0, $found, $class.': settings 디렉토리 생성 지점을 찾지 못했다');
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects settings_directory_seed_inherits_ownership
|
||||
*/
|
||||
#[Test]
|
||||
public function 모듈_설정_시드_디렉토리와_파일은_부모_소유권을_상속한다(): void
|
||||
{
|
||||
$this->assertMakeDirectoryInheritsOwnership(ModuleManager::class);
|
||||
|
||||
$source = $this->strippedSource(ModuleManager::class);
|
||||
$this->assertStringContainsString(
|
||||
"File::put(\$filePath, \$jsonContent);\n FilePermissionHelper::inheritOwnershipFromParent(\$filePath);",
|
||||
$source,
|
||||
'ModuleManager: 설정 시드 파일 쓰기 뒤 부모 소유권 상속이 없다'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects settings_directory_seed_inherits_ownership
|
||||
*/
|
||||
#[Test]
|
||||
public function 플러그인_설정_시드_디렉토리와_파일은_부모_소유권을_상속한다(): void
|
||||
{
|
||||
$this->assertMakeDirectoryInheritsOwnership(PluginManager::class);
|
||||
|
||||
$source = $this->strippedSource(PluginManager::class);
|
||||
$this->assertStringContainsString(
|
||||
"File::put(\$settingsPath, \$content);\n FilePermissionHelper::inheritOwnershipFromParent(\$settingsPath);",
|
||||
$source,
|
||||
'PluginManager: 설정 시드 파일 쓰기 뒤 부모 소유권 상속이 없다'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 세 매니저의 업데이트 임시 폴더 확보가 공유 헬퍼를 경유한다 — 복사본은 갈라진다.
|
||||
*
|
||||
* @effects update_temp_directory_inherits_ownership
|
||||
*/
|
||||
#[Test]
|
||||
public function 업데이트_임시_폴더는_공유_헬퍼로_확보한다(): void
|
||||
{
|
||||
foreach ([ModuleManager::class, PluginManager::class, TemplateManager::class] as $class) {
|
||||
$source = $this->strippedSource($class);
|
||||
|
||||
$this->assertStringContainsString(
|
||||
'ExtensionPendingHelper::ensureUpdateTempDirectory($tempDir)',
|
||||
$source,
|
||||
$class.': 업데이트 임시 폴더를 공유 헬퍼로 확보하지 않는다'
|
||||
);
|
||||
$this->assertStringNotContainsString(
|
||||
"File::ensureDirectoryExists(\$tempDir);\n",
|
||||
$source,
|
||||
$class.': 임시 폴더를 직접 생성하는 옛 경로가 남아 있다 — 부모 storage/app/temp 가 root 로 굳는다'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 공유 헬퍼는 부모를 먼저 확보하고 자식에 소유권을 상속시킨다 (동작).
|
||||
*
|
||||
* @effects update_temp_directory_inherits_ownership
|
||||
*/
|
||||
#[Test]
|
||||
public function 공유_헬퍼는_부모와_자식을_함께_확보한다(): void
|
||||
{
|
||||
$parent = storage_path('framework/testing/temp-parent-'.uniqid());
|
||||
$child = $parent.'/module_update_'.uniqid();
|
||||
|
||||
try {
|
||||
ExtensionPendingHelper::ensureUpdateTempDirectory($child);
|
||||
|
||||
$this->assertDirectoryExists($parent);
|
||||
$this->assertDirectoryExists($child);
|
||||
$this->assertTrue(is_writable($child));
|
||||
} finally {
|
||||
File::deleteDirectory($parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,76 @@ class TemplateUpdateConfigCacheInvalidationTest extends TestCase
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 업데이트 tail 은 활성/비활성과 무관하게 **무조건** 캐시 버전을 올린다 (#651 F1).
|
||||
*
|
||||
* 종전에는 `if ($previousStatus !== ExtensionStatus::Active->value)` 가드 안에서만 올렸다.
|
||||
* 활성 템플릿은 `refreshTemplateLayouts()` 의 조건부 bump(레이아웃 변경 건수 > 0)에
|
||||
* 위임됐는데, 그 조건은 게시 입력 중 레이아웃 축만 보므로 lang/routes/dist 만 바뀐
|
||||
* 릴리스는 정적 게시본이 immutable 로 stale 하게 남았다. 모듈·플러그인 update 는
|
||||
* 무조건 bump 다 — 템플릿만 다를 이유가 없다.
|
||||
*
|
||||
* @scenario cache_state=warm_current,lifecycle_trigger=template_update,template_type=admin
|
||||
*
|
||||
* @effects template_update_always_bumps_cache_version
|
||||
*/
|
||||
#[Test]
|
||||
public function update_template_tail_bumps_cache_version_unconditionally(): void
|
||||
{
|
||||
$body = $this->methodSource(
|
||||
base_path('app/Extension/TemplateManager.php'),
|
||||
'updateTemplate'
|
||||
);
|
||||
|
||||
$this->assertStringNotContainsString(
|
||||
'if ($previousStatus !== ExtensionStatus::Active->value)',
|
||||
$body,
|
||||
'updateTemplate() 의 bump 가 previousStatus 가드 안에 있으면 활성 템플릿의 lang/routes/dist 변경이 게시본에 반영되지 않습니다.'
|
||||
);
|
||||
|
||||
// 성공 tail + 실패 catch 두 자리 — 최소 2회
|
||||
$this->assertGreaterThanOrEqual(
|
||||
2,
|
||||
substr_count($body, '$this->incrementExtensionCacheVersion();'),
|
||||
'updateTemplate() 는 성공 tail 과 실패 복원 경로 양쪽에서 캐시 버전을 올려야 합니다.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 실패·복원 경로도 캐시 버전을 올린다 (#651 F2).
|
||||
*
|
||||
* 백업 복원이 실패했거나 부분 반영된 디스크가 남을 수 있어, 게시본을 새 버전으로 다시
|
||||
* 굽는 쪽이 옛 게시본을 그대로 두는 쪽보다 안전하다. bump 실패는 원래 예외를 가리지
|
||||
* 않도록 삼킨다.
|
||||
*
|
||||
* @scenario cache_state=warm_current,lifecycle_trigger=template_update,template_type=user
|
||||
*
|
||||
* @effects template_update_failure_bumps_after_restore
|
||||
*/
|
||||
#[Test]
|
||||
public function update_template_failure_path_bumps_after_restore(): void
|
||||
{
|
||||
$body = $this->methodSource(
|
||||
base_path('app/Extension/TemplateManager.php'),
|
||||
'updateTemplate'
|
||||
);
|
||||
|
||||
$catchAt = strrpos($body, 'catch (\Throwable $e)');
|
||||
$this->assertNotFalse($catchAt, 'updateTemplate() 의 최외곽 catch 를 찾지 못했습니다.');
|
||||
|
||||
$catchBody = substr($body, $catchAt);
|
||||
|
||||
$restoreAt = strpos($catchBody, "'status' => \$previousStatus");
|
||||
$bumpAt = strpos($catchBody, '$this->incrementExtensionCacheVersion();');
|
||||
$throwAt = strpos($catchBody, 'throw new \RuntimeException(');
|
||||
|
||||
$this->assertNotFalse($restoreAt, '실패 경로의 상태 복원 코드를 찾지 못했습니다.');
|
||||
$this->assertNotFalse($bumpAt, '실패 경로에 캐시 버전 bump 가 없습니다 — 부분 반영된 디스크가 옛 게시본과 함께 남습니다.');
|
||||
$this->assertNotFalse($throwAt, '실패 경로의 재던지기를 찾지 못했습니다.');
|
||||
|
||||
$this->assertTrue($restoreAt < $bumpAt && $bumpAt < $throwAt, 'bump 는 상태 복원 뒤, 재던지기 앞에 있어야 합니다.');
|
||||
}
|
||||
|
||||
/**
|
||||
* 대상 메서드 본문을 주석 제거 후 반환합니다.
|
||||
*
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace Tests\Unit\Helpers;
|
||||
|
||||
use App\Extension\Helpers\FilePermissionHelper;
|
||||
use App\Extension\Helpers\SettingsMigrator;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
@@ -96,6 +97,31 @@ class SettingsMigratorOwnershipTest extends TestCase
|
||||
$this->assertSame($parentOwnerBefore, fileowner($child), '자식 owner 가 부모와 동일');
|
||||
}
|
||||
|
||||
/**
|
||||
* settings 디렉토리 생성도 파일과 대칭으로 부모 소유권을 상속한다 (#651 B1).
|
||||
*
|
||||
* 파일(`writeJsonFile`)만 상속하고 디렉토리(`makeDirectory`)는 상속하지 않던 비대칭 — sudo
|
||||
* 업그레이드 스텝이 디렉토리를 root 로 만들면 `storage/app/{modules,plugins}` 는 restore_ownership
|
||||
* 의도적 제외 경로라 되돌려지지 않고, 이후 웹 프로세스의 그 모듈 설정 저장이 영구 실패한다.
|
||||
*
|
||||
* @effects settings_directory_seed_inherits_ownership
|
||||
*/
|
||||
public function test_settings_migrator_make_directory_invokes_inherit_ownership(): void
|
||||
{
|
||||
$body = (string) file_get_contents((new \ReflectionClass(SettingsMigrator::class))->getFileName());
|
||||
|
||||
$pos = strpos($body, 'File::makeDirectory($settingsDir');
|
||||
$this->assertNotFalse($pos, 'SettingsMigrator 의 settings 디렉토리 생성 지점을 찾지 못했다');
|
||||
|
||||
$window = implode("\n", array_slice(explode("\n", substr($body, $pos)), 0, 4));
|
||||
|
||||
$this->assertStringContainsString(
|
||||
'FilePermissionHelper::inheritOwnershipFromParent($settingsDir)',
|
||||
$window,
|
||||
'SettingsMigrator: settings 디렉토리 생성 뒤 부모 소유권 상속이 없다 (파일만 상속하는 비대칭)'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* SettingsMigrator::writeJsonFile 호출 후 *.json 의 owner 가 부모와 일치.
|
||||
*
|
||||
@@ -107,7 +133,7 @@ class SettingsMigratorOwnershipTest extends TestCase
|
||||
*/
|
||||
public function test_settings_migrator_write_json_file_invokes_inherit_ownership(): void
|
||||
{
|
||||
$reflection = new \ReflectionClass(\App\Extension\Helpers\SettingsMigrator::class);
|
||||
$reflection = new \ReflectionClass(SettingsMigrator::class);
|
||||
$method = $reflection->getMethod('writeJsonFile');
|
||||
$body = file_get_contents($method->getFileName());
|
||||
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Installer;
|
||||
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 설치기 best-effort 작업 실패 문구 테스트 (#651 C3).
|
||||
*
|
||||
* 종전에는 작업 종류와 무관하게 언어팩 전용 문구를 재사용해, 대상이 없는 `static_publish`·
|
||||
* `config_cache` 실패가 "언어팩 일부 설치에 실패했습니다: (계속 진행)" 으로 찍혔다.
|
||||
*
|
||||
* `task-runner.php` 는 진입과 함께 작업을 실행하는 파일이라 테스트에서 include 할 수 없다 —
|
||||
* 조립 함수의 존재·호출과 문구 키의 형태를 소스로 잠근다.
|
||||
*/
|
||||
class InstallerBestEffortMessageTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* @effects installer_best_effort_message_names_the_task
|
||||
*/
|
||||
#[Test]
|
||||
public function best_effort_분기는_작업_라벨_기반_문구_조립_함수를_쓴다(): void
|
||||
{
|
||||
$source = (string) file_get_contents(base_path('public/install/includes/task-runner.php'));
|
||||
|
||||
$this->assertStringContainsString('function bestEffortFailureMessage(string $taskId, string $target): string', $source);
|
||||
$this->assertStringContainsString('lang("task_{$taskId}")', $source);
|
||||
$this->assertStringContainsString("lang('warning_best_effort_task_failed', ['task' => \$display])", $source);
|
||||
|
||||
// 실패 분기가 새 조립 함수를 부른다 — 언어팩 전용 키를 직접 부르는 옛 줄은 남아 있지 않다
|
||||
$this->assertStringContainsString('$warnMsg = bestEffortFailureMessage((string) $taskId, (string) $target);', $source);
|
||||
$this->assertStringNotContainsString("lang('warning_language_pack_install_partial', ['identifier' => (string) \$target])", $source);
|
||||
}
|
||||
|
||||
/**
|
||||
* 문구 키가 `:task` 치환 자리를 갖고, best-effort 작업 3종의 라벨 키가 양 로케일에 있다.
|
||||
*
|
||||
* @effects installer_best_effort_message_names_the_task
|
||||
*/
|
||||
#[Test]
|
||||
public function 문구_키와_작업_라벨_키가_양_로케일에_있다(): void
|
||||
{
|
||||
foreach (['ko', 'en'] as $locale) {
|
||||
$messages = require base_path("public/install/lang/{$locale}.php");
|
||||
|
||||
$this->assertStringContainsString(':task', $messages['warning_best_effort_task_failed'] ?? '', "{$locale}: :task 치환 자리가 없다");
|
||||
|
||||
foreach (['task_static_publish', 'task_config_cache', 'task_language_pack_install'] as $key) {
|
||||
$this->assertNotEmpty($messages[$key] ?? null, "{$locale}: {$key} 라벨이 없다");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -293,6 +293,7 @@ class InstallerJsonOutputTest extends TestCase
|
||||
'error_empty_server_response',
|
||||
'error_invalid_server_response',
|
||||
'error_polling_response_invalid',
|
||||
'warning_best_effort_task_failed',
|
||||
];
|
||||
|
||||
foreach (['ko', 'en'] as $locale) {
|
||||
|
||||
@@ -28,6 +28,32 @@ class CoreUpdateRuntimeOwnershipTest extends TestCase
|
||||
$this->assertTrue(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 정상화 타깃에 확장 업데이트 임시 폴더와 로그 디렉토리가 포함된다 (#651 B5).
|
||||
*
|
||||
* `storage/app/temp` 의 부모는 sudo 업데이트가 최초 생성자가 되면 root 로 굳어 이후 관리자 화면의
|
||||
* 확장 업데이트가 임시 폴더를 만들지 못하고, `storage/logs` 는 restore_ownership 복원(Step 11)
|
||||
* 뒤에 만들어지는 daily 롤오버·신규 로그 파일이 root 로 남는다.
|
||||
*
|
||||
* @effects runtime_ownership_targets_cover_temp_and_logs
|
||||
*/
|
||||
public function test_runtime_ownership_targets_include_temp_and_logs(): void
|
||||
{
|
||||
$method = new \ReflectionMethod(CoreUpdateService::class, 'normalizeRuntimeOwnershipAfterRootRun');
|
||||
$lines = file($method->getFileName()) ?: [];
|
||||
$body = implode('', array_slice($lines, $method->getStartLine() - 1, $method->getEndLine() - $method->getStartLine() + 1));
|
||||
|
||||
foreach ([
|
||||
"storage_path('framework/cache')",
|
||||
"base_path('bootstrap/cache')",
|
||||
"storage_path('app/ext-bundles')",
|
||||
"storage_path('app/temp')",
|
||||
"storage_path('logs')",
|
||||
] as $target) {
|
||||
$this->assertStringContainsString($target, $body, "런타임 소유권 정상화 타깃에 {$target} 이 없다");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 부모(CoreUpdateCommand)·자식(ExecuteUpgradeStepsCommand) 흐름 종료부가
|
||||
* 정상화를 호출한다 — 로그 소유권 정상화(restoreUpgradeLogOwnership)와
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services;
|
||||
|
||||
use App\Exceptions\CustomAssetOperationException;
|
||||
use App\Services\CustomAssetService;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* `custom/` 디렉토리 생성 실패 안내 테스트 (#651 D6·C2).
|
||||
*
|
||||
* `custom/` 은 지연 생성이라 `deploy:deploy 0755` 로 배포된 확장 디렉토리에서 운영자의 첫 저장이
|
||||
* 여기서 실패한다. 종전 문구는 경로만 적어 무엇을 고쳐야 하는지 알 수 없었다 — 사유·소유자·권한·
|
||||
* 실행 계정·조치 예시를 함께 싣는다(정적 게시 프리플라이트와 같은 식).
|
||||
*/
|
||||
class CustomAssetServiceDirectoryFailureTest extends TestCase
|
||||
{
|
||||
/** 테스트용 가짜 플러그인 식별자 */
|
||||
private const FAKE_PLUGIN = 'g7test-dirfail';
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
File::deleteDirectory(base_path('plugins/'.self::FAKE_PLUGIN));
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 같은 이름의 **파일**이 `custom/` 자리를 차지하면 사유·조치가 실린 메시지로 실패한다.
|
||||
*
|
||||
* (POSIX 권한 거부는 Windows 에서 재현할 수 없어 파일 점유 사유로 실패 경로를 태운다 — 사유 코드는
|
||||
* 공통 프리미티브가 돌려주므로 매핑 경로는 같다.)
|
||||
*
|
||||
* @scenario custom_source=convention_scan, custom_asset=css
|
||||
*
|
||||
* @effects custom_directory_failure_explains_reason_and_action
|
||||
*/
|
||||
#[Test]
|
||||
public function 디렉토리_생성_실패는_사유와_조치를_함께_알린다(): void
|
||||
{
|
||||
$pluginDir = base_path('plugins/'.self::FAKE_PLUGIN);
|
||||
File::ensureDirectoryExists($pluginDir);
|
||||
// `custom` 자리를 파일로 점유 — mkdir 이 실패하는 결정적 조건
|
||||
File::put($pluginDir.'/custom', 'not a directory');
|
||||
|
||||
try {
|
||||
app(CustomAssetService::class)->save('plugins', self::FAKE_PLUGIN, 'custom.css', '/* x */');
|
||||
$this->fail('디렉토리를 만들 수 없는데 예외가 나지 않았다');
|
||||
} catch (CustomAssetOperationException $e) {
|
||||
$this->assertSame('custom_assets.errors.directory_failed', $e->errorKey);
|
||||
|
||||
foreach (['path', 'reason', 'owner', 'perms', 'process_user', 'hint'] as $param) {
|
||||
$this->assertArrayHasKey($param, $e->params, "실패 메시지 파라미터 {$param} 이 없다");
|
||||
}
|
||||
|
||||
// 사유 코드가 번역된 문장으로 실려야 한다 (키 노출 금지)
|
||||
$this->assertStringNotContainsString('custom_assets.', (string) $e->params['reason']);
|
||||
$this->assertStringNotContainsString('custom_assets.', (string) $e->params['hint']);
|
||||
$this->assertStringContainsString('chown', (string) $e->params['hint']);
|
||||
|
||||
// 최종 문장에 치환 자리가 남아 있지 않다
|
||||
$this->assertStringNotContainsString(':reason', $e->getMessage());
|
||||
$this->assertStringNotContainsString(':hint', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 사유 코드 4종은 ko/en 양쪽에 번역이 있다 — 없는 코드는 키 문자열이 화면에 나간다.
|
||||
*
|
||||
* @effects custom_directory_failure_explains_reason_and_action
|
||||
*/
|
||||
#[Test]
|
||||
public function 사유_코드_4종은_양_로케일에_번역이_있다(): void
|
||||
{
|
||||
foreach (['ko', 'en'] as $locale) {
|
||||
$messages = require base_path("lang/{$locale}/custom_assets.php");
|
||||
|
||||
foreach (['occupied_by_file', 'ancestor_not_writable', 'create_failed', 'not_writable'] as $code) {
|
||||
$this->assertNotEmpty($messages['errors']['reason'][$code] ?? null, "{$locale}: reason.{$code} 번역이 없다");
|
||||
}
|
||||
|
||||
$this->assertNotEmpty($messages['errors']['directory_failed_hint'] ?? null, "{$locale}: directory_failed_hint 가 없다");
|
||||
$this->assertStringContainsString(':hint', $messages['errors']['directory_failed']);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,11 @@ namespace Tests\Unit\Services;
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Repositories\AttachmentRepositoryInterface;
|
||||
use App\Contracts\Repositories\ConfigRepositoryInterface;
|
||||
use App\Extension\Traits\ClearsTemplateCaches;
|
||||
use App\Seo\Contracts\SeoCacheManagerInterface;
|
||||
use App\Services\SettingsService;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
@@ -144,6 +146,140 @@ class SettingsServiceSetSettingSideEffectsTest extends TestCase
|
||||
$this->assertFalse($service->setSetting('drivers.queue_driver', 'redis'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 자산 URL 방식을 단건으로 바꾸면 확장 캐시 버전이 오른다 — 실제 키 관측 (#651 F5).
|
||||
*
|
||||
* 병합 번들 CSS 에는 그 시점의 자산 URL 형태(확장자 / `?file=`)가 구워져 있고, 디스크 번들과
|
||||
* 정적 게시본은 캐시 버전으로 키드된다. 버전이 오르지 않으면 모드를 바꿔도 옛 형태의
|
||||
* `url()` 이 남아 글꼴·이미지가 404 가 된다.
|
||||
*
|
||||
* @effects asset_url_mode_change_bumps_extension_cache_version
|
||||
*/
|
||||
public function test_asset_url_mode_change_bumps_extension_cache_version(): void
|
||||
{
|
||||
$this->mock(SeoCacheManagerInterface::class)->shouldIgnoreMissing();
|
||||
Artisan::shouldReceive('call')->zeroOrMoreTimes();
|
||||
|
||||
ClearsTemplateCaches::resetExtensionCacheStoreMemo();
|
||||
Cache::put('g7:core:ext.cache_version', 1000);
|
||||
|
||||
$service = $this->makeService(existingValue: 'extensionless');
|
||||
$this->assertTrue($service->setSetting('general.asset_url_mode', 'extension'));
|
||||
|
||||
$this->assertGreaterThan(
|
||||
1000,
|
||||
(int) Cache::get('g7:core:ext.cache_version'),
|
||||
'자산 URL 방식 단건 변경이 확장 캐시 버전을 올리지 않았다 — 번들 CSS 의 옛 url() 형태가 남는다.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 값이 그대로면 확장 캐시 버전도 그대로다.
|
||||
*
|
||||
* @effects asset_url_mode_change_bumps_extension_cache_version
|
||||
*/
|
||||
public function test_same_asset_url_mode_keeps_extension_cache_version(): void
|
||||
{
|
||||
$this->mock(SeoCacheManagerInterface::class)->shouldIgnoreMissing();
|
||||
Artisan::shouldReceive('call')->zeroOrMoreTimes();
|
||||
|
||||
ClearsTemplateCaches::resetExtensionCacheStoreMemo();
|
||||
Cache::put('g7:core:ext.cache_version', 1000);
|
||||
|
||||
$service = $this->makeService(existingValue: 'extension');
|
||||
$this->assertTrue($service->setSetting('general.asset_url_mode', 'extension'));
|
||||
|
||||
$this->assertSame(1000, (int) Cache::get('g7:core:ext.cache_version'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 벌크 저장(saveSettings) 경로도 같은 부수효과를 갖는다 — 화면 [저장] 버튼이 타는 경로다.
|
||||
*
|
||||
* @effects asset_url_mode_change_bumps_extension_cache_version
|
||||
*/
|
||||
public function test_bulk_save_asset_url_mode_change_bumps_extension_cache_version(): void
|
||||
{
|
||||
$this->mock(SeoCacheManagerInterface::class)->shouldIgnoreMissing();
|
||||
Artisan::shouldReceive('call')->zeroOrMoreTimes();
|
||||
|
||||
$existing = ['asset_url_mode' => 'extensionless'];
|
||||
$configRepository = $this->mock(ConfigRepositoryInterface::class)->shouldIgnoreMissing();
|
||||
$configRepository->shouldReceive('getCategory')->with('general')->andReturnUsing(function () use (&$existing): array {
|
||||
return $existing;
|
||||
});
|
||||
$configRepository->shouldReceive('saveCategory')->andReturn(true);
|
||||
$this->mock(AttachmentRepositoryInterface::class)->shouldIgnoreMissing();
|
||||
$this->mock(CacheInterface::class)->shouldIgnoreMissing();
|
||||
|
||||
ClearsTemplateCaches::resetExtensionCacheStoreMemo();
|
||||
Cache::put('g7:core:ext.cache_version', 1000);
|
||||
|
||||
$service = app(SettingsService::class);
|
||||
$this->assertTrue($service->saveSettings(['_tab' => 'general', 'general' => ['asset_url_mode' => 'extension']]));
|
||||
|
||||
$this->assertGreaterThan(1000, (int) Cache::get('g7:core:ext.cache_version'));
|
||||
|
||||
// 같은 값 재저장은 올리지 않는다
|
||||
Cache::put('g7:core:ext.cache_version', 2000);
|
||||
$existing = ['asset_url_mode' => 'extension'];
|
||||
$this->assertTrue($service->saveSettings(['_tab' => 'general', 'general' => ['asset_url_mode' => 'extension']]));
|
||||
$this->assertSame(2000, (int) Cache::get('g7:core:ext.cache_version'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 설정 복원으로 자산 URL 방식이 바뀌면 SEO 캐시 삭제 + 확장 캐시 버전 bump 가 따른다.
|
||||
*
|
||||
* 복원은 설정 전체를 갈아엎는 쓰기라 두 저장 경로와 같은 부수효과를 받아야 한다 —
|
||||
* 종전에는 변경 감지 자체가 없었다.
|
||||
*
|
||||
* @effects asset_url_mode_change_bumps_extension_cache_version
|
||||
*/
|
||||
public function test_restore_asset_url_mode_change_bumps_extension_cache_version(): void
|
||||
{
|
||||
$this->mock(SeoCacheManagerInterface::class)->shouldReceive('clearAll')->once();
|
||||
Artisan::shouldReceive('call')->zeroOrMoreTimes();
|
||||
|
||||
$configRepository = $this->mock(ConfigRepositoryInterface::class)->shouldIgnoreMissing();
|
||||
// 복원 전 / 복원 후 순서대로 읽힌다
|
||||
$configRepository->shouldReceive('get')->with('general.asset_url_mode')->andReturn('extensionless', 'extension');
|
||||
$configRepository->shouldReceive('restore')->andReturn(true);
|
||||
$this->mock(AttachmentRepositoryInterface::class)->shouldIgnoreMissing();
|
||||
$this->mock(CacheInterface::class)->shouldIgnoreMissing();
|
||||
|
||||
ClearsTemplateCaches::resetExtensionCacheStoreMemo();
|
||||
Cache::put('g7:core:ext.cache_version', 1000);
|
||||
|
||||
$service = app(SettingsService::class);
|
||||
$this->assertTrue($service->restoreSettings('/tmp/backup.json'));
|
||||
|
||||
$this->assertGreaterThan(1000, (int) Cache::get('g7:core:ext.cache_version'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 복원 전후 값이 같으면 두 부수효과 모두 없다.
|
||||
*
|
||||
* @effects asset_url_mode_change_bumps_extension_cache_version
|
||||
*/
|
||||
public function test_restore_with_same_asset_url_mode_has_no_side_effects(): void
|
||||
{
|
||||
$this->mock(SeoCacheManagerInterface::class)->shouldReceive('clearAll')->never();
|
||||
Artisan::shouldReceive('call')->zeroOrMoreTimes();
|
||||
|
||||
$configRepository = $this->mock(ConfigRepositoryInterface::class)->shouldIgnoreMissing();
|
||||
$configRepository->shouldReceive('get')->with('general.asset_url_mode')->andReturn('extensionless');
|
||||
$configRepository->shouldReceive('restore')->andReturn(true);
|
||||
$this->mock(AttachmentRepositoryInterface::class)->shouldIgnoreMissing();
|
||||
$this->mock(CacheInterface::class)->shouldIgnoreMissing();
|
||||
|
||||
ClearsTemplateCaches::resetExtensionCacheStoreMemo();
|
||||
Cache::put('g7:core:ext.cache_version', 1000);
|
||||
|
||||
$service = app(SettingsService::class);
|
||||
$this->assertTrue($service->restoreSettings('/tmp/backup.json'));
|
||||
|
||||
$this->assertSame(1000, (int) Cache::get('g7:core:ext.cache_version'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 단건 저장은 받은 키를 변형 없이 저장소에 넘긴다. (벌크 위임 금지 — 계약 고정)
|
||||
*
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Support;
|
||||
|
||||
use App\Support\ConfigCacheHelper;
|
||||
use Illuminate\Container\Container;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* `ConfigCacheHelper` 가 `config:cache` 뒤 전역 컨테이너 인스턴스를 되돌리는지 (#651 F2 실측 파생).
|
||||
*
|
||||
* `config:cache` 는 새 Application 을 부팅하고 그 생성자가 `Container::setInstance()` 를 호출한다.
|
||||
* 되돌리지 않으면 같은 프로세스의 후속 `app()->terminating()` 이 종료되지 않는 일회용 앱에 등록되어
|
||||
* 정적 재게시 예약이 조용히 사라진다 — 예외도 로그도 없이 "다음 렌더에야 반영" 으로만 나타난다.
|
||||
*/
|
||||
class ConfigCacheHelperContainerTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* 콜백이 전역 인스턴스를 바꿔 놓아도 실행 후 원래 앱으로 돌아온다.
|
||||
*
|
||||
* @effects config_cache_rebuild_preserves_container_instance
|
||||
*/
|
||||
#[Test]
|
||||
public function 콜백이_전역_인스턴스를_바꿔도_원래_앱으로_되돌린다(): void
|
||||
{
|
||||
$original = Container::getInstance();
|
||||
$stray = new Container;
|
||||
|
||||
ConfigCacheHelper::withPreservedContainer(static function () use ($stray): void {
|
||||
Container::setInstance($stray);
|
||||
});
|
||||
|
||||
$this->assertSame($original, Container::getInstance(), 'config:cache 뒤 app() 이 일회용 앱을 가리킨 채 남는다 — 후속 terminating 예약이 사라진다');
|
||||
$this->assertSame($original, app());
|
||||
}
|
||||
|
||||
/**
|
||||
* 콜백이 예외를 던져도 인스턴스는 되돌린다.
|
||||
*
|
||||
* @effects config_cache_rebuild_preserves_container_instance
|
||||
*/
|
||||
#[Test]
|
||||
public function 콜백이_실패해도_원래_앱으로_되돌린다(): void
|
||||
{
|
||||
$original = Container::getInstance();
|
||||
|
||||
try {
|
||||
ConfigCacheHelper::withPreservedContainer(static function (): void {
|
||||
Container::setInstance(new Container);
|
||||
|
||||
throw new \RuntimeException('boom');
|
||||
});
|
||||
$this->fail('예외가 전파되어야 한다');
|
||||
} catch (\RuntimeException) {
|
||||
// 기대한 예외
|
||||
}
|
||||
|
||||
$this->assertSame($original, Container::getInstance());
|
||||
}
|
||||
|
||||
/**
|
||||
* `rebuild()` 가 `config:cache` 호출을 보존 래퍼로 감싼다 (소스 구조).
|
||||
*
|
||||
* @effects config_cache_rebuild_preserves_container_instance
|
||||
*/
|
||||
#[Test]
|
||||
public function rebuild_는_config_cache_를_보존_래퍼로_감싼다(): void
|
||||
{
|
||||
$method = new \ReflectionMethod(ConfigCacheHelper::class, 'rebuild');
|
||||
$lines = file($method->getFileName()) ?: [];
|
||||
$body = implode('', array_slice($lines, $method->getStartLine() - 1, $method->getEndLine() - $method->getStartLine() + 1));
|
||||
|
||||
$this->assertStringContainsString("withPreservedContainer(static fn () => Artisan::call('config:cache'))", $body);
|
||||
$this->assertStringNotContainsString("\n Artisan::call('config:cache');", $body);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Support;
|
||||
|
||||
use App\Support\CustomAssets;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* `CustomAssets::publishableFiles()` — 게시·변경 감지가 공유하는 열거자 테스트 (#651 F7).
|
||||
*
|
||||
* 정적 게시는 `custom/**` 를 재귀로 복사하고, 변경 감지는 종전에 최상위 css/js 의 mtime 만
|
||||
* 서명했다. 두 범위를 서로 다른 코드가 정의하면 어긋나고, 그 어긋남은 "글꼴을 바꿨는데
|
||||
* 반영되지 않는다" 로만 나타난다. 이 열거자 하나가 두 소비자의 집합을 정한다.
|
||||
*
|
||||
* DB 를 쓰지 않는다 — 파일 시스템 해석만 검증한다.
|
||||
*/
|
||||
class CustomAssetsPublishableFilesTest extends TestCase
|
||||
{
|
||||
/** 테스트용 가짜 플러그인 식별자 */
|
||||
private const FAKE_PLUGIN = 'g7test-publishable';
|
||||
|
||||
private function pluginDir(): string
|
||||
{
|
||||
return base_path('plugins/'.self::FAKE_PLUGIN);
|
||||
}
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
CustomAssets::flushCache();
|
||||
File::ensureDirectoryExists($this->pluginDir().'/custom');
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
File::deleteDirectory($this->pluginDir());
|
||||
CustomAssets::flushCache();
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function writeCustom(string $relative, string $contents = '/* x */'): void
|
||||
{
|
||||
$path = $this->pluginDir().'/custom/'.$relative;
|
||||
File::ensureDirectoryExists(dirname($path));
|
||||
File::put($path, $contents);
|
||||
}
|
||||
|
||||
/**
|
||||
* 하위 디렉토리의 글꼴·이미지까지 열거한다 — 게시와 같은 범위.
|
||||
*
|
||||
* @scenario custom_source=convention_scan, custom_asset=static_file, custom_change_detection=nested_static_file
|
||||
*
|
||||
* @effects custom_signature_covers_publishable_tree
|
||||
*/
|
||||
#[Test]
|
||||
public function 하위_디렉토리의_정적_파일까지_열거한다(): void
|
||||
{
|
||||
$this->writeCustom('custom.css');
|
||||
$this->writeCustom('fonts/x.woff2', 'font');
|
||||
$this->writeCustom('img/deep/marker.svg', '<svg/>');
|
||||
|
||||
$relatives = array_column(CustomAssets::publishableFiles('plugins', self::FAKE_PLUGIN), 'relative');
|
||||
|
||||
$this->assertSame(['custom.css', 'fonts/x.woff2', 'img/deep/marker.svg'], $relatives);
|
||||
}
|
||||
|
||||
/**
|
||||
* 허용 확장자 밖(텍스트·PHP)과 소스맵은 뺀다 — 게시 화이트리스트와 동일.
|
||||
*
|
||||
* @scenario custom_source=convention_scan, custom_asset=static_file, custom_change_detection=nested_static_file
|
||||
*
|
||||
* @effects custom_signature_covers_publishable_tree
|
||||
*/
|
||||
#[Test]
|
||||
public function 허용_확장자_밖과_소스맵은_열거하지_않는다(): void
|
||||
{
|
||||
$this->writeCustom('custom.css');
|
||||
$this->writeCustom('notes.txt', 'not an asset');
|
||||
$this->writeCustom('evil.php', '<?php');
|
||||
$this->writeCustom('custom.css.map', '{}');
|
||||
|
||||
$relatives = array_column(CustomAssets::publishableFiles('plugins', self::FAKE_PLUGIN), 'relative');
|
||||
|
||||
$this->assertSame(['custom.css'], $relatives);
|
||||
}
|
||||
|
||||
/**
|
||||
* 항목마다 절대 경로·수정 시각·크기를 싣는다 — 서명 재료이자 게시 복사 원본이다.
|
||||
*
|
||||
* @scenario custom_source=convention_scan, custom_asset=css, custom_change_detection=top_level_asset
|
||||
*
|
||||
* @effects custom_signature_covers_publishable_tree
|
||||
*/
|
||||
#[Test]
|
||||
public function 항목은_절대경로_mtime_크기를_갖는다(): void
|
||||
{
|
||||
$this->writeCustom('custom.css', '/* twelve b */');
|
||||
|
||||
$files = CustomAssets::publishableFiles('plugins', self::FAKE_PLUGIN);
|
||||
|
||||
$this->assertCount(1, $files);
|
||||
$this->assertSame('custom.css', $files[0]['relative']);
|
||||
$this->assertFileExists($files[0]['absolute']);
|
||||
$this->assertSame(14, $files[0]['size']);
|
||||
$this->assertGreaterThan(0, $files[0]['mtime']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 요청 스코프 메모이즈 — 같은 요청에서 두 번 물어도 디스크를 다시 훑지 않고, `flushCache()` 가 비운다.
|
||||
*
|
||||
* @scenario custom_source=convention_scan, custom_asset=css, custom_change_detection=no_change
|
||||
*
|
||||
* @effects custom_signature_covers_publishable_tree
|
||||
*/
|
||||
#[Test]
|
||||
public function 결과는_요청_스코프로_메모이즈되고_flush_로_비워진다(): void
|
||||
{
|
||||
$this->writeCustom('custom.css');
|
||||
|
||||
$first = CustomAssets::publishableFiles('plugins', self::FAKE_PLUGIN);
|
||||
|
||||
// 메모가 살아 있는 동안 추가한 파일은 보이지 않는다
|
||||
$this->writeCustom('fonts/x.woff2', 'font');
|
||||
$this->assertSame($first, CustomAssets::publishableFiles('plugins', self::FAKE_PLUGIN));
|
||||
|
||||
CustomAssets::flushCache();
|
||||
|
||||
$this->assertCount(2, CustomAssets::publishableFiles('plugins', self::FAKE_PLUGIN));
|
||||
}
|
||||
|
||||
/**
|
||||
* 디렉토리가 없거나 타입이 유효하지 않으면 빈 목록이다.
|
||||
*
|
||||
* @scenario custom_source=none, custom_asset=css, custom_change_detection=no_change
|
||||
*
|
||||
* @effects custom_signature_covers_publishable_tree
|
||||
*/
|
||||
#[Test]
|
||||
public function 디렉토리_부재와_무효_타입은_빈_목록이다(): void
|
||||
{
|
||||
File::deleteDirectory($this->pluginDir());
|
||||
|
||||
$this->assertSame([], CustomAssets::publishableFiles('plugins', self::FAKE_PLUGIN));
|
||||
$this->assertSame([], CustomAssets::publishableFiles('unknown', self::FAKE_PLUGIN));
|
||||
$this->assertSame([], CustomAssets::publishableFiles('plugins', '../escape'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 로드 목록(`forExtension`)은 그대로 최상위 css/js 만 싣는다 — 열거자 도입이 로드 의미를 바꾸지 않는다.
|
||||
*
|
||||
* @scenario custom_source=convention_scan, custom_asset=static_file, custom_change_detection=nested_static_file
|
||||
*
|
||||
* @effects custom_signature_covers_publishable_tree
|
||||
*/
|
||||
#[Test]
|
||||
public function 로드_목록은_여전히_최상위_css_js_만_싣는다(): void
|
||||
{
|
||||
$this->writeCustom('custom.css');
|
||||
$this->writeCustom('fonts/inner.css');
|
||||
$this->writeCustom('img/marker.svg', '<svg/>');
|
||||
|
||||
$loaded = CustomAssets::forExtension('plugins', self::FAKE_PLUGIN);
|
||||
$publishable = CustomAssets::publishableFiles('plugins', self::FAKE_PLUGIN);
|
||||
|
||||
$this->assertCount(1, $loaded);
|
||||
$this->assertStringContainsString('custom.css', $loaded[0]['url']);
|
||||
$this->assertCount(3, $publishable);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Upgrade;
|
||||
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 번들 확장 업그레이드 마이그레이션의 파일 쓰기 소유권 상속 패리티 (#651 B3).
|
||||
*
|
||||
* 업그레이드 스텝은 sudo 코어 업데이트 안에서 root 로 실행될 수 있다. `File::put()` 으로 설정 파일을
|
||||
* 쓰는 스텝 중 일부(gdpr 02·ckeditor5·pay_*)는 `inheritOwnershipFromParent` 를 부르고 일부는 부르지
|
||||
* 않아 진영이 갈렸다 — 지금은 전부 기존 파일 갱신이라 inode 소유자가 보존되지만, "없으면 생성" 으로
|
||||
* 바뀌는 순간 root 소유 파일이 남는다.
|
||||
*
|
||||
* 모집단은 **파일시스템에서 파생**한다 — 8개 파일을 열거하면 9번째 마이그레이션이 사각이 된다.
|
||||
*/
|
||||
class BundledUpgradeMigrationOwnershipParityTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* `File::put(` 뒤 5줄 안에 상속 호출이 없는 마이그레이션 파일을 모읍니다.
|
||||
*
|
||||
* @return array<int, string> 위반 파일 (base_path 상대)
|
||||
*/
|
||||
private function collectViolations(): array
|
||||
{
|
||||
$pattern = base_path('{modules,plugins}/_bundled/*/upgrades');
|
||||
$violations = [];
|
||||
$population = 0;
|
||||
|
||||
foreach (glob($pattern, GLOB_BRACE) ?: [] as $upgradesDir) {
|
||||
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($upgradesDir, \FilesystemIterator::SKIP_DOTS));
|
||||
|
||||
/** @var \SplFileInfo $file */
|
||||
foreach ($iterator as $file) {
|
||||
if (! $file->isFile() || strtolower($file->getExtension()) !== 'php') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$lines = file($file->getPathname(), FILE_IGNORE_NEW_LINES) ?: [];
|
||||
|
||||
foreach ($lines as $index => $line) {
|
||||
if (! str_contains($line, 'File::put(')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$population++;
|
||||
$window = implode("\n", array_slice($lines, $index, 6));
|
||||
|
||||
if (! str_contains($window, 'inheritOwnershipFromParent')) {
|
||||
$violations[] = str_replace('\\', '/', substr($file->getPathname(), strlen(base_path()) + 1)).':'.($index + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertGreaterThan(0, $population, '모집단이 비었다 — 번들 확장 upgrades 에서 File::put 을 찾지 못했다 (판정식 회귀 의심)');
|
||||
|
||||
return $violations;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 `File::put(` 은 5줄 안에 `inheritOwnershipFromParent` 를 동반한다.
|
||||
*
|
||||
* @effects bundled_upgrade_migrations_inherit_ownership
|
||||
*/
|
||||
#[Test]
|
||||
public function 번들_업그레이드_마이그레이션의_파일_쓰기는_전부_소유권을_상속한다(): void
|
||||
{
|
||||
$violations = $this->collectViolations();
|
||||
|
||||
$this->assertSame(
|
||||
[],
|
||||
$violations,
|
||||
"File::put 뒤 소유권 상속이 없는 업그레이드 마이그레이션:\n - ".implode("\n - ", $violations)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,9 @@ coverage_strategy: pairwise
|
||||
axes:
|
||||
custom_source: [none, convention_scan, assets_json, assets_json_broken]
|
||||
custom_asset: [css, js, static_file, external_url]
|
||||
# 변경 감지 범위 축 (#651 F7) — 감지 서명이 게시 집합(custom/** 재귀)과 같은 열거자를 쓰는지.
|
||||
# 종전 서명은 최상위 css/js 의 mtime 만 봐서 하위 디렉토리 글꼴·이미지 교체가 영영 미게시였다.
|
||||
custom_change_detection: [top_level_asset, nested_static_file, no_change]
|
||||
|
||||
exclusions:
|
||||
- { custom_source: none, custom_asset: css, reason: "출처가 없으면 자산 종류 축이 성립하지 않는다" }
|
||||
@@ -32,6 +35,21 @@ exclusions:
|
||||
- { custom_source: assets_json_broken, custom_asset: js, reason: "깨진 선언은 종류와 무관하게 빈 목록" }
|
||||
- { custom_source: assets_json_broken, custom_asset: static_file, reason: "동일" }
|
||||
- { custom_source: assets_json_broken, custom_asset: external_url, reason: "동일" }
|
||||
# --- custom_change_detection: 파일이 있어야 변경이 성립한다 ---
|
||||
- { custom_source: none, custom_change_detection: top_level_asset, reason: "출처가 없으면 바뀔 파일도 없다 — no_change 만 성립" }
|
||||
- { custom_source: none, custom_change_detection: nested_static_file, reason: "동일" }
|
||||
- { custom_asset: external_url, custom_change_detection: top_level_asset, reason: "외부 URL 은 파일 서명이 없다 — 감지 재료가 아니다" }
|
||||
- { custom_asset: external_url, custom_change_detection: nested_static_file, reason: "동일" }
|
||||
- { custom_source: assets_json_broken, custom_change_detection: top_level_asset, reason: "깨진 선언은 로드 목록이 비지만 감지 집합은 디스크 기준 — 대표 조합(convention_scan)으로 고정" }
|
||||
- { custom_source: assets_json_broken, custom_change_detection: nested_static_file, reason: "동일" }
|
||||
- { custom_source: assets_json_broken, custom_change_detection: no_change, reason: "동일" }
|
||||
- { custom_source: assets_json, custom_change_detection: top_level_asset, reason: "선언 파일 여부는 감지 집합(디스크 전체)과 직교 — 대표 조합(convention_scan)으로 고정" }
|
||||
- { custom_source: assets_json, custom_change_detection: nested_static_file, reason: "동일" }
|
||||
- { custom_source: assets_json, custom_change_detection: no_change, reason: "동일" }
|
||||
- { custom_asset: css, custom_change_detection: nested_static_file, reason: "하위 디렉토리 파일 축은 static_file 에서만 성립 — css/js 는 최상위 로드 자산" }
|
||||
- { custom_asset: js, custom_change_detection: nested_static_file, reason: "동일" }
|
||||
- { custom_asset: static_file, custom_change_detection: top_level_asset, reason: "최상위 로드 자산 축은 css/js 에서만 성립" }
|
||||
- { custom_asset: js, custom_change_detection: top_level_asset, reason: "감지 재료는 확장자와 무관(경로·mtime·크기) — 대표 조합(css)으로 고정" }
|
||||
|
||||
effects:
|
||||
- custom_asset_loaded_after_extension_bundles
|
||||
@@ -51,10 +69,16 @@ effects:
|
||||
- custom_asset_containment_base_matches_serving_root
|
||||
- custom_asset_published_with_extension_assets
|
||||
- custom_assets_disabled_by_request_parameter
|
||||
- custom_asset_signature_is_scoped_per_render
|
||||
- custom_signature_covers_publishable_tree
|
||||
- custom_signature_scoped_per_host
|
||||
- custom_directory_failure_explains_reason_and_action
|
||||
|
||||
test_files:
|
||||
- tests/Unit/Support/CustomAssetsTest.php
|
||||
- tests/Feature/View/CustomAssetInjectionTest.php
|
||||
- tests/Unit/Support/CustomAssetsPublishableFilesTest.php
|
||||
- tests/Unit/Services/CustomAssetServiceDirectoryFailureTest.php
|
||||
- tests/Feature/Extension/CustomAssetPreservationTest.php
|
||||
- resources/js/core/__tests__/ModuleAssetLoader.customAssets.test.ts
|
||||
- tests/Playwright/specs/custom-assets.spec.ts
|
||||
|
||||
@@ -129,6 +129,16 @@ effects:
|
||||
- admin_catch_all_shares_static_exclusion
|
||||
- prune_skips_active_serving_path
|
||||
- extension_copy_paths_inherit_directory_ownership
|
||||
# #651 — 재게시 누락 3건·버전 수명·root 안내
|
||||
- template_update_always_bumps_cache_version
|
||||
- template_update_failure_bumps_after_restore
|
||||
- asset_url_mode_change_bumps_extension_cache_version
|
||||
- cache_version_key_does_not_expire
|
||||
- custom_signature_covers_publishable_tree
|
||||
- custom_signature_scoped_per_host
|
||||
- status_command_warns_root_and_hints_web_account
|
||||
- publish_command_warns_root_but_continues
|
||||
- status_command_consumes_service_report
|
||||
|
||||
test_files:
|
||||
- tests/Feature/Services/ExtensionStaticCacheServiceTest.php
|
||||
@@ -143,6 +153,11 @@ test_files:
|
||||
- tests/Feature/Console/BuildCommandPruneScopeTest.php
|
||||
- tests/Feature/Extension/ExtensionPendingOwnershipTest.php
|
||||
- tests/Unit/Extension/ClearsTemplateCachesTest.php
|
||||
- tests/Unit/Extension/TemplateUpdateConfigCacheInvalidationTest.php
|
||||
- tests/Unit/Services/SettingsServiceSetSettingSideEffectsTest.php
|
||||
- tests/Unit/Support/CustomAssetsPublishableFilesTest.php
|
||||
- tests/Feature/View/CustomAssetInjectionTest.php
|
||||
- tests/Feature/Console/ExtStaticStatusCommandTest.php
|
||||
- tests/Unit/Services/ExtensionBundleServiceTest.php
|
||||
- tests/Unit/Build/ViteOutDirContractTest.php
|
||||
- tests/Unit/Support/AssetUrlTest.php
|
||||
@@ -160,7 +175,12 @@ notes: |
|
||||
게시·게이트·폴백은 리소스 무관 공통 메커니즘이고, 리소스별 형상 차이는
|
||||
published_* effects (payload/봉투/소스맵 제외) 가 각각 단언한다.
|
||||
environment=dev 축은 PHPUnit(환경 분기 케이스)과 AssetUrl 게이트 단위가 담당한다 —
|
||||
E2E 대상 사이트(g7_2.dev)는 production 이라 dev 축을 브라우저로 실측할 수 없다.
|
||||
E2E 대상 사이트(g7_2.dev)는 평소 local 이라, 브라우저 실측은 실측 창 동안만 `.env` 를
|
||||
production 으로 전환해 수행하고 끝나면 원본을 복구한다(md5 대조). dev 축 자체는 브라우저로
|
||||
실측하지 않는다.
|
||||
관리자 수동 복구(상태 GET + 재게시 POST + 카드·모달·알림 버튼)는 축이 다르므로 별도
|
||||
매니페스트 `tests/scenarios/static-cache-admin-rebuild.yaml` 이 소유한다 — 이 파일의 6축에
|
||||
trigger 값을 더하면 108 조합의 exclusions 가 필요해진다.
|
||||
trigger=lifecycle 의 실기기 검증(확장 비활성/활성 → 재게시 → 새 staticBase)은
|
||||
Chrome MCP 매트릭스 T10a~T10d 가 수행한다 (원상 복구 의무 포함).
|
||||
publish_state=partial 은 태그 계층(개별 file_exists 게이트)과 fetch 계층
|
||||
|
||||
@@ -49,6 +49,7 @@ effects:
|
||||
- queue_workers_not_restarted_for_other_categories
|
||||
- side_effects_skipped_when_save_fails
|
||||
- single_key_save_uses_storage_key_verbatim # 화면 키 역변환 미적용 (프로그램 호출자 보호)
|
||||
- asset_url_mode_change_bumps_extension_cache_version # 번들 CSS 에 구워진 URL 형태 재생성 (#651)
|
||||
|
||||
sub_flows:
|
||||
- id: single_key_side_effects
|
||||
@@ -64,6 +65,7 @@ sub_flows:
|
||||
- queue_workers_not_restarted_for_other_categories
|
||||
- side_effects_skipped_when_save_fails
|
||||
- single_key_save_uses_storage_key_verbatim
|
||||
- asset_url_mode_change_bumps_extension_cache_version
|
||||
|
||||
test_files:
|
||||
- tests/Feature/Api/Admin/SettingsSingleValueUpdateTest.php
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
feature: 초기 화면 정적 파일 — 관리자 상태 조회 + 수동 복구 (다시 만들기)
|
||||
|
||||
description: |
|
||||
부트스트랩 리소스 정적 게시(#122)의 캐시 버전은 만료로 재생성되지 않는다(영구 번호, #651). 그래서
|
||||
재게시 트리거가 하나라도 빠지면 게시본은 무기한 stale 이 된다. 운영자가 그 상태를 **보고 즉시
|
||||
되돌릴** 통로가 이 기능이다 — 환경설정 > 일반 「초기 화면 정적 파일」 카드(상태 배지·버전·파일 수·
|
||||
마지막 게시 시각·실행 계정·최근 실패)와 [지금 다시 만들기](확인 모달 → POST → 토스트 → 카드 재조회),
|
||||
그리고 대시보드의 게시 실패 알림에 붙는 [다시 만들기] 버튼(같은 엔드포인트).
|
||||
|
||||
핵심 동작:
|
||||
- 상태 판정은 서비스 한 곳(`statusReport`)이 소유하고 CLI(`ext-static:status`)·API·화면이 소비한다
|
||||
- 재게시는 캐시 버전 bump + **강제** 재게시 — 같은 초 재클릭도 내용을 다시 만든다
|
||||
- 게시가 쓰이지 않는 환경(kill-switch 꺼짐 / 비프로덕션)은 bump 하지 않고 사유를 돌려준다
|
||||
- 게시 실패는 요청 실패가 아니라 진단 결과 — HTTP 200 + `republished=false` (사이트는 API 폴백으로 정상)
|
||||
- 읽기는 `core.settings.read`, 재게시는 `core.settings.update`
|
||||
|
||||
`tests/scenarios/ext-static-cache.yaml` 의 6축(게시 상태·환경·트리거·실행 주체·무결성·쓰기 가능성)과
|
||||
교차시키지 않는다 — 수동 복구의 축(권한·publishable·결과)은 그것들과 직교하고, 곱하면 108 조합의
|
||||
exclusions 가 필요하다.
|
||||
|
||||
coverage_strategy: pairwise
|
||||
|
||||
axes:
|
||||
permission: [granted, denied]
|
||||
publishable: [production_enabled, kill_switch_off, non_production]
|
||||
outcome: [success, publish_failed_marker]
|
||||
|
||||
exclusions:
|
||||
- { permission: denied, outcome: publish_failed_marker, reason: "거부된 요청은 게시를 시도하지 않는다 — 결과 축이 성립하지 않는다" }
|
||||
- { publishable: kill_switch_off, outcome: success, reason: "kill-switch 꺼짐은 재게시를 시도하지 않는다 — republished=false 만 성립" }
|
||||
- { publishable: non_production, outcome: success, reason: "비프로덕션은 재게시를 시도하지 않는다 — republished=false 만 성립" }
|
||||
|
||||
effects:
|
||||
- status_endpoint_returns_report_fields
|
||||
- republish_bumps_version_and_publishes
|
||||
- republish_denied_without_settings_update_permission
|
||||
- republish_disabled_when_not_publishable
|
||||
- card_renders_status_rows
|
||||
- republish_button_disabled_when_not_publishable
|
||||
- confirm_modal_then_toast_and_refetch
|
||||
- dashboard_alert_points_to_admin_republish
|
||||
|
||||
test_files:
|
||||
- tests/Feature/Api/Admin/SettingsStaticCacheTest.php
|
||||
- tests/Feature/Services/ExtensionStaticCacheServiceTest.php
|
||||
- tests/Feature/Dashboard/StaticPublishAlertTest.php
|
||||
- tests/Feature/Console/ExtStaticStatusCommandTest.php
|
||||
- templates/_bundled/sirsoft-admin_basic/__tests__/layouts/admin-settings-static-cache.test.tsx
|
||||
- templates/_bundled/sirsoft-admin_basic/__tests__/layouts/admin_dashboard.recovery.test.tsx
|
||||
- tests/Playwright/specs/admin/settings-static-cache-rebuild.spec.ts
|
||||
|
||||
notes: |
|
||||
outcome=publish_failed_marker 의 마커는 게시 실패(권한·디스크)에서만 생겨 Windows 개발기와 브라우저로는
|
||||
재현할 수 없다 — 카드의 실패 행 분기는 Vitest 가 페이로드로, 마커 기록은 ExtensionStaticCacheServiceTest 가
|
||||
덮는다. 대시보드 알림의 [다시 만들기] 버튼은 T2(UI) 와 같은 엔드포인트를 POST 하므로 동작 검증은
|
||||
카드 경로가 대표한다(리스너 페이로드 + 레이아웃 `if` 분기는 단위로 잠근다).
|
||||
E2E 대상 사이트(g7_2.dev)는 평소 local 이라 재게시 케이스는 운영 모드 실측 창에서만 수행되고, 그 밖에서는
|
||||
비활성 계약(버튼 disabled + 사유 힌트)만 잠근 채 skip 된다.
|
||||
Reference in new issue
Block a user