feat(seo): 사이트맵 안전 서빙·잡 견고화·분할 설정 + 캐시 설정 정합

봇 요청 스레드의 동기 생성을 제거하고 디스크 스트리밍 서빙으로 전환했다.
신선도가 만료되면 생성 잡만 예약하고 기존 세트(stale) 또는 503+Retry-After 로
응답해, 대용량에서 봇 요청이 OOM/타임아웃을 유발하던 경로를 끊었다.

- 잡: ShouldBeUnique(고정 uniqueId)+uniqueFor+retryUntil, timeout 300→1800, backoff
- 컨트롤러: 인덱스 stale/503 분기 + 자식 라우트(.xml/.xml.gz 동일 액션)
- 스케줄 withoutOverlapping, 관리자 재생성 큐 이관
- 설정 4키(분할 기준·압축·stale 서빙·수집기 상한) + 고급탭 Sitemap 캐시 짝
- SitemapManager 응답 메시지 다국어화

설정 저장 테스트가 실제 설정 파일(사이트명/언어 포함)을 덮어쓰던 사전결함을
TestCase 전역 격리로 차단하고, 두 탭이 같은 다국어 키를 공유해 한쪽에 틀린
한도를 안내하던 사전결함을 키 분리로 해소했다.
This commit is contained in:
HeuJung committed 2026-07-18 11:32:11 +09:00
1 parent 21f666e4b5
commit 1c99547bc1
71 files changed
+3767 -2472

No files matched your search

@@ -3,6 +3,7 @@
namespace Tests\Feature\Api\Admin;
use App\Enums\ExtensionOwnerType;
use App\Jobs\GenerateSitemapJob;
use App\Models\Permission;
use App\Models\Role;
use App\Models\SeoCacheStat;
@@ -10,7 +11,9 @@ use App\Models\User;
use App\Seo\Contracts\SeoCacheManagerInterface;
use App\Seo\SitemapManager;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Queue;
use Mockery;
use Tests\TestCase;
@@ -389,76 +392,72 @@ class SeoCacheControllerTest extends TestCase
}
/**
* 정상 재생성 시 200 + last_updated_at 데이터 반환
* 재생성 요청 시 200 + 예약 상태와 직전 생성 시각을 반환
*/
public function test_regenerate_sitemap_returns_200_with_data(): void
public function test_regenerate_sitemap_returns_200_with_dispatched_status(): void
{
$mock = Mockery::mock(SitemapManager::class);
$mock->shouldReceive('regenerate')
->once()
->andReturn([
'success' => true,
'status' => 'updated',
'message' => 'Sitemap 생성이 완료되었습니다.',
'data' => [
'last_updated_at' => '2026-04-29T10:00:00+00:00',
'size_bytes' => 1234,
'ttl' => 86400,
],
]);
$this->app->instance(SitemapManager::class, $mock);
Queue::fake();
Config::set('g7_settings.core.seo.sitemap_enabled', true);
Config::set('g7_settings.core.seo.sitemap_last_updated_at', '2026-04-29T10:00:00+00:00');
$response = $this->withHeader('Authorization', 'Bearer '.$this->token)
->postJson('/api/admin/seo/sitemap/regenerate');
$response->assertStatus(200);
$this->assertTrue($response->json('success'));
$this->assertSame('dispatched', $response->json('data.status'));
$this->assertSame('2026-04-29T10:00:00+00:00', $response->json('data.last_updated_at'));
$this->assertSame(1234, $response->json('data.size_bytes'));
}
/**
* Sitemap 비활성 상태 시 400 반환
* 재생성 요청이 큐 잡을 1건만 디스패치하는지 확인
*/
public function test_regenerate_sitemap_dispatches_job(): void
{
Queue::fake();
Config::set('g7_settings.core.seo.sitemap_enabled', true);
$this->withHeader('Authorization', 'Bearer '.$this->token)
->postJson('/api/admin/seo/sitemap/regenerate')
->assertStatus(200);
Queue::assertPushed(GenerateSitemapJob::class, 1);
}
/**
* 재생성 요청이 요청 스레드에서 동기 생성하지 않는지 확인
*
* 이 회귀가 무너지면 1.4M 규모에서 관리자 워커가 OOM 으로 죽습니다.
*/
public function test_regenerate_sitemap_does_not_generate_inline(): void
{
Queue::fake();
Config::set('g7_settings.core.seo.sitemap_enabled', true);
$mock = Mockery::mock(SitemapManager::class);
$mock->shouldNotReceive('regenerate');
$mock->shouldReceive('getStatus')->andReturn(['last_updated_at' => null]);
$this->app->instance(SitemapManager::class, $mock);
$this->withHeader('Authorization', 'Bearer '.$this->token)
->postJson('/api/admin/seo/sitemap/regenerate')
->assertStatus(200);
}
/**
* Sitemap 비활성 상태 시 400 반환 + 잡 미디스패치
*/
public function test_regenerate_sitemap_returns_400_when_disabled(): void
{
$mock = Mockery::mock(SitemapManager::class);
$mock->shouldReceive('regenerate')
->once()
->andReturn([
'success' => false,
'status' => 'disabled',
'message' => 'Sitemap 생성이 비활성화되어 있습니다.',
]);
$this->app->instance(SitemapManager::class, $mock);
Queue::fake();
Config::set('g7_settings.core.seo.sitemap_enabled', false);
$response = $this->withHeader('Authorization', 'Bearer '.$this->token)
->postJson('/api/admin/seo/sitemap/regenerate');
$response->assertStatus(400);
$this->assertFalse($response->json('success'));
}
/**
* 내부 실패 시 500 반환
*/
public function test_regenerate_sitemap_returns_500_on_failure(): void
{
$mock = Mockery::mock(SitemapManager::class);
$mock->shouldReceive('regenerate')
->once()
->andReturn([
'success' => false,
'status' => 'failed',
'message' => 'Sitemap 생성에 실패했습니다: contributor crashed',
]);
$this->app->instance(SitemapManager::class, $mock);
$response = $this->withHeader('Authorization', 'Bearer '.$this->token)
->postJson('/api/admin/seo/sitemap/regenerate');
$response->assertStatus(500);
$this->assertFalse($response->json('success'));
Queue::assertNotPushed(GenerateSitemapJob::class);
}
protected function tearDown(): void
@@ -2,12 +2,14 @@
namespace Tests\Feature\Seo;
use App\Contracts\Repositories\ConfigRepositoryInterface;
use App\Enums\ExtensionOwnerType;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Testing\TestResponse;
use Tests\TestCase;
/**
@@ -35,6 +37,20 @@ class SaveSettingsRequestSeoTest extends TestCase
$this->token = $this->admin->createToken('test-token')->plainTextToken;
}
/**
* 저장된 설정 카테고리를 디스크에서 다시 읽습니다.
*
* g7_core_settings() 는 부팅 시점에 로드된 Config 를 보므로, 같은 프로세스에서
* 저장 직후 값을 확인할 때는 저장소를 직접 읽어야 합니다.
*
* @param string $category 설정 카테고리
* @return array 저장된 설정 배열
*/
private function storedSettings(string $category): array
{
return app(ConfigRepositoryInterface::class)->getCategory($category);
}
/**
* 관리자 역할 및 권한을 가진 사용자를 생성합니다.
*
@@ -99,7 +115,7 @@ class SaveSettingsRequestSeoTest extends TestCase
*
* @param array $seoData SEO 필드 데이터
*/
private function postSeoSettings(array $seoData): \Illuminate\Testing\TestResponse
private function postSeoSettings(array $seoData): TestResponse
{
return $this->actingAs($this->admin)
->postJson('/api/admin/settings', [
@@ -385,4 +401,239 @@ class SaveSettingsRequestSeoTest extends TestCase
$response->assertStatus(422)
->assertJsonValidationErrors(['seo.generator_content']);
}
// ========================================
// sitemap 분할/압축/서빙 설정 검증 테스트
// ========================================
/**
* sitemap 분할/압축/서빙 설정이 저장되어 설정값에 반영되는지 확인
*/
public function test_sitemap_generation_settings_are_saved(): void
{
$response = $this->postSeoSettings([
'sitemap_urls_per_file' => 20000,
'sitemap_gzip' => true,
'sitemap_serve_stale_on_miss' => false,
'sitemap_max_urls_per_contributor' => 100000,
]);
$response->assertStatus(200);
$seo = $this->storedSettings('seo');
$this->assertSame(20000, $seo['sitemap_urls_per_file']);
$this->assertTrue((bool) $seo['sitemap_gzip']);
$this->assertFalse((bool) $seo['sitemap_serve_stale_on_miss']);
$this->assertSame(100000, $seo['sitemap_max_urls_per_contributor']);
}
/**
* 파일당 URL 수 상한(50000)을 넘기면 422 응답
*
* 50000 은 sitemaps.org 프로토콜 상한이므로 저장 자체를 막습니다.
*/
public function test_sitemap_urls_per_file_exceeding_protocol_limit_fails(): void
{
$response = $this->postSeoSettings([
'sitemap_urls_per_file' => 50001,
]);
$response->assertStatus(422)
->assertJsonValidationErrors(['seo.sitemap_urls_per_file']);
}
/**
* 파일당 URL 수 하한(1000) 미만이면 422 응답
*/
public function test_sitemap_urls_per_file_below_minimum_fails(): void
{
$response = $this->postSeoSettings([
'sitemap_urls_per_file' => 999,
]);
$response->assertStatus(422)
->assertJsonValidationErrors(['seo.sitemap_urls_per_file']);
}
/**
* 파일당 URL 수 경계값(1000/50000)은 통과하는지 확인
*/
public function test_sitemap_urls_per_file_boundary_values_pass(): void
{
$this->postSeoSettings(['sitemap_urls_per_file' => 1000])->assertStatus(200);
$this->postSeoSettings(['sitemap_urls_per_file' => 50000])->assertStatus(200);
}
/**
* 수집기당 최대 URL 수는 0(무제한)을 허용하고 음수는 거부하는지 확인
*/
public function test_sitemap_max_urls_per_contributor_allows_zero_and_rejects_negative(): void
{
$this->postSeoSettings(['sitemap_max_urls_per_contributor' => 0])->assertStatus(200);
$this->postSeoSettings(['sitemap_max_urls_per_contributor' => -1])
->assertStatus(422)
->assertJsonValidationErrors(['seo.sitemap_max_urls_per_contributor']);
}
/**
* gzip 이 boolean 이 아니면 422 응답
*/
public function test_sitemap_gzip_non_boolean_fails_validation(): void
{
$response = $this->postSeoSettings([
'sitemap_gzip' => 'yes-please',
]);
$response->assertStatus(422)
->assertJsonValidationErrors(['seo.sitemap_gzip']);
}
// ========================================
// 고급 탭 Sitemap 캐시 기준값 (D19 의 메인 값)
// ========================================
/**
* 고급 탭 설정 저장 요청을 전송합니다.
*
* @param array $advancedData 고급 필드 데이터
*/
private function postAdvancedSettings(array $advancedData): TestResponse
{
return $this->actingAs($this->admin)
->postJson('/api/admin/settings', [
'_tab' => 'advanced',
'advanced' => $advancedData,
]);
}
/**
* 고급 탭의 Sitemap 캐시 기준값이 저장되어 cache 카테고리에 반영되는지 확인
*/
public function test_advanced_sitemap_cache_ttl_is_saved_to_cache_category(): void
{
$response = $this->postAdvancedSettings([
'cache_enabled' => true,
'layout_cache_enabled' => true,
'layout_cache_ttl' => 3600,
'stats_cache_enabled' => true,
'stats_cache_ttl' => 3600,
'seo_cache_enabled' => true,
'seo_cache_ttl' => 3600,
'seo_sitemap_cache_ttl' => 43200,
'debug_mode' => false,
'sql_query_log' => false,
]);
$response->assertStatus(200);
$this->assertSame(43200, $this->storedSettings('cache')['seo_sitemap_ttl']);
}
/**
* 고급 탭 Sitemap 캐시 기준값이 기본값(86400)을 허용하는지 확인
*
* 형제 캐시 TTL 규칙(최대 14400)을 그대로 재사용하면 화면 기본값조차 저장할 수 없게 됩니다.
*/
public function test_advanced_sitemap_cache_ttl_accepts_default_value(): void
{
$this->postAdvancedSettings([
'cache_enabled' => true,
'layout_cache_enabled' => true,
'layout_cache_ttl' => 3600,
'stats_cache_enabled' => true,
'stats_cache_ttl' => 3600,
'seo_cache_enabled' => true,
'seo_cache_ttl' => 3600,
'seo_sitemap_cache_ttl' => 86400,
'debug_mode' => false,
'sql_query_log' => false,
])->assertStatus(200);
$this->assertSame(86400, $this->storedSettings('cache')['seo_sitemap_ttl']);
}
/**
* 고급 탭 Sitemap 캐시 기준값의 허용 범위를 벗어나면 422 응답
*/
public function test_advanced_sitemap_cache_ttl_out_of_range_fails(): void
{
$this->postAdvancedSettings(['seo_sitemap_cache_ttl' => 604801])
->assertStatus(422)
->assertJsonValidationErrors(['advanced.seo_sitemap_cache_ttl']);
$this->postAdvancedSettings(['seo_sitemap_cache_ttl' => 3599])
->assertStatus(422)
->assertJsonValidationErrors(['advanced.seo_sitemap_cache_ttl']);
}
/**
* 신규 키를 보내지 않는 기존 클라이언트의 고급 탭 저장이 계속 동작하는지 확인
*
* 형제 키처럼 required 로 두면 이전 화면/외부 클라이언트의 저장이 422 로 깨집니다.
*/
public function test_advanced_tab_saves_without_new_sitemap_cache_key(): void
{
$this->postAdvancedSettings([
'cache_enabled' => true,
'layout_cache_enabled' => true,
'layout_cache_ttl' => 3600,
'stats_cache_enabled' => true,
'stats_cache_ttl' => 3600,
'seo_cache_enabled' => true,
'seo_cache_ttl' => 3600,
'debug_mode' => false,
'sql_query_log' => false,
])->assertStatus(200);
}
/**
* 두 탭의 SEO 캐시 TTL 안내 문구가 각자의 실제 한도를 알려주는지 확인
*
* 두 탭이 같은 다국어 키를 공유하면 PHP 배열의 나중 정의가 이겨서
* 한쪽 탭이 반드시 틀린 한도를 안내하게 됩니다(ko/en 이 서로 반대로 틀어졌던 사례).
*/
public function test_seo_cache_ttl_messages_state_each_tabs_own_limit(): void
{
$seoTabErrors = $this->postSeoSettings(['cache_ttl' => 86401])
->assertStatus(422)
->json('errors');
$advancedTabErrors = $this->postAdvancedSettings(['seo_cache_ttl' => 14401])
->assertStatus(422)
->json('errors');
$this->assertStringContainsString('86400', $seoTabErrors['seo.cache_ttl'][0]);
$this->assertStringContainsString('14400', $advancedTabErrors['advanced.seo_cache_ttl'][0]);
}
// ========================================
// 캐시 오버라이드 칸 비우기 (D19)
// ========================================
/**
* 캐시 오버라이드 칸을 비워서 저장하면 null(미설정)로 정규화되는지 확인
*
* 폼에서 칸을 비우면 빈 문자열로 전송될 수 있는데, 이것이 null 로 정규화되지 않으면
* "미설정" 으로 판정되지 않아 고급 설정 값을 따르지 못하고 오버라이드가 계속 발동합니다.
*/
public function test_emptied_cache_override_fields_are_normalized_to_null(): void
{
$this->postSeoSettings([
'cache_ttl' => 3600,
'sitemap_cache_ttl' => 7200,
])->assertStatus(200);
$seo = $this->storedSettings('seo');
$this->assertSame(3600, $seo['cache_ttl']);
$this->assertSame(7200, $seo['sitemap_cache_ttl']);
$this->postSeoSettings([
'cache_ttl' => '',
'sitemap_cache_ttl' => '',
])->assertStatus(200);
$seo = $this->storedSettings('seo');
$this->assertNull($seo['cache_ttl']);
$this->assertNull($seo['sitemap_cache_ttl']);
}
}
+227 -119
View File
@@ -2,169 +2,277 @@
namespace Tests\Feature\Seo;
use App\Seo\SitemapGenerator;
use App\Extension\Storage\CoreStorageDriver;
use App\Jobs\GenerateSitemapJob;
use App\Seo\SitemapFileStore;
use App\Seo\SitemapManager;
use App\Seo\SitemapWriter;
use App\Seo\SitemapXmlRenderer;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use Mockery;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;
use Illuminate\Testing\TestResponse;
use Tests\TestCase;
/**
* Sitemap XML 엔드포인트 기능 테스트
*
* GET /sitemap.xml 라우트가 올바른 XML 응답을 반환하고,
* 캐싱/비활성화 설정이 올바르게 동작하는지 검증합니다.
* 봇 요청 스레드에서 sitemap 을 생성하지 않고(대용량 OOM 원인),
* 비공개 디스크에 커밋된 세트를 스트리밍 서빙하는 계약을 검증합니다.
* 신선도가 만료되면 생성은 큐에 맡기고 기존 세트(stale)를 내보냅니다.
*/
class SitemapTest extends TestCase
{
private CoreStorageDriver $storage;
/**
* 테스트 종료 - Mockery 리소스를 정리합니다.
* 테스트 초기화 - 가짜 비공개 디스크와 활성화 설정을 준비합니다.
*/
protected function tearDown(): void
protected function setUp(): void
{
Mockery::close();
parent::tearDown();
parent::setUp();
Config::set('app.locale', 'ko');
Config::set('app.supported_locales', ['ko']);
Config::set('g7_settings.core.seo.sitemap_enabled', true);
Storage::fake('local');
$this->storage = new CoreStorageDriver('local');
$this->app->instance(SitemapFileStore::class, new SitemapFileStore($this->storage));
Cache::forget('g7:core:'.SitemapManager::META_CACHE_KEY);
}
/**
* sitemap.xml 요청이 application/xml Content-Type을 반환하는지 확인합니다.
* 커밋된 sitemap 세트를 디스크에 만듭니다.
*
* @param int $urlCount 생성할 URL 수
* @param int $urlsPerFile 파일당 URL 수
* @param bool $gzip gzip 압축 여부
* @return array 커밋 결과 메타
*/
public function test_sitemap_returns_xml_content_type(): void
private function commitSet(int $urlCount = 3, int $urlsPerFile = 50000, bool $gzip = false): array
{
// sitemap 활성화 설정
Config::set('g7_settings.core.seo.sitemap_enabled', true);
$writer = new SitemapWriter(
$this->storage,
SitemapXmlRenderer::fromConfig(),
$urlsPerFile,
$gzip,
);
// 캐시에 XML 미리 저장하여 Generator 호출 방지
$sampleXml = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>';
Cache::put('g7:core:seo.sitemap', $sampleXml, 86400);
$writer->open();
for ($i = 1; $i <= $urlCount; $i++) {
$writer->addUrl(['loc' => url("/page/{$i}")]);
}
$writer->close();
return $writer->commit();
}
/**
* 메타 캐시를 신선한 상태로 만듭니다.
*
* @param array $meta 커밋 메타
*/
private function markFresh(array $meta): void
{
Cache::put('g7:core:'.SitemapManager::META_CACHE_KEY, $meta, 86400);
}
/**
* 응답 본문을 문자열로 수집합니다.
*
* @param TestResponse $response 테스트 응답
* @return string 응답 본문
*/
private function streamBody($response): string
{
ob_start();
$response->baseResponse->sendContent();
return (string) ob_get_clean();
}
/**
* 신선한 세트가 있으면 디스크의 sitemapindex 를 XML 로 서빙하는지 확인합니다.
*/
public function test_index_is_served_from_disk_when_fresh(): void
{
$meta = $this->commitSet();
$this->markFresh($meta);
$response = $this->get('/sitemap.xml');
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/xml');
$body = $this->streamBody($response);
$this->assertStringContainsString('<sitemapindex', $body);
$this->assertStringContainsString('/sitemap-1.xml', $body);
}
/**
* sitemap_enabled가 false일 때 404를 반환하는지 확인합니다.
* 신선한 세트를 서빙할 때는 생성 잡을 디스패치하지 않는지 확인합니다.
*/
public function test_sitemap_returns_404_when_disabled(): void
public function test_index_does_not_dispatch_job_when_fresh(): void
{
Queue::fake();
$meta = $this->commitSet();
$this->markFresh($meta);
$this->get('/sitemap.xml')->assertStatus(200);
Queue::assertNotPushed(GenerateSitemapJob::class);
}
/**
* 메타 캐시가 만료되면 봇 요청 스레드에서 생성하지 않고 잡만 디스패치하는지 확인합니다.
*
* 이 회귀가 무너지면 1.4M 규모에서 봇 요청이 OOM/타임아웃을 유발합니다.
*/
public function test_index_dispatches_job_and_serves_stale_on_cache_miss(): void
{
Queue::fake();
$this->commitSet();
// 메타 캐시 없음 = 신선도 만료 상태
$response = $this->get('/sitemap.xml');
$response->assertStatus(200);
$this->assertStringContainsString('<sitemapindex', $this->streamBody($response));
Queue::assertPushed(GenerateSitemapJob::class, 1);
}
/**
* serve_stale_on_miss 가 false 면 만료 시 stale 을 내보내지 않고 503 을 반환하는지 확인합니다.
*/
public function test_index_returns_503_on_miss_when_stale_serving_disabled(): void
{
Queue::fake();
Config::set('g7_settings.core.seo.sitemap_serve_stale_on_miss', false);
$this->commitSet();
$response = $this->get('/sitemap.xml');
$response->assertStatus(503);
$response->assertHeader('Retry-After', '120');
Queue::assertPushed(GenerateSitemapJob::class, 1);
}
/**
* 커밋된 세트가 전혀 없으면 503 + Retry-After 를 반환하는지 확인합니다.
*/
public function test_index_returns_503_with_retry_after_when_no_set_exists(): void
{
Queue::fake();
$response = $this->get('/sitemap.xml');
$response->assertStatus(503);
$response->assertHeader('Retry-After', '120');
Queue::assertPushed(GenerateSitemapJob::class, 1);
}
/**
* 자식 sitemap 라우트가 디스크 파일을 스트리밍하는지 확인합니다.
*/
public function test_child_route_streams_child_sitemap(): void
{
$this->commitSet(urlCount: 3, urlsPerFile: 2);
$response = $this->get('/sitemap-1.xml');
$response->assertStatus(200);
$body = $this->streamBody($response);
$this->assertStringContainsString('<urlset', $body);
$this->assertStringContainsString('/page/1', $body);
}
/**
* 인덱스가 가리키는 모든 자식 경로가 실제로 서빙되는지 확인합니다.
*
* 인덱스의 <loc> 규칙(SitemapFileStore::childUrl)과 라우트 경로가 어긋나면
* 검색엔진에 404 를 가리키는 인덱스를 내보내게 됩니다.
*/
public function test_index_child_locs_are_all_routable(): void
{
$meta = $this->commitSet(urlCount: 5, urlsPerFile: 2);
$this->assertSame(3, $meta['child_count']);
for ($n = 1; $n <= $meta['child_count']; $n++) {
$this->get(SitemapFileStore::childUrl($n))->assertStatus(200);
}
}
/**
* 존재하지 않는 자식 번호는 404 를 반환하는지 확인합니다.
*/
public function test_child_route_returns_404_for_unknown_child(): void
{
$this->commitSet(urlCount: 1, urlsPerFile: 50000);
$this->get('/sitemap-99.xml')->assertStatus(404);
}
/**
* gzip 세트는 .xml.gz 경로에서 Content-Encoding 과 함께 서빙되는지 확인합니다.
*/
public function test_child_route_serves_gzip_set(): void
{
$this->commitSet(urlCount: 2, urlsPerFile: 50000, gzip: true);
$response = $this->get('/sitemap-1.xml.gz');
$response->assertStatus(200);
$response->assertHeader('Content-Encoding', 'gzip');
$this->assertStringContainsString('<urlset', (string) gzdecode($this->streamBody($response)));
}
/**
* sitemap_enabled 가 false 이면 인덱스/자식 모두 404 를 반환하는지 확인합니다.
*/
public function test_routes_return_404_when_disabled(): void
{
$meta = $this->commitSet();
$this->markFresh($meta);
Config::set('g7_settings.core.seo.sitemap_enabled', false);
$response = $this->get('/sitemap.xml');
$response->assertStatus(404);
$this->get('/sitemap.xml')->assertStatus(404);
$this->get('/sitemap-1.xml')->assertStatus(404);
}
/**
* 캐시에 저장된 XML이 있으면 해당 내용을 반환하는지 확인합니다.
* sitemap_enabled 가 null 이면 (bool) 캐스팅으로 비활성 처리되는지 확인합니다.
*/
public function test_sitemap_returns_cached_content(): void
{
Config::set('g7_settings.core.seo.sitemap_enabled', true);
$cachedXml = '<?xml version="1.0" encoding="UTF-8"?>'
.'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
.'<url><loc>https://example.com/cached</loc></url>'
.'</urlset>';
Cache::put('g7:core:seo.sitemap', $cachedXml, 86400);
$response = $this->get('/sitemap.xml');
$response->assertStatus(200);
$response->assertSee('https://example.com/cached');
$this->assertSame($cachedXml, $response->getContent());
}
/**
* 캐시가 없을 때 SitemapGenerator::generate()를 호출하고
* 결과를 캐시에 저장하는지 확인합니다.
*/
public function test_sitemap_generates_and_caches_when_not_cached(): void
{
Config::set('g7_settings.core.seo.sitemap_enabled', true);
Config::set('g7_settings.core.seo.sitemap_cache_ttl', 3600);
// 캐시 비우기
Cache::forget('g7:core:seo.sitemap');
$generatedXml = '<?xml version="1.0" encoding="UTF-8"?>'
.'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
.'<url><loc>https://example.com/generated</loc></url>'
.'</urlset>';
// SitemapGenerator Mock
$generatorMock = Mockery::mock(SitemapGenerator::class);
$generatorMock->shouldReceive('generate')
->once()
->andReturn($generatedXml);
// 컨테이너에 Mock 바인딩
$this->app->instance(SitemapGenerator::class, $generatorMock);
$response = $this->get('/sitemap.xml');
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/xml');
$this->assertSame($generatedXml, $response->getContent());
// 캐시에 저장되었는지 확인
$this->assertSame($generatedXml, Cache::get('g7:core:seo.sitemap'));
}
/**
* sitemap_enabled가 null로 설정되면 (bool) 캐스팅에 의해 비활성으로 처리되는지 확인합니다.
*
* Config에 키가 null로 존재하면 Config::get()이 null을 반환하고,
* (bool) null = false이므로 404가 됩니다.
*/
public function test_sitemap_returns_404_when_enabled_is_null(): void
public function test_index_returns_404_when_enabled_is_null(): void
{
Config::set('g7_settings.core.seo.sitemap_enabled', null);
$response = $this->get('/sitemap.xml');
$response->assertStatus(404);
$this->get('/sitemap.xml')->assertStatus(404);
}
/**
* sitemap_enabled가 true일 때 정상 동작하는지 확인합니다.
* 서빙된 인덱스/자식이 유효한 XML 인지 확인합니다.
*/
public function test_sitemap_works_when_explicitly_enabled(): void
public function test_served_documents_are_valid_xml(): void
{
Config::set('g7_settings.core.seo.sitemap_enabled', true);
$meta = $this->commitSet(urlCount: 3, urlsPerFile: 2);
$this->markFresh($meta);
$sampleXml = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>';
Cache::put('g7:core:seo.sitemap', $sampleXml, 86400);
$index = simplexml_load_string($this->streamBody($this->get('/sitemap.xml')));
$this->assertNotFalse($index, 'sitemapindex 응답이 유효한 XML 이어야 합니다');
$this->assertSame('sitemapindex', $index->getName());
$response = $this->get('/sitemap.xml');
$response->assertStatus(200);
}
/**
* sitemap XML 응답 본문이 XML 형식인지 확인합니다.
*/
public function test_sitemap_response_body_is_valid_xml(): void
{
Config::set('g7_settings.core.seo.sitemap_enabled', true);
$validXml = '<?xml version="1.0" encoding="UTF-8"?>'."\n"
.'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\n"
.' <url>'."\n"
.' <loc>https://example.com/</loc>'."\n"
.' </url>'."\n"
.'</urlset>';
Cache::put('g7:core:seo.sitemap', $validXml, 86400);
$response = $this->get('/sitemap.xml');
$response->assertStatus(200);
// XML 파싱이 성공하는지 확인
$xml = simplexml_load_string($response->getContent());
$this->assertNotFalse($xml, 'sitemap 응답이 유효한 XML이어야 합니다');
$this->assertSame('urlset', $xml->getName());
$child = simplexml_load_string($this->streamBody($this->get('/sitemap-1.xml')));
$this->assertNotFalse($child, '자식 sitemap 응답이 유효한 XML 이어야 합니다');
$this->assertSame('urlset', $child->getName());
}
}
@@ -0,0 +1,69 @@
<?php
namespace Tests\Feature\Settings;
use App\Contracts\Repositories\ConfigRepositoryInterface;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
/**
* settings 디스크 격리 회귀 테스트
*
* settings 디스크의 root 는 storage/app/settings — 개발/운영이 실제로 쓰는 설정 파일입니다.
* TestCase 가 이 디스크를 페이크로 대체하지 않으면, 설정 저장 경로를 타는 모든 테스트가
* 실제 설정을 덮어쓰고 RefreshDatabase 로도 되돌아가지 않습니다.
*
* 실제 피해 사례: 설정 저장 테스트가 general.json 의 사이트명/언어를 테스트 값으로 덮어써
* 개발 사이트 언어가 ja 로 바뀌어 있었고, SEO/캐시 TTL 도 테스트 값으로 대체되어 있었음.
*
* 이 가드가 풀리면 조용히 환경이 오염되므로(테스트는 계속 green) 명시적으로 고정합니다.
*/
class SettingsDiskIsolationTest extends TestCase
{
/**
* settings 디스크가 페이크로 대체되어 실경로를 가리키지 않는지 확인합니다.
*
* config 의 root 는 페이크 후에도 실경로 그대로이므로(Storage::fake 는 해석된 디스크
* 인스턴스만 교체), 반드시 해석된 디스크의 경로로 판정해야 합니다.
*/
public function test_settings_disk_is_faked_and_does_not_point_to_real_storage(): void
{
$root = str_replace('\\', '/', Storage::disk('settings')->path(''));
$this->assertStringContainsString(
'framework/testing',
$root,
'settings 디스크가 페이크로 대체되지 않았습니다 — 테스트가 실제 설정 파일을 덮어씁니다.'
);
$this->assertStringNotContainsString(
'storage/app/settings',
$root,
'settings 디스크가 실제 설정 경로를 가리킵니다.'
);
}
/**
* 설정을 저장해도 실제 설정 파일이 만들어지지 않는지 확인합니다.
*/
public function test_saving_settings_does_not_write_to_real_storage_path(): void
{
$realPath = storage_path('app/settings/general.json');
$before = file_exists($realPath) ? file_get_contents($realPath) : null;
app(ConfigRepositoryInterface::class)->saveCategory('general', [
'site_name' => '격리 검증용 값',
'language' => 'ja',
]);
$after = file_exists($realPath) ? file_get_contents($realPath) : null;
$this->assertSame($before, $after, '설정 저장이 실제 설정 파일을 변경했습니다.');
// 저장 자체는 페이크 디스크에서 정상 동작해야 한다 (격리가 기능을 죽이면 안 됨)
Storage::disk('settings')->assertExists('general.json');
$this->assertSame(
'격리 검증용 값',
app(ConfigRepositoryInterface::class)->getCategory('general')['site_name']
);
}
}
@@ -0,0 +1,177 @@
/**
* E2E: 환경설정 > SEO/고급 — Sitemap 생성 설정 칸 (#481)
*
* @scenario admin_settings_sitemap_generation_fields
* @effects fields_mounted, fields_persisted, regenerate_is_async
*
* 배경: 대용량 사이트에서 sitemap 을 여러 파일로 나눠 생성하도록 분할 기준/압축 설정을
* 추가하고, 관리자 "지금 생성" 버튼을 즉시 실행에서 큐 예약으로 바꿨다. 설정 칸이 실제로
* 마운트·저장되는지, 재생성 버튼이 응답을 기다리며 멈추지 않는지 브라우저에서 확인한다.
*
* 검증:
* 1. SEO 탭에 분할 기준/압축 칸이 번역문과 함께 마운트된다
* 2. 분할 기준을 바꿔 저장하면 422 없이 성공하고 재진입 시 유지된다
* 3. 고급 탭에 Sitemap 캐시 기준값 칸이 마운트되고 기본값(86400)이 저장된다
* 4. "지금 생성" 클릭이 즉시 응답을 받는다 (동기 생성이면 대용량에서 타임아웃)
*/
import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth';
const URLS_PER_FILE = '#field_sitemap_urls_per_file';
const GZIP_ROW = '#field_sitemap_gzip';
const ADVANCED_SITEMAP_CACHE = '#cache_seo_sitemap';
/** 관리자 환경설정 SEO 탭 진입 */
async function gotoSeoTab(page: import('@playwright/test').Page): Promise<void> {
await page.goto('/admin/settings?tab=seo');
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
await expect(page.locator(URLS_PER_FILE)).toBeAttached({ timeout: 20_000 });
}
/** 관리자 환경설정 고급 탭 진입 */
async function gotoAdvancedTab(page: import('@playwright/test').Page): Promise<void> {
await page.goto('/admin/settings?tab=advanced');
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
await expect(page.locator(ADVANCED_SITEMAP_CACHE)).toBeAttached({ timeout: 20_000 });
}
// @scenario tab=seo, permitted=yes
// @effects fields_mounted
test('@smoke #481 - SEO 탭에 Sitemap 분할 기준/압축 칸이 번역문과 함께 마운트된다', async ({ page }) => {
const token = issueToken('core.settings.read', 'core.settings.update');
await authenticatePage(page, token);
await gotoSeoTab(page);
expect(page.url()).not.toMatch(/\/admin\/login/);
const urlsPerFile = page.locator(URLS_PER_FILE);
await expect(urlsPerFile).toBeAttached();
// 다국어 키 미해석 회귀 가드
const urlsText = (await urlsPerFile.innerText()).trim();
expect(urlsText).not.toContain('$t:');
expect(urlsText.length).toBeGreaterThan(0);
// 프로토콜 상한이 입력 단계에서 그대로 반영된다
const input = urlsPerFile.locator('input[type="number"]').first();
await expect(input).toHaveAttribute('max', '50000');
await expect(input).toHaveAttribute('min', '1000');
const gzipRow = page.locator(GZIP_ROW);
await expect(gzipRow).toBeAttached();
expect((await gzipRow.innerText()).trim()).not.toContain('$t:');
await expect(gzipRow.locator('input[type="checkbox"]').first()).toBeAttached();
});
// @scenario tab=seo, permitted=yes
// @effects fields_persisted
test('#481 - 분할 기준을 바꿔 저장하면 성공하고 재진입 시 유지된다', async ({ page }) => {
const token = issueToken('core.settings.read', 'core.settings.update');
await authenticatePage(page, token);
await gotoSeoTab(page);
const input = page.locator(`${URLS_PER_FILE} input[type="number"]`).first();
// 폼이 저장된 설정으로 채워진 뒤에 수정해야 한다 (로드 전 입력은 다른 필드가 빈 채로 전송됨)
await expect.poll(() => input.inputValue(), { timeout: 15_000 }).not.toBe('');
const original = await input.inputValue();
const next = original === '30000' ? '40000' : '30000';
await input.fill(next);
await expect(page.locator('#save_button')).toBeEnabled({ timeout: 10_000 });
const save = page.waitForResponse(
(r) => r.url().includes('/api/admin/settings') && r.request().method() === 'POST',
{ timeout: 20_000 }
);
await page.locator('#save_button').click();
// 신규 키가 검증 규칙에 없으면 422 로 떨어진다 (배관 누락 회귀 가드)
expect((await save).status()).toBe(200);
await gotoSeoTab(page);
const reloaded = page.locator(`${URLS_PER_FILE} input[type="number"]`).first();
await expect.poll(() => reloaded.inputValue(), { timeout: 15_000 }).toBe(next);
// 원상 복구 (E2E 는 실제 환경 설정을 건드린다)
await reloaded.fill(original);
const restore = page.waitForResponse(
(r) => r.url().includes('/api/admin/settings') && r.request().method() === 'POST',
{ timeout: 20_000 }
);
await page.locator('#save_button').click();
expect((await restore).status()).toBe(200);
});
// @scenario tab=advanced, permitted=yes
// @effects fields_mounted, fields_persisted
test('#481 - 고급 탭 Sitemap 캐시 기준값 칸이 마운트되고 기본값이 저장된다', async ({ page }) => {
const token = issueToken('core.settings.read', 'core.settings.update');
await authenticatePage(page, token);
await gotoAdvancedTab(page);
const row = page.locator(ADVANCED_SITEMAP_CACHE);
await expect(row).toBeAttached();
expect((await row.innerText()).trim()).not.toContain('$t:');
const input = row.locator('input[type="number"]').first();
await expect(input).toBeAttached();
// 폼이 저장된 설정으로 채워진 뒤에 수정해야 한다 (로드 전 입력은 다른 필드가 빈 채로 전송됨)
await expect.poll(() => input.inputValue(), { timeout: 15_000 }).not.toBe('');
const original = await input.inputValue();
// 기본값 86400 은 형제 칸 규칙(최대 14400)을 재사용하면 저장 자체가 막힌다
const next = original === '86400' ? '43200' : '86400';
await input.fill(next);
await expect(page.locator('#save_button')).toBeEnabled({ timeout: 10_000 });
const save = page.waitForResponse(
(r) => r.url().includes('/api/admin/settings') && r.request().method() === 'POST',
{ timeout: 20_000 }
);
await page.locator('#save_button').click();
expect((await save).status()).toBe(200);
// 원상 복구 (E2E 는 실제 환경 설정을 건드린다)
await gotoAdvancedTab(page);
const restored = page.locator(`${ADVANCED_SITEMAP_CACHE} input[type="number"]`).first();
await expect.poll(() => restored.inputValue(), { timeout: 15_000 }).toBe(next);
await restored.fill(original);
const restore = page.waitForResponse(
(r) => r.url().includes('/api/admin/settings') && r.request().method() === 'POST',
{ timeout: 20_000 }
);
await page.locator('#save_button').click();
expect((await restore).status()).toBe(200);
});
// @scenario tab=seo, permitted=yes
// @effects regenerate_is_async
test('#481 - "지금 생성" 클릭이 큐에 예약되고 즉시 응답한다', async ({ page }) => {
const token = issueToken('core.settings.read', 'core.settings.update');
await authenticatePage(page, token);
await gotoSeoTab(page);
const regenerate = page.waitForResponse(
(r) => r.url().includes('/api/admin/seo/sitemap/regenerate'),
{ timeout: 20_000 }
);
const startedAt = Date.now();
await page.locator('#sitemap_last_updated_block button').first().click();
const response = await regenerate;
const elapsed = Date.now() - startedAt;
expect(response.status()).toBe(200);
expect((await response.json())?.data?.status).toBe('dispatched');
// 동기 생성으로 되돌아가면 응답 시간이 데이터 규모에 비례해 늘어난다.
// 절대 하한 대신 "예약 응답이라면 당연히 만족하는" 상한으로 회귀만 잡는다.
expect(elapsed).toBeLessThan(10_000);
});
+27
View File
@@ -6,6 +6,7 @@ use App\Extension\Testing\ExtensionTestAllowlist;
use App\Listeners\Identity\EnforceIdentityPolicyListener;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
abstract class TestCase extends BaseTestCase
{
@@ -39,12 +40,18 @@ abstract class TestCase extends BaseTestCase
* createApplication() 단계에서 모든 ServiceProvider 의 register()/boot() 가
* 실행되므로, allowlist 는 그 이전(= parent::setUp() 호출 전)에 설정되어야
* provider 자동 등록 가드가 올바른 시점에 적용됩니다.
*
* settings 디스크는 앱 부팅 직후 페이크로 대체합니다 (아래 fakeSettingsDisk).
*/
protected function setUp(): void
{
// 앱 생성 전에 확장 allowlist 설정 (provider register 가드 적용 시점 보장)
ExtensionTestAllowlist::set($this->resolveAllowedExtensions());
$this->afterApplicationCreated(function () {
$this->fakeSettingsDisk();
});
if (! self::$staleConnectionsCleaned) {
// Laravel 앱 부팅 전이므로 부트스트랩 후 콜백으로 등록
$this->afterApplicationCreated(function () {
@@ -56,6 +63,26 @@ abstract class TestCase extends BaseTestCase
parent::setUp();
}
/**
* settings 디스크를 페이크로 대체하여 실제 설정 파일을 보호합니다.
*
* `settings` 디스크의 root 는 `storage/app/settings` 로, 개발/운영 환경이 실제로
* 사용하는 설정 파일 그 자체입니다. 페이크로 대체하지 않으면 설정 저장 경로를 타는
* 테스트(설정 API 호출, ConfigRepository::saveCategory 등)가 실제 설정을 덮어쓰고,
* RefreshDatabase 는 DB 만 되돌리므로 그 오염이 그대로 남습니다.
*
* 실제 피해 사례: 설정 저장 테스트가 `general.json` 의 사이트명/언어를 테스트 값으로
* 덮어써 개발 사이트 언어가 ja 로 바뀌어 있었고, SEO/캐시 TTL 도 테스트 값으로 대체됨.
*
* 설정 *읽기* 는 부팅 시 Config(`g7_settings.*`)로 이미 적재된 뒤이므로 이 페이크의
* 영향을 받지 않습니다. 저장소를 직접 읽어야 하는 테스트는 페이크 디스크에 직접
* 값을 넣고 검증합니다.
*/
private function fakeSettingsDisk(): void
{
Storage::fake('settings');
}
/**
* 테스트 종료 시 확장 allowlist 를 초기화합니다.
*
+61 -8
View File
@@ -4,7 +4,9 @@ namespace Tests\Unit\Jobs;
use App\Jobs\GenerateSitemapJob;
use App\Seo\SitemapManager;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
use Mockery;
use Tests\TestCase;
@@ -28,20 +30,71 @@ class GenerateSitemapJobTest extends TestCase
*/
public function test_job_implements_should_queue(): void
{
$job = new GenerateSitemapJob();
$job = new GenerateSitemapJob;
$this->assertInstanceOf(ShouldQueue::class, $job);
}
/**
* tries=3, timeout=300 속성을 확인합니다.
* 대용량 생성을 견디는 큐 속성을 확인합니다.
*/
public function test_job_has_correct_tries_and_timeout(): void
{
$job = new GenerateSitemapJob();
$job = new GenerateSitemapJob;
$this->assertSame(3, $job->tries);
$this->assertSame(300, $job->timeout);
$this->assertSame(1800, $job->timeout);
$this->assertSame(120, $job->backoff);
}
/**
* ShouldBeUnique 를 구현하여 동시 실행을 막는지 확인합니다.
*
* 봇 요청 캐시 미스마다 dispatch 되어도 큐에 한 건만 남아야 합니다.
*/
public function test_job_implements_should_be_unique(): void
{
$job = new GenerateSitemapJob;
$this->assertInstanceOf(ShouldBeUnique::class, $job);
}
/**
* 유니크 락 키가 인스턴스와 무관하게 고정값인지 확인합니다.
*
* 인스턴스마다 키가 다르면 중복 디스패치가 그대로 통과합니다.
*/
public function test_unique_id_is_stable_across_instances(): void
{
$this->assertSame('seo-sitemap', (new GenerateSitemapJob)->uniqueId());
$this->assertSame('seo-sitemap', (new GenerateSitemapJob)->uniqueId());
}
/**
* 유니크 락이 영구 고착되지 않도록 만료 시간이 설정되어 있는지 확인합니다.
*/
public function test_unique_lock_expires(): void
{
$job = new GenerateSitemapJob;
$this->assertSame(900, $job->uniqueFor);
}
/**
* retryUntil 이 재시도 누적을 30분으로 제한하는지 확인합니다.
*/
public function test_retry_until_limits_retry_window(): void
{
Carbon::setTestNow(Carbon::parse('2026-07-17 10:00:00'));
$job = new GenerateSitemapJob;
$this->assertSame(
'2026-07-17 10:30:00',
Carbon::instance($job->retryUntil())->format('Y-m-d H:i:s')
);
Carbon::setTestNow();
}
/**
@@ -68,7 +121,7 @@ class GenerateSitemapJobTest extends TestCase
return $context['size'] === 1234 && $context['ttl'] === 86400;
}));
$job = new GenerateSitemapJob();
$job = new GenerateSitemapJob;
$job->handle($manager);
$this->addToAssertionCount(Mockery::getContainer()->mockery_getExpectationCount());
@@ -92,7 +145,7 @@ class GenerateSitemapJobTest extends TestCase
->once()
->with('[SEO] Sitemap generation skipped (disabled)');
$job = new GenerateSitemapJob();
$job = new GenerateSitemapJob;
$job->handle($manager);
$this->addToAssertionCount(Mockery::getContainer()->mockery_getExpectationCount());
@@ -115,7 +168,7 @@ class GenerateSitemapJobTest extends TestCase
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('contributor crashed');
$job = new GenerateSitemapJob();
$job = new GenerateSitemapJob;
$job->handle($manager);
}
@@ -132,7 +185,7 @@ class GenerateSitemapJobTest extends TestCase
return $context['error'] === 'Sitemap generation timeout';
}));
$job = new GenerateSitemapJob();
$job = new GenerateSitemapJob;
$job->failed($exception);
$this->addToAssertionCount(Mockery::getContainer()->mockery_getExpectationCount());