feat(seo): 사이트맵 스트리밍 생성 + SEO 캐시 설정 정합화
대용량 사이트에서 사이트맵 생성이 메모리 부족으로 반복 실패하던 문제(공개 )의 1단계로, 전체 URL을 메모리에 적재하던 구조를 스트리밍 분할 생성으로 교체한다. 사이트맵 스트리밍 코어: - SitemapWriter — 자식 파일 1개 분량만 버퍼링하고 임계 도달 시 flush. StorageInterface가 append를 제공하지 않아(put이 전체 덮어쓰기) 택한 구조이며, 최대 메모리가 "자식 파일 1개 크기"로 유계가 된다. URL 수(50,000)와 바이트(45MB) 두 임계로 분할해 sitemaps.org 프로토콜을 지킨다. - 커밋은 _tmp 전량 기록 → live 재배치 → manifest 마지막 기록 순. manifest 존재가 커밋 완료 신호다. 기존 manifest를 먼저 지우지 않아 스왑 중 봇에게 503이 나가지 않는다. - SitemapFileStore — 읽기측 + 파일 경로 SSoT. SitemapXmlRenderer — escape 단일 출처. 데이터 접근 계층 정리: - contributor 3종이 쿼리를 직접 조립하던 것을 Repository 위임으로 전환. MySQL 버퍼드 쿼리에서 cursor는 결과셋 전체를 적재하므로 lazyById를 쓴다. - SeoCacheStatsService → SeoCacheStatRepository 신설 (집계 4쿼리 → 1쿼리). - audit 룰 service-direct-data-access의 사각 2건 수정 — 확장 디렉토리 정규식이 상대경로를 매칭하지 못해 *Contributor처럼 접미사 없는 클래스가 전부 미검출이었다. SEO 캐시 설정 정합화: - SEO 설정의 캐시 3키가 cache 카테고리 형제 키에 항상 져서 운영자 입력이 조용히 무시되고 있었다(설정을 cache 카테고리로 이관하며 SEO 탭 옛 칸을 미제거). 고급 탭을 기준값으로 두되 SEO 탭에 지정이 있으면 오버라이드하도록 SeoCacheSettings 단일 출처로 정리. "지정 여부"는 null로 판정하므로 기본값을 비웠다. - 기존 설치는 Upgrade_7_1_0이 이행 — 옛 기본값과 같으면 미설정으로 비우고, 다르면 운영자 의도로 보아 보존한다. 코어 버전 bump와 루트 CHANGELOG는 계획서 결정(D20)에 따라 마감 단계에서 일괄 수행한다.
This commit is contained in:
1 parent
fcaacad8d1
commit
21f666e4b5
75 files changed
+4767
-951
No files matched your search
@@ -1,181 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Seo\Contracts\SitemapContributorInterface;
|
||||
use Mockery;
|
||||
use Modules\Sirsoft\Board\Enums\PostStatus;
|
||||
use Modules\Sirsoft\Board\Models\Board;
|
||||
use Modules\Sirsoft\Board\Models\Post;
|
||||
use Modules\Sirsoft\Board\Seo\BoardSitemapContributor;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* BoardSitemapContributor 단위 테스트
|
||||
*
|
||||
* Board 모듈의 Sitemap 기여자가 올바른 식별자를 반환하고,
|
||||
* 게시판/게시글 URL을 올바르게 생성하는지 검증합니다.
|
||||
*/
|
||||
class BoardSitemapContributorTest extends TestCase
|
||||
{
|
||||
private BoardSitemapContributor $contributor;
|
||||
|
||||
/**
|
||||
* 테스트 초기화 - BoardSitemapContributor 인스턴스를 준비합니다.
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->contributor = new BoardSitemapContributor;
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트 종료 - Mockery 리소스를 정리합니다.
|
||||
*/
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Mockery::close();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* SitemapContributorInterface를 구현하는지 확인합니다.
|
||||
*/
|
||||
public function test_implements_sitemap_contributor_interface(): void
|
||||
{
|
||||
$this->assertInstanceOf(SitemapContributorInterface::class, $this->contributor);
|
||||
}
|
||||
|
||||
/**
|
||||
* getIdentifier()가 'sirsoft-board'를 반환하는지 확인합니다.
|
||||
*/
|
||||
public function test_get_identifier_returns_correct_value(): void
|
||||
{
|
||||
$this->assertSame('sirsoft-board', $this->contributor->getIdentifier());
|
||||
}
|
||||
|
||||
/**
|
||||
* getUrls()가 게시판/게시글 URL을 포함한 배열을 반환하는지 확인합니다.
|
||||
*
|
||||
* @runInSeparateProcess
|
||||
*
|
||||
* @preserveGlobalState disabled
|
||||
*/
|
||||
public function test_get_urls_returns_board_and_post_urls(): void
|
||||
{
|
||||
// Board::where('is_active', true)->get() Mock
|
||||
$boardCollection = collect([
|
||||
(object) ['id' => 1, 'slug' => 'notice', 'updated_at' => now()],
|
||||
(object) ['id' => 2, 'slug' => 'free', 'updated_at' => now()],
|
||||
]);
|
||||
|
||||
$boardQuery = Mockery::mock('Illuminate\Database\Eloquent\Builder');
|
||||
$boardQuery->shouldReceive('get')
|
||||
->with(['id', 'slug', 'updated_at'])
|
||||
->andReturn($boardCollection);
|
||||
|
||||
$boardMock = Mockery::mock('alias:'.Board::class);
|
||||
$boardMock->shouldReceive('where')
|
||||
->with('is_active', true)
|
||||
->andReturn($boardQuery);
|
||||
|
||||
// Post::where(...)->where(...)->where(...)->get() Mock - notice 게시판
|
||||
$noticePostCollection = collect([
|
||||
(object) ['id' => 100, 'updated_at' => now()],
|
||||
]);
|
||||
|
||||
// Post::where(...)->where(...)->where(...)->get() Mock - free 게시판
|
||||
$freePostCollection = collect([
|
||||
(object) ['id' => 200, 'updated_at' => now()],
|
||||
(object) ['id' => 201, 'updated_at' => now()],
|
||||
]);
|
||||
|
||||
// Post 쿼리 빌더 체이닝 Mock
|
||||
$postQueryNotice = Mockery::mock('Illuminate\Database\Eloquent\Builder');
|
||||
$postQueryNotice->shouldReceive('where')
|
||||
->with('status', PostStatus::Published)
|
||||
->andReturnSelf();
|
||||
$postQueryNotice->shouldReceive('where')
|
||||
->with('is_secret', false)
|
||||
->andReturnSelf();
|
||||
$postQueryNotice->shouldReceive('get')
|
||||
->with(['id', 'updated_at'])
|
||||
->andReturn($noticePostCollection);
|
||||
|
||||
$postQueryFree = Mockery::mock('Illuminate\Database\Eloquent\Builder');
|
||||
$postQueryFree->shouldReceive('where')
|
||||
->with('status', PostStatus::Published)
|
||||
->andReturnSelf();
|
||||
$postQueryFree->shouldReceive('where')
|
||||
->with('is_secret', false)
|
||||
->andReturnSelf();
|
||||
$postQueryFree->shouldReceive('get')
|
||||
->with(['id', 'updated_at'])
|
||||
->andReturn($freePostCollection);
|
||||
|
||||
$postMock = Mockery::mock('alias:'.Post::class);
|
||||
$postMock->shouldReceive('where')
|
||||
->with('board_id', 1)
|
||||
->andReturn($postQueryNotice);
|
||||
$postMock->shouldReceive('where')
|
||||
->with('board_id', 2)
|
||||
->andReturn($postQueryFree);
|
||||
|
||||
$contributor = new BoardSitemapContributor;
|
||||
$urls = $contributor->getUrls();
|
||||
|
||||
$this->assertIsArray($urls);
|
||||
|
||||
// 1(정적 목록) + 2(게시판) + 1(notice 게시글) + 2(free 게시글) = 6
|
||||
$this->assertCount(6, $urls);
|
||||
|
||||
// 정적 게시판 목록 URL
|
||||
$this->assertSame('/boards', $urls[0]['url']);
|
||||
$this->assertSame('weekly', $urls[0]['changefreq']);
|
||||
$this->assertSame(0.5, $urls[0]['priority']);
|
||||
|
||||
// notice 게시판 URL
|
||||
$this->assertSame('/board/notice', $urls[1]['url']);
|
||||
$this->assertSame('daily', $urls[1]['changefreq']);
|
||||
$this->assertSame(0.6, $urls[1]['priority']);
|
||||
|
||||
// notice 게시판의 게시글 URL
|
||||
$this->assertSame('/board/notice/100', $urls[2]['url']);
|
||||
$this->assertSame('monthly', $urls[2]['changefreq']);
|
||||
$this->assertSame(0.5, $urls[2]['priority']);
|
||||
|
||||
// free 게시판 URL
|
||||
$this->assertSame('/board/free', $urls[3]['url']);
|
||||
|
||||
// free 게시판의 게시글 URL
|
||||
$this->assertSame('/board/free/200', $urls[4]['url']);
|
||||
$this->assertSame('/board/free/201', $urls[5]['url']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 게시판이 없을 때 정적 URL만 반환하는지 확인합니다.
|
||||
*
|
||||
* @runInSeparateProcess
|
||||
*
|
||||
* @preserveGlobalState disabled
|
||||
*/
|
||||
public function test_get_urls_returns_only_static_url_when_no_active_boards(): void
|
||||
{
|
||||
$boardQuery = Mockery::mock('Illuminate\Database\Eloquent\Builder');
|
||||
$boardQuery->shouldReceive('get')
|
||||
->with(['id', 'slug', 'updated_at'])
|
||||
->andReturn(collect([]));
|
||||
|
||||
$boardMock = Mockery::mock('alias:'.Board::class);
|
||||
$boardMock->shouldReceive('where')
|
||||
->with('is_active', true)
|
||||
->andReturn($boardQuery);
|
||||
|
||||
$contributor = new BoardSitemapContributor;
|
||||
$urls = $contributor->getUrls();
|
||||
|
||||
$this->assertCount(1, $urls);
|
||||
$this->assertSame('/boards', $urls[0]['url']);
|
||||
}
|
||||
}
|
||||
@@ -1,233 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Seo\Contracts\SitemapContributorInterface;
|
||||
use Mockery;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ProductDisplayStatus;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Category;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
use Modules\Sirsoft\Ecommerce\Seo\EcommerceSitemapContributor;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* EcommerceSitemapContributor 단위 테스트
|
||||
*
|
||||
* Ecommerce 모듈의 Sitemap 기여자가 올바른 식별자를 반환하고,
|
||||
* 상품/카테고리 URL을 올바르게 생성하는지 검증합니다.
|
||||
*/
|
||||
class EcommerceSitemapContributorTest extends TestCase
|
||||
{
|
||||
private EcommerceSitemapContributor $contributor;
|
||||
|
||||
/**
|
||||
* 테스트 초기화 - EcommerceSitemapContributor 인스턴스를 준비합니다.
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->contributor = new EcommerceSitemapContributor;
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트 종료 - Mockery 리소스를 정리합니다.
|
||||
*/
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Mockery::close();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* SitemapContributorInterface를 구현하는지 확인합니다.
|
||||
*/
|
||||
public function test_implements_sitemap_contributor_interface(): void
|
||||
{
|
||||
$this->assertInstanceOf(SitemapContributorInterface::class, $this->contributor);
|
||||
}
|
||||
|
||||
/**
|
||||
* getIdentifier()가 'sirsoft-ecommerce'를 반환하는지 확인합니다.
|
||||
*/
|
||||
public function test_get_identifier_returns_correct_value(): void
|
||||
{
|
||||
$this->assertSame('sirsoft-ecommerce', $this->contributor->getIdentifier());
|
||||
}
|
||||
|
||||
/**
|
||||
* getUrls()가 배열을 반환하는지 확인합니다.
|
||||
*
|
||||
* Category/Product 모델 쿼리를 Mock하여 DB 의존성 없이 테스트합니다.
|
||||
*
|
||||
* @runInSeparateProcess
|
||||
*
|
||||
* @preserveGlobalState disabled
|
||||
*/
|
||||
public function test_get_urls_returns_array_with_mocked_models(): void
|
||||
{
|
||||
// Category::where('is_active', true)->get() Mock
|
||||
$categoryCollection = collect([
|
||||
(object) ['id' => 1, 'slug' => 'electronics', 'updated_at' => now()],
|
||||
(object) ['id' => 2, 'slug' => 'fashion', 'updated_at' => now()],
|
||||
]);
|
||||
|
||||
$categoryQuery = Mockery::mock('Illuminate\Database\Eloquent\Builder');
|
||||
$categoryQuery->shouldReceive('get')
|
||||
->with(['id', 'slug', 'updated_at'])
|
||||
->andReturn($categoryCollection);
|
||||
|
||||
// Category 모델 정적 호출 Mock (alias)
|
||||
$categoryMock = Mockery::mock('alias:'.Category::class);
|
||||
$categoryMock->shouldReceive('where')
|
||||
->with('is_active', true)
|
||||
->andReturn($categoryQuery);
|
||||
|
||||
// Product::where('display_status', ProductDisplayStatus::VISIBLE)->get() Mock
|
||||
$productCollection = collect([
|
||||
(object) ['id' => 10, 'updated_at' => now()],
|
||||
(object) ['id' => 20, 'updated_at' => now()],
|
||||
]);
|
||||
|
||||
$productQuery = Mockery::mock('Illuminate\Database\Eloquent\Builder');
|
||||
$productQuery->shouldReceive('get')
|
||||
->with(['id', 'updated_at'])
|
||||
->andReturn($productCollection);
|
||||
|
||||
$productMock = Mockery::mock('alias:'.Product::class);
|
||||
$productMock->shouldReceive('where')
|
||||
->with('display_status', ProductDisplayStatus::VISIBLE)
|
||||
->andReturn($productQuery);
|
||||
|
||||
// route_path 설정
|
||||
$this->app['config']->set('g7_settings.modules.sirsoft-ecommerce.basic_info.route_path', 'shop');
|
||||
|
||||
$contributor = new EcommerceSitemapContributor;
|
||||
$urls = $contributor->getUrls();
|
||||
|
||||
$this->assertIsArray($urls);
|
||||
$this->assertNotEmpty($urls);
|
||||
|
||||
// 첫 번째는 정적 상품 목록 URL
|
||||
$this->assertSame('/shop/products', $urls[0]['url']);
|
||||
$this->assertSame('daily', $urls[0]['changefreq']);
|
||||
$this->assertSame(0.7, $urls[0]['priority']);
|
||||
|
||||
// 카테고리 URL 확인 (2개)
|
||||
$this->assertSame('/shop/category/electronics', $urls[1]['url']);
|
||||
$this->assertSame('/shop/category/fashion', $urls[2]['url']);
|
||||
|
||||
// 상품 URL 확인 (2개)
|
||||
$this->assertSame('/shop/products/10', $urls[3]['url']);
|
||||
$this->assertSame('/shop/products/20', $urls[4]['url']);
|
||||
|
||||
// 총 5개 URL (1 정적 + 2 카테고리 + 2 상품)
|
||||
$this->assertCount(5, $urls);
|
||||
}
|
||||
|
||||
/**
|
||||
* getUrls()가 route_path 기본값 'shop'을 사용하는지 확인합니다.
|
||||
*
|
||||
* @runInSeparateProcess
|
||||
*
|
||||
* @preserveGlobalState disabled
|
||||
*/
|
||||
public function test_get_urls_uses_default_route_path_when_not_configured(): void
|
||||
{
|
||||
// Category 빈 컬렉션 반환
|
||||
$categoryQuery = Mockery::mock('Illuminate\Database\Eloquent\Builder');
|
||||
$categoryQuery->shouldReceive('get')
|
||||
->with(['id', 'slug', 'updated_at'])
|
||||
->andReturn(collect([]));
|
||||
|
||||
$categoryMock = Mockery::mock('alias:'.Category::class);
|
||||
$categoryMock->shouldReceive('where')
|
||||
->with('is_active', true)
|
||||
->andReturn($categoryQuery);
|
||||
|
||||
// Product 빈 컬렉션 반환
|
||||
$productQuery = Mockery::mock('Illuminate\Database\Eloquent\Builder');
|
||||
$productQuery->shouldReceive('get')
|
||||
->with(['id', 'updated_at'])
|
||||
->andReturn(collect([]));
|
||||
|
||||
$productMock = Mockery::mock('alias:'.Product::class);
|
||||
$productMock->shouldReceive('where')
|
||||
->with('display_status', ProductDisplayStatus::VISIBLE)
|
||||
->andReturn($productQuery);
|
||||
|
||||
// route_path 미설정 (기본값 'shop' 사용)
|
||||
$this->app['config']->set('g7_settings.modules.sirsoft-ecommerce.basic_info.route_path', null);
|
||||
|
||||
$contributor = new EcommerceSitemapContributor;
|
||||
$urls = $contributor->getUrls();
|
||||
|
||||
$this->assertCount(1, $urls);
|
||||
$this->assertSame('/shop/products', $urls[0]['url']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 각 URL 항목이 올바른 키 구조를 가지는지 확인합니다.
|
||||
*
|
||||
* @runInSeparateProcess
|
||||
*
|
||||
* @preserveGlobalState disabled
|
||||
*/
|
||||
public function test_url_entries_have_correct_structure(): void
|
||||
{
|
||||
$categoryCollection = collect([
|
||||
(object) ['id' => 1, 'slug' => 'test-cat', 'updated_at' => now()],
|
||||
]);
|
||||
|
||||
$categoryQuery = Mockery::mock('Illuminate\Database\Eloquent\Builder');
|
||||
$categoryQuery->shouldReceive('get')
|
||||
->with(['id', 'slug', 'updated_at'])
|
||||
->andReturn($categoryCollection);
|
||||
|
||||
$categoryMock = Mockery::mock('alias:'.Category::class);
|
||||
$categoryMock->shouldReceive('where')
|
||||
->with('is_active', true)
|
||||
->andReturn($categoryQuery);
|
||||
|
||||
$productCollection = collect([
|
||||
(object) ['id' => 5, 'updated_at' => now()],
|
||||
]);
|
||||
|
||||
$productQuery = Mockery::mock('Illuminate\Database\Eloquent\Builder');
|
||||
$productQuery->shouldReceive('get')
|
||||
->with(['id', 'updated_at'])
|
||||
->andReturn($productCollection);
|
||||
|
||||
$productMock = Mockery::mock('alias:'.Product::class);
|
||||
$productMock->shouldReceive('where')
|
||||
->with('display_status', ProductDisplayStatus::VISIBLE)
|
||||
->andReturn($productQuery);
|
||||
|
||||
$this->app['config']->set('g7_settings.modules.sirsoft-ecommerce.basic_info.route_path', 'shop');
|
||||
|
||||
$contributor = new EcommerceSitemapContributor;
|
||||
$urls = $contributor->getUrls();
|
||||
|
||||
// 정적 URL 구조 확인 (lastmod 없음)
|
||||
$this->assertArrayHasKey('url', $urls[0]);
|
||||
$this->assertArrayHasKey('changefreq', $urls[0]);
|
||||
$this->assertArrayHasKey('priority', $urls[0]);
|
||||
$this->assertArrayNotHasKey('lastmod', $urls[0]);
|
||||
|
||||
// 카테고리 URL 구조 확인 (lastmod 있음)
|
||||
$this->assertArrayHasKey('url', $urls[1]);
|
||||
$this->assertArrayHasKey('lastmod', $urls[1]);
|
||||
$this->assertArrayHasKey('changefreq', $urls[1]);
|
||||
$this->assertArrayHasKey('priority', $urls[1]);
|
||||
$this->assertSame('weekly', $urls[1]['changefreq']);
|
||||
$this->assertSame(0.6, $urls[1]['priority']);
|
||||
|
||||
// 상품 URL 구조 확인 (lastmod 있음)
|
||||
$this->assertArrayHasKey('url', $urls[2]);
|
||||
$this->assertArrayHasKey('lastmod', $urls[2]);
|
||||
$this->assertArrayHasKey('changefreq', $urls[2]);
|
||||
$this->assertArrayHasKey('priority', $urls[2]);
|
||||
$this->assertSame('weekly', $urls[2]['changefreq']);
|
||||
$this->assertSame(0.8, $urls[2]['priority']);
|
||||
}
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Seo\Contracts\SitemapContributorInterface;
|
||||
use Mockery;
|
||||
use Modules\Sirsoft\Page\Models\Page;
|
||||
use Modules\Sirsoft\Page\Seo\PageSitemapContributor;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* PageSitemapContributor 단위 테스트
|
||||
*
|
||||
* Page 모듈의 Sitemap 기여자가 올바른 식별자를 반환하고,
|
||||
* 발행된 페이지 URL을 올바르게 생성하는지 검증합니다.
|
||||
*/
|
||||
class PageSitemapContributorTest extends TestCase
|
||||
{
|
||||
private PageSitemapContributor $contributor;
|
||||
|
||||
/**
|
||||
* 테스트 초기화 - PageSitemapContributor 인스턴스를 준비합니다.
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->contributor = new PageSitemapContributor;
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트 종료 - Mockery 리소스를 정리합니다.
|
||||
*/
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Mockery::close();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* SitemapContributorInterface를 구현하는지 확인합니다.
|
||||
*/
|
||||
public function test_implements_sitemap_contributor_interface(): void
|
||||
{
|
||||
$this->assertInstanceOf(SitemapContributorInterface::class, $this->contributor);
|
||||
}
|
||||
|
||||
/**
|
||||
* getIdentifier()가 'sirsoft-page'를 반환하는지 확인합니다.
|
||||
*/
|
||||
public function test_get_identifier_returns_correct_value(): void
|
||||
{
|
||||
$this->assertSame('sirsoft-page', $this->contributor->getIdentifier());
|
||||
}
|
||||
|
||||
/**
|
||||
* getUrls()가 발행된 페이지 URL을 반환하는지 확인합니다.
|
||||
*
|
||||
* @runInSeparateProcess
|
||||
*
|
||||
* @preserveGlobalState disabled
|
||||
*/
|
||||
public function test_get_urls_returns_published_page_urls(): void
|
||||
{
|
||||
$pageCollection = collect([
|
||||
(object) ['slug' => 'about', 'updated_at' => now()],
|
||||
(object) ['slug' => 'contact', 'updated_at' => now()],
|
||||
(object) ['slug' => 'terms', 'updated_at' => now()],
|
||||
]);
|
||||
|
||||
$pageQuery = Mockery::mock('Illuminate\Database\Eloquent\Builder');
|
||||
$pageQuery->shouldReceive('get')
|
||||
->with(['slug', 'updated_at'])
|
||||
->andReturn($pageCollection);
|
||||
|
||||
$pageMock = Mockery::mock('alias:'.Page::class);
|
||||
$pageMock->shouldReceive('where')
|
||||
->with('published', true)
|
||||
->andReturn($pageQuery);
|
||||
|
||||
$contributor = new PageSitemapContributor;
|
||||
$urls = $contributor->getUrls();
|
||||
|
||||
$this->assertIsArray($urls);
|
||||
$this->assertCount(3, $urls);
|
||||
|
||||
// 각 페이지 URL 확인
|
||||
$this->assertSame('/page/about', $urls[0]['url']);
|
||||
$this->assertSame('monthly', $urls[0]['changefreq']);
|
||||
$this->assertSame(0.5, $urls[0]['priority']);
|
||||
$this->assertArrayHasKey('lastmod', $urls[0]);
|
||||
|
||||
$this->assertSame('/page/contact', $urls[1]['url']);
|
||||
$this->assertSame('/page/terms', $urls[2]['url']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 발행된 페이지가 없을 때 빈 배열을 반환하는지 확인합니다.
|
||||
*
|
||||
* @runInSeparateProcess
|
||||
*
|
||||
* @preserveGlobalState disabled
|
||||
*/
|
||||
public function test_get_urls_returns_empty_array_when_no_published_pages(): void
|
||||
{
|
||||
$pageQuery = Mockery::mock('Illuminate\Database\Eloquent\Builder');
|
||||
$pageQuery->shouldReceive('get')
|
||||
->with(['slug', 'updated_at'])
|
||||
->andReturn(collect([]));
|
||||
|
||||
$pageMock = Mockery::mock('alias:'.Page::class);
|
||||
$pageMock->shouldReceive('where')
|
||||
->with('published', true)
|
||||
->andReturn($pageQuery);
|
||||
|
||||
$contributor = new PageSitemapContributor;
|
||||
$urls = $contributor->getUrls();
|
||||
|
||||
$this->assertIsArray($urls);
|
||||
$this->assertEmpty($urls);
|
||||
}
|
||||
|
||||
/**
|
||||
* URL 항목이 올바른 키 구조를 가지는지 확인합니다.
|
||||
*
|
||||
* @runInSeparateProcess
|
||||
*
|
||||
* @preserveGlobalState disabled
|
||||
*/
|
||||
public function test_url_entries_have_correct_structure(): void
|
||||
{
|
||||
$pageCollection = collect([
|
||||
(object) ['slug' => 'test-page', 'updated_at' => now()],
|
||||
]);
|
||||
|
||||
$pageQuery = Mockery::mock('Illuminate\Database\Eloquent\Builder');
|
||||
$pageQuery->shouldReceive('get')
|
||||
->with(['slug', 'updated_at'])
|
||||
->andReturn($pageCollection);
|
||||
|
||||
$pageMock = Mockery::mock('alias:'.Page::class);
|
||||
$pageMock->shouldReceive('where')
|
||||
->with('published', true)
|
||||
->andReturn($pageQuery);
|
||||
|
||||
$contributor = new PageSitemapContributor;
|
||||
$urls = $contributor->getUrls();
|
||||
|
||||
$this->assertCount(1, $urls);
|
||||
|
||||
$entry = $urls[0];
|
||||
$this->assertArrayHasKey('url', $entry);
|
||||
$this->assertArrayHasKey('lastmod', $entry);
|
||||
$this->assertArrayHasKey('changefreq', $entry);
|
||||
$this->assertArrayHasKey('priority', $entry);
|
||||
|
||||
$this->assertSame('/page/test-page', $entry['url']);
|
||||
$this->assertSame('monthly', $entry['changefreq']);
|
||||
$this->assertSame(0.5, $entry['priority']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Seo\SeoCacheSettings;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* SeoCacheSettings 단위 테스트 (결정 D19)
|
||||
*
|
||||
* 우선순위 규칙:
|
||||
* 고급 탭(`cache.*`) = 메인 / SEO 탭(`seo.*`)에 별도 지정이 있으면 오버라이드.
|
||||
* "별도 지정" 판정은 null 여부 — null 이면 미설정으로 보고 고급 탭 값을 따른다.
|
||||
*
|
||||
* 회귀 배경: 과거에는 `cache.*` 가 **항상** 이겨 SEO 탭 입력이 조용히 무시되었다.
|
||||
* 이 저장소의 `seo.json` 에 `cache_ttl=3600` 이 저장돼 있었으나 실제로는
|
||||
* `cache.seo_ttl=7200` 으로 동작하던 것이 실증 사례다.
|
||||
*/
|
||||
class SeoCacheSettingsTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* 테스트 초기화 - 두 카테고리를 모두 미설정 상태로 비웁니다.
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Config::set('g7_settings.core.seo', []);
|
||||
Config::set('g7_settings.core.cache', []);
|
||||
}
|
||||
|
||||
/**
|
||||
* pageCacheTtl: SEO 탭이 미설정이면 고급 탭 값을 따른다
|
||||
*/
|
||||
public function test_page_cache_ttl_follows_advanced_tab_when_seo_is_unset(): void
|
||||
{
|
||||
Config::set('g7_settings.core.cache.seo_ttl', 7200);
|
||||
Config::set('g7_settings.core.seo.cache_ttl', null);
|
||||
|
||||
$this->assertSame(7200, SeoCacheSettings::pageCacheTtl());
|
||||
}
|
||||
|
||||
/**
|
||||
* pageCacheTtl: SEO 탭에 값이 있으면 고급 탭을 오버라이드한다 (회귀 — 과거엔 무시됨)
|
||||
*/
|
||||
public function test_page_cache_ttl_seo_override_wins_over_advanced_tab(): void
|
||||
{
|
||||
Config::set('g7_settings.core.cache.seo_ttl', 7200);
|
||||
Config::set('g7_settings.core.seo.cache_ttl', 3600);
|
||||
|
||||
$this->assertSame(
|
||||
3600,
|
||||
SeoCacheSettings::pageCacheTtl(),
|
||||
'SEO 탭에 지정한 값이 고급 탭보다 우선해야 합니다.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* pageCacheTtl: 양쪽 다 미설정이면 최종 기본값
|
||||
*/
|
||||
public function test_page_cache_ttl_falls_back_to_default_when_both_unset(): void
|
||||
{
|
||||
$this->assertSame(7200, SeoCacheSettings::pageCacheTtl());
|
||||
}
|
||||
|
||||
/**
|
||||
* pageCacheEnabled: SEO 탭이 미설정이면 고급 탭 값을 따른다
|
||||
*/
|
||||
public function test_page_cache_enabled_follows_advanced_tab_when_seo_is_unset(): void
|
||||
{
|
||||
Config::set('g7_settings.core.cache.seo_enabled', false);
|
||||
Config::set('g7_settings.core.seo.cache_enabled', null);
|
||||
|
||||
$this->assertFalse(SeoCacheSettings::pageCacheEnabled());
|
||||
}
|
||||
|
||||
/**
|
||||
* pageCacheEnabled: SEO 탭의 false 는 미설정이 아니라 오버라이드다
|
||||
*
|
||||
* null 이 아닌 falsy 값(false)을 "미설정" 으로 잘못 판정하면, 운영자가 SEO 캐시를
|
||||
* 끄려 해도 고급 탭의 true 가 이겨 캐시가 계속 켜진다.
|
||||
*/
|
||||
public function test_page_cache_enabled_treats_false_as_explicit_override(): void
|
||||
{
|
||||
Config::set('g7_settings.core.cache.seo_enabled', true);
|
||||
Config::set('g7_settings.core.seo.cache_enabled', false);
|
||||
|
||||
$this->assertFalse(
|
||||
SeoCacheSettings::pageCacheEnabled(),
|
||||
'false 는 미설정이 아니라 명시적 오버라이드여야 합니다.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* pageCacheEnabled: SEO 탭의 true 도 오버라이드로 동작한다
|
||||
*/
|
||||
public function test_page_cache_enabled_true_overrides_disabled_advanced_tab(): void
|
||||
{
|
||||
Config::set('g7_settings.core.cache.seo_enabled', false);
|
||||
Config::set('g7_settings.core.seo.cache_enabled', true);
|
||||
|
||||
$this->assertTrue(SeoCacheSettings::pageCacheEnabled());
|
||||
}
|
||||
|
||||
/**
|
||||
* sitemapCacheTtl: SEO 탭이 미설정이면 고급 탭 값을 따른다
|
||||
*/
|
||||
public function test_sitemap_cache_ttl_follows_advanced_tab_when_seo_is_unset(): void
|
||||
{
|
||||
Config::set('g7_settings.core.cache.seo_sitemap_ttl', 86400);
|
||||
Config::set('g7_settings.core.seo.sitemap_cache_ttl', null);
|
||||
|
||||
$this->assertSame(86400, SeoCacheSettings::sitemapCacheTtl());
|
||||
}
|
||||
|
||||
/**
|
||||
* sitemapCacheTtl: SEO 탭에 값이 있으면 고급 탭을 오버라이드한다 (회귀)
|
||||
*/
|
||||
public function test_sitemap_cache_ttl_seo_override_wins_over_advanced_tab(): void
|
||||
{
|
||||
Config::set('g7_settings.core.cache.seo_sitemap_ttl', 86400);
|
||||
Config::set('g7_settings.core.seo.sitemap_cache_ttl', 3600);
|
||||
|
||||
$this->assertSame(3600, SeoCacheSettings::sitemapCacheTtl());
|
||||
}
|
||||
|
||||
/**
|
||||
* sitemapCacheTtl: 양쪽 다 미설정이면 최종 기본값
|
||||
*/
|
||||
public function test_sitemap_cache_ttl_falls_back_to_default_when_both_unset(): void
|
||||
{
|
||||
$this->assertSame(86400, SeoCacheSettings::sitemapCacheTtl());
|
||||
}
|
||||
|
||||
/**
|
||||
* 각 영역은 서로 독립이다 — SEO 페이지 캐시 지정이 sitemap 에 새지 않는다
|
||||
*/
|
||||
public function test_domains_are_independent(): void
|
||||
{
|
||||
Config::set('g7_settings.core.cache.seo_ttl', 7200);
|
||||
Config::set('g7_settings.core.cache.seo_sitemap_ttl', 86400);
|
||||
Config::set('g7_settings.core.seo.cache_ttl', 60);
|
||||
|
||||
$this->assertSame(60, SeoCacheSettings::pageCacheTtl());
|
||||
$this->assertSame(
|
||||
86400,
|
||||
SeoCacheSettings::sitemapCacheTtl(),
|
||||
'SEO 페이지 캐시 오버라이드가 sitemap 캐시에 영향을 주면 안 됩니다.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 문자열로 저장된 값도 정수로 정규화된다 (폼 입력은 문자열로 올 수 있음)
|
||||
*/
|
||||
public function test_string_values_are_normalized_to_int(): void
|
||||
{
|
||||
Config::set('g7_settings.core.seo.sitemap_cache_ttl', '3600');
|
||||
|
||||
$this->assertSame(3600, SeoCacheSettings::sitemapCacheTtl());
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,8 @@ class SeoCacheStatsServiceTest extends TestCase
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->statsService = new SeoCacheStatsService;
|
||||
// Repository 주입이 필요하므로 컨테이너로 해석합니다.
|
||||
$this->statsService = $this->app->make(SeoCacheStatsService::class);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Extension\Storage\CoreStorageDriver;
|
||||
use App\Seo\SitemapFileStore;
|
||||
use App\Seo\SitemapWriter;
|
||||
use App\Seo\SitemapXmlRenderer;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* SitemapFileStore 단위 테스트
|
||||
*
|
||||
* 읽기측 API(exists/getManifest/indexResponse/childResponse/lastGeneratedAt)와
|
||||
* 경로 SSoT(childFilename/childUrl)를 검증합니다. 이 API 는 sitemap 라우트가
|
||||
* 그대로 소비하는 표면이므로 단위 수준에서 계약을 고정합니다.
|
||||
*/
|
||||
class SitemapFileStoreTest extends TestCase
|
||||
{
|
||||
private CoreStorageDriver $storage;
|
||||
|
||||
private SitemapFileStore $store;
|
||||
|
||||
/**
|
||||
* 테스트 초기화 - 가짜 로컬 디스크를 준비합니다.
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Config::set('app.locale', 'ko');
|
||||
Config::set('app.supported_locales', ['ko']);
|
||||
|
||||
Storage::fake('local');
|
||||
|
||||
$this->storage = new CoreStorageDriver('local');
|
||||
$this->store = new SitemapFileStore($this->storage);
|
||||
}
|
||||
|
||||
/**
|
||||
* 커밋된 sitemap 세트를 생성합니다.
|
||||
*
|
||||
* @param int $urlCount 생성할 URL 수
|
||||
* @param int $urlsPerFile 파일당 URL 수
|
||||
* @param bool $gzip gzip 압축 여부
|
||||
* @return array 커밋 결과 메타
|
||||
*/
|
||||
private function commitSet(int $urlCount = 3, int $urlsPerFile = 10, bool $gzip = false): array
|
||||
{
|
||||
$writer = new SitemapWriter(
|
||||
$this->storage,
|
||||
SitemapXmlRenderer::fromConfig(),
|
||||
$urlsPerFile,
|
||||
$gzip,
|
||||
);
|
||||
|
||||
$writer->open();
|
||||
for ($i = 1; $i <= $urlCount; $i++) {
|
||||
// writer 는 절대 URL(loc) 을 받는다 — 상대 경로(url) 는 Generator 가 정규화하는 형식이다.
|
||||
$writer->addUrl(['loc' => url("/page/{$i}")]);
|
||||
}
|
||||
$writer->close();
|
||||
|
||||
return $writer->commit();
|
||||
}
|
||||
|
||||
/**
|
||||
* StreamedResponse 본문을 문자열로 수집합니다.
|
||||
*
|
||||
* @param StreamedResponse $response 스트리밍 응답
|
||||
* @return string 응답 본문
|
||||
*/
|
||||
private function streamBody(StreamedResponse $response): string
|
||||
{
|
||||
ob_start();
|
||||
$response->sendContent();
|
||||
|
||||
return (string) ob_get_clean();
|
||||
}
|
||||
|
||||
/**
|
||||
* childFilename: 자식 파일명 규칙이 고정된다 (경로 SSoT)
|
||||
*/
|
||||
public function test_child_filename_follows_naming_rule(): void
|
||||
{
|
||||
$this->assertSame('sitemap-1.xml', SitemapFileStore::childFilename(1));
|
||||
$this->assertSame('sitemap-7.xml', SitemapFileStore::childFilename(7));
|
||||
$this->assertSame('sitemap-1.xml.gz', SitemapFileStore::childFilename(1, true));
|
||||
}
|
||||
|
||||
/**
|
||||
* childUrl: 자식 sitemap 의 공개 절대 URL 을 반환한다
|
||||
*/
|
||||
public function test_child_url_returns_absolute_url(): void
|
||||
{
|
||||
$this->assertSame(url('/sitemap-1.xml'), SitemapFileStore::childUrl(1));
|
||||
$this->assertSame(url('/sitemap-2.xml.gz'), SitemapFileStore::childUrl(2, true));
|
||||
}
|
||||
|
||||
/**
|
||||
* exists: 커밋된 세트가 없으면 false
|
||||
*/
|
||||
public function test_exists_returns_false_without_committed_set(): void
|
||||
{
|
||||
$this->assertFalse($this->store->exists());
|
||||
}
|
||||
|
||||
/**
|
||||
* exists: 커밋 후 true
|
||||
*/
|
||||
public function test_exists_returns_true_after_commit(): void
|
||||
{
|
||||
$this->commitSet();
|
||||
|
||||
$this->assertTrue($this->store->exists());
|
||||
}
|
||||
|
||||
/**
|
||||
* getManifest: 세트가 없으면 null
|
||||
*/
|
||||
public function test_get_manifest_returns_null_without_committed_set(): void
|
||||
{
|
||||
$this->assertNull($this->store->getManifest());
|
||||
}
|
||||
|
||||
/**
|
||||
* getManifest: 커밋된 메타를 반환한다
|
||||
*/
|
||||
public function test_get_manifest_returns_committed_metadata(): void
|
||||
{
|
||||
$this->commitSet(urlCount: 3);
|
||||
|
||||
$manifest = $this->store->getManifest();
|
||||
|
||||
$this->assertIsArray($manifest);
|
||||
$this->assertSame(3, $manifest['url_count']);
|
||||
$this->assertSame(1, $manifest['child_count']);
|
||||
$this->assertCount(1, $manifest['children']);
|
||||
$this->assertSame('sitemap-1.xml', $manifest['children'][0]['file']);
|
||||
}
|
||||
|
||||
/**
|
||||
* getManifest: manifest 가 손상되면 null 을 반환한다 (예외 전파 금지)
|
||||
*/
|
||||
public function test_get_manifest_returns_null_when_manifest_is_corrupted(): void
|
||||
{
|
||||
$this->commitSet();
|
||||
$this->storage->put(
|
||||
SitemapFileStore::CATEGORY,
|
||||
SitemapFileStore::LIVE_DIR.'/'.SitemapFileStore::MANIFEST_FILE,
|
||||
'{ this is not json',
|
||||
);
|
||||
|
||||
$this->assertNull($this->store->getManifest());
|
||||
}
|
||||
|
||||
/**
|
||||
* indexResponse: 세트가 없으면 null
|
||||
*/
|
||||
public function test_index_response_returns_null_without_committed_set(): void
|
||||
{
|
||||
$this->assertNull($this->store->indexResponse());
|
||||
}
|
||||
|
||||
/**
|
||||
* indexResponse: sitemapindex 를 XML Content-Type 으로 스트리밍한다
|
||||
*/
|
||||
public function test_index_response_streams_sitemap_index(): void
|
||||
{
|
||||
$this->commitSet(urlCount: 12, urlsPerFile: 10);
|
||||
|
||||
$response = $this->store->indexResponse();
|
||||
|
||||
$this->assertInstanceOf(StreamedResponse::class, $response);
|
||||
$this->assertSame('application/xml', $response->headers->get('Content-Type'));
|
||||
|
||||
$body = $this->streamBody($response);
|
||||
$this->assertStringContainsString('<sitemapindex', $body);
|
||||
$this->assertStringContainsString(url('/sitemap-1.xml'), $body);
|
||||
$this->assertStringContainsString(url('/sitemap-2.xml'), $body);
|
||||
}
|
||||
|
||||
/**
|
||||
* childResponse: 세트가 없으면 null
|
||||
*/
|
||||
public function test_child_response_returns_null_without_committed_set(): void
|
||||
{
|
||||
$this->assertNull($this->store->childResponse(1));
|
||||
}
|
||||
|
||||
/**
|
||||
* childResponse: 자식 sitemap 본문을 스트리밍한다
|
||||
*/
|
||||
public function test_child_response_streams_child_sitemap(): void
|
||||
{
|
||||
$this->commitSet(urlCount: 2);
|
||||
|
||||
$response = $this->store->childResponse(1);
|
||||
|
||||
$this->assertInstanceOf(StreamedResponse::class, $response);
|
||||
$this->assertSame('application/xml', $response->headers->get('Content-Type'));
|
||||
$this->assertNull($response->headers->get('Content-Encoding'));
|
||||
|
||||
$body = $this->streamBody($response);
|
||||
$this->assertStringContainsString('<urlset', $body);
|
||||
$this->assertStringContainsString(url('/page/1'), $body);
|
||||
}
|
||||
|
||||
/**
|
||||
* childResponse: 존재하지 않는 자식 번호는 null
|
||||
*/
|
||||
public function test_child_response_returns_null_for_out_of_range_number(): void
|
||||
{
|
||||
$this->commitSet(urlCount: 2, urlsPerFile: 10);
|
||||
|
||||
$this->assertNull($this->store->childResponse(2), '자식이 1개뿐이면 2번은 없어야 합니다.');
|
||||
}
|
||||
|
||||
/**
|
||||
* childResponse: 0 이하 번호는 null (경로 조작 방어)
|
||||
*/
|
||||
public function test_child_response_returns_null_for_non_positive_number(): void
|
||||
{
|
||||
$this->commitSet();
|
||||
|
||||
$this->assertNull($this->store->childResponse(0));
|
||||
$this->assertNull($this->store->childResponse(-1));
|
||||
}
|
||||
|
||||
/**
|
||||
* childResponse: gzip 세트는 Content-Encoding 헤더를 붙인다
|
||||
*/
|
||||
public function test_child_response_sets_gzip_content_encoding(): void
|
||||
{
|
||||
$this->commitSet(urlCount: 2, urlsPerFile: 10, gzip: true);
|
||||
|
||||
$response = $this->store->childResponse(1);
|
||||
|
||||
$this->assertInstanceOf(StreamedResponse::class, $response);
|
||||
$this->assertSame('gzip', $response->headers->get('Content-Encoding'));
|
||||
}
|
||||
|
||||
/**
|
||||
* indexResponse: gzip 세트여도 인덱스는 비압축이다 (D13)
|
||||
*/
|
||||
public function test_index_response_is_never_gzip_encoded(): void
|
||||
{
|
||||
$this->commitSet(urlCount: 2, urlsPerFile: 10, gzip: true);
|
||||
|
||||
$response = $this->store->indexResponse();
|
||||
|
||||
$this->assertInstanceOf(StreamedResponse::class, $response);
|
||||
$this->assertNull($response->headers->get('Content-Encoding'));
|
||||
}
|
||||
|
||||
/**
|
||||
* lastGeneratedAt: 세트가 없으면 null
|
||||
*/
|
||||
public function test_last_generated_at_returns_null_without_committed_set(): void
|
||||
{
|
||||
$this->assertNull($this->store->lastGeneratedAt());
|
||||
}
|
||||
|
||||
/**
|
||||
* lastGeneratedAt: manifest 의 생성 시각을 반환한다
|
||||
*/
|
||||
public function test_last_generated_at_returns_manifest_timestamp(): void
|
||||
{
|
||||
$meta = $this->commitSet();
|
||||
|
||||
$this->assertNotNull($this->store->lastGeneratedAt());
|
||||
$this->assertSame($meta['generated_at'], $this->store->lastGeneratedAt());
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Extension\TemplateManager;
|
||||
use App\Seo\Contracts\SitemapContributorInterface;
|
||||
use App\Seo\SitemapGenerator;
|
||||
use App\Seo\SitemapWriter;
|
||||
use App\Seo\TemplateRouteResolver;
|
||||
use App\Services\TemplateService;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
@@ -475,6 +475,180 @@ class SitemapGeneratorTest extends TestCase
|
||||
$this->assertEquals(1, substr_count($xml, '<url>'));
|
||||
}
|
||||
|
||||
// ─── renderUrlBlock / urlset 헤더·푸터 ──────────────────
|
||||
|
||||
/**
|
||||
* renderUrlBlock()이 단일 언어 <url> 블록을 생성하는지 확인합니다.
|
||||
*/
|
||||
public function test_render_url_block_single_locale(): void
|
||||
{
|
||||
$block = $this->generator->renderUrlBlock([
|
||||
'loc' => 'https://example.test/a',
|
||||
'changefreq' => 'daily',
|
||||
'priority' => 0.8,
|
||||
]);
|
||||
|
||||
$this->assertStringContainsString('<loc>https://example.test/a</loc>', $block);
|
||||
$this->assertStringContainsString('<changefreq>daily</changefreq>', $block);
|
||||
$this->assertStringContainsString('<priority>0.8</priority>', $block);
|
||||
$this->assertStringNotContainsString('xhtml:link', $block);
|
||||
$this->assertSame(1, substr_count($block, '<url>'));
|
||||
}
|
||||
|
||||
/**
|
||||
* renderUrlBlock()이 다국어에서 로케일별 블록과 hreflang을 생성하는지 확인합니다.
|
||||
*/
|
||||
public function test_render_url_block_multilingual(): void
|
||||
{
|
||||
config(['app.locale' => 'ko', 'app.supported_locales' => ['ko', 'en']]);
|
||||
|
||||
$block = $this->generator->renderUrlBlock(['loc' => 'https://example.test/a']);
|
||||
|
||||
$this->assertSame(2, substr_count($block, '<url>'));
|
||||
$this->assertStringContainsString('<loc>https://example.test/a</loc>', $block);
|
||||
$this->assertStringContainsString('<loc>https://example.test/a?locale=en</loc>', $block);
|
||||
$this->assertStringContainsString('hreflang="x-default"', $block);
|
||||
}
|
||||
|
||||
/**
|
||||
* XML 특수문자가 이스케이프되는지 확인합니다.
|
||||
*/
|
||||
public function test_render_url_block_escapes_xml_special_characters(): void
|
||||
{
|
||||
$block = $this->generator->renderUrlBlock(['loc' => 'https://example.test/a?x=1&y=2']);
|
||||
|
||||
$this->assertStringContainsString('<loc>https://example.test/a?x=1&y=2</loc>', $block);
|
||||
// 이스케이프되지 않은 원본 & 가 남아 있으면 XML 파싱이 깨집니다.
|
||||
$this->assertNotFalse(simplexml_load_string('<urlset>'.$block.'</urlset>'));
|
||||
}
|
||||
|
||||
/**
|
||||
* urlset 헤더/푸터가 로케일 수에 따라 분기되는지 확인합니다.
|
||||
*/
|
||||
public function test_urlset_header_switches_on_multilingual(): void
|
||||
{
|
||||
$this->assertStringNotContainsString('xmlns:xhtml', $this->generator->buildUrlsetHeader());
|
||||
$this->assertSame('</urlset>', $this->generator->buildUrlsetFooter());
|
||||
|
||||
config(['app.supported_locales' => ['ko', 'en']]);
|
||||
|
||||
$this->assertStringContainsString('xmlns:xhtml', $this->generator->buildUrlsetHeader());
|
||||
}
|
||||
|
||||
// ─── generateToWriter ────────────────────────────────
|
||||
|
||||
/**
|
||||
* generateToWriter()가 기여자 URL을 writer 에 한 건씩 전달하고
|
||||
* 상대 url 을 절대 loc 으로 변환하는지 확인합니다.
|
||||
*/
|
||||
public function test_generate_to_writer_streams_entries_without_cross_merge(): void
|
||||
{
|
||||
Log::shouldReceive('warning')->zeroOrMoreTimes();
|
||||
|
||||
$contributorA = Mockery::mock(SitemapContributorInterface::class);
|
||||
$contributorA->shouldReceive('getIdentifier')->andReturn('mod-a');
|
||||
$contributorA->shouldReceive('getUrls')->andReturn([
|
||||
['url' => '/a/1'],
|
||||
['url' => '/a/2'],
|
||||
]);
|
||||
|
||||
$contributorB = Mockery::mock(SitemapContributorInterface::class);
|
||||
$contributorB->shouldReceive('getIdentifier')->andReturn('mod-b');
|
||||
$contributorB->shouldReceive('getUrls')->andReturn([
|
||||
['url' => '/b/1'],
|
||||
]);
|
||||
|
||||
$this->generator->registerContributor($contributorA);
|
||||
$this->generator->registerContributor($contributorB);
|
||||
|
||||
$writer = new SpySitemapWriter;
|
||||
$meta = $this->generator->generateToWriter($writer);
|
||||
|
||||
$this->assertTrue($writer->opened);
|
||||
$this->assertTrue($writer->closed);
|
||||
$this->assertTrue($writer->committed);
|
||||
$this->assertSame(['committed' => true], $meta);
|
||||
|
||||
$locs = array_column($writer->entries, 'loc');
|
||||
$this->assertContains(url('/a/1'), $locs);
|
||||
$this->assertContains(url('/a/2'), $locs);
|
||||
$this->assertContains(url('/b/1'), $locs);
|
||||
|
||||
// 'url' 키는 절대 loc 으로 변환되어 남지 않아야 합니다.
|
||||
foreach ($writer->entries as $entry) {
|
||||
$this->assertArrayNotHasKey('url', $entry);
|
||||
$this->assertArrayHasKey('loc', $entry);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 기여자를 하나씩 소진하여 writer 로 흘려보내는지 확인합니다 (전체 병합 부재 증명).
|
||||
*
|
||||
* 모든 기여자의 URL 을 배열로 모은 뒤 한 번에 쓰는 구현이라면, 두 번째 기여자의
|
||||
* getUrls() 가 호출되는 시점에 writer 는 아직 비어 있다. 이 테스트는 그 구현을 걸러낸다.
|
||||
*/
|
||||
public function test_generate_to_writer_drains_each_contributor_before_calling_the_next(): void
|
||||
{
|
||||
Log::shouldReceive('warning')->zeroOrMoreTimes();
|
||||
|
||||
$writer = new SpySitemapWriter;
|
||||
|
||||
$contributorA = Mockery::mock(SitemapContributorInterface::class);
|
||||
$contributorA->shouldReceive('getIdentifier')->andReturn('mod-a');
|
||||
$contributorA->shouldReceive('getUrls')->andReturn([['url' => '/a/1']]);
|
||||
|
||||
$locsSeenWhenBWasAsked = null;
|
||||
|
||||
$contributorB = Mockery::mock(SitemapContributorInterface::class);
|
||||
$contributorB->shouldReceive('getIdentifier')->andReturn('mod-b');
|
||||
$contributorB->shouldReceive('getUrls')->andReturnUsing(
|
||||
function () use ($writer, &$locsSeenWhenBWasAsked): array {
|
||||
$locsSeenWhenBWasAsked = array_column($writer->entries, 'loc');
|
||||
|
||||
return [['url' => '/b/1']];
|
||||
}
|
||||
);
|
||||
|
||||
$this->generator->registerContributor($contributorA);
|
||||
$this->generator->registerContributor($contributorB);
|
||||
$this->generator->generateToWriter($writer);
|
||||
|
||||
$this->assertNotNull($locsSeenWhenBWasAsked, 'B 기여자가 호출되어야 합니다.');
|
||||
$this->assertContains(
|
||||
url('/a/1'),
|
||||
$locsSeenWhenBWasAsked,
|
||||
'B 를 호출하기 전에 A 의 URL 이 이미 writer 로 전달되어야 합니다 (전체 병합 금지).'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 한 기여자가 실패해도 다른 기여자의 URL 이 계속 기록되는지 확인합니다.
|
||||
*/
|
||||
public function test_generate_to_writer_isolates_contributor_failure(): void
|
||||
{
|
||||
$failing = Mockery::mock(SitemapContributorInterface::class);
|
||||
$failing->shouldReceive('getIdentifier')->andReturn('failing-module');
|
||||
$failing->shouldReceive('getUrls')->andThrow(new \RuntimeException('DB connection failed'));
|
||||
|
||||
$working = Mockery::mock(SitemapContributorInterface::class);
|
||||
$working->shouldReceive('getIdentifier')->andReturn('working-module');
|
||||
$working->shouldReceive('getUrls')->andReturn([['url' => '/ok']]);
|
||||
|
||||
Log::shouldReceive('warning')
|
||||
->once()
|
||||
->withArgs(fn (string $message, array $context) => str_contains($message, 'Sitemap contributor failed')
|
||||
&& $context['contributor'] === 'failing-module');
|
||||
Log::shouldReceive('warning')->zeroOrMoreTimes();
|
||||
|
||||
$this->generator->registerContributor($failing);
|
||||
$this->generator->registerContributor($working);
|
||||
|
||||
$writer = new SpySitemapWriter;
|
||||
$this->generator->generateToWriter($writer);
|
||||
|
||||
$this->assertContains(url('/ok'), array_column($writer->entries, 'loc'));
|
||||
}
|
||||
|
||||
// ─── 헬퍼 메서드 ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -542,3 +716,76 @@ class SitemapGeneratorTest extends TestCase
|
||||
return $urls;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SitemapWriter 호출을 기록하는 테스트 더블.
|
||||
*
|
||||
* generateToWriter 가 URL 을 한 건씩 스트리밍하는지(전체 배열 병합 없음)와
|
||||
* open/close/commit 생명주기를 검증하기 위해 사용합니다.
|
||||
* 스토리지 없이 동작하도록 부모 생성자를 호출하지 않습니다.
|
||||
*/
|
||||
class SpySitemapWriter extends SitemapWriter
|
||||
{
|
||||
/**
|
||||
* open() 호출 여부
|
||||
*/
|
||||
public bool $opened = false;
|
||||
|
||||
/**
|
||||
* close() 호출 여부
|
||||
*/
|
||||
public bool $closed = false;
|
||||
|
||||
/**
|
||||
* commit() 호출 여부
|
||||
*/
|
||||
public bool $committed = false;
|
||||
|
||||
/**
|
||||
* addUrl() 로 전달된 URL 항목 목록
|
||||
*
|
||||
* @var array<int, array<string, mixed>>
|
||||
*/
|
||||
public array $entries = [];
|
||||
|
||||
/**
|
||||
* SpySitemapWriter 생성자 (의존성 없이 생성).
|
||||
*/
|
||||
public function __construct() {}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function open(): void
|
||||
{
|
||||
$this->opened = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function addUrl(array $entry): void
|
||||
{
|
||||
$this->entries[] = $entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function close(): array
|
||||
{
|
||||
$this->closed = true;
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function commit(): array
|
||||
{
|
||||
$this->committed = true;
|
||||
|
||||
return ['committed' => true];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Repositories\ConfigRepositoryInterface;
|
||||
use App\Extension\HookManager;
|
||||
use App\Extension\Storage\CoreStorageDriver;
|
||||
use App\Seo\Contracts\SitemapContributorInterface;
|
||||
use App\Seo\SitemapFileStore;
|
||||
use App\Seo\SitemapGenerator;
|
||||
use App\Seo\SitemapManager;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* SitemapManager::regenerate 단위 테스트
|
||||
*
|
||||
* regenerate() 는 S1 의 4대 산출물 중 하나이며 S2 의 Controller 가 반환 메타를 소비한다.
|
||||
* 기존 테스트(SeoCacheControllerTest / GenerateSitemapJobTest)는 SitemapManager 를 통째로
|
||||
* mock 하므로 본문이 한 번도 실행되지 않는다 — 이 테스트가 그 공백을 메운다.
|
||||
*
|
||||
* 검증 목적:
|
||||
* - sitemap_enabled=false 시 disabled 반환 + 훅 미발화
|
||||
* - 성공 시 반환 메타 5키 · 캐시(구 XML 키 정리 + 메타 저장) · last_updated_at 기록 · after_regenerate 훅
|
||||
* - 실패 시 failed 반환 + after_regenerate_failed 훅 발화(페이로드 포함)
|
||||
* - writer 가 설정(urls_per_file / gzip)을 반영
|
||||
* - ttl 폴백 사슬
|
||||
*/
|
||||
class SitemapManagerTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* 이 테스트가 등록·검증하는 sitemap 훅 목록
|
||||
*/
|
||||
private const SITEMAP_HOOKS = [
|
||||
'core.seo.sitemap.before_regenerate',
|
||||
'core.seo.sitemap.after_regenerate',
|
||||
'core.seo.sitemap.after_regenerate_failed',
|
||||
];
|
||||
|
||||
private CoreStorageDriver $storage;
|
||||
|
||||
/**
|
||||
* 테스트 초기화 - 가짜 디스크와 훅 레지스트리를 준비합니다.
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
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->clearSitemapHooks();
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트 정리 - 등록한 훅 리스너가 다른 테스트로 누출되지 않도록 제거합니다.
|
||||
*/
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->clearSitemapHooks();
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* sitemap 훅 리스너를 모두 제거합니다.
|
||||
*/
|
||||
private function clearSitemapHooks(): void
|
||||
{
|
||||
foreach (self::SITEMAP_HOOKS as $hook) {
|
||||
HookManager::clearAction($hook);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 지정한 URL 을 내보내는 가짜 contributor 를 만듭니다.
|
||||
*
|
||||
* @param array<int, string> $urls 상대 경로 목록
|
||||
* @return SitemapContributorInterface 가짜 기여자
|
||||
*/
|
||||
private function fakeContributor(array $urls): SitemapContributorInterface
|
||||
{
|
||||
return new class($urls) implements SitemapContributorInterface
|
||||
{
|
||||
/**
|
||||
* @param array<int, string> $urls 상대 경로 목록
|
||||
*/
|
||||
public function __construct(private array $urls) {}
|
||||
|
||||
public function getIdentifier(): string
|
||||
{
|
||||
return 'fake-contributor';
|
||||
}
|
||||
|
||||
public function getUrls(): array
|
||||
{
|
||||
return array_map(fn (string $url): array => ['url' => $url], $this->urls);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트용 SitemapManager 를 만듭니다.
|
||||
*
|
||||
* @param array<int, string> $urls 기여자가 내보낼 URL 목록
|
||||
* @param CacheInterface|null $cache 캐시 (미지정 시 기대 없는 spy)
|
||||
* @param ConfigRepositoryInterface|null $config 설정 Repository
|
||||
* @return SitemapManager manager 인스턴스
|
||||
*/
|
||||
private function makeManager(
|
||||
array $urls = ['/a'],
|
||||
?CacheInterface $cache = null,
|
||||
?ConfigRepositoryInterface $config = null,
|
||||
): SitemapManager {
|
||||
// generator 는 라우트 해석기/템플릿 서비스에 의존하므로 컨테이너로 해석합니다.
|
||||
$generator = $this->app->make(SitemapGenerator::class);
|
||||
$generator->registerContributor($this->fakeContributor($urls));
|
||||
|
||||
return new SitemapManager(
|
||||
$generator,
|
||||
$cache ?? Mockery::spy(CacheInterface::class),
|
||||
$config ?? Mockery::spy(ConfigRepositoryInterface::class),
|
||||
$this->storage,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* regenerate: sitemap 이 비활성화되면 생성하지 않고 disabled 를 반환한다
|
||||
*/
|
||||
public function test_regenerate_returns_disabled_when_sitemap_is_disabled(): void
|
||||
{
|
||||
Config::set('g7_settings.core.seo.sitemap_enabled', false);
|
||||
|
||||
$fired = [];
|
||||
HookManager::addAction('core.seo.sitemap.before_regenerate', function () use (&$fired) {
|
||||
$fired[] = 'before';
|
||||
});
|
||||
|
||||
$result = $this->makeManager()->regenerate();
|
||||
|
||||
$this->assertFalse($result['success']);
|
||||
$this->assertSame('disabled', $result['status']);
|
||||
$this->assertArrayNotHasKey('data', $result);
|
||||
$this->assertSame([], $fired, '비활성화 시 훅이 발화하면 안 됩니다.');
|
||||
$this->assertFalse(
|
||||
$this->storage->exists(SitemapFileStore::CATEGORY, SitemapFileStore::LIVE_DIR.'/'.SitemapFileStore::MANIFEST_FILE),
|
||||
'비활성화 시 파일을 커밋하면 안 됩니다.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* regenerate: 성공 시 status=updated 와 메타 5키를 반환한다
|
||||
*/
|
||||
public function test_regenerate_returns_updated_with_meta_payload(): void
|
||||
{
|
||||
$result = $this->makeManager(['/a', '/b'])->regenerate();
|
||||
|
||||
$this->assertTrue($result['success']);
|
||||
$this->assertSame('updated', $result['status']);
|
||||
$this->assertSame(
|
||||
['last_updated_at', 'size_bytes', 'url_count', 'child_count', 'ttl'],
|
||||
array_keys($result['data']),
|
||||
'S2 Controller 가 소비하는 메타 키 집합이 고정되어야 합니다.'
|
||||
);
|
||||
$this->assertSame(1, $result['data']['child_count']);
|
||||
$this->assertGreaterThan(0, $result['data']['size_bytes']);
|
||||
}
|
||||
|
||||
/**
|
||||
* regenerate: 성공 시 sitemap 세트가 디스크에 커밋된다
|
||||
*/
|
||||
public function test_regenerate_commits_sitemap_set_to_disk(): void
|
||||
{
|
||||
$this->makeManager(['/a'])->regenerate();
|
||||
|
||||
$store = new SitemapFileStore($this->storage);
|
||||
|
||||
$this->assertTrue($store->exists());
|
||||
$this->assertNotNull($store->indexResponse());
|
||||
$this->assertNotNull($store->childResponse(1));
|
||||
}
|
||||
|
||||
/**
|
||||
* regenerate: 구 XML 본문 캐시를 정리하고 메타만 캐시에 저장한다
|
||||
*/
|
||||
public function test_regenerate_forgets_legacy_xml_cache_and_puts_meta(): void
|
||||
{
|
||||
Config::set('g7_settings.core.cache.seo_sitemap_ttl', 3600);
|
||||
Config::set('g7_settings.core.seo.sitemap_cache_ttl', null);
|
||||
|
||||
$cache = Mockery::mock(CacheInterface::class);
|
||||
$cache->shouldReceive('forget')->once()->with('seo.sitemap');
|
||||
$cache->shouldReceive('put')
|
||||
->once()
|
||||
->with(SitemapManager::META_CACHE_KEY, Mockery::type('array'), 3600);
|
||||
|
||||
$this->makeManager(['/a'], $cache)->regenerate();
|
||||
}
|
||||
|
||||
/**
|
||||
* regenerate: SEO 탭 지정이 없으면 고급 탭(cache.seo_sitemap_ttl) 값을 ttl 로 쓴다 (D19)
|
||||
*/
|
||||
public function test_regenerate_uses_advanced_tab_ttl_when_seo_override_is_unset(): void
|
||||
{
|
||||
Config::set('g7_settings.core.cache.seo_sitemap_ttl', 7200);
|
||||
Config::set('g7_settings.core.seo.sitemap_cache_ttl', null);
|
||||
|
||||
$result = $this->makeManager()->regenerate();
|
||||
|
||||
$this->assertSame(7200, $result['data']['ttl']);
|
||||
}
|
||||
|
||||
/**
|
||||
* regenerate: SEO 탭에 지정이 있으면 그 값이 고급 탭을 오버라이드한다 (D19)
|
||||
*/
|
||||
public function test_regenerate_uses_seo_override_ttl_when_set(): void
|
||||
{
|
||||
Config::set('g7_settings.core.cache.seo_sitemap_ttl', 7200);
|
||||
Config::set('g7_settings.core.seo.sitemap_cache_ttl', 3600);
|
||||
|
||||
$result = $this->makeManager()->regenerate();
|
||||
|
||||
$this->assertSame(3600, $result['data']['ttl'], 'SEO 탭 지정이 고급 탭보다 우선해야 합니다.');
|
||||
}
|
||||
|
||||
/**
|
||||
* regenerate: last_updated_at 을 seo 설정 카테고리에 기록한다
|
||||
*/
|
||||
public function test_regenerate_records_last_updated_at_in_settings(): void
|
||||
{
|
||||
$config = Mockery::mock(ConfigRepositoryInterface::class);
|
||||
$config->shouldReceive('getCategory')->once()->with('seo')->andReturn(['existing' => 'keep']);
|
||||
$config->shouldReceive('saveCategory')
|
||||
->once()
|
||||
->with('seo', Mockery::on(function (array $saved): bool {
|
||||
// 기존 키를 보존하면서 타임스탬프만 추가해야 한다
|
||||
return $saved['existing'] === 'keep'
|
||||
&& ! empty($saved['sitemap_last_updated_at']);
|
||||
}));
|
||||
|
||||
$result = $this->makeManager(['/a'], null, $config)->regenerate();
|
||||
|
||||
$this->assertTrue($result['success']);
|
||||
}
|
||||
|
||||
/**
|
||||
* regenerate: 설정 기록이 실패해도 생성 자체는 성공으로 유지된다
|
||||
*/
|
||||
public function test_regenerate_survives_settings_write_failure(): void
|
||||
{
|
||||
$config = Mockery::mock(ConfigRepositoryInterface::class);
|
||||
$config->shouldReceive('getCategory')->andThrow(new \RuntimeException('설정 저장소 장애'));
|
||||
|
||||
$result = $this->makeManager(['/a'], null, $config)->regenerate();
|
||||
|
||||
$this->assertTrue($result['success'], 'last_updated_at 기록 실패가 sitemap 생성을 무효화하면 안 됩니다.');
|
||||
$this->assertSame('updated', $result['status']);
|
||||
}
|
||||
|
||||
/**
|
||||
* regenerate: 성공 시 before/after_regenerate 훅이 순서대로 발화한다
|
||||
*/
|
||||
public function test_regenerate_fires_before_and_after_hooks_in_order(): void
|
||||
{
|
||||
$order = [];
|
||||
HookManager::addAction('core.seo.sitemap.before_regenerate', function () use (&$order) {
|
||||
$order[] = 'before';
|
||||
});
|
||||
HookManager::addAction('core.seo.sitemap.after_regenerate', function () use (&$order) {
|
||||
$order[] = 'after';
|
||||
});
|
||||
|
||||
$this->makeManager()->regenerate();
|
||||
|
||||
$this->assertSame(['before', 'after'], $order);
|
||||
}
|
||||
|
||||
/**
|
||||
* regenerate: 실패 시 failed 를 반환하고 after_regenerate_failed 훅이 발화한다
|
||||
*
|
||||
* 이 훅은 확장이 구독하는 공개 표면이므로 발화 여부와 페이로드 형태를 고정한다.
|
||||
*/
|
||||
public function test_regenerate_fires_after_regenerate_failed_hook_on_failure(): void
|
||||
{
|
||||
$payloads = [];
|
||||
HookManager::addAction('core.seo.sitemap.after_regenerate_failed', function ($result) use (&$payloads) {
|
||||
$payloads[] = $result;
|
||||
});
|
||||
HookManager::addAction('core.seo.sitemap.after_regenerate', function () {
|
||||
throw new \LogicException('성공 훅이 발화하면 안 됩니다.');
|
||||
});
|
||||
|
||||
// 생성 도중 예외를 던지는 generator 로 실패를 강제한다.
|
||||
$generator = Mockery::mock(SitemapGenerator::class);
|
||||
$generator->shouldReceive('generateToWriter')->andThrow(new \RuntimeException('디스크 장애'));
|
||||
|
||||
$manager = new SitemapManager(
|
||||
$generator,
|
||||
Mockery::spy(CacheInterface::class),
|
||||
Mockery::spy(ConfigRepositoryInterface::class),
|
||||
$this->storage,
|
||||
);
|
||||
|
||||
$result = $manager->regenerate();
|
||||
|
||||
$this->assertFalse($result['success']);
|
||||
$this->assertSame('failed', $result['status']);
|
||||
$this->assertStringContainsString('디스크 장애', $result['message']);
|
||||
|
||||
$this->assertCount(1, $payloads, 'after_regenerate_failed 훅이 정확히 1회 발화해야 합니다.');
|
||||
$this->assertSame('failed', $payloads[0]['status']);
|
||||
$this->assertFalse($payloads[0]['success']);
|
||||
}
|
||||
|
||||
/**
|
||||
* regenerate: 실패 시 캐시를 갱신하지 않는다 (구 세트 유지)
|
||||
*/
|
||||
public function test_regenerate_does_not_touch_cache_on_failure(): void
|
||||
{
|
||||
$cache = Mockery::mock(CacheInterface::class);
|
||||
$cache->shouldNotReceive('put');
|
||||
$cache->shouldNotReceive('forget');
|
||||
|
||||
$generator = Mockery::mock(SitemapGenerator::class);
|
||||
$generator->shouldReceive('generateToWriter')->andThrow(new \RuntimeException('장애'));
|
||||
|
||||
$manager = new SitemapManager(
|
||||
$generator,
|
||||
$cache,
|
||||
Mockery::spy(ConfigRepositoryInterface::class),
|
||||
$this->storage,
|
||||
);
|
||||
|
||||
$this->assertFalse($manager->regenerate()['success']);
|
||||
}
|
||||
|
||||
/**
|
||||
* regenerate: seo.sitemap_urls_per_file 설정이 자식 분할에 반영된다
|
||||
*/
|
||||
public function test_regenerate_applies_urls_per_file_setting(): void
|
||||
{
|
||||
Config::set('g7_settings.core.seo.sitemap_urls_per_file', 2);
|
||||
|
||||
// 정적 라우트 + 기여자 4건 → 파일당 2건이면 자식이 2개 이상으로 나뉜다
|
||||
$result = $this->makeManager(['/a', '/b', '/c', '/d'])->regenerate();
|
||||
|
||||
$this->assertGreaterThan(1, $result['data']['child_count'], 'urls_per_file 설정이 분할에 반영돼야 합니다.');
|
||||
}
|
||||
|
||||
/**
|
||||
* regenerate: seo.sitemap_gzip 설정이 커밋 파일명에 반영된다
|
||||
*/
|
||||
public function test_regenerate_applies_gzip_setting(): void
|
||||
{
|
||||
Config::set('g7_settings.core.seo.sitemap_gzip', true);
|
||||
|
||||
$this->makeManager(['/a'])->regenerate();
|
||||
|
||||
$manifest = (new SitemapFileStore($this->storage))->getManifest();
|
||||
|
||||
$this->assertStringEndsWith('.xml.gz', $manifest['children'][0]['file']);
|
||||
}
|
||||
|
||||
/**
|
||||
* getStatus: 기록된 last_updated_at 을 반환하고, 미기록 시 null 을 반환한다
|
||||
*/
|
||||
public function test_get_status_returns_last_updated_at_or_null(): void
|
||||
{
|
||||
$manager = $this->makeManager();
|
||||
|
||||
Config::set('g7_settings.core.seo.sitemap_last_updated_at', '');
|
||||
$this->assertNull($manager->getStatus()['last_updated_at']);
|
||||
|
||||
Config::set('g7_settings.core.seo.sitemap_last_updated_at', '2026-07-16T00:00:00+09:00');
|
||||
$this->assertSame('2026-07-16T00:00:00+09:00', $manager->getStatus()['last_updated_at']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,639 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Contracts\Extension\StorageInterface;
|
||||
use App\Extension\Storage\CoreStorageDriver;
|
||||
use App\Seo\SitemapFileStore;
|
||||
use App\Seo\SitemapWriter;
|
||||
use App\Seo\SitemapXmlRenderer;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* SitemapWriter 단위 테스트
|
||||
*
|
||||
* 임계 분할, sitemapindex 생성, gzip, atomic commit(manifest 마지막 기록),
|
||||
* stale 파일 정리, 대용량 시 bounded memory 를 검증합니다.
|
||||
*/
|
||||
class SitemapWriterTest extends TestCase
|
||||
{
|
||||
private RecordingStorage $storage;
|
||||
|
||||
/**
|
||||
* 테스트 초기화 - 가짜 로컬 디스크와 put 순서 기록 스토리지를 준비합니다.
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Config::set('app.locale', 'ko');
|
||||
Config::set('app.supported_locales', ['ko']);
|
||||
|
||||
Storage::fake('local');
|
||||
|
||||
$this->storage = new RecordingStorage(new CoreStorageDriver('local'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트용 writer 를 생성합니다.
|
||||
*
|
||||
* @param int $urlsPerFile 파일당 URL 수
|
||||
* @param bool $gzip gzip 압축 여부
|
||||
* @return SitemapWriter writer 인스턴스
|
||||
*/
|
||||
private function makeWriter(int $urlsPerFile = 10, bool $gzip = false): SitemapWriter
|
||||
{
|
||||
return new SitemapWriter(
|
||||
$this->storage,
|
||||
SitemapXmlRenderer::fromConfig(),
|
||||
$urlsPerFile,
|
||||
$gzip,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 커밋된 live 파일 내용을 읽습니다.
|
||||
*
|
||||
* @param string $filename 파일명
|
||||
* @return string|null 파일 내용
|
||||
*/
|
||||
private function liveContent(string $filename): ?string
|
||||
{
|
||||
return $this->storage->get(SitemapFileStore::CATEGORY, SitemapFileStore::LIVE_DIR.'/'.$filename);
|
||||
}
|
||||
|
||||
// ─── 분할 ────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* URL 수가 임계를 넘으면 자식 파일로 분할되는지 확인합니다.
|
||||
*/
|
||||
public function test_splits_children_at_threshold(): void
|
||||
{
|
||||
$writer = $this->makeWriter(urlsPerFile: 10);
|
||||
$writer->open();
|
||||
|
||||
// 25건 / 파일당 10건 → 자식 3개 (10, 10, 5)
|
||||
for ($i = 1; $i <= 25; $i++) {
|
||||
$writer->addUrl(['loc' => url("/p/{$i}"), 'priority' => 0.5]);
|
||||
}
|
||||
|
||||
$writer->close();
|
||||
$meta = $writer->commit();
|
||||
|
||||
$this->assertSame(3, $meta['child_count']);
|
||||
$this->assertSame(25, $meta['url_count']);
|
||||
$this->assertSame(10, $meta['children'][0]['url_count']);
|
||||
$this->assertSame(10, $meta['children'][1]['url_count']);
|
||||
$this->assertSame(5, $meta['children'][2]['url_count']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 임계에 정확히 맞아떨어지면 빈 자식 파일이 생기지 않는지 확인합니다.
|
||||
*/
|
||||
public function test_exact_threshold_does_not_create_empty_child(): void
|
||||
{
|
||||
$writer = $this->makeWriter(urlsPerFile: 10);
|
||||
$writer->open();
|
||||
|
||||
for ($i = 1; $i <= 20; $i++) {
|
||||
$writer->addUrl(['loc' => url("/p/{$i}")]);
|
||||
}
|
||||
|
||||
$writer->close();
|
||||
$meta = $writer->commit();
|
||||
|
||||
$this->assertSame(2, $meta['child_count']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 각 자식 파일이 well-formed urlset XML 인지 확인합니다.
|
||||
*/
|
||||
public function test_children_are_well_formed_urlsets(): void
|
||||
{
|
||||
$writer = $this->makeWriter(urlsPerFile: 10);
|
||||
$writer->open();
|
||||
|
||||
for ($i = 1; $i <= 25; $i++) {
|
||||
$writer->addUrl(['loc' => url("/p/{$i}"), 'changefreq' => 'daily']);
|
||||
}
|
||||
|
||||
$writer->close();
|
||||
$meta = $writer->commit();
|
||||
|
||||
foreach ($meta['children'] as $child) {
|
||||
$xml = $this->liveContent($child['file']);
|
||||
|
||||
$this->assertNotNull($xml);
|
||||
$this->assertStringStartsWith('<?xml version="1.0" encoding="UTF-8"?>', $xml);
|
||||
$this->assertStringEndsWith('</urlset>', $xml);
|
||||
$this->assertLessThanOrEqual(SitemapWriter::HARD_URL_CAP, substr_count($xml, '<loc>'));
|
||||
$this->assertNotFalse(simplexml_load_string($xml), '자식 sitemap 이 유효한 XML 이어야 합니다.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* sitemapindex 가 모든 자식을 절대 URL 로 참조하는지 확인합니다.
|
||||
*/
|
||||
public function test_index_references_all_children(): void
|
||||
{
|
||||
$writer = $this->makeWriter(urlsPerFile: 10);
|
||||
$writer->open();
|
||||
|
||||
for ($i = 1; $i <= 25; $i++) {
|
||||
$writer->addUrl(['loc' => url("/p/{$i}")]);
|
||||
}
|
||||
|
||||
$writer->close();
|
||||
$writer->commit();
|
||||
|
||||
$index = $this->liveContent(SitemapFileStore::INDEX_FILE);
|
||||
|
||||
$this->assertNotNull($index);
|
||||
$this->assertStringContainsString('<sitemapindex', $index);
|
||||
$this->assertSame(3, substr_count($index, '<sitemap>'));
|
||||
$this->assertStringContainsString('<loc>'.url('/sitemap-1.xml').'</loc>', $index);
|
||||
$this->assertStringContainsString('<loc>'.url('/sitemap-3.xml').'</loc>', $index);
|
||||
$this->assertNotFalse(simplexml_load_string($index));
|
||||
}
|
||||
|
||||
/**
|
||||
* URL 이 하나도 없어도 빈 urlset 자식 1개와 인덱스를 남기는지 확인합니다.
|
||||
*/
|
||||
public function test_empty_set_still_emits_index_and_one_child(): void
|
||||
{
|
||||
$writer = $this->makeWriter();
|
||||
$writer->open();
|
||||
$writer->close();
|
||||
$meta = $writer->commit();
|
||||
|
||||
$this->assertSame(1, $meta['child_count']);
|
||||
$this->assertSame(0, $meta['url_count']);
|
||||
|
||||
$xml = $this->liveContent('sitemap-1.xml');
|
||||
$this->assertStringNotContainsString('<url>', $xml);
|
||||
$this->assertNotFalse(simplexml_load_string($xml));
|
||||
}
|
||||
|
||||
/**
|
||||
* loc 이 없는 항목은 무시되는지 확인합니다.
|
||||
*/
|
||||
public function test_entry_without_loc_is_skipped(): void
|
||||
{
|
||||
$writer = $this->makeWriter();
|
||||
$writer->open();
|
||||
$writer->addUrl(['changefreq' => 'daily']);
|
||||
$writer->close();
|
||||
$meta = $writer->commit();
|
||||
|
||||
$this->assertSame(0, $meta['url_count']);
|
||||
}
|
||||
|
||||
// ─── 다국어 ──────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 다국어에서는 URL 하나가 로케일 수만큼의 <url> 블록으로 계산되는지 확인합니다.
|
||||
*/
|
||||
public function test_multilingual_counts_url_blocks_per_locale(): void
|
||||
{
|
||||
Config::set('app.supported_locales', ['ko', 'en']);
|
||||
|
||||
$writer = $this->makeWriter(urlsPerFile: 10);
|
||||
$writer->open();
|
||||
|
||||
// 6건 × 2로케일 = 12블록 → 자식 2개
|
||||
for ($i = 1; $i <= 6; $i++) {
|
||||
$writer->addUrl(['loc' => url("/p/{$i}")]);
|
||||
}
|
||||
|
||||
$writer->close();
|
||||
$meta = $writer->commit();
|
||||
|
||||
$this->assertSame(12, $meta['url_count']);
|
||||
$this->assertSame(2, $meta['child_count']);
|
||||
}
|
||||
|
||||
// ─── gzip ────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* gzip 활성 시 .xml.gz 로 압축 저장되고 인덱스 loc 도 .gz 를 가리키는지 확인합니다.
|
||||
*/
|
||||
public function test_gzip_writes_compressed_children(): void
|
||||
{
|
||||
$writer = $this->makeWriter(urlsPerFile: 10, gzip: true);
|
||||
$writer->open();
|
||||
|
||||
for ($i = 1; $i <= 5; $i++) {
|
||||
$writer->addUrl(['loc' => url("/p/{$i}")]);
|
||||
}
|
||||
|
||||
$writer->close();
|
||||
$meta = $writer->commit();
|
||||
|
||||
$this->assertTrue($meta['gzip']);
|
||||
$this->assertSame('sitemap-1.xml.gz', $meta['children'][0]['file']);
|
||||
|
||||
$raw = $this->liveContent('sitemap-1.xml.gz');
|
||||
$decoded = gzdecode($raw);
|
||||
|
||||
$this->assertNotFalse($decoded, 'gzip 자식 파일이 해제 가능해야 합니다.');
|
||||
$this->assertStringEndsWith('</urlset>', $decoded);
|
||||
|
||||
// 인덱스는 비압축이며 .gz 자식을 가리킵니다.
|
||||
$index = $this->liveContent(SitemapFileStore::INDEX_FILE);
|
||||
$this->assertStringContainsString('<loc>'.url('/sitemap-1.xml.gz').'</loc>', $index);
|
||||
}
|
||||
|
||||
/**
|
||||
* gzip 비활성이 기본값인지 확인합니다.
|
||||
*/
|
||||
public function test_gzip_disabled_by_default(): void
|
||||
{
|
||||
$writer = $this->makeWriter(urlsPerFile: 10);
|
||||
$writer->open();
|
||||
$writer->addUrl(['loc' => url('/p/1')]);
|
||||
$writer->close();
|
||||
$meta = $writer->commit();
|
||||
|
||||
$this->assertFalse($meta['gzip']);
|
||||
$this->assertSame('sitemap-1.xml', $meta['children'][0]['file']);
|
||||
}
|
||||
|
||||
// ─── 커밋 ────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* manifest.json 이 커밋의 마지막 기록인지 확인합니다 (커밋 마커).
|
||||
*/
|
||||
public function test_manifest_is_written_last(): void
|
||||
{
|
||||
$writer = $this->makeWriter(urlsPerFile: 10);
|
||||
$writer->open();
|
||||
|
||||
for ($i = 1; $i <= 25; $i++) {
|
||||
$writer->addUrl(['loc' => url("/p/{$i}")]);
|
||||
}
|
||||
|
||||
$writer->close();
|
||||
$writer->commit();
|
||||
|
||||
$manifestPath = SitemapFileStore::LIVE_DIR.'/'.SitemapFileStore::MANIFEST_FILE;
|
||||
|
||||
$this->assertSame($manifestPath, end($this->storage->putOrder));
|
||||
|
||||
// live 자식/인덱스가 모두 manifest 보다 먼저 기록되었는지 확인
|
||||
$manifestIndex = array_search($manifestPath, $this->storage->putOrder, true);
|
||||
foreach (['sitemap-1.xml', 'sitemap-2.xml', 'sitemap-3.xml', SitemapFileStore::INDEX_FILE] as $file) {
|
||||
$position = array_search(SitemapFileStore::LIVE_DIR.'/'.$file, $this->storage->putOrder, true);
|
||||
|
||||
$this->assertNotFalse($position, "{$file} 이 live 에 기록되어야 합니다.");
|
||||
$this->assertLessThan($manifestIndex, $position);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 커밋 후 임시 디렉토리가 정리되는지 확인합니다.
|
||||
*/
|
||||
public function test_commit_cleans_tmp_directory(): void
|
||||
{
|
||||
$writer = $this->makeWriter(urlsPerFile: 10);
|
||||
$writer->open();
|
||||
$writer->addUrl(['loc' => url('/p/1')]);
|
||||
$writer->close();
|
||||
$writer->commit();
|
||||
|
||||
$this->assertSame([], $this->storage->files(SitemapFileStore::CATEGORY, SitemapFileStore::TMP_DIR));
|
||||
}
|
||||
|
||||
/**
|
||||
* 이전 생성물 중 새 세트에 없는 자식 파일이 정리되는지 확인합니다.
|
||||
*/
|
||||
public function test_commit_removes_stale_children(): void
|
||||
{
|
||||
// 1차: 자식 3개
|
||||
$writer = $this->makeWriter(urlsPerFile: 10);
|
||||
$writer->open();
|
||||
for ($i = 1; $i <= 25; $i++) {
|
||||
$writer->addUrl(['loc' => url("/p/{$i}")]);
|
||||
}
|
||||
$writer->close();
|
||||
$writer->commit();
|
||||
|
||||
$this->assertNotNull($this->liveContent('sitemap-3.xml'));
|
||||
|
||||
// 2차: 자식 1개로 축소 → sitemap-2/3 은 stale
|
||||
$writer = $this->makeWriter(urlsPerFile: 10);
|
||||
$writer->open();
|
||||
$writer->addUrl(['loc' => url('/p/1')]);
|
||||
$writer->close();
|
||||
$meta = $writer->commit();
|
||||
|
||||
$this->assertSame(1, $meta['child_count']);
|
||||
$this->assertNotNull($this->liveContent('sitemap-1.xml'));
|
||||
$this->assertNull($this->liveContent('sitemap-2.xml'));
|
||||
$this->assertNull($this->liveContent('sitemap-3.xml'));
|
||||
}
|
||||
|
||||
/**
|
||||
* open() 이 이전 실행의 임시 파일을 정리하는지 확인합니다.
|
||||
*/
|
||||
public function test_open_clears_previous_tmp_files(): void
|
||||
{
|
||||
$this->storage->put(SitemapFileStore::CATEGORY, SitemapFileStore::TMP_DIR.'/sitemap-9.xml', 'stale');
|
||||
|
||||
$writer = $this->makeWriter();
|
||||
$writer->open();
|
||||
|
||||
$this->assertNull($this->storage->get(SitemapFileStore::CATEGORY, SitemapFileStore::TMP_DIR.'/sitemap-9.xml'));
|
||||
}
|
||||
|
||||
/**
|
||||
* manifest 에 세트 메타데이터가 기록되는지 확인합니다.
|
||||
*/
|
||||
public function test_manifest_contains_set_metadata(): void
|
||||
{
|
||||
$writer = $this->makeWriter(urlsPerFile: 10);
|
||||
$writer->open();
|
||||
for ($i = 1; $i <= 15; $i++) {
|
||||
$writer->addUrl(['loc' => url("/p/{$i}")]);
|
||||
}
|
||||
$writer->close();
|
||||
$writer->commit();
|
||||
|
||||
$manifest = json_decode($this->liveContent(SitemapFileStore::MANIFEST_FILE), true);
|
||||
|
||||
$this->assertSame(2, $manifest['child_count']);
|
||||
$this->assertSame(15, $manifest['url_count']);
|
||||
$this->assertSame(10, $manifest['urls_per_file']);
|
||||
$this->assertNotEmpty($manifest['generated_at']);
|
||||
$this->assertCount(2, $manifest['children']);
|
||||
}
|
||||
|
||||
// ─── 상한 / 메모리 ────────────────────────────────────
|
||||
|
||||
/**
|
||||
* urlsPerFile 이 프로토콜 상한(50,000)을 넘지 못하도록 클램프되는지 확인합니다.
|
||||
*/
|
||||
public function test_urls_per_file_is_clamped_to_protocol_cap(): void
|
||||
{
|
||||
$writer = $this->makeWriter(urlsPerFile: 999999);
|
||||
$writer->open();
|
||||
$writer->addUrl(['loc' => url('/p/1')]);
|
||||
$writer->close();
|
||||
$writer->commit();
|
||||
|
||||
$manifest = json_decode($this->liveContent(SitemapFileStore::MANIFEST_FILE), true);
|
||||
|
||||
$this->assertSame(SitemapWriter::HARD_URL_CAP, $manifest['urls_per_file']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 대용량(120,001건) 생성 시 자식 수가 정확하고 메모리가 유계인지 확인합니다.
|
||||
*
|
||||
* 전체 in-memory 적재(회귀)라면 URL 수에 비례해 메모리가 증가합니다.
|
||||
*/
|
||||
public function test_large_volume_splits_and_keeps_memory_bounded(): void
|
||||
{
|
||||
$writer = $this->makeWriter(urlsPerFile: 50000);
|
||||
|
||||
// peak 는 프로세스 전체의 high-water mark 라, 선행 테스트가 올려둔 peak 때문에
|
||||
// 델타가 0 으로 나와 거짓 통과할 수 있다. 이 테스트 구간만 측정하도록 리셋한다.
|
||||
memory_reset_peak_usage();
|
||||
$before = memory_get_peak_usage(true);
|
||||
|
||||
$writer->open();
|
||||
for ($i = 1; $i <= 120001; $i++) {
|
||||
$writer->addUrl(['loc' => url("/p/{$i}"), 'priority' => 0.5]);
|
||||
}
|
||||
$writer->close();
|
||||
$meta = $writer->commit();
|
||||
|
||||
$growth = memory_get_peak_usage(true) - $before;
|
||||
|
||||
// 120001 = 50000 + 50000 + 20001
|
||||
$this->assertSame(3, $meta['child_count']);
|
||||
$this->assertSame(120001, $meta['url_count']);
|
||||
$this->assertSame(50000, $meta['children'][0]['url_count']);
|
||||
$this->assertSame(50000, $meta['children'][1]['url_count']);
|
||||
$this->assertSame(20001, $meta['children'][2]['url_count']);
|
||||
|
||||
// 자식 파일 1개 버퍼(수 MB) 수준을 넘지 않아야 합니다.
|
||||
// 실측 약 10MB (자식 파일 1개 버퍼 수준). 전체 적재 회귀 시 수십~수백 MB 로 튄다.
|
||||
$this->assertLessThan(
|
||||
64 * 1024 * 1024,
|
||||
$growth,
|
||||
'메모리 증가가 자식 파일 1개 버퍼 수준을 넘었습니다 (전체 적재 회귀 의심): '.$growth,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* URL 수가 상한에 못 미쳐도 바이트 임계에 도달하면 자식이 분할됩니다.
|
||||
*
|
||||
* sitemaps.org 는 파일당 50MB 를 제한하므로 URL 수 상한만으로는 프로토콜 위반을 막지 못한다
|
||||
* (긴 URL 5만 건이면 50MB 초과). MAX_FILE_BYTES 분기가 그 방어인데, 45MB 를 실제로 채우면
|
||||
* 테스트가 과도하게 무거우므로 하위 클래스로 임계값만 낮춰 같은 경로를 검증한다.
|
||||
*/
|
||||
public function test_byte_threshold_splits_child_even_below_url_cap(): void
|
||||
{
|
||||
$writer = new SmallByteCapSitemapWriter(
|
||||
$this->storage,
|
||||
SitemapXmlRenderer::fromConfig(),
|
||||
10000, // URL 수 상한 — 이번 케이스에서는 절대 도달하지 않는다
|
||||
false,
|
||||
);
|
||||
|
||||
$writer->open();
|
||||
// URL 블록 1개가 임계(2KB)를 넘도록 긴 loc 를 쓴다 → 매 건마다 flush
|
||||
for ($i = 1; $i <= 3; $i++) {
|
||||
$writer->addUrl(['loc' => url('/p/'.str_repeat("long-segment-{$i}-", 200))]);
|
||||
}
|
||||
$writer->close();
|
||||
$meta = $writer->commit();
|
||||
|
||||
$this->assertSame(3, $meta['url_count']);
|
||||
$this->assertSame(
|
||||
3,
|
||||
$meta['child_count'],
|
||||
'URL 수 상한(10000) 미달이어도 바이트 임계 도달 시 자식이 분할돼야 합니다.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 바이트 임계로 분할된 자식들도 well-formed urlset 이며 전량 보존됩니다.
|
||||
*/
|
||||
public function test_byte_threshold_split_children_are_well_formed_and_lossless(): void
|
||||
{
|
||||
$writer = new SmallByteCapSitemapWriter(
|
||||
$this->storage,
|
||||
SitemapXmlRenderer::fromConfig(),
|
||||
10000,
|
||||
false,
|
||||
);
|
||||
|
||||
$writer->open();
|
||||
$locs = [];
|
||||
for ($i = 1; $i <= 3; $i++) {
|
||||
$loc = url('/p/'.str_repeat("seg-{$i}-", 200));
|
||||
$locs[] = $loc;
|
||||
$writer->addUrl(['loc' => $loc]);
|
||||
}
|
||||
$writer->close();
|
||||
$meta = $writer->commit();
|
||||
|
||||
$combined = '';
|
||||
foreach ($meta['children'] as $child) {
|
||||
$xml = $this->liveContent($child['file']);
|
||||
|
||||
$this->assertStringStartsWith('<?xml version="1.0" encoding="UTF-8"?>', $xml);
|
||||
$this->assertStringContainsString('</urlset>', $xml);
|
||||
$combined .= $xml;
|
||||
}
|
||||
|
||||
// 분할 과정에서 URL 이 유실되면 안 된다
|
||||
foreach ($locs as $loc) {
|
||||
$this->assertStringContainsString($loc, $combined);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 바이트 임계를 2KB 로 낮춘 writer (테스트 전용).
|
||||
*
|
||||
* MAX_FILE_BYTES 분기는 static:: 바인딩이므로 상수 재정의만으로 임계값을 바꿀 수 있다.
|
||||
*/
|
||||
class SmallByteCapSitemapWriter extends SitemapWriter
|
||||
{
|
||||
public const MAX_FILE_BYTES = 2048;
|
||||
}
|
||||
|
||||
/**
|
||||
* put() 호출 경로를 순서대로 기록하는 StorageInterface 데코레이터 (테스트 전용).
|
||||
*
|
||||
* manifest.json 이 커밋의 마지막 기록인지 검증하기 위해 사용합니다.
|
||||
*/
|
||||
class RecordingStorage implements StorageInterface
|
||||
{
|
||||
/**
|
||||
* put 이 호출된 경로 목록 (호출 순서)
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
public array $putOrder = [];
|
||||
|
||||
/**
|
||||
* RecordingStorage 생성자
|
||||
*
|
||||
* @param StorageInterface $inner 위임 대상 스토리지
|
||||
*/
|
||||
public function __construct(private StorageInterface $inner) {}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function put(string $category, string $path, mixed $content): bool
|
||||
{
|
||||
$this->putOrder[] = $path;
|
||||
|
||||
return $this->inner->put($category, $path, $content);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function get(string $category, string $path): ?string
|
||||
{
|
||||
return $this->inner->get($category, $path);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function exists(string $category, string $path): bool
|
||||
{
|
||||
return $this->inner->exists($category, $path);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function delete(string $category, string $path): bool
|
||||
{
|
||||
return $this->inner->delete($category, $path);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function url(string $category, string $path): ?string
|
||||
{
|
||||
return $this->inner->url($category, $path);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function files(string $category, string $directory = ''): array
|
||||
{
|
||||
return $this->inner->files($category, $directory);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function deleteDirectory(string $category, string $directory = ''): bool
|
||||
{
|
||||
return $this->inner->deleteDirectory($category, $directory);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getBasePath(string $category): string
|
||||
{
|
||||
return $this->inner->getBasePath($category);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getDisk(): string
|
||||
{
|
||||
return $this->inner->getDisk();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function deleteAll(string $category): bool
|
||||
{
|
||||
return $this->inner->deleteAll($category);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function response(string $category, string $path, string $filename, array $headers = []): ?StreamedResponse
|
||||
{
|
||||
return $this->inner->response($category, $path, $filename, $headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function withDisk(string $disk): static
|
||||
{
|
||||
$clone = clone $this;
|
||||
$clone->inner = $this->inner->withDisk($disk);
|
||||
|
||||
return $clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function download(string $category, string $path, string $filename, array $headers = []): ?StreamedResponse
|
||||
{
|
||||
return $this->inner->download($category, $path, $filename, $headers);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Seo\SitemapXmlRenderer;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* SitemapXmlRenderer 단위 테스트
|
||||
*
|
||||
* D14 로 추출된 XML 조각 렌더러이며 sitemap 이스케이프의 단일 출처다.
|
||||
* SitemapGenerator(수집측)와 SitemapWriter(기록측)가 이 클래스를 공유하므로,
|
||||
* 여기서 깨지면 양쪽이 함께 깨진다.
|
||||
*
|
||||
* S3 ⑮(hreflang N² 해소)의 실제 편집 대상이 이 클래스이므로, 그 작업의
|
||||
* 회귀 기준선으로서 현재 동작을 고정한다.
|
||||
*
|
||||
* 검증 목적:
|
||||
* - 이스케이프: loc/lastmod/changefreq/hreflang/sitemapindex 전 경로
|
||||
* - 단일 언어 vs 다국어 분기 (헤더 xmlns / urlBlockCount / <url> 블록 수)
|
||||
* - hreflang alternate 구조 (현재: 로케일 수 × (로케일 수 + x-default))
|
||||
* - 로케일 URL 규칙 (기본 로케일은 원본, 그 외 ?locale=)
|
||||
* - sitemapindex 구조
|
||||
*/
|
||||
class SitemapXmlRendererTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* 단일 언어 렌더러를 만듭니다.
|
||||
*
|
||||
* @return SitemapXmlRenderer 렌더러
|
||||
*/
|
||||
private function singleLocale(): SitemapXmlRenderer
|
||||
{
|
||||
return new SitemapXmlRenderer(['ko'], 'ko');
|
||||
}
|
||||
|
||||
/**
|
||||
* 다국어 렌더러를 만듭니다.
|
||||
*
|
||||
* @param array<int, string> $locales 지원 로케일
|
||||
* @return SitemapXmlRenderer 렌더러
|
||||
*/
|
||||
private function multiLocale(array $locales = ['ko', 'en', 'ja']): SitemapXmlRenderer
|
||||
{
|
||||
return new SitemapXmlRenderer($locales, 'ko');
|
||||
}
|
||||
|
||||
/**
|
||||
* fromConfig: 앱 로케일 설정을 반영한다
|
||||
*/
|
||||
public function test_from_config_reflects_app_locale_settings(): void
|
||||
{
|
||||
Config::set('app.locale', 'ko');
|
||||
Config::set('app.supported_locales', ['ko', 'en']);
|
||||
|
||||
$renderer = SitemapXmlRenderer::fromConfig();
|
||||
|
||||
$this->assertTrue($renderer->isMultilingual());
|
||||
$this->assertSame(2, $renderer->urlBlockCount());
|
||||
}
|
||||
|
||||
/**
|
||||
* fromConfig: supported_locales 미설정 시 기본 로케일 단독으로 동작한다
|
||||
*/
|
||||
public function test_from_config_falls_back_to_default_locale_only(): void
|
||||
{
|
||||
Config::set('app.locale', 'ko');
|
||||
Config::set('app.supported_locales', null);
|
||||
|
||||
$renderer = SitemapXmlRenderer::fromConfig();
|
||||
|
||||
$this->assertFalse($renderer->isMultilingual());
|
||||
$this->assertSame(1, $renderer->urlBlockCount());
|
||||
}
|
||||
|
||||
/**
|
||||
* isMultilingual: 로케일이 1개면 단일 언어다
|
||||
*/
|
||||
public function test_is_multilingual_is_false_for_single_locale(): void
|
||||
{
|
||||
$this->assertFalse($this->singleLocale()->isMultilingual());
|
||||
$this->assertTrue($this->multiLocale(['ko', 'en'])->isMultilingual());
|
||||
}
|
||||
|
||||
/**
|
||||
* urlBlockCount: 다국어면 로케일 수, 단일 언어면 1
|
||||
*
|
||||
* 이 값이 틀리면 writer 의 파일당 URL 수 임계 계산이 어긋나 프로토콜을 위반한다.
|
||||
*/
|
||||
public function test_url_block_count_matches_locale_count(): void
|
||||
{
|
||||
$this->assertSame(1, $this->singleLocale()->urlBlockCount());
|
||||
$this->assertSame(3, $this->multiLocale()->urlBlockCount());
|
||||
}
|
||||
|
||||
/**
|
||||
* urlsetHeader: 단일 언어는 xhtml 네임스페이스를 선언하지 않는다
|
||||
*/
|
||||
public function test_urlset_header_omits_xhtml_namespace_for_single_locale(): void
|
||||
{
|
||||
$header = $this->singleLocale()->urlsetHeader();
|
||||
|
||||
$this->assertStringStartsWith('<?xml version="1.0" encoding="UTF-8"?>', $header);
|
||||
$this->assertStringContainsString('xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"', $header);
|
||||
$this->assertStringNotContainsString('xmlns:xhtml', $header);
|
||||
}
|
||||
|
||||
/**
|
||||
* urlsetHeader: 다국어는 xhtml 네임스페이스를 선언한다 (hreflang 사용)
|
||||
*/
|
||||
public function test_urlset_header_declares_xhtml_namespace_for_multilingual(): void
|
||||
{
|
||||
$this->assertStringContainsString(
|
||||
'xmlns:xhtml="http://www.w3.org/1999/xhtml"',
|
||||
$this->multiLocale()->urlsetHeader()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* urlsetFooter: urlset 을 닫는다
|
||||
*/
|
||||
public function test_urlset_footer_closes_urlset(): void
|
||||
{
|
||||
$this->assertSame('</urlset>', $this->singleLocale()->urlsetFooter());
|
||||
}
|
||||
|
||||
/**
|
||||
* urlBlock: loc 이 없으면 빈 문자열을 반환한다 (writer 가 이것으로 skip 판정)
|
||||
*/
|
||||
public function test_url_block_returns_empty_string_without_loc(): void
|
||||
{
|
||||
$this->assertSame('', $this->singleLocale()->urlBlock([]));
|
||||
$this->assertSame('', $this->singleLocale()->urlBlock(['loc' => '']));
|
||||
$this->assertSame('', $this->singleLocale()->urlBlock(['changefreq' => 'daily']));
|
||||
}
|
||||
|
||||
/**
|
||||
* urlBlock: 단일 언어는 <url> 블록 1개를 만들고 hreflang 을 붙이지 않는다
|
||||
*/
|
||||
public function test_url_block_renders_single_url_without_hreflang(): void
|
||||
{
|
||||
$xml = $this->singleLocale()->urlBlock(['loc' => 'https://example.test/a']);
|
||||
|
||||
$this->assertSame(1, substr_count($xml, '<url>'));
|
||||
$this->assertStringContainsString('<loc>https://example.test/a</loc>', $xml);
|
||||
$this->assertStringNotContainsString('xhtml:link', $xml);
|
||||
}
|
||||
|
||||
/**
|
||||
* urlBlock: 메타 필드를 렌더링하며 priority 는 소수 1자리로 고정한다
|
||||
*/
|
||||
public function test_url_block_renders_meta_fields(): void
|
||||
{
|
||||
$xml = $this->singleLocale()->urlBlock([
|
||||
'loc' => 'https://example.test/a',
|
||||
'lastmod' => '2026-07-17T00:00:00+09:00',
|
||||
'changefreq' => 'daily',
|
||||
'priority' => 0.8,
|
||||
]);
|
||||
|
||||
$this->assertStringContainsString('<lastmod>2026-07-17T00:00:00+09:00</lastmod>', $xml);
|
||||
$this->assertStringContainsString('<changefreq>daily</changefreq>', $xml);
|
||||
$this->assertStringContainsString('<priority>0.8</priority>', $xml);
|
||||
}
|
||||
|
||||
/**
|
||||
* urlBlock: priority 는 정수로 줘도 소수 1자리로 정규화된다
|
||||
*/
|
||||
public function test_url_block_normalizes_integer_priority(): void
|
||||
{
|
||||
$xml = $this->singleLocale()->urlBlock(['loc' => 'https://example.test/a', 'priority' => 1]);
|
||||
|
||||
$this->assertStringContainsString('<priority>1.0</priority>', $xml);
|
||||
}
|
||||
|
||||
/**
|
||||
* urlBlock: 메타 필드가 없으면 해당 태그를 생략한다
|
||||
*/
|
||||
public function test_url_block_omits_absent_meta_fields(): void
|
||||
{
|
||||
$xml = $this->singleLocale()->urlBlock(['loc' => 'https://example.test/a']);
|
||||
|
||||
$this->assertStringNotContainsString('<lastmod>', $xml);
|
||||
$this->assertStringNotContainsString('<changefreq>', $xml);
|
||||
$this->assertStringNotContainsString('<priority>', $xml);
|
||||
}
|
||||
|
||||
/**
|
||||
* urlBlock: 다국어는 로케일 수만큼 <url> 블록을 만든다
|
||||
*/
|
||||
public function test_url_block_renders_one_url_per_locale(): void
|
||||
{
|
||||
$xml = $this->multiLocale()->urlBlock(['loc' => 'https://example.test/a']);
|
||||
|
||||
$this->assertSame(3, substr_count($xml, '<url>'));
|
||||
}
|
||||
|
||||
/**
|
||||
* urlBlock: 기본 로케일은 원본 URL, 그 외는 ?locale= 를 붙인다
|
||||
*/
|
||||
public function test_url_block_localizes_loc_per_locale(): void
|
||||
{
|
||||
$xml = $this->multiLocale()->urlBlock(['loc' => 'https://example.test/a']);
|
||||
|
||||
// 기본 로케일(ko)은 쿼리 없이 원본
|
||||
$this->assertStringContainsString('<loc>https://example.test/a</loc>', $xml);
|
||||
$this->assertStringContainsString('<loc>https://example.test/a?locale=en</loc>', $xml);
|
||||
$this->assertStringContainsString('<loc>https://example.test/a?locale=ja</loc>', $xml);
|
||||
}
|
||||
|
||||
/**
|
||||
* urlBlock: hreflang alternate 가 현재 N² 구조임을 고정한다 (S3 ⑮ 회귀 기준선)
|
||||
*
|
||||
* 현재 구현은 <url> 블록마다 모든 로케일의 alternate + x-default 를 넣는다.
|
||||
* 즉 로케일 L 개면 L × (L + 1) 개의 xhtml:link 가 생성된다 — 이것이 S3 ⑮ 가
|
||||
* 해소하려는 N² 팽창이다. S3 에서 이 수치가 바뀌면 의도된 변경이므로
|
||||
* 이 테스트를 함께 갱신할 것.
|
||||
*/
|
||||
public function test_url_block_currently_emits_quadratic_hreflang_links(): void
|
||||
{
|
||||
$xml = $this->multiLocale(['ko', 'en', 'ja'])->urlBlock(['loc' => 'https://example.test/a']);
|
||||
|
||||
// 3 로케일 → 3 블록 × (3 alternate + 1 x-default) = 12
|
||||
$this->assertSame(12, substr_count($xml, 'xhtml:link'));
|
||||
$this->assertSame(3, substr_count($xml, 'hreflang="x-default"'));
|
||||
}
|
||||
|
||||
/**
|
||||
* urlBlock: x-default 는 항상 기본 로케일 URL 을 가리킨다
|
||||
*/
|
||||
public function test_url_block_x_default_points_to_base_loc(): void
|
||||
{
|
||||
$xml = $this->multiLocale()->urlBlock(['loc' => 'https://example.test/a']);
|
||||
|
||||
$this->assertStringContainsString(
|
||||
'<xhtml:link rel="alternate" hreflang="x-default" href="https://example.test/a"/>',
|
||||
$xml
|
||||
);
|
||||
$this->assertStringNotContainsString('hreflang="x-default" href="https://example.test/a?locale=', $xml);
|
||||
}
|
||||
|
||||
/**
|
||||
* urlBlock: loc 의 XML 특수문자를 이스케이프한다 (단일 출처 방어)
|
||||
*/
|
||||
public function test_url_block_escapes_special_characters_in_loc(): void
|
||||
{
|
||||
$xml = $this->singleLocale()->urlBlock(['loc' => 'https://example.test/a?x=1&y=2<z>']);
|
||||
|
||||
$this->assertStringContainsString('<loc>https://example.test/a?x=1&y=2<z></loc>', $xml);
|
||||
$this->assertStringNotContainsString('&y=2', $xml);
|
||||
}
|
||||
|
||||
/**
|
||||
* urlBlock: 메타 필드의 XML 특수문자도 이스케이프한다
|
||||
*/
|
||||
public function test_url_block_escapes_special_characters_in_meta_fields(): void
|
||||
{
|
||||
$xml = $this->singleLocale()->urlBlock([
|
||||
'loc' => 'https://example.test/a',
|
||||
'lastmod' => '2026 & later',
|
||||
'changefreq' => 'da<ily',
|
||||
]);
|
||||
|
||||
$this->assertStringContainsString('<lastmod>2026 & later</lastmod>', $xml);
|
||||
$this->assertStringContainsString('<changefreq>da<ily</changefreq>', $xml);
|
||||
}
|
||||
|
||||
/**
|
||||
* urlBlock: 다국어 alternate href 도 이스케이프한다
|
||||
*/
|
||||
public function test_url_block_escapes_hreflang_alternate_href(): void
|
||||
{
|
||||
$xml = $this->multiLocale(['ko', 'en'])->urlBlock(['loc' => 'https://example.test/a?x=1&y=2']);
|
||||
|
||||
$this->assertStringContainsString('href="https://example.test/a?x=1&y=2"', $xml);
|
||||
// 이스케이프되지 않은 & 가 남으면 XML 파서가 깨진다
|
||||
$this->assertStringNotContainsString('&y=2"', $xml);
|
||||
}
|
||||
|
||||
/**
|
||||
* urlBlock: 다국어 출력이 well-formed XML 이다 (이스케이프 종합 검증)
|
||||
*/
|
||||
public function test_multilingual_url_block_is_well_formed_xml(): void
|
||||
{
|
||||
$renderer = $this->multiLocale();
|
||||
$xml = $renderer->urlsetHeader()
|
||||
.$renderer->urlBlock(['loc' => 'https://example.test/a?x=1&y=2', 'changefreq' => 'daily'])
|
||||
.$renderer->urlsetFooter();
|
||||
|
||||
$this->assertNotFalse(simplexml_load_string($xml), 'urlset 이 파싱 가능한 XML 이어야 합니다.');
|
||||
}
|
||||
|
||||
/**
|
||||
* sitemapIndex: 자식 목록을 sitemapindex 로 렌더링한다
|
||||
*/
|
||||
public function test_sitemap_index_renders_children(): void
|
||||
{
|
||||
$xml = $this->singleLocale()->sitemapIndex([
|
||||
['loc' => 'https://example.test/sitemap-1.xml', 'lastmod' => '2026-07-17T00:00:00+09:00'],
|
||||
['loc' => 'https://example.test/sitemap-2.xml', 'lastmod' => null],
|
||||
]);
|
||||
|
||||
$this->assertStringStartsWith('<?xml version="1.0" encoding="UTF-8"?>', $xml);
|
||||
$this->assertStringContainsString('<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">', $xml);
|
||||
$this->assertSame(2, substr_count($xml, '<sitemap>'));
|
||||
$this->assertStringContainsString('<loc>https://example.test/sitemap-1.xml</loc>', $xml);
|
||||
// lastmod 가 null 인 자식은 태그를 생략한다
|
||||
$this->assertSame(1, substr_count($xml, '<lastmod>'));
|
||||
$this->assertStringEndsWith('</sitemapindex>', $xml);
|
||||
}
|
||||
|
||||
/**
|
||||
* sitemapIndex: 자식이 없어도 well-formed 인 빈 인덱스를 만든다
|
||||
*/
|
||||
public function test_sitemap_index_is_well_formed_when_empty(): void
|
||||
{
|
||||
$xml = $this->singleLocale()->sitemapIndex([]);
|
||||
|
||||
$this->assertNotFalse(simplexml_load_string($xml));
|
||||
$this->assertStringNotContainsString('<sitemap>', $xml);
|
||||
}
|
||||
|
||||
/**
|
||||
* sitemapIndex: 자식 loc/lastmod 의 특수문자를 이스케이프한다
|
||||
*/
|
||||
public function test_sitemap_index_escapes_special_characters(): void
|
||||
{
|
||||
$xml = $this->singleLocale()->sitemapIndex([
|
||||
['loc' => 'https://example.test/sitemap-1.xml?v=1&t=2', 'lastmod' => '2026 & later'],
|
||||
]);
|
||||
|
||||
$this->assertStringContainsString('<loc>https://example.test/sitemap-1.xml?v=1&t=2</loc>', $xml);
|
||||
$this->assertStringContainsString('<lastmod>2026 & later</lastmod>', $xml);
|
||||
$this->assertNotFalse(simplexml_load_string($xml));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Upgrades;
|
||||
|
||||
require_once __DIR__.'/../../../upgrades/data/7.1.0/migrations/01_NullifyUntouchedSeoCacheOverrides.php';
|
||||
|
||||
use App\Extension\UpgradeContext;
|
||||
use App\Upgrades\Data\V7_1_0\Migrations\NullifyUntouchedSeoCacheOverrides;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 7.1.0 업그레이드 스텝 — SEO 캐시 오버라이드 이행 (결정 D19)
|
||||
*
|
||||
* 판정 규칙:
|
||||
* 옛 기본값과 같으면 "안 건드린 것" → null(미설정)로 비움
|
||||
* 옛 기본값과 다르면 "의도적으로 바꾼 것" → 보존 (이제부터 오버라이드로 발동)
|
||||
*
|
||||
* 이 판정이 틀리면 기존 사이트의 캐시 동작이 의도치 않게 바뀐다.
|
||||
*/
|
||||
class NullifyUntouchedSeoCacheOverridesTest extends TestCase
|
||||
{
|
||||
private NullifyUntouchedSeoCacheOverrides $migration;
|
||||
|
||||
/**
|
||||
* 테스트 초기화 - settings 디스크를 가짜로 대체합니다.
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Storage::fake('settings');
|
||||
$this->migration = new NullifyUntouchedSeoCacheOverrides;
|
||||
}
|
||||
|
||||
/**
|
||||
* 업그레이드 컨텍스트를 만듭니다.
|
||||
*
|
||||
* @return UpgradeContext 컨텍스트
|
||||
*/
|
||||
private function context(): UpgradeContext
|
||||
{
|
||||
return new UpgradeContext('7.0.5', '7.1.0', '7.1.0');
|
||||
}
|
||||
|
||||
/**
|
||||
* seo.json 을 기록합니다.
|
||||
*
|
||||
* @param array<string, mixed> $settings 설정 배열
|
||||
*/
|
||||
private function writeSeoJson(array $settings): void
|
||||
{
|
||||
Storage::disk('settings')->put('seo.json', json_encode($settings));
|
||||
}
|
||||
|
||||
/**
|
||||
* seo.json 을 읽습니다.
|
||||
*
|
||||
* @return array<string, mixed> 설정 배열
|
||||
*/
|
||||
private function readSeoJson(): array
|
||||
{
|
||||
return json_decode(Storage::disk('settings')->get('seo.json'), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* name: 로그용 식별자를 반환한다
|
||||
*/
|
||||
public function test_name_returns_identifier(): void
|
||||
{
|
||||
$this->assertSame('NullifyUntouchedSeoCacheOverrides', $this->migration->name());
|
||||
}
|
||||
|
||||
/**
|
||||
* 옛 기본값 그대로인 키는 null 로 비운다 (안 건드린 것으로 추정)
|
||||
*/
|
||||
public function test_clears_keys_left_at_legacy_defaults(): void
|
||||
{
|
||||
$this->writeSeoJson([
|
||||
'cache_enabled' => true,
|
||||
'cache_ttl' => 7200,
|
||||
'sitemap_cache_ttl' => 86400,
|
||||
'sitemap_enabled' => true,
|
||||
]);
|
||||
|
||||
$this->migration->run($this->context());
|
||||
$result = $this->readSeoJson();
|
||||
|
||||
$this->assertNull($result['cache_enabled']);
|
||||
$this->assertNull($result['cache_ttl']);
|
||||
$this->assertNull($result['sitemap_cache_ttl']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 옛 기본값과 다른 값은 보존한다 (의도적으로 바꾼 것 → 오버라이드로 발동)
|
||||
*
|
||||
* 실제 사례: seo.cache_ttl=3600 을 설정해 뒀으나 그동안 무시되던 사이트.
|
||||
*/
|
||||
public function test_preserves_values_that_differ_from_legacy_defaults(): void
|
||||
{
|
||||
$this->writeSeoJson([
|
||||
'cache_enabled' => false,
|
||||
'cache_ttl' => 3600,
|
||||
'sitemap_cache_ttl' => 604800,
|
||||
]);
|
||||
|
||||
$this->migration->run($this->context());
|
||||
$result = $this->readSeoJson();
|
||||
|
||||
$this->assertFalse($result['cache_enabled'], 'false 는 기본값(true)과 다르므로 보존돼야 합니다.');
|
||||
$this->assertSame(3600, $result['cache_ttl']);
|
||||
$this->assertSame(604800, $result['sitemap_cache_ttl']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 일부만 바뀐 경우 — 바뀐 것만 보존하고 나머지는 비운다
|
||||
*/
|
||||
public function test_clears_untouched_and_preserves_changed_in_same_file(): void
|
||||
{
|
||||
$this->writeSeoJson([
|
||||
'cache_enabled' => true, // 기본값 → 비움
|
||||
'cache_ttl' => 3600, // 변경됨 → 보존
|
||||
'sitemap_cache_ttl' => 86400, // 기본값 → 비움
|
||||
]);
|
||||
|
||||
$this->migration->run($this->context());
|
||||
$result = $this->readSeoJson();
|
||||
|
||||
$this->assertNull($result['cache_enabled']);
|
||||
$this->assertSame(3600, $result['cache_ttl']);
|
||||
$this->assertNull($result['sitemap_cache_ttl']);
|
||||
}
|
||||
|
||||
/**
|
||||
* seo 카테고리의 다른 키는 건드리지 않는다
|
||||
*/
|
||||
public function test_does_not_touch_unrelated_keys(): void
|
||||
{
|
||||
$this->writeSeoJson([
|
||||
'cache_ttl' => 7200,
|
||||
'sitemap_enabled' => true,
|
||||
'sitemap_schedule' => 'hourly',
|
||||
'sitemap_schedule_time' => '03:00',
|
||||
'meta_title_suffix' => ' | G7',
|
||||
]);
|
||||
|
||||
$this->migration->run($this->context());
|
||||
$result = $this->readSeoJson();
|
||||
|
||||
$this->assertTrue($result['sitemap_enabled']);
|
||||
$this->assertSame('hourly', $result['sitemap_schedule'], '재생성 주기는 이 이행과 무관합니다.');
|
||||
$this->assertSame('03:00', $result['sitemap_schedule_time']);
|
||||
$this->assertSame(' | G7', $result['meta_title_suffix']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 멱등: 두 번 실행해도 결과가 같다
|
||||
*/
|
||||
public function test_is_idempotent(): void
|
||||
{
|
||||
$this->writeSeoJson([
|
||||
'cache_ttl' => 7200,
|
||||
'sitemap_cache_ttl' => 3600,
|
||||
]);
|
||||
|
||||
$this->migration->run($this->context());
|
||||
$first = $this->readSeoJson();
|
||||
|
||||
$this->migration->run($this->context());
|
||||
$second = $this->readSeoJson();
|
||||
|
||||
$this->assertSame($first, $second);
|
||||
$this->assertNull($second['cache_ttl']);
|
||||
$this->assertSame(3600, $second['sitemap_cache_ttl']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 이미 null 인 키는 그대로 둔다 (재실행 안전)
|
||||
*/
|
||||
public function test_leaves_already_null_keys_untouched(): void
|
||||
{
|
||||
$this->writeSeoJson(['cache_ttl' => null, 'sitemap_cache_ttl' => null]);
|
||||
|
||||
$this->migration->run($this->context());
|
||||
$result = $this->readSeoJson();
|
||||
|
||||
$this->assertNull($result['cache_ttl']);
|
||||
$this->assertNull($result['sitemap_cache_ttl']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 키가 아예 없으면 새로 만들지 않는다
|
||||
*/
|
||||
public function test_does_not_add_absent_keys(): void
|
||||
{
|
||||
$this->writeSeoJson(['meta_title_suffix' => ' | G7']);
|
||||
|
||||
$this->migration->run($this->context());
|
||||
$result = $this->readSeoJson();
|
||||
|
||||
$this->assertArrayNotHasKey('cache_ttl', $result);
|
||||
$this->assertArrayNotHasKey('sitemap_cache_ttl', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* seo.json 이 없으면 no-op (예외 없음)
|
||||
*/
|
||||
public function test_no_op_when_settings_file_is_absent(): void
|
||||
{
|
||||
$this->migration->run($this->context());
|
||||
|
||||
$this->assertFalse(Storage::disk('settings')->exists('seo.json'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 손상된 JSON 은 덮어쓰지 않고 보존한다 (파괴 금지)
|
||||
*/
|
||||
public function test_preserves_corrupted_json_without_overwriting(): void
|
||||
{
|
||||
Storage::disk('settings')->put('seo.json', '{ this is not json');
|
||||
|
||||
$this->migration->run($this->context());
|
||||
|
||||
$this->assertSame('{ this is not json', Storage::disk('settings')->get('seo.json'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 타입이 다른 동일 값은 오버라이드로 본다 (느슨한 비교 금지)
|
||||
*
|
||||
* 문자열 "7200" 은 기본값 7200(int)과 == 로는 같지만, 운영자가 폼으로 입력한
|
||||
* 흔적이므로 === 비교로 보존해야 한다.
|
||||
*/
|
||||
public function test_treats_type_mismatched_value_as_override(): void
|
||||
{
|
||||
$this->writeSeoJson(['cache_ttl' => '7200']);
|
||||
|
||||
$this->migration->run($this->context());
|
||||
|
||||
$this->assertSame('7200', $this->readSeoJson()['cache_ttl']);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user