feat(seo): 사이트맵 증분 저장소 + 리소스 리스너 재배선

사이트맵을 리소스 단위로 영속화(sitemap_urls)해 진정한 증분 갱신과
도메인 재쿼리 없는 파일 재작성을 구현했다. 리소스 공개/비공개/삭제 시
해당 항목만 색인이 갱신되고, 관리자=full·스케줄러=auto·리소스 변경=증분으로 동작한다.

- sitemap_urls 마이그레이션 + SitemapUrl 모델. loc(2048) 를 unique 에 직접 넣으면
 InnoDB 키 길이를 초과하므로 loc_hash(sha256) 컬럼을 identity 로 사용
- SitemapUrlRepository(멱등 upsert / remove / 스트리밍) + SitemapIndexer
 (+ 제3자용 sitemap.index.collect_for_resource 필터 훅)
- 4 리스너 재배선: 공개→색인 / 비공개·삭제→색인 해제 + 재생성 잡 디바운스 디스패치.
 3 기여자가 resource_type/resource_id 를 함께 emit 해 전체·증분 identity 를 일치
- 재생성 모드를 SitemapGenerationMode Backed Enum 으로 통일(Command→Job→Manager)
- seo:generate-sitemap 에 --rebuild / --mode 옵션 추가
This commit is contained in:
HeuJung committed 2026-07-18 16:19:49 +09:00
1 parent 1a6fca0d6b
commit 1629684156
34 files changed
+2027 -23

No files matched your search

+90
View File
@@ -0,0 +1,90 @@
<?php
namespace Tests\Feature\Seo;
use App\Extension\Storage\CoreStorageDriver;
use App\Models\SitemapUrl;
use App\Seo\AbstractSitemapContributor;
use App\Seo\SitemapFileStore;
use App\Seo\SitemapGenerator;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
/**
* 사이트맵 백필 통합 테스트 (S4 — 커맨드 → 잡 → 매니저 → 저장소)
*
* 검증 목적:
* - seo:generate-sitemap --rebuild --sync 가 기여자로부터 sitemap_urls 를 백필하고 파일을 커밋
* - 빈 저장소에서 --mode=auto 가 full 로 동작해 자동 백필
*/
class SitemapBackfillTest extends TestCase
{
use RefreshDatabase;
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);
Config::set('queue.default', 'sync');
Storage::fake('local');
// 컨테이너 싱글톤 generator 에 가짜 기여자를 등록 → 잡이 해석하는 매니저가 이를 사용
$this->app->make(SitemapGenerator::class)->registerContributor($this->fakeContributor());
}
/**
* resource identity 를 emit 하는 가짜 기여자를 만듭니다.
*
* @return AbstractSitemapContributor 가짜 기여자
*/
private function fakeContributor(): AbstractSitemapContributor
{
return new class extends AbstractSitemapContributor
{
public function getIdentifier(): string
{
return 'fake-contributor';
}
public function getUrlsLazy(): iterable
{
yield ['url' => '/x/1', 'resource_type' => 'thing', 'resource_id' => '1', 'changefreq' => 'daily', 'priority' => 0.7];
yield ['url' => '/x/2', 'resource_type' => 'thing', 'resource_id' => '2', 'changefreq' => 'daily', 'priority' => 0.7];
}
};
}
/**
* --rebuild --sync: 기여자로부터 저장소를 백필하고 파일을 커밋한다.
*/
public function test_rebuild_backfills_store_and_commits_files(): void
{
$this->artisan('seo:generate-sitemap', ['--rebuild' => true, '--sync' => true])
->assertExitCode(0);
$rows = SitemapUrl::where('contributor', 'fake-contributor')->pluck('resource_id')->sort()->values()->all();
$this->assertSame(['1', '2'], $rows, '기여자 URL 이 저장소에 백필돼야 합니다.');
$store = new SitemapFileStore(new CoreStorageDriver('local'));
$this->assertTrue($store->exists(), '백필 후 sitemap 파일 세트가 커밋돼야 합니다.');
}
/**
* --mode=auto --sync: 빈 저장소에서 full 로 자동 백필한다.
*/
public function test_auto_mode_backfills_when_store_empty(): void
{
$this->assertSame(0, SitemapUrl::count());
$this->artisan('seo:generate-sitemap', ['--mode' => 'auto', '--sync' => true])
->assertExitCode(0);
$this->assertSame(2, SitemapUrl::where('contributor', 'fake-contributor')->count(), '빈 저장소에서 auto 는 full 백필이어야 합니다.');
}
}
+112
View File
@@ -0,0 +1,112 @@
<?php
namespace Tests\Feature\Seo;
use App\Extension\HookManager;
use App\Models\SitemapUrl;
use App\Seo\SitemapIndexer;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* SitemapIndexer 통합 테스트 (S4 리스너 경유 색인기)
*
* 검증 목적:
* - indexResource 로 공개 리소스 색인(upsert)
* - deindexResource 로 비공개/삭제 리소스 색인 해제
* - url(상대) → loc(절대) 정규화
* - collect_for_resource filter 훅으로 제3자 항목 가공
* - 필터가 항목을 모두 제거하면 색인도 제거됨
*/
class SitemapIndexerTest extends TestCase
{
use RefreshDatabase;
private SitemapIndexer $indexer;
/**
* 테스트 초기화
*/
protected function setUp(): void
{
parent::setUp();
$this->indexer = $this->app->make(SitemapIndexer::class);
HookManager::clearFilter(SitemapIndexer::COLLECT_FILTER);
}
/**
* 테스트 정리 - filter 훅 누출 방지
*/
protected function tearDown(): void
{
HookManager::clearFilter(SitemapIndexer::COLLECT_FILTER);
parent::tearDown();
}
/**
* indexResource: 공개 리소스를 색인하며 url 을 loc 으로 정규화한다.
*/
public function test_index_resource_upserts_and_normalizes_url(): void
{
$this->indexer->indexResource('product', 7, 'sirsoft-ecommerce', [[
'url' => '/shop/products/7',
'changefreq' => 'weekly',
'priority' => 0.8,
]]);
$row = SitemapUrl::where('resource_type', 'product')->where('resource_id', '7')->first();
$this->assertNotNull($row);
$this->assertSame(url('/shop/products/7'), $row->loc, 'url 은 절대 loc 으로 정규화돼야 합니다.');
$this->assertSame('sirsoft-ecommerce', $row->contributor);
}
/**
* deindexResource: 색인을 제거한다.
*/
public function test_deindex_resource_removes_index(): void
{
$this->indexer->indexResource('page', 3, 'sirsoft-page', [['url' => '/page/about']]);
$this->assertSame(1, SitemapUrl::where('resource_type', 'page')->where('resource_id', '3')->count());
$this->indexer->deindexResource('page', 3);
$this->assertSame(0, SitemapUrl::where('resource_type', 'page')->where('resource_id', '3')->count());
}
/**
* collect_for_resource filter 훅으로 제3자가 항목을 가공할 수 있다.
*/
public function test_collect_filter_hook_can_transform_entries(): void
{
HookManager::addFilter(SitemapIndexer::COLLECT_FILTER, function (array $entries) {
$entries[] = ['url' => '/extra'];
return $entries;
});
$this->indexer->indexResource('product', 8, 'sirsoft-ecommerce', [['url' => '/shop/products/8']]);
$locs = SitemapUrl::where('resource_type', 'product')->where('resource_id', '8')->pluck('loc')->all();
$this->assertContains(url('/shop/products/8'), $locs);
$this->assertContains(url('/extra'), $locs, 'filter 훅이 추가한 항목이 색인돼야 합니다.');
}
/**
* 필터가 항목을 모두 제거하면 색인도 제거된다(정합 유지).
*/
public function test_filter_removing_all_entries_deindexes(): void
{
$this->indexer->indexResource('product', 9, 'sirsoft-ecommerce', [['url' => '/shop/products/9']]);
$this->assertSame(1, SitemapUrl::where('resource_id', '9')->count());
HookManager::addFilter(SitemapIndexer::COLLECT_FILTER, fn () => []);
$this->indexer->indexResource('product', 9, 'sirsoft-ecommerce', [['url' => '/shop/products/9']]);
$this->assertSame(0, SitemapUrl::where('resource_id', '9')->count(), '항목이 모두 제거되면 색인이 제거돼야 합니다.');
}
}
@@ -0,0 +1,187 @@
<?php
namespace Tests\Feature\Seo;
use App\Contracts\Extension\CacheInterface;
use App\Contracts\Repositories\ConfigRepositoryInterface;
use App\Contracts\Repositories\SitemapUrlRepositoryInterface;
use App\Enums\SitemapGenerationMode;
use App\Extension\Storage\CoreStorageDriver;
use App\Models\SitemapUrl;
use App\Seo\AbstractSitemapContributor;
use App\Seo\SitemapFileStore;
use App\Seo\SitemapGenerator;
use App\Seo\SitemapManager;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Storage;
use Mockery;
use Tests\TestCase;
/**
* SitemapManager 재생성 모드 분기 테스트 (S4 ㉑)
*
* 검증 목적 (DoD: 모드 분기 green + 도메인 재쿼리 0):
* - full: 저장소가 채워져 있어도 기여자를 스트리밍해 전량 대체
* - auto: 저장소 비었으면 full(기여자 드레인), 채워졌으면 incremental(드레인 없음)
* - incremental: 기여자 재쿼리 없이 저장소 스트림만으로 파일 재작성
*/
class SitemapManagerModeTest extends TestCase
{
use RefreshDatabase;
private CoreStorageDriver $storage;
private SitemapUrlRepositoryInterface $repository;
/**
* 테스트 초기화
*/
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->repository = $this->app->make(SitemapUrlRepositoryInterface::class);
}
/**
* 호출 횟수를 세는 가짜 기여자를 만듭니다.
*
* @param array<int, array{url: string, resource_type: string, resource_id: ?string}> $entries emit 항목
* @return AbstractSitemapContributor 카운터가 달린 기여자
*/
private function countingContributor(array $entries): AbstractSitemapContributor
{
return new class($entries) extends AbstractSitemapContributor
{
public int $drainCount = 0;
/**
* @param array<int, array<string, mixed>> $entries emit 항목
*/
public function __construct(private array $entries) {}
public function getIdentifier(): string
{
return 'fake-contributor';
}
public function getUrlsLazy(): iterable
{
$this->drainCount++;
yield from $this->entries;
}
};
}
/**
* 매니저를 구성합니다 (기여자 등록 포함).
*
* @param AbstractSitemapContributor $contributor 등록할 기여자
* @return SitemapManager 매니저
*/
private function makeManager(AbstractSitemapContributor $contributor): SitemapManager
{
$generator = $this->app->make(SitemapGenerator::class);
$generator->registerContributor($contributor);
return new SitemapManager(
$generator,
Mockery::spy(CacheInterface::class),
Mockery::spy(ConfigRepositoryInterface::class),
$this->storage,
$this->repository,
);
}
/**
* 커밋된 첫 자식 sitemap 의 XML 본문을 반환합니다.
*
* @return string 자식 XML
*/
private function firstChildXml(): string
{
return (string) $this->storage->get(SitemapFileStore::CATEGORY, SitemapFileStore::LIVE_DIR.'/'.SitemapFileStore::childFilename(1));
}
/**
* full: 저장소가 이미 채워져 있어도 기여자를 스트리밍해 전량 대체한다.
*/
public function test_full_mode_rebuilds_store_from_contributors(): void
{
// 옛(stale) 저장소 상태 — 전량 대체로 사라져야 한다
$this->repository->replaceAllForContributor('fake-contributor', [
['loc' => url('/stale'), 'resource_type' => 'product', 'resource_id' => '999'],
]);
$contributor = $this->countingContributor([
['url' => '/fresh', 'resource_type' => 'product', 'resource_id' => '1'],
]);
$this->makeManager($contributor)->regenerate(SitemapGenerationMode::Full);
$this->assertSame(1, $contributor->drainCount, 'full 은 기여자를 드레인해야 합니다.');
$locs = SitemapUrl::where('contributor', 'fake-contributor')->pluck('loc')->all();
$this->assertSame([url('/fresh')], $locs, 'full 은 저장소를 전량 대체해야 합니다.');
$this->assertStringContainsString(url('/fresh'), $this->firstChildXml());
}
/**
* auto: 저장소가 비어 있으면 full 로 동작(기여자 드레인 + 저장소 채움).
*/
public function test_auto_mode_is_full_when_store_empty(): void
{
$contributor = $this->countingContributor([
['url' => '/a', 'resource_type' => 'product', 'resource_id' => '1'],
]);
$this->makeManager($contributor)->regenerate(SitemapGenerationMode::Auto);
$this->assertSame(1, $contributor->drainCount, '빈 저장소에서 auto 는 full 이어야 합니다.');
$this->assertSame(1, $this->repository->countVisible());
}
/**
* auto: 저장소가 채워져 있으면 incremental 로 동작(기여자 드레인 없음).
*/
public function test_auto_mode_is_incremental_when_store_populated(): void
{
// 다른 경로(리스너)로 채워진 저장소 — auto 는 이를 재쿼리 없이 사용
$this->repository->upsertForResource('page', '1', [['loc' => url('/page/seeded'), 'contributor' => 'sirsoft-page']]);
$contributor = $this->countingContributor([
['url' => '/should-not-appear', 'resource_type' => 'product', 'resource_id' => '1'],
]);
$this->makeManager($contributor)->regenerate(SitemapGenerationMode::Auto);
$this->assertSame(0, $contributor->drainCount, '채워진 저장소에서 auto 는 기여자를 재쿼리하면 안 됩니다.');
$xml = $this->firstChildXml();
$this->assertStringContainsString(url('/page/seeded'), $xml);
$this->assertStringNotContainsString(url('/should-not-appear'), $xml);
}
/**
* incremental: 기여자 재쿼리 없이 저장소 스트림만으로 파일을 재작성한다.
*/
public function test_incremental_mode_streams_store_without_domain_requery(): void
{
$this->repository->upsertForResource('board_post', '1', [['loc' => url('/board/a/1'), 'contributor' => 'sirsoft-board']]);
$contributor = $this->countingContributor([
['url' => '/should-not-appear', 'resource_type' => 'product', 'resource_id' => '1'],
]);
$this->makeManager($contributor)->regenerate(SitemapGenerationMode::Incremental);
$this->assertSame(0, $contributor->drainCount, 'incremental 은 기여자를 재쿼리하면 안 됩니다.');
$this->assertStringContainsString(url('/board/a/1'), $this->firstChildXml());
}
}
@@ -0,0 +1,176 @@
<?php
namespace Tests\Feature\Seo;
use App\Contracts\Repositories\SitemapUrlRepositoryInterface;
use App\Models\SitemapUrl;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* SitemapUrlRepository 통합 테스트 (S4 증분 저장소)
*
* 검증 목적:
* - upsertForResource 멱등 (같은 입력 반복 호출 → 테이블 내용 동일)
* - loc 변경(슬러그 변경) 흡수 (옛 loc 행 잔존 금지)
* - removeForResource 로 리소스 단위 제거
* - streamVisible id 순서 + contributor 스코핑 + is_visible 필터
* - replaceAllForContributor 전량 대체 (타 기여자 미영향)
* - 긴 loc(2000자) 도 loc_hash unique 인덱스로 안전 저장
*/
class SitemapUrlRepositoryTest extends TestCase
{
use RefreshDatabase;
private SitemapUrlRepositoryInterface $repository;
/**
* 테스트 초기화 - 저장소를 컨테이너에서 해석합니다.
*/
protected function setUp(): void
{
parent::setUp();
$this->repository = $this->app->make(SitemapUrlRepositoryInterface::class);
}
/**
* upsertForResource: 항목을 삽입하고 반복 호출해도 테이블 내용이 동일하다(멱등).
*/
public function test_upsert_for_resource_is_idempotent(): void
{
$entries = [[
'loc' => 'https://example.com/shop/products/1',
'contributor' => 'sirsoft-ecommerce',
'lastmod' => '2026-07-18T00:00:00+00:00',
'changefreq' => 'weekly',
'priority' => 0.8,
]];
$this->repository->upsertForResource('product', '1', $entries);
$this->repository->upsertForResource('product', '1', $entries);
$rows = SitemapUrl::where('resource_type', 'product')->where('resource_id', '1')->get();
$this->assertCount(1, $rows, '같은 입력 반복 호출 시 행이 중복되면 안 됩니다.');
$this->assertSame('https://example.com/shop/products/1', $rows[0]->loc);
$this->assertSame('sirsoft-ecommerce', $rows[0]->contributor);
$this->assertSame(0.8, $rows[0]->priority);
$this->assertTrue($rows[0]->is_visible);
}
/**
* upsertForResource: loc(슬러그) 변경 시 옛 loc 행이 남지 않는다.
*/
public function test_upsert_for_resource_absorbs_loc_change(): void
{
$this->repository->upsertForResource('category', '5', [[
'loc' => 'https://example.com/shop/category/old-slug',
'contributor' => 'sirsoft-ecommerce',
]]);
$this->repository->upsertForResource('category', '5', [[
'loc' => 'https://example.com/shop/category/new-slug',
'contributor' => 'sirsoft-ecommerce',
]]);
$locs = SitemapUrl::where('resource_type', 'category')->where('resource_id', '5')->pluck('loc');
$this->assertSame(['https://example.com/shop/category/new-slug'], $locs->all());
}
/**
* removeForResource: 해당 리소스 행만 제거한다.
*/
public function test_remove_for_resource_deletes_only_that_resource(): void
{
$this->repository->upsertForResource('product', '1', [['loc' => 'https://example.com/p/1', 'contributor' => 'sirsoft-ecommerce']]);
$this->repository->upsertForResource('product', '2', [['loc' => 'https://example.com/p/2', 'contributor' => 'sirsoft-ecommerce']]);
$this->repository->removeForResource('product', '1');
$this->assertSame(0, SitemapUrl::where('resource_type', 'product')->where('resource_id', '1')->count());
$this->assertSame(1, SitemapUrl::where('resource_type', 'product')->where('resource_id', '2')->count());
}
/**
* streamVisible: is_visible=true 행을 id 순으로, contributor 스코핑하여 반환한다.
*/
public function test_stream_visible_orders_by_id_and_scopes_by_contributor(): void
{
$this->repository->upsertForResource('board_post', '1', [['loc' => 'https://example.com/board/a/1', 'contributor' => 'sirsoft-board']]);
$this->repository->upsertForResource('product', '1', [['loc' => 'https://example.com/shop/products/1', 'contributor' => 'sirsoft-ecommerce']]);
$this->repository->upsertForResource('board_post', '2', [['loc' => 'https://example.com/board/a/2', 'contributor' => 'sirsoft-board']]);
$all = collect($this->repository->streamVisible())->map(fn ($r) => $r->loc)->all();
$boardOnly = collect($this->repository->streamVisible('sirsoft-board'))->map(fn ($r) => $r->loc)->all();
$this->assertSame([
'https://example.com/board/a/1',
'https://example.com/shop/products/1',
'https://example.com/board/a/2',
], $all, 'id(삽입) 순서를 유지해야 합니다.');
$this->assertSame([
'https://example.com/board/a/1',
'https://example.com/board/a/2',
], $boardOnly, 'contributor 스코핑이 적용돼야 합니다.');
}
/**
* countVisible: 공개 행 개수를 센다.
*/
public function test_count_visible_counts_rows(): void
{
$this->assertSame(0, $this->repository->countVisible());
$this->repository->upsertForResource('page', '1', [['loc' => 'https://example.com/page/a', 'contributor' => 'sirsoft-page']]);
$this->repository->upsertForResource('page', '2', [['loc' => 'https://example.com/page/b', 'contributor' => 'sirsoft-page']]);
$this->assertSame(2, $this->repository->countVisible());
}
/**
* replaceAllForContributor: 기여자 스코프를 전량 대체하고 타 기여자는 건드리지 않는다.
*/
public function test_replace_all_for_contributor_replaces_scope_only(): void
{
// 다른 기여자(page) 는 보존돼야 한다
$this->repository->upsertForResource('page', '1', [['loc' => 'https://example.com/page/a', 'contributor' => 'sirsoft-page']]);
// board 기여자 1차 적재
$this->repository->replaceAllForContributor('sirsoft-board', [
['loc' => 'https://example.com/board/a', 'resource_type' => 'board', 'resource_id' => '1'],
['loc' => 'https://example.com/board/a/1', 'resource_type' => 'board_post', 'resource_id' => '1'],
]);
// board 기여자 2차 전량 대체 (1건으로 축소)
$this->repository->replaceAllForContributor('sirsoft-board', [
['loc' => 'https://example.com/board/b', 'resource_type' => 'board', 'resource_id' => '2'],
]);
$board = SitemapUrl::where('contributor', 'sirsoft-board')->pluck('loc')->all();
$page = SitemapUrl::where('contributor', 'sirsoft-page')->pluck('loc')->all();
$this->assertSame(['https://example.com/board/b'], $board, 'board 스코프는 전량 대체돼야 합니다.');
$this->assertSame(['https://example.com/page/a'], $page, '다른 기여자 행은 보존돼야 합니다.');
}
/**
* 긴 loc(2000자) 도 loc_hash 로 안전 저장 및 식별된다 (MySQL 키 길이 회피).
*/
public function test_long_loc_is_stored_via_hash_identity(): void
{
$longLoc = 'https://example.com/'.str_repeat('a', 1990);
$this->repository->upsertForResource('product', '9', [['loc' => $longLoc, 'contributor' => 'sirsoft-ecommerce']]);
// 동일 loc 재호출 → 멱등 (해시 identity 로 대체)
$this->repository->upsertForResource('product', '9', [['loc' => $longLoc, 'contributor' => 'sirsoft-ecommerce']]);
$rows = SitemapUrl::where('resource_type', 'product')->where('resource_id', '9')->get();
$this->assertCount(1, $rows);
$this->assertSame($longLoc, $rows[0]->loc);
$this->assertSame(hash('sha256', $longLoc), $rows[0]->loc_hash);
}
}
@@ -2,6 +2,7 @@
namespace Tests\Unit\Console\Commands;
use App\Enums\SitemapGenerationMode;
use App\Jobs\GenerateSitemapJob;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Bus;
@@ -12,7 +13,8 @@ use Tests\TestCase;
/**
* SeoGenerateSitemapCommand 유닛 테스트
*
* seo:generate-sitemap 커맨드의 큐 드라이버 분기, 강제 동기, 출력 메시지를 검증합니다.
* seo:generate-sitemap 커맨드의 큐 드라이버 분기, 강제 동기, 모드 옵션(--mode/--rebuild),
* 출력 메시지를 검증합니다.
*/
class SeoGenerateSitemapCommandTest extends TestCase
{
@@ -31,10 +33,10 @@ class SeoGenerateSitemapCommandTest extends TestCase
Bus::fake([GenerateSitemapJob::class]);
$this->artisan('seo:generate-sitemap')
->expectsOutput('Sitemap 생성이 큐에 디스패치되었습니다.')
->expectsOutput('Sitemap 생성이 큐에 디스패치되었습니다. (모드: auto)')
->assertExitCode(Command::SUCCESS);
Bus::assertDispatched(GenerateSitemapJob::class);
Bus::assertDispatched(GenerateSitemapJob::class, fn (GenerateSitemapJob $job) => $job->mode === SitemapGenerationMode::Auto);
Bus::assertNotDispatchedSync(GenerateSitemapJob::class);
}
@@ -47,7 +49,7 @@ class SeoGenerateSitemapCommandTest extends TestCase
Bus::fake([GenerateSitemapJob::class]);
$this->artisan('seo:generate-sitemap')
->expectsOutput('Sitemap이 생성되었습니다.')
->expectsOutput('Sitemap이 생성되었습니다. (모드: auto)')
->assertExitCode(Command::SUCCESS);
Bus::assertDispatchedSync(GenerateSitemapJob::class);
@@ -62,9 +64,53 @@ class SeoGenerateSitemapCommandTest extends TestCase
Bus::fake([GenerateSitemapJob::class]);
$this->artisan('seo:generate-sitemap', ['--sync' => true])
->expectsOutput('Sitemap이 생성되었습니다.')
->expectsOutput('Sitemap이 생성되었습니다. (모드: auto)')
->assertExitCode(Command::SUCCESS);
Bus::assertDispatchedSync(GenerateSitemapJob::class);
}
/**
* --mode 옵션이 잡에 그대로 전달됩니다.
*/
public function test_command_passes_mode_option_to_job(): void
{
Config::set('queue.default', 'database');
Bus::fake([GenerateSitemapJob::class]);
$this->artisan('seo:generate-sitemap', ['--mode' => 'incremental'])
->expectsOutput('Sitemap 생성이 큐에 디스패치되었습니다. (모드: incremental)')
->assertExitCode(Command::SUCCESS);
Bus::assertDispatched(GenerateSitemapJob::class, fn (GenerateSitemapJob $job) => $job->mode === SitemapGenerationMode::Incremental);
}
/**
* --rebuild 옵션은 --mode 보다 우선하며 full 로 강제합니다.
*/
public function test_rebuild_option_forces_full_mode(): void
{
Config::set('queue.default', 'database');
Bus::fake([GenerateSitemapJob::class]);
$this->artisan('seo:generate-sitemap', ['--rebuild' => true, '--mode' => 'incremental'])
->expectsOutput('Sitemap 생성이 큐에 디스패치되었습니다. (모드: full)')
->assertExitCode(Command::SUCCESS);
Bus::assertDispatched(GenerateSitemapJob::class, fn (GenerateSitemapJob $job) => $job->mode === SitemapGenerationMode::Full);
}
/**
* 잘못된 --mode 값은 INVALID 로 거부하고 잡을 디스패치하지 않습니다.
*/
public function test_invalid_mode_is_rejected(): void
{
Config::set('queue.default', 'database');
Bus::fake([GenerateSitemapJob::class]);
$this->artisan('seo:generate-sitemap', ['--mode' => 'bogus'])
->assertExitCode(Command::INVALID);
Bus::assertNotDispatched(GenerateSitemapJob::class);
}
}
+26 -2
View File
@@ -4,12 +4,14 @@ namespace Tests\Unit\Seo;
use App\Contracts\Extension\CacheInterface;
use App\Contracts\Repositories\ConfigRepositoryInterface;
use App\Contracts\Repositories\SitemapUrlRepositoryInterface;
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\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Storage;
use Mockery;
@@ -31,6 +33,8 @@ use Tests\TestCase;
*/
class SitemapManagerTest extends TestCase
{
use RefreshDatabase;
/**
* 이 테스트가 등록·검증하는 sitemap 훅 목록
*/
@@ -128,6 +132,7 @@ class SitemapManagerTest extends TestCase
$cache ?? Mockery::spy(CacheInterface::class),
$config ?? Mockery::spy(ConfigRepositoryInterface::class),
$this->storage,
$this->app->make(SitemapUrlRepositoryInterface::class),
);
}
@@ -299,13 +304,14 @@ class SitemapManagerTest extends TestCase
// 생성 도중 예외를 던지는 generator 로 실패를 강제한다.
$generator = Mockery::mock(SitemapGenerator::class);
$generator->shouldReceive('generateToWriter')->andThrow(new \RuntimeException('디스크 장애'));
$generator->shouldReceive('generateToWriterFromEntries')->andThrow(new \RuntimeException('디스크 장애'));
$manager = new SitemapManager(
$generator,
Mockery::spy(CacheInterface::class),
Mockery::spy(ConfigRepositoryInterface::class),
$this->storage,
$this->incrementalRepository(),
);
$result = $manager->regenerate();
@@ -329,18 +335,36 @@ class SitemapManagerTest extends TestCase
$cache->shouldNotReceive('forget');
$generator = Mockery::mock(SitemapGenerator::class);
$generator->shouldReceive('generateToWriter')->andThrow(new \RuntimeException('장애'));
$generator->shouldReceive('generateToWriterFromEntries')->andThrow(new \RuntimeException('장애'));
$manager = new SitemapManager(
$generator,
$cache,
Mockery::spy(ConfigRepositoryInterface::class),
$this->storage,
$this->incrementalRepository(),
);
$this->assertFalse($manager->regenerate()['success']);
}
/**
* incremental 모드로 진입시키는(테이블이 비어있지 않은) mock 저장소를 만듭니다.
*
* countVisible()>0 → auto 가 incremental 로 해석되어 rebuildStore(전체 재적재)를 건너뛰고
* 곧바로 generateToWriterFromEntries 로 진입합니다(실패 경로 단순화).
*
* @return SitemapUrlRepositoryInterface mock 저장소
*/
private function incrementalRepository(): SitemapUrlRepositoryInterface
{
$repository = Mockery::mock(SitemapUrlRepositoryInterface::class);
$repository->shouldReceive('countVisible')->andReturn(1);
$repository->shouldReceive('streamVisible')->andReturn([]);
return $repository;
}
/**
* regenerate: seo.sitemap_urls_per_file 설정이 자식 분할에 반영된다
*/