v7.0.0-beta.1 release
This commit is contained in:
commit
6595fd0eb5
3967 files changed
+1875383
No files matched your search
@@ -0,0 +1,181 @@
|
||||
<?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']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Seo\BotDetector;
|
||||
use Illuminate\Http\Request;
|
||||
use Tests\TestCase;
|
||||
|
||||
class BotDetectorTest extends TestCase
|
||||
{
|
||||
private BotDetector $detector;
|
||||
|
||||
/**
|
||||
* 테스트 초기화 - BotDetector 인스턴스 및 기본 설정을 준비합니다.
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->detector = new BotDetector;
|
||||
|
||||
// 기본 설정: 봇 감지 활성화 + 주요 봇 UA 패턴
|
||||
config()->set('g7_settings.core.seo.bot_detection_enabled', true);
|
||||
config()->set('g7_settings.core.seo.bot_user_agents', [
|
||||
'Googlebot',
|
||||
'Bingbot',
|
||||
'Yeti',
|
||||
'Naverbot',
|
||||
'Slurp',
|
||||
'DuckDuckBot',
|
||||
'Baiduspider',
|
||||
'facebookexternalhit',
|
||||
'Twitterbot',
|
||||
'LinkedInBot',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 주어진 User-Agent 문자열로 Request를 생성합니다.
|
||||
*
|
||||
* @param string $userAgent User-Agent 문자열
|
||||
* @param array $query 쿼리 파라미터
|
||||
* @return Request 생성된 요청 객체
|
||||
*/
|
||||
private function createRequest(string $userAgent = '', array $query = []): Request
|
||||
{
|
||||
$server = [];
|
||||
if ($userAgent !== '') {
|
||||
$server['HTTP_USER_AGENT'] = $userAgent;
|
||||
}
|
||||
|
||||
return Request::create('/', 'GET', $query, [], [], $server);
|
||||
}
|
||||
|
||||
/**
|
||||
* Googlebot User-Agent를 봇으로 감지합니다.
|
||||
*/
|
||||
public function test_detects_googlebot(): void
|
||||
{
|
||||
$request = $this->createRequest('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)');
|
||||
|
||||
$this->assertTrue($this->detector->isBot($request));
|
||||
}
|
||||
|
||||
/**
|
||||
* Bingbot User-Agent를 봇으로 감지합니다.
|
||||
*/
|
||||
public function test_detects_bingbot(): void
|
||||
{
|
||||
$request = $this->createRequest('Mozilla/5.0 (compatible; Bingbot/2.0; +http://www.bing.com/bingbot.htm)');
|
||||
|
||||
$this->assertTrue($this->detector->isBot($request));
|
||||
}
|
||||
|
||||
/**
|
||||
* Naverbot User-Agent를 봇으로 감지합니다.
|
||||
*/
|
||||
public function test_detects_naverbot(): void
|
||||
{
|
||||
$request = $this->createRequest('Mozilla/5.0 (compatible; Naverbot/1.0; +http://naver.me/bot)');
|
||||
|
||||
$this->assertTrue($this->detector->isBot($request));
|
||||
}
|
||||
|
||||
/**
|
||||
* Yeti User-Agent를 봇으로 감지합니다.
|
||||
*/
|
||||
public function test_detects_yeti(): void
|
||||
{
|
||||
$request = $this->createRequest('Yeti/1.1 (Naver Corp.; http://help.naver.com/robots/)');
|
||||
|
||||
$this->assertTrue($this->detector->isBot($request));
|
||||
}
|
||||
|
||||
/**
|
||||
* 일반 Chrome User-Agent는 봇이 아닙니다.
|
||||
*/
|
||||
public function test_normal_chrome_ua_is_not_bot(): void
|
||||
{
|
||||
$request = $this->createRequest('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
|
||||
|
||||
$this->assertFalse($this->detector->isBot($request));
|
||||
}
|
||||
|
||||
/**
|
||||
* 일반 Safari User-Agent는 봇이 아닙니다.
|
||||
*/
|
||||
public function test_normal_safari_ua_is_not_bot(): void
|
||||
{
|
||||
$request = $this->createRequest('Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15');
|
||||
|
||||
$this->assertFalse($this->detector->isBot($request));
|
||||
}
|
||||
|
||||
/**
|
||||
* 빈 User-Agent는 봇이 아닙니다.
|
||||
*/
|
||||
public function test_empty_ua_is_not_bot(): void
|
||||
{
|
||||
$request = $this->createRequest('');
|
||||
|
||||
$this->assertFalse($this->detector->isBot($request));
|
||||
}
|
||||
|
||||
/**
|
||||
* _escaped_fragment_ 쿼리 파라미터가 있으면 일반 UA여도 봇으로 감지합니다.
|
||||
*/
|
||||
public function test_escaped_fragment_param_detected_as_bot(): void
|
||||
{
|
||||
$request = $this->createRequest(
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0',
|
||||
['_escaped_fragment_' => '']
|
||||
);
|
||||
|
||||
$this->assertTrue($this->detector->isBot($request));
|
||||
}
|
||||
|
||||
/**
|
||||
* 대소문자를 구분하지 않고 봇 패턴을 매칭합니다.
|
||||
*/
|
||||
public function test_case_insensitive_bot_detection(): void
|
||||
{
|
||||
$request = $this->createRequest('Mozilla/5.0 (compatible; googleBot/2.1)');
|
||||
|
||||
$this->assertTrue($this->detector->isBot($request));
|
||||
}
|
||||
|
||||
/**
|
||||
* bot_detection_enabled=false일 때 항상 false를 반환합니다.
|
||||
*/
|
||||
public function test_returns_false_when_detection_disabled(): void
|
||||
{
|
||||
config()->set('g7_settings.core.seo.bot_detection_enabled', false);
|
||||
|
||||
$googlebot = $this->createRequest('Googlebot/2.1');
|
||||
$this->assertFalse($this->detector->isBot($googlebot));
|
||||
|
||||
$fragment = $this->createRequest('Chrome', ['_escaped_fragment_' => '']);
|
||||
$this->assertFalse($this->detector->isBot($fragment));
|
||||
}
|
||||
|
||||
/**
|
||||
* 커스텀 봇 패턴이 추가되면 해당 패턴도 매칭합니다.
|
||||
*/
|
||||
public function test_custom_bot_pattern_matches(): void
|
||||
{
|
||||
config()->set('g7_settings.core.seo.bot_user_agents', [
|
||||
'Googlebot',
|
||||
'MyCustomCrawler',
|
||||
]);
|
||||
|
||||
$request = $this->createRequest('MyCustomCrawler/1.0');
|
||||
|
||||
$this->assertTrue($this->detector->isBot($request));
|
||||
}
|
||||
|
||||
/**
|
||||
* bot_user_agents가 빈 배열이면 모든 요청이 봇이 아닙니다.
|
||||
*/
|
||||
public function test_empty_bot_patterns_returns_false_for_all(): void
|
||||
{
|
||||
config()->set('g7_settings.core.seo.bot_user_agents', []);
|
||||
|
||||
$googlebot = $this->createRequest('Googlebot/2.1');
|
||||
$this->assertFalse($this->detector->isBot($googlebot));
|
||||
|
||||
$chrome = $this->createRequest('Mozilla/5.0 Chrome/120.0.0.0');
|
||||
$this->assertFalse($this->detector->isBot($chrome));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,465 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Seo\DataSourceResolver;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* DataSourceResolver 단위 테스트
|
||||
*
|
||||
* 내부 API 호출을 통한 데이터 소스 해석 기능을 테스트합니다.
|
||||
* Http::fake()를 사용하여 외부 HTTP 호출을 모킹합니다.
|
||||
*/
|
||||
class DataSourceResolverTest extends TestCase
|
||||
{
|
||||
private DataSourceResolver $resolver;
|
||||
|
||||
/**
|
||||
* 테스트 초기화 - DataSourceResolver 인스턴스를 준비합니다.
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->resolver = new DataSourceResolver;
|
||||
}
|
||||
|
||||
/**
|
||||
* 정상 API 호출 시 데이터 소스 ID에 응답 데이터가 매핑됩니다.
|
||||
*/
|
||||
public function test_normal_api_call_maps_data_to_ds_id(): void
|
||||
{
|
||||
$responseData = ['data' => ['id' => 1, 'name' => '상품A']];
|
||||
|
||||
Http::fake([
|
||||
'*/api/products/123' => Http::response($responseData, 200),
|
||||
]);
|
||||
|
||||
$dataSources = [
|
||||
['id' => 'product', 'endpoint' => '/api/products/123', 'method' => 'GET'],
|
||||
];
|
||||
|
||||
$result = $this->resolver->resolve($dataSources, ['product'], [], 'ko');
|
||||
|
||||
$this->assertArrayHasKey('product', $result);
|
||||
$this->assertSame($responseData, $result['product']);
|
||||
}
|
||||
|
||||
/**
|
||||
* API 타임아웃 발생 시 fallback 데이터를 반환합니다.
|
||||
*/
|
||||
public function test_api_timeout_returns_fallback_data(): void
|
||||
{
|
||||
Http::fake([
|
||||
'*' => function () {
|
||||
throw new ConnectionException('Connection timed out');
|
||||
},
|
||||
]);
|
||||
|
||||
$fallback = ['data' => ['name' => '기본값']];
|
||||
$dataSources = [
|
||||
['id' => 'product', 'endpoint' => '/api/products/1', 'method' => 'GET', 'fallback' => $fallback],
|
||||
];
|
||||
|
||||
$result = $this->resolver->resolve($dataSources, ['product'], [], 'ko');
|
||||
|
||||
$this->assertSame($fallback, $result['product']);
|
||||
}
|
||||
|
||||
/**
|
||||
* API 404 응답 시 fallback 데이터를 반환합니다.
|
||||
*/
|
||||
public function test_api_404_returns_fallback_data(): void
|
||||
{
|
||||
Http::fake([
|
||||
'*' => Http::response(['error' => 'Not Found'], 404),
|
||||
]);
|
||||
|
||||
$fallback = ['data' => []];
|
||||
$dataSources = [
|
||||
['id' => 'product', 'endpoint' => '/api/products/999', 'method' => 'GET', 'fallback' => $fallback],
|
||||
];
|
||||
|
||||
$result = $this->resolver->resolve($dataSources, ['product'], [], 'ko');
|
||||
|
||||
$this->assertSame($fallback, $result['product']);
|
||||
}
|
||||
|
||||
/**
|
||||
* API 500 응답 시 fallback 데이터를 반환합니다.
|
||||
*/
|
||||
public function test_api_500_returns_fallback_data(): void
|
||||
{
|
||||
Http::fake([
|
||||
'*' => Http::response(['error' => 'Server Error'], 500),
|
||||
]);
|
||||
|
||||
$fallback = ['data' => ['default' => true]];
|
||||
$dataSources = [
|
||||
['id' => 'product', 'endpoint' => '/api/products/1', 'method' => 'GET', 'fallback' => $fallback],
|
||||
];
|
||||
|
||||
$result = $this->resolver->resolve($dataSources, ['product'], [], 'ko');
|
||||
|
||||
$this->assertSame($fallback, $result['product']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 라우트 파라미터 {{route.id}} 패턴이 실제 값으로 치환됩니다.
|
||||
*/
|
||||
public function test_route_params_substitution(): void
|
||||
{
|
||||
$responseData = ['data' => ['id' => 456, 'name' => '상품B']];
|
||||
|
||||
Http::fake([
|
||||
'*/api/products/456' => Http::response($responseData, 200),
|
||||
]);
|
||||
|
||||
$dataSources = [
|
||||
['id' => 'product', 'endpoint' => '/api/products/{{route.id}}', 'method' => 'GET'],
|
||||
];
|
||||
|
||||
$result = $this->resolver->resolve($dataSources, ['product'], ['id' => '456'], 'ko');
|
||||
|
||||
$this->assertArrayHasKey('product', $result);
|
||||
$this->assertSame($responseData, $result['product']);
|
||||
|
||||
Http::assertSent(function ($request) {
|
||||
return str_contains($request->url(), '/api/products/456');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* seoDataSourceIds에 포함되지 않은 데이터 소스는 호출하지 않습니다.
|
||||
*/
|
||||
public function test_ds_id_not_in_seo_data_source_ids_is_not_called(): void
|
||||
{
|
||||
Http::fake([
|
||||
'*' => Http::response(['data' => []], 200),
|
||||
]);
|
||||
|
||||
$dataSources = [
|
||||
['id' => 'product', 'endpoint' => '/api/products/1', 'method' => 'GET'],
|
||||
['id' => 'sidebar', 'endpoint' => '/api/sidebar', 'method' => 'GET'],
|
||||
];
|
||||
|
||||
$result = $this->resolver->resolve($dataSources, ['product'], [], 'ko');
|
||||
|
||||
$this->assertArrayHasKey('product', $result);
|
||||
$this->assertArrayNotHasKey('sidebar', $result);
|
||||
|
||||
Http::assertSentCount(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept-Language 헤더가 로케일 값으로 전달됩니다.
|
||||
*/
|
||||
public function test_accept_language_header_passed(): void
|
||||
{
|
||||
Http::fake([
|
||||
'*' => Http::response(['data' => []], 200),
|
||||
]);
|
||||
|
||||
$dataSources = [
|
||||
['id' => 'product', 'endpoint' => '/api/products/1', 'method' => 'GET'],
|
||||
];
|
||||
|
||||
$this->resolver->resolve($dataSources, ['product'], [], 'en');
|
||||
|
||||
Http::assertSent(function ($request) {
|
||||
return $request->header('Accept-Language')[0] === 'en'
|
||||
&& $request->header('Accept')[0] === 'application/json';
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 쿼리 파라미터가 포함된 엔드포인트를 정상 호출합니다.
|
||||
*/
|
||||
public function test_query_params_in_endpoint(): void
|
||||
{
|
||||
$responseData = ['data' => ['items' => []]];
|
||||
|
||||
Http::fake([
|
||||
'*' => Http::response($responseData, 200),
|
||||
]);
|
||||
|
||||
$dataSources = [
|
||||
['id' => 'search', 'endpoint' => '/api/products?category=shoes&page=1', 'method' => 'GET'],
|
||||
];
|
||||
|
||||
$result = $this->resolver->resolve($dataSources, ['search'], [], 'ko');
|
||||
|
||||
$this->assertSame($responseData, $result['search']);
|
||||
|
||||
Http::assertSent(function ($request) {
|
||||
return str_contains($request->url(), 'category=shoes')
|
||||
&& str_contains($request->url(), 'page=1');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 빈 엔드포인트는 건너뜁니다.
|
||||
*/
|
||||
public function test_empty_endpoint_skipped(): void
|
||||
{
|
||||
Http::fake([
|
||||
'*' => Http::response(['data' => []], 200),
|
||||
]);
|
||||
|
||||
$dataSources = [
|
||||
['id' => 'product', 'endpoint' => '', 'method' => 'GET'],
|
||||
];
|
||||
|
||||
$result = $this->resolver->resolve($dataSources, ['product'], [], 'ko');
|
||||
|
||||
$this->assertArrayNotHasKey('product', $result);
|
||||
Http::assertNothingSent();
|
||||
}
|
||||
|
||||
/**
|
||||
* 여러 라우트 파라미터가 동시에 치환됩니다.
|
||||
*/
|
||||
public function test_multiple_route_params_substituted(): void
|
||||
{
|
||||
$responseData = ['data' => ['id' => 10]];
|
||||
|
||||
Http::fake([
|
||||
'*' => Http::response($responseData, 200),
|
||||
]);
|
||||
|
||||
$dataSources = [
|
||||
['id' => 'item', 'endpoint' => '/api/categories/{{route.category}}/products/{{route.id}}', 'method' => 'GET'],
|
||||
];
|
||||
|
||||
$result = $this->resolver->resolve($dataSources, ['item'], ['category' => 'shoes', 'id' => '10'], 'ko');
|
||||
|
||||
Http::assertSent(function ($request) {
|
||||
return str_contains($request->url(), '/api/categories/shoes/products/10');
|
||||
});
|
||||
|
||||
$this->assertSame($responseData, $result['item']);
|
||||
}
|
||||
|
||||
/**
|
||||
* fallback이 정의되지 않은 경우 빈 배열을 반환합니다.
|
||||
*/
|
||||
public function test_no_fallback_defined_returns_empty_array(): void
|
||||
{
|
||||
Http::fake([
|
||||
'*' => Http::response(null, 500),
|
||||
]);
|
||||
|
||||
$dataSources = [
|
||||
['id' => 'product', 'endpoint' => '/api/products/1', 'method' => 'GET'],
|
||||
];
|
||||
|
||||
$result = $this->resolver->resolve($dataSources, ['product'], [], 'ko');
|
||||
|
||||
$this->assertSame([], $result['product']);
|
||||
}
|
||||
|
||||
/**
|
||||
* optional chaining {{route?.slug}} 패턴이 정상 치환됩니다.
|
||||
*/
|
||||
public function test_optional_chaining_route_params_substitution(): void
|
||||
{
|
||||
$responseData = ['data' => ['id' => 1, 'title' => '페이지']];
|
||||
|
||||
Http::fake([
|
||||
'*/api/pages/my-page' => Http::response($responseData, 200),
|
||||
]);
|
||||
|
||||
$dataSources = [
|
||||
['id' => 'page', 'endpoint' => '/api/pages/{{route?.slug}}', 'method' => 'GET'],
|
||||
];
|
||||
|
||||
$result = $this->resolver->resolve($dataSources, ['page'], ['slug' => 'my-page'], 'ko');
|
||||
|
||||
$this->assertArrayHasKey('page', $result);
|
||||
$this->assertSame($responseData, $result['page']);
|
||||
|
||||
Http::assertSent(function ($request) {
|
||||
return str_contains($request->url(), '/api/pages/my-page');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* POST 메서드 데이터 소스를 호출합니다.
|
||||
*/
|
||||
public function test_post_method_data_source(): void
|
||||
{
|
||||
$responseData = ['data' => ['results' => []]];
|
||||
|
||||
Http::fake([
|
||||
'*' => Http::response($responseData, 200),
|
||||
]);
|
||||
|
||||
$dataSources = [
|
||||
['id' => 'search', 'endpoint' => '/api/search', 'method' => 'POST'],
|
||||
];
|
||||
|
||||
$result = $this->resolver->resolve($dataSources, ['search'], [], 'ko');
|
||||
|
||||
$this->assertSame($responseData, $result['search']);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// params 해석 + 쿼리 파라미터 전달 테스트
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* params의 {{query.xxx}} 표현식이 쿼리 파라미터에서 해석됩니다.
|
||||
*/
|
||||
public function test_params_resolve_query_expressions(): void
|
||||
{
|
||||
$responseData = ['data' => [['id' => 1]]];
|
||||
|
||||
Http::fake([
|
||||
'*' => Http::response($responseData, 200),
|
||||
]);
|
||||
|
||||
$dataSources = [
|
||||
[
|
||||
'id' => 'products',
|
||||
'endpoint' => '/api/products',
|
||||
'method' => 'GET',
|
||||
'params' => [
|
||||
'page' => '{{query.page ?? 1}}',
|
||||
'per_page' => 12,
|
||||
'sort' => '{{query.sort ?? \'latest\'}}',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$queryParams = ['page' => '2', 'sort' => 'price_asc'];
|
||||
|
||||
$result = $this->resolver->resolve($dataSources, ['products'], [], 'ko', $queryParams);
|
||||
|
||||
$this->assertSame($responseData, $result['products']);
|
||||
|
||||
Http::assertSent(function ($request) {
|
||||
$url = $request->url();
|
||||
|
||||
return str_contains($url, 'page=2')
|
||||
&& str_contains($url, 'per_page=12')
|
||||
&& str_contains($url, 'sort=price_asc');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* params의 {{route.xxx}} 표현식이 라우트 파라미터에서 해석됩니다.
|
||||
*/
|
||||
public function test_params_resolve_route_expressions(): void
|
||||
{
|
||||
Http::fake([
|
||||
'*' => Http::response(['data' => []], 200),
|
||||
]);
|
||||
|
||||
$dataSources = [
|
||||
[
|
||||
'id' => 'products',
|
||||
'endpoint' => '/api/products',
|
||||
'method' => 'GET',
|
||||
'params' => [
|
||||
'category_slug' => '{{route.slug}}',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$this->resolver->resolve($dataSources, ['products'], ['slug' => 'shoes'], 'ko');
|
||||
|
||||
Http::assertSent(function ($request) {
|
||||
return str_contains($request->url(), 'category_slug=shoes');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* params에서 빈 문자열로 해석된 선택적 파라미터는 전달되지 않습니다.
|
||||
*/
|
||||
public function test_params_empty_optional_param_not_sent(): void
|
||||
{
|
||||
Http::fake([
|
||||
'*' => Http::response(['data' => []], 200),
|
||||
]);
|
||||
|
||||
$dataSources = [
|
||||
[
|
||||
'id' => 'products',
|
||||
'endpoint' => '/api/products',
|
||||
'method' => 'GET',
|
||||
'params' => [
|
||||
'search' => "{{query.keyword ?? ''}}",
|
||||
'page' => '{{query.page ?? 1}}',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
// keyword 없음 → search 파라미터 미전달
|
||||
$this->resolver->resolve($dataSources, ['products'], [], 'ko', []);
|
||||
|
||||
Http::assertSent(function ($request) {
|
||||
$url = $request->url();
|
||||
|
||||
return str_contains($url, 'page=1')
|
||||
&& ! str_contains($url, 'search=');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* params가 비어있으면 쿼리 파라미터 없이 호출합니다.
|
||||
*/
|
||||
public function test_params_empty_no_query_string(): void
|
||||
{
|
||||
Http::fake([
|
||||
'*/api/products' => Http::response(['data' => []], 200),
|
||||
]);
|
||||
|
||||
$dataSources = [
|
||||
[
|
||||
'id' => 'products',
|
||||
'endpoint' => '/api/products',
|
||||
'method' => 'GET',
|
||||
'params' => [],
|
||||
],
|
||||
];
|
||||
|
||||
$this->resolver->resolve($dataSources, ['products'], [], 'ko', ['page' => '2']);
|
||||
|
||||
Http::assertSent(function ($request) {
|
||||
// params가 빈 배열이면 query string 미추가
|
||||
return ! str_contains($request->url(), '?');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 숫자 리터럴 params는 그대로 전달됩니다.
|
||||
*/
|
||||
public function test_params_numeric_literal_passed_as_is(): void
|
||||
{
|
||||
Http::fake([
|
||||
'*' => Http::response(['data' => []], 200),
|
||||
]);
|
||||
|
||||
$dataSources = [
|
||||
[
|
||||
'id' => 'products',
|
||||
'endpoint' => '/api/products',
|
||||
'method' => 'GET',
|
||||
'params' => [
|
||||
'per_page' => 12,
|
||||
'page' => '{{query.page ?? 1}}',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$this->resolver->resolve($dataSources, ['products'], [], 'ko', ['page' => '3']);
|
||||
|
||||
Http::assertSent(function ($request) {
|
||||
return str_contains($request->url(), 'per_page=12')
|
||||
&& str_contains($request->url(), 'page=3');
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
<?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']);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,274 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo\Listeners;
|
||||
|
||||
use App\Listeners\SeoExtensionCacheListener;
|
||||
use App\Seo\Contracts\SeoCacheManagerInterface;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 확장 라이프사이클 SEO 캐시 무효화 리스너 테스트
|
||||
*
|
||||
* 모듈/플러그인/템플릿 설치·활성화·업데이트 시
|
||||
* 전체 SEO 캐시 삭제를 검증합니다.
|
||||
*/
|
||||
class SeoExtensionCacheListenerTest extends TestCase
|
||||
{
|
||||
private SeoExtensionCacheListener $listener;
|
||||
|
||||
private SeoCacheManagerInterface $cacheMock;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->cacheMock = Mockery::mock(SeoCacheManagerInterface::class);
|
||||
$this->app->instance(SeoCacheManagerInterface::class, $this->cacheMock);
|
||||
|
||||
$this->listener = new SeoExtensionCacheListener;
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Mockery::close();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
// ─── 훅 구독 등록 ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 9개 확장 라이프사이클 훅이 올바르게 등록되어 있는지 확인합니다.
|
||||
*/
|
||||
public function test_get_subscribed_hooks_returns_all_9_extension_hooks(): void
|
||||
{
|
||||
$hooks = SeoExtensionCacheListener::getSubscribedHooks();
|
||||
|
||||
$expectedHooks = [
|
||||
'core.modules.installed',
|
||||
'core.modules.activated',
|
||||
'core.modules.updated',
|
||||
'core.plugins.installed',
|
||||
'core.plugins.activated',
|
||||
'core.plugins.updated',
|
||||
'core.templates.installed',
|
||||
'core.templates.activated',
|
||||
'core.templates.updated',
|
||||
];
|
||||
|
||||
$this->assertCount(9, $hooks);
|
||||
|
||||
foreach ($expectedHooks as $hookName) {
|
||||
$this->assertArrayHasKey($hookName, $hooks);
|
||||
$this->assertEquals('onExtensionChanged', $hooks[$hookName]['method']);
|
||||
$this->assertEquals(30, $hooks[$hookName]['priority']);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 모듈 라이프사이클 ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 모듈 설치 시 전체 SEO 캐시 + sitemap 삭제 확인
|
||||
*/
|
||||
public function test_on_module_install_clears_all_seo_cache(): void
|
||||
{
|
||||
$this->cacheMock->shouldReceive('clearAll')->once();
|
||||
|
||||
Cache::shouldReceive('forget')
|
||||
->once()
|
||||
->with('seo:sitemap');
|
||||
|
||||
Log::shouldReceive('info')
|
||||
->once()
|
||||
->with('[SEO] Extension changed — all cache cleared', Mockery::on(function ($context) {
|
||||
return $context['identifier'] === 'sirsoft-ecommerce';
|
||||
}));
|
||||
|
||||
$this->listener->onExtensionChanged('sirsoft-ecommerce', ['name' => 'Ecommerce']);
|
||||
|
||||
$this->addToAssertionCount(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 활성화 시 전체 SEO 캐시 + sitemap 삭제 확인
|
||||
*/
|
||||
public function test_on_module_activate_clears_all_seo_cache(): void
|
||||
{
|
||||
$this->cacheMock->shouldReceive('clearAll')->once();
|
||||
|
||||
Cache::shouldReceive('forget')
|
||||
->once()
|
||||
->with('seo:sitemap');
|
||||
|
||||
Log::shouldReceive('info')->once();
|
||||
|
||||
$this->listener->onExtensionChanged('sirsoft-ecommerce', ['name' => 'Ecommerce']);
|
||||
|
||||
$this->addToAssertionCount(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 업데이트 시 전체 SEO 캐시 + sitemap 삭제 확인
|
||||
*/
|
||||
public function test_on_module_update_clears_all_seo_cache(): void
|
||||
{
|
||||
$this->cacheMock->shouldReceive('clearAll')->once();
|
||||
|
||||
Cache::shouldReceive('forget')
|
||||
->once()
|
||||
->with('seo:sitemap');
|
||||
|
||||
Log::shouldReceive('info')->once();
|
||||
|
||||
$this->listener->onExtensionChanged('sirsoft-ecommerce', ['success' => true], ['name' => 'Ecommerce']);
|
||||
|
||||
$this->addToAssertionCount(1);
|
||||
}
|
||||
|
||||
// ─── 플러그인 라이프사이클 ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 플러그인 설치 시 전체 SEO 캐시 + sitemap 삭제 확인
|
||||
*/
|
||||
public function test_on_plugin_install_clears_all_seo_cache(): void
|
||||
{
|
||||
$this->cacheMock->shouldReceive('clearAll')->once();
|
||||
|
||||
Cache::shouldReceive('forget')
|
||||
->once()
|
||||
->with('seo:sitemap');
|
||||
|
||||
Log::shouldReceive('info')->once();
|
||||
|
||||
$this->listener->onExtensionChanged('sirsoft-payment', ['name' => 'Payment']);
|
||||
|
||||
$this->addToAssertionCount(1);
|
||||
}
|
||||
|
||||
// ─── 템플릿 라이프사이클 ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 템플릿 활성화 시 전체 SEO 캐시 + sitemap 삭제 확인
|
||||
*/
|
||||
public function test_on_template_activate_clears_all_seo_cache(): void
|
||||
{
|
||||
$this->cacheMock->shouldReceive('clearAll')->once();
|
||||
|
||||
Cache::shouldReceive('forget')
|
||||
->once()
|
||||
->with('seo:sitemap');
|
||||
|
||||
Log::shouldReceive('info')->once();
|
||||
|
||||
// 템플릿 활성화는 Template model 객체가 전달됨
|
||||
$templateModel = Mockery::mock();
|
||||
$templateModel->shouldReceive('getIdentifier')
|
||||
->andReturn('sirsoft-basic');
|
||||
|
||||
$this->listener->onExtensionChanged($templateModel);
|
||||
|
||||
$this->addToAssertionCount(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 버전 업데이트 시 전체 SEO 캐시 + sitemap 삭제 확인
|
||||
*/
|
||||
public function test_on_template_version_update_clears_all_seo_cache(): void
|
||||
{
|
||||
$this->cacheMock->shouldReceive('clearAll')->once();
|
||||
|
||||
Cache::shouldReceive('forget')
|
||||
->once()
|
||||
->with('seo:sitemap');
|
||||
|
||||
Log::shouldReceive('info')->once();
|
||||
|
||||
$this->listener->onExtensionChanged('sirsoft-basic', ['success' => true], ['name' => 'Basic']);
|
||||
|
||||
$this->addToAssertionCount(1);
|
||||
}
|
||||
|
||||
// ─── 예외 처리 ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 캐시 삭제 중 예외 발생 시 graceful하게 처리되는지 확인
|
||||
*/
|
||||
public function test_handles_exceptions_gracefully(): void
|
||||
{
|
||||
$this->cacheMock->shouldReceive('clearAll')
|
||||
->andThrow(new \RuntimeException('Cache unavailable'));
|
||||
|
||||
Log::shouldReceive('warning')
|
||||
->once()
|
||||
->with('[SEO] Extension cache invalidation failed', Mockery::on(function ($context) {
|
||||
return $context['error'] === 'Cache unavailable'
|
||||
&& $context['identifier'] === 'sirsoft-ecommerce';
|
||||
}));
|
||||
|
||||
$this->listener->onExtensionChanged('sirsoft-ecommerce', ['name' => 'Ecommerce']);
|
||||
|
||||
$this->addToAssertionCount(1);
|
||||
}
|
||||
|
||||
// ─── handle (인터페이스 준수) ───────────────────────────
|
||||
|
||||
/**
|
||||
* handle 메서드가 존재하는지 확인합니다 (HookListenerInterface 준수).
|
||||
*/
|
||||
public function test_handle_method_exists(): void
|
||||
{
|
||||
$this->assertTrue(method_exists($this->listener, 'handle'));
|
||||
$this->listener->handle();
|
||||
}
|
||||
|
||||
// ─── 로그 검증 ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 로그에 확장 식별자 정보가 포함되는지 확인
|
||||
*/
|
||||
public function test_log_includes_extension_context(): void
|
||||
{
|
||||
$this->cacheMock->shouldReceive('clearAll')->once();
|
||||
|
||||
Cache::shouldReceive('forget')
|
||||
->once()
|
||||
->with('seo:sitemap');
|
||||
|
||||
Log::shouldReceive('info')
|
||||
->once()
|
||||
->with('[SEO] Extension changed — all cache cleared', Mockery::on(function ($context) {
|
||||
return isset($context['identifier'])
|
||||
&& $context['identifier'] === 'sirsoft-payment';
|
||||
}));
|
||||
|
||||
$this->listener->onExtensionChanged('sirsoft-payment', ['name' => 'Payment']);
|
||||
|
||||
$this->addToAssertionCount(1);
|
||||
}
|
||||
|
||||
// ─── 빈 인자 처리 ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 인자 없이 호출해도 정상 동작하는지 확인
|
||||
*/
|
||||
public function test_does_not_fail_with_empty_args(): void
|
||||
{
|
||||
$this->cacheMock->shouldReceive('clearAll')->once();
|
||||
|
||||
Cache::shouldReceive('forget')
|
||||
->once()
|
||||
->with('seo:sitemap');
|
||||
|
||||
Log::shouldReceive('info')
|
||||
->once()
|
||||
->with('[SEO] Extension changed — all cache cleared', Mockery::on(function ($context) {
|
||||
return $context['identifier'] === 'unknown';
|
||||
}));
|
||||
|
||||
$this->listener->onExtensionChanged();
|
||||
|
||||
$this->addToAssertionCount(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo\Listeners;
|
||||
|
||||
use App\Listeners\SeoSettingsCacheListener;
|
||||
use App\Seo\Contracts\SeoCacheManagerInterface;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 코어 SEO 설정 리스너 테스트
|
||||
*
|
||||
* 코어 환경설정 SEO 탭 저장 시 전체 캐시 삭제를 검증합니다.
|
||||
*/
|
||||
class SeoSettingsCacheListenerTest extends TestCase
|
||||
{
|
||||
private SeoSettingsCacheListener $listener;
|
||||
|
||||
private SeoCacheManagerInterface $cacheMock;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->cacheMock = Mockery::mock(SeoCacheManagerInterface::class);
|
||||
$this->app->instance(SeoCacheManagerInterface::class, $this->cacheMock);
|
||||
|
||||
$this->listener = new SeoSettingsCacheListener;
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Mockery::close();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
// ─── 훅 구독 등록 ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 훅 구독이 올바르게 등록되어 있는지 확인합니다.
|
||||
*/
|
||||
public function test_get_subscribed_hooks_returns_correct_mapping(): void
|
||||
{
|
||||
$hooks = SeoSettingsCacheListener::getSubscribedHooks();
|
||||
|
||||
$this->assertArrayHasKey('core.settings.after_save', $hooks);
|
||||
$this->assertEquals('onSettingsSave', $hooks['core.settings.after_save']['method']);
|
||||
$this->assertEquals(20, $hooks['core.settings.after_save']['priority']);
|
||||
}
|
||||
|
||||
// ─── SEO 탭 저장 ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* SEO 탭 저장 시 전체 캐시 삭제 + sitemap 삭제 확인
|
||||
*/
|
||||
public function test_on_settings_save_clears_all_cache_for_seo_tab(): void
|
||||
{
|
||||
$this->cacheMock->shouldReceive('clearAll')->once();
|
||||
|
||||
Cache::shouldReceive('forget')
|
||||
->once()
|
||||
->with('seo:sitemap');
|
||||
|
||||
Log::shouldReceive('info')
|
||||
->once()
|
||||
->with('[SEO] Core SEO settings changed — all cache cleared', Mockery::type('array'));
|
||||
|
||||
$this->listener->onSettingsSave('seo', ['cache_ttl' => 3600], ['success' => true]);
|
||||
|
||||
$this->addToAssertionCount(1);
|
||||
}
|
||||
|
||||
// ─── 비-SEO 탭 저장 ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* SEO 탭이 아닌 경우 아무 동작도 하지 않는지 확인
|
||||
*/
|
||||
public function test_on_settings_save_does_nothing_for_non_seo_tab(): void
|
||||
{
|
||||
$this->cacheMock->shouldNotReceive('clearAll');
|
||||
|
||||
$this->listener->onSettingsSave('general', ['site_name' => 'Test'], ['success' => true]);
|
||||
|
||||
$this->addToAssertionCount(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 탭이 null인 경우 무시하는지 확인
|
||||
*/
|
||||
public function test_on_settings_save_ignores_null_tab(): void
|
||||
{
|
||||
$this->cacheMock->shouldNotReceive('clearAll');
|
||||
|
||||
$this->listener->onSettingsSave(null);
|
||||
|
||||
$this->addToAssertionCount(1);
|
||||
}
|
||||
|
||||
// ─── 예외 처리 ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 캐시 삭제 중 예외 발생 시 graceful하게 처리되는지 확인
|
||||
*/
|
||||
public function test_handles_exceptions_gracefully(): void
|
||||
{
|
||||
$this->cacheMock->shouldReceive('clearAll')
|
||||
->andThrow(new \RuntimeException('Cache unavailable'));
|
||||
|
||||
Log::shouldReceive('warning')
|
||||
->once()
|
||||
->with('[SEO] Core SEO settings cache invalidation failed', Mockery::on(function ($context) {
|
||||
return $context['error'] === 'Cache unavailable';
|
||||
}));
|
||||
|
||||
$this->listener->onSettingsSave('seo', [], []);
|
||||
|
||||
$this->addToAssertionCount(1);
|
||||
}
|
||||
|
||||
// ─── handle (인터페이스 준수) ───────────────────────────
|
||||
|
||||
/**
|
||||
* handle 메서드가 존재하는지 확인합니다 (HookListenerInterface 준수).
|
||||
*/
|
||||
public function test_handle_method_exists(): void
|
||||
{
|
||||
$this->assertTrue(method_exists($this->listener, 'handle'));
|
||||
$this->listener->handle();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
<?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,457 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Seo\PipeRegistry;
|
||||
use Tests\TestCase;
|
||||
|
||||
class PipeRegistryTest extends TestCase
|
||||
{
|
||||
private PipeRegistry $registry;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->registry = new PipeRegistry;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 파이프 분리 (splitPipes)
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* 단일 파이프를 정확하게 분리합니다.
|
||||
*/
|
||||
public function test_split_pipes_single(): void
|
||||
{
|
||||
[$expr, $pipes] = PipeRegistry::splitPipes('value | uppercase');
|
||||
$this->assertSame('value', $expr);
|
||||
$this->assertSame(['uppercase'], $pipes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 다중 파이프 체인을 분리합니다.
|
||||
*/
|
||||
public function test_split_pipes_chain(): void
|
||||
{
|
||||
[$expr, $pipes] = PipeRegistry::splitPipes('value | truncate(100) | uppercase');
|
||||
$this->assertSame('value', $expr);
|
||||
$this->assertSame(['truncate(100)', 'uppercase'], $pipes);
|
||||
}
|
||||
|
||||
/**
|
||||
* OR 연산자(||)는 파이프로 인식하지 않습니다.
|
||||
*/
|
||||
public function test_split_pipes_ignores_or_operator(): void
|
||||
{
|
||||
[$expr, $pipes] = PipeRegistry::splitPipes("a || b ? 'yes' : 'no'");
|
||||
$this->assertSame("a || b ? 'yes' : 'no'", $expr);
|
||||
$this->assertSame([], $pipes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 파이프 없는 표현식에서는 빈 배열을 반환합니다.
|
||||
*/
|
||||
public function test_split_pipes_no_pipe(): void
|
||||
{
|
||||
[$expr, $pipes] = PipeRegistry::splitPipes('user.name');
|
||||
$this->assertSame('user.name', $expr);
|
||||
$this->assertSame([], $pipes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 문자열 내부의 | 는 파이프로 인식하지 않습니다.
|
||||
*/
|
||||
public function test_split_pipes_inside_string_ignored(): void
|
||||
{
|
||||
[$expr, $pipes] = PipeRegistry::splitPipes("'a|b'");
|
||||
$this->assertSame("'a|b'", $expr);
|
||||
$this->assertSame([], $pipes);
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// hasPipes
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* 파이프가 포함된 표현식을 감지합니다.
|
||||
*/
|
||||
public function test_has_pipes_true(): void
|
||||
{
|
||||
$this->assertTrue(PipeRegistry::hasPipes('value | date'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 파이프가 없는 표현식에서 false를 반환합니다.
|
||||
*/
|
||||
public function test_has_pipes_false(): void
|
||||
{
|
||||
$this->assertFalse(PipeRegistry::hasPipes('a || b'));
|
||||
$this->assertFalse(PipeRegistry::hasPipes('user.name'));
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// parsePipeExpression
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* 인자 없는 파이프를 파싱합니다.
|
||||
*/
|
||||
public function test_parse_pipe_no_args(): void
|
||||
{
|
||||
$result = PipeRegistry::parsePipeExpression('uppercase');
|
||||
$this->assertSame('uppercase', $result['name']);
|
||||
$this->assertSame([], $result['args']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 인자가 있는 파이프를 파싱합니다.
|
||||
*/
|
||||
public function test_parse_pipe_with_args(): void
|
||||
{
|
||||
$result = PipeRegistry::parsePipeExpression('truncate(100)');
|
||||
$this->assertSame('truncate', $result['name']);
|
||||
$this->assertSame([100], $result['args']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 다중 인자가 있는 파이프를 파싱합니다.
|
||||
*/
|
||||
public function test_parse_pipe_multiple_args(): void
|
||||
{
|
||||
$result = PipeRegistry::parsePipeExpression("truncate(50, '...')");
|
||||
$this->assertSame('truncate', $result['name']);
|
||||
$this->assertSame([50, '...'], $result['args']);
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 날짜 파이프
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* date 파이프가 날짜를 기본 포맷으로 변환합니다.
|
||||
*/
|
||||
public function test_date_pipe_default_format(): void
|
||||
{
|
||||
$result = $this->registry->execute('date', '2024-01-15 14:30:00');
|
||||
$this->assertSame('2024-01-15', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* date 파이프가 커스텀 포맷을 적용합니다.
|
||||
*/
|
||||
public function test_date_pipe_custom_format(): void
|
||||
{
|
||||
$result = $this->registry->execute('date', '2024-01-15', ['YYYY/MM/DD']);
|
||||
$this->assertSame('2024/01/15', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* datetime 파이프가 날짜+시간을 포맷합니다.
|
||||
*/
|
||||
public function test_datetime_pipe(): void
|
||||
{
|
||||
$result = $this->registry->execute('datetime', '2024-01-15 14:30:45');
|
||||
$this->assertSame('2024-01-15 14:30', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* null 날짜에 대해 빈 문자열을 반환합니다.
|
||||
*/
|
||||
public function test_date_pipe_null(): void
|
||||
{
|
||||
$result = $this->registry->execute('date', null);
|
||||
$this->assertSame('', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* relativeTime 파이프가 상대 시간을 반환합니다.
|
||||
*/
|
||||
public function test_relative_time_pipe(): void
|
||||
{
|
||||
$result = $this->registry->execute('relativeTime', now()->subMinutes(5)->toDateTimeString());
|
||||
$this->assertNotEmpty($result);
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 숫자 파이프
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* number 파이프가 천단위 구분자를 추가합니다.
|
||||
*/
|
||||
public function test_number_pipe_formatting(): void
|
||||
{
|
||||
$result = $this->registry->execute('number', 1234567);
|
||||
$this->assertSame('1,234,567', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* number 파이프가 소수점 자릿수를 지정합니다.
|
||||
*/
|
||||
public function test_number_pipe_with_decimals(): void
|
||||
{
|
||||
$result = $this->registry->execute('number', 1234.5, [2]);
|
||||
$this->assertSame('1,234.50', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* number 파이프가 비숫자에 대해 원본을 반환합니다.
|
||||
*/
|
||||
public function test_number_pipe_non_numeric(): void
|
||||
{
|
||||
$result = $this->registry->execute('number', 'abc');
|
||||
$this->assertSame('abc', $result);
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 문자열 파이프
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* truncate 파이프가 문자열을 자릅니다.
|
||||
*/
|
||||
public function test_truncate_pipe(): void
|
||||
{
|
||||
$result = $this->registry->execute('truncate', '안녕하세요 반갑습니다 좋은 하루 되세요', [10]);
|
||||
$this->assertSame('안녕하세요 반갑습니...', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* truncate 파이프가 짧은 문자열은 그대로 반환합니다.
|
||||
*/
|
||||
public function test_truncate_pipe_short_string(): void
|
||||
{
|
||||
$result = $this->registry->execute('truncate', '짧은 텍스트', [100]);
|
||||
$this->assertSame('짧은 텍스트', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* uppercase 파이프가 대문자로 변환합니다.
|
||||
*/
|
||||
public function test_uppercase_pipe(): void
|
||||
{
|
||||
$result = $this->registry->execute('uppercase', 'hello');
|
||||
$this->assertSame('HELLO', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* lowercase 파이프가 소문자로 변환합니다.
|
||||
*/
|
||||
public function test_lowercase_pipe(): void
|
||||
{
|
||||
$result = $this->registry->execute('lowercase', 'HELLO');
|
||||
$this->assertSame('hello', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* stripHtml 파이프가 HTML 태그를 제거합니다.
|
||||
*/
|
||||
public function test_strip_html_pipe(): void
|
||||
{
|
||||
$result = $this->registry->execute('stripHtml', '<p>Hello <b>World</b></p>');
|
||||
$this->assertSame('Hello World', $result);
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 기본값 파이프
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* default 파이프가 null에 기본값을 적용합니다.
|
||||
*/
|
||||
public function test_default_pipe_null(): void
|
||||
{
|
||||
$result = $this->registry->execute('default', null, ['Unknown']);
|
||||
$this->assertSame('Unknown', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* default 파이프가 빈 문자열에 기본값을 적용합니다.
|
||||
*/
|
||||
public function test_default_pipe_empty_string(): void
|
||||
{
|
||||
$result = $this->registry->execute('default', '', ['N/A']);
|
||||
$this->assertSame('N/A', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* default 파이프가 값이 있으면 원본을 반환합니다.
|
||||
*/
|
||||
public function test_default_pipe_with_value(): void
|
||||
{
|
||||
$result = $this->registry->execute('default', '홍길동', ['Unknown']);
|
||||
$this->assertSame('홍길동', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* fallback 파이프가 null에만 폴백을 적용합니다.
|
||||
*/
|
||||
public function test_fallback_pipe(): void
|
||||
{
|
||||
$this->assertSame('fallback', $this->registry->execute('fallback', null, ['fallback']));
|
||||
$this->assertSame('', $this->registry->execute('fallback', '', ['fallback'])); // 빈 문자열은 유지
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 배열 파이프
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* first 파이프가 배열의 첫 요소를 반환합니다.
|
||||
*/
|
||||
public function test_first_pipe(): void
|
||||
{
|
||||
$this->assertSame('a', $this->registry->execute('first', ['a', 'b', 'c']));
|
||||
}
|
||||
|
||||
/**
|
||||
* last 파이프가 배열의 마지막 요소를 반환합니다.
|
||||
*/
|
||||
public function test_last_pipe(): void
|
||||
{
|
||||
$this->assertSame('c', $this->registry->execute('last', ['a', 'b', 'c']));
|
||||
}
|
||||
|
||||
/**
|
||||
* join 파이프가 배열을 결합합니다.
|
||||
*/
|
||||
public function test_join_pipe(): void
|
||||
{
|
||||
$result = $this->registry->execute('join', ['태그1', '태그2', '태그3']);
|
||||
$this->assertSame('태그1, 태그2, 태그3', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* join 파이프가 커스텀 구분자로 결합합니다.
|
||||
*/
|
||||
public function test_join_pipe_custom_separator(): void
|
||||
{
|
||||
$result = $this->registry->execute('join', ['a', 'b', 'c'], [' | ']);
|
||||
$this->assertSame('a | b | c', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* length 파이프가 배열 길이를 반환합니다.
|
||||
*/
|
||||
public function test_length_pipe_array(): void
|
||||
{
|
||||
$this->assertSame(3, $this->registry->execute('length', ['a', 'b', 'c']));
|
||||
}
|
||||
|
||||
/**
|
||||
* length 파이프가 문자열 길이를 반환합니다.
|
||||
*/
|
||||
public function test_length_pipe_string(): void
|
||||
{
|
||||
$this->assertSame(5, $this->registry->execute('length', '안녕하세요'));
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 객체 파이프
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* keys 파이프가 키 배열을 반환합니다.
|
||||
*/
|
||||
public function test_keys_pipe(): void
|
||||
{
|
||||
$result = $this->registry->execute('keys', ['a' => 1, 'b' => 2]);
|
||||
$this->assertSame(['a', 'b'], $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* values 파이프가 값 배열을 반환합니다.
|
||||
*/
|
||||
public function test_values_pipe(): void
|
||||
{
|
||||
$result = $this->registry->execute('values', ['a' => 1, 'b' => 2]);
|
||||
$this->assertSame([1, 2], $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* json 파이프가 JSON 문자열을 반환합니다.
|
||||
*/
|
||||
public function test_json_pipe(): void
|
||||
{
|
||||
$result = $this->registry->execute('json', ['key' => '값']);
|
||||
$this->assertSame('{"key":"값"}', $result);
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 다국어 파이프
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* localized 파이프가 현재 로케일 값을 추출합니다.
|
||||
*/
|
||||
public function test_localized_pipe(): void
|
||||
{
|
||||
$this->registry->setLocale('ko');
|
||||
$result = $this->registry->execute('localized', ['ko' => '상품명', 'en' => 'Product']);
|
||||
$this->assertSame('상품명', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* localized 파이프가 지정된 로케일 값을 추출합니다.
|
||||
*/
|
||||
public function test_localized_pipe_with_locale_arg(): void
|
||||
{
|
||||
$result = $this->registry->execute('localized', ['ko' => '상품명', 'en' => 'Product'], ['en']);
|
||||
$this->assertSame('Product', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* localized 파이프가 문자열 값은 그대로 반환합니다.
|
||||
*/
|
||||
public function test_localized_pipe_string(): void
|
||||
{
|
||||
$result = $this->registry->execute('localized', '일반 문자열');
|
||||
$this->assertSame('일반 문자열', $result);
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 미등록 파이프 안전 처리
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* 존재하지 않는 파이프는 원본 값을 반환합니다.
|
||||
*/
|
||||
public function test_unknown_pipe_returns_original(): void
|
||||
{
|
||||
$result = $this->registry->execute('nonexistent', 'hello');
|
||||
$this->assertSame('hello', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* has()가 등록된 파이프를 확인합니다.
|
||||
*/
|
||||
public function test_has_pipe(): void
|
||||
{
|
||||
$this->assertTrue($this->registry->has('date'));
|
||||
$this->assertTrue($this->registry->has('number'));
|
||||
$this->assertFalse($this->registry->has('nonexistent'));
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// filterBy 파이프
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* filterBy 파이프가 허용 목록으로 필터링합니다.
|
||||
*/
|
||||
public function test_filter_by_pipe(): void
|
||||
{
|
||||
$items = [
|
||||
['id' => 1, 'name' => 'A'],
|
||||
['id' => 2, 'name' => 'B'],
|
||||
['id' => 3, 'name' => 'C'],
|
||||
];
|
||||
|
||||
$result = $this->registry->execute('filterBy', $items, [[1, 3], 'id']);
|
||||
$this->assertCount(2, $result);
|
||||
$this->assertSame('A', $result[0]['name']);
|
||||
$this->assertSame('C', $result[1]['name']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,900 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Seo\ComponentHtmlMapper;
|
||||
use App\Seo\ExpressionEvaluator;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 실제 상품 상세 페이지 렌더링 시나리오를 검증합니다.
|
||||
*
|
||||
* PO 피드백 기반: 실제 SEO 페이지에서 발생한 문제들을 재현하여 검증합니다.
|
||||
* - Icon이 <div> 대신 <i>로 렌더링되는지
|
||||
* - Img가 <img> 셀프 클로징 태그로 렌더링되는지
|
||||
* - 상품 데이터 바인딩 (이름, 가격, 이미지) 적용 여부
|
||||
* - $t: 번역 키 해석 여부
|
||||
* - 표현식 평가 여부
|
||||
* - 템플릿 CSS 경로 포함 여부
|
||||
*/
|
||||
class RealWorldRenderingTest extends TestCase
|
||||
{
|
||||
private ComponentHtmlMapper $mapper;
|
||||
|
||||
private ExpressionEvaluator $evaluator;
|
||||
|
||||
/**
|
||||
* sirsoft-basic 템플릿의 실제 seo-config.json을 로드하여 테스트합니다.
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->mapper = new ComponentHtmlMapper;
|
||||
$this->evaluator = new ExpressionEvaluator;
|
||||
|
||||
// 실제 seo-config.json 로드
|
||||
$configPath = base_path('templates/_bundled/sirsoft-basic/seo-config.json');
|
||||
$this->assertTrue(file_exists($configPath), 'seo-config.json must exist');
|
||||
|
||||
$config = json_decode(file_get_contents($configPath), true);
|
||||
$this->assertIsArray($config);
|
||||
|
||||
if (! empty($config['component_map'])) {
|
||||
$this->mapper->setComponentMap($config['component_map']);
|
||||
}
|
||||
if (! empty($config['render_modes'])) {
|
||||
$this->mapper->setRenderModes($config['render_modes']);
|
||||
}
|
||||
if (! empty($config['self_closing'])) {
|
||||
$this->mapper->setSelfClosing($config['self_closing']);
|
||||
}
|
||||
if (! empty($config['text_props'])) {
|
||||
$this->mapper->setTextProps($config['text_props']);
|
||||
}
|
||||
if (! empty($config['attr_map'])) {
|
||||
$this->mapper->setAttrMap($config['attr_map']);
|
||||
}
|
||||
if (! empty($config['allowed_attrs'])) {
|
||||
$this->mapper->setAllowedAttrs($config['allowed_attrs']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트 헬퍼: 컴포넌트를 렌더링합니다.
|
||||
*
|
||||
* @param array $components 컴포넌트 배열
|
||||
* @param array $context 데이터 컨텍스트
|
||||
* @return string 렌더링된 HTML
|
||||
*/
|
||||
private function render(array $components, array $context = []): string
|
||||
{
|
||||
return $this->mapper->render($components, $context, $this->evaluator);
|
||||
}
|
||||
|
||||
// ========================================================
|
||||
// 1. 태그 매핑 검증 — Icon, Img 등이 올바른 HTML 태그를 사용하는지
|
||||
// ========================================================
|
||||
|
||||
/**
|
||||
* Icon 컴포넌트가 <i> 태그로 렌더링됩니다 (PO 버그: <div>로 렌더링됨).
|
||||
*/
|
||||
public function test_icon_renders_as_i_tag(): void
|
||||
{
|
||||
$components = [
|
||||
[
|
||||
'name' => 'Icon',
|
||||
'props' => ['name' => 'shopping-cart', 'className' => 'w-5 h-5'],
|
||||
],
|
||||
];
|
||||
|
||||
$html = $this->render($components);
|
||||
|
||||
$this->assertStringContainsString('<i', $html);
|
||||
$this->assertStringNotContainsString('<div', $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Img 컴포넌트가 <img> 셀프 클로징 태그로 렌더링됩니다.
|
||||
*/
|
||||
public function test_img_renders_as_img_tag_self_closing(): void
|
||||
{
|
||||
$components = [
|
||||
[
|
||||
'name' => 'Img',
|
||||
'props' => [
|
||||
'src' => '/images/product.jpg',
|
||||
'alt' => '상품 이미지',
|
||||
'className' => 'w-full',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$html = $this->render($components);
|
||||
|
||||
$this->assertStringContainsString('<img', $html);
|
||||
$this->assertStringNotContainsString('</img>', $html);
|
||||
$this->assertStringContainsString('src=', $html);
|
||||
$this->assertStringContainsString('alt="상품 이미지"', $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Button 컴포넌트가 <button> 태그로 렌더링됩니다.
|
||||
*/
|
||||
public function test_button_renders_as_button_tag(): void
|
||||
{
|
||||
$components = [
|
||||
[
|
||||
'name' => 'Button',
|
||||
'props' => ['className' => 'px-4 py-2', 'text' => '구매하기'],
|
||||
],
|
||||
];
|
||||
|
||||
$html = $this->render($components);
|
||||
|
||||
$this->assertStringContainsString('<button', $html);
|
||||
$this->assertStringContainsString('</button>', $html);
|
||||
$this->assertStringContainsString('구매하기', $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Nav 컴포넌트가 <nav> 태그로 렌더링됩니다.
|
||||
*/
|
||||
public function test_nav_renders_as_nav_tag(): void
|
||||
{
|
||||
$components = [
|
||||
[
|
||||
'name' => 'Nav',
|
||||
'props' => ['className' => 'flex items-center'],
|
||||
'children' => [
|
||||
['name' => 'A', 'props' => ['href' => '/', 'text' => 'Home']],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$html = $this->render($components);
|
||||
|
||||
$this->assertStringContainsString('<nav', $html);
|
||||
$this->assertStringContainsString('</nav>', $html);
|
||||
$this->assertStringContainsString('<a', $html);
|
||||
$this->assertStringContainsString('Home', $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* H1~H6 컴포넌트가 올바른 헤딩 태그로 렌더링됩니다.
|
||||
*/
|
||||
public function test_headings_render_correct_tags(): void
|
||||
{
|
||||
$headings = ['H1' => 'h1', 'H2' => 'h2', 'H3' => 'h3', 'H4' => 'h4', 'H5' => 'h5', 'H6' => 'h6'];
|
||||
|
||||
foreach ($headings as $component => $tag) {
|
||||
$components = [['name' => $component, 'props' => ['text' => 'Heading']]];
|
||||
$html = $this->render($components);
|
||||
$this->assertStringContainsString("<{$tag}", $html, "{$component}가 <{$tag}>로 렌더링되어야 합니다");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Input 컴포넌트가 <input> 셀프 클로징 태그로 렌더링됩니다.
|
||||
*/
|
||||
public function test_input_renders_as_input_self_closing(): void
|
||||
{
|
||||
$components = [
|
||||
[
|
||||
'name' => 'Input',
|
||||
'props' => ['type' => 'text', 'placeholder' => '검색어 입력'],
|
||||
],
|
||||
];
|
||||
|
||||
$html = $this->render($components);
|
||||
|
||||
$this->assertStringContainsString('<input', $html);
|
||||
$this->assertStringNotContainsString('</input>', $html);
|
||||
}
|
||||
|
||||
// ========================================================
|
||||
// 2. 데이터 바인딩 검증 — 상품 데이터가 렌더링에 반영되는지
|
||||
// ========================================================
|
||||
|
||||
/**
|
||||
* 상품명이 바인딩으로 올바르게 표시됩니다.
|
||||
*/
|
||||
public function test_product_name_binding(): void
|
||||
{
|
||||
$components = [
|
||||
[
|
||||
'name' => 'H1',
|
||||
'props' => [
|
||||
'className' => 'text-xl font-bold',
|
||||
'text' => '{{product.data.name_localized}}',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$context = [
|
||||
'product' => [
|
||||
'data' => [
|
||||
'name_localized' => '무선 마우스 세트 #99',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$html = $this->render($components, $context);
|
||||
|
||||
$this->assertStringContainsString('<h1', $html);
|
||||
$this->assertStringContainsString('무선 마우스 세트 #99', $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* 상품 가격이 바인딩으로 올바르게 표시됩니다.
|
||||
*/
|
||||
public function test_product_price_binding(): void
|
||||
{
|
||||
$components = [
|
||||
[
|
||||
'name' => 'Span',
|
||||
'props' => [
|
||||
'className' => 'text-2xl font-bold',
|
||||
'text' => '{{product.data.selling_price_formatted}}',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$context = [
|
||||
'product' => [
|
||||
'data' => [
|
||||
'selling_price_formatted' => '129,000원',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$html = $this->render($components, $context);
|
||||
|
||||
$this->assertStringContainsString('129,000원', $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* 상품 카테고리명이 바인딩으로 표시됩니다.
|
||||
*/
|
||||
public function test_product_category_binding(): void
|
||||
{
|
||||
$components = [
|
||||
[
|
||||
'name' => 'Span',
|
||||
'props' => [
|
||||
'className' => 'text-sm text-gray-500',
|
||||
'text' => '{{product.data.category_name}}',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$context = [
|
||||
'product' => ['data' => ['category_name' => '소파']],
|
||||
];
|
||||
|
||||
$html = $this->render($components, $context);
|
||||
|
||||
$this->assertStringContainsString('소파', $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* 브랜드명이 바인딩으로 표시됩니다.
|
||||
*/
|
||||
public function test_brand_name_binding(): void
|
||||
{
|
||||
$components = [
|
||||
[
|
||||
'name' => 'Div',
|
||||
'children' => [
|
||||
[
|
||||
'name' => 'Span',
|
||||
'props' => ['className' => 'text-sm text-gray-500', 'text' => '브랜드'],
|
||||
],
|
||||
[
|
||||
'name' => 'Span',
|
||||
'props' => ['text' => '{{product.data.brand_name}}'],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$context = [
|
||||
'product' => ['data' => ['brand_name' => 'LG Electronics']],
|
||||
];
|
||||
|
||||
$html = $this->render($components, $context);
|
||||
|
||||
$this->assertStringContainsString('LG Electronics', $html);
|
||||
$this->assertStringContainsString('브랜드', $html);
|
||||
}
|
||||
|
||||
// ========================================================
|
||||
// 3. 이미지 렌더링 검증 — ProductImageViewer + 이미지 바인딩
|
||||
// ========================================================
|
||||
|
||||
/**
|
||||
* ProductImageViewer가 이미지 갤러리를 올바르게 렌더링합니다.
|
||||
*/
|
||||
public function test_product_image_viewer_renders_images(): void
|
||||
{
|
||||
$components = [
|
||||
[
|
||||
'name' => 'ProductImageViewer',
|
||||
'props' => [
|
||||
'images' => '{{product.data.images}}',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$context = [
|
||||
'product' => [
|
||||
'data' => [
|
||||
'images' => [
|
||||
['url' => '/storage/products/mouse-1.jpg', 'alt' => '마우스 정면'],
|
||||
['url' => '/storage/products/mouse-2.jpg', 'alt' => '마우스 측면'],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$html = $this->render($components, $context);
|
||||
|
||||
// img 태그가 생성되어야 함
|
||||
$this->assertStringContainsString('<img', $html);
|
||||
// 2개 이미지의 src 포함
|
||||
$this->assertStringContainsString('mouse-1.jpg', $html);
|
||||
$this->assertStringContainsString('mouse-2.jpg', $html);
|
||||
// alt 속성 포함
|
||||
$this->assertStringContainsString('마우스 정면', $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* ProductImageViewer에 이미지가 배열로 직접 전달될 때도 렌더링됩니다.
|
||||
*/
|
||||
public function test_product_image_viewer_with_direct_array(): void
|
||||
{
|
||||
$components = [
|
||||
[
|
||||
'name' => 'ProductImageViewer',
|
||||
'props' => [
|
||||
'images' => [
|
||||
['src' => 'https://example.com/img1.jpg', 'alt' => '이미지1'],
|
||||
['src' => 'https://example.com/img2.jpg', 'alt' => '이미지2'],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$html = $this->render($components);
|
||||
|
||||
$this->assertStringContainsString('<img', $html);
|
||||
$this->assertStringContainsString('https://example.com/img1.jpg', $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* 일반 Img 컴포넌트로 상품 이미지를 렌더링할 수 있습니다.
|
||||
*/
|
||||
public function test_img_with_bound_src(): void
|
||||
{
|
||||
$components = [
|
||||
[
|
||||
'name' => 'Img',
|
||||
'props' => [
|
||||
'src' => '{{product.data.thumbnail}}',
|
||||
'alt' => '{{product.data.name_localized}}',
|
||||
'className' => 'w-full rounded-lg',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$context = [
|
||||
'product' => [
|
||||
'data' => [
|
||||
'thumbnail' => '/storage/products/thumb.jpg',
|
||||
'name_localized' => '무선 마우스',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$html = $this->render($components, $context);
|
||||
|
||||
$this->assertStringContainsString('<img', $html);
|
||||
$this->assertStringContainsString('thumb.jpg', $html);
|
||||
$this->assertStringContainsString('무선 마우스', $html);
|
||||
}
|
||||
|
||||
// ========================================================
|
||||
// 4. 번역 ($t:) 검증
|
||||
// ========================================================
|
||||
|
||||
/**
|
||||
* $t: 번역 키가 해석됩니다 (PO 버그: $t:shop.product.reviews_count 그대로 노출).
|
||||
*/
|
||||
public function test_translation_key_resolved(): void
|
||||
{
|
||||
$this->evaluator->setTranslations([
|
||||
'shop' => [
|
||||
'product' => [
|
||||
'reviews_count' => '개의 리뷰',
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$components = [
|
||||
[
|
||||
'name' => 'Span',
|
||||
'props' => ['text' => '$t:shop.product.reviews_count'],
|
||||
],
|
||||
];
|
||||
|
||||
$html = $this->render($components);
|
||||
|
||||
$this->assertStringContainsString('개의 리뷰', $html);
|
||||
$this->assertStringNotContainsString('$t:shop', $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* $t: 번역 키와 데이터 바인딩이 혼합된 텍스트가 올바르게 렌더링됩니다.
|
||||
*/
|
||||
public function test_translation_mixed_with_binding(): void
|
||||
{
|
||||
$this->evaluator->setTranslations([
|
||||
'shop' => [
|
||||
'product' => [
|
||||
'write_question' => '질문 작성',
|
||||
],
|
||||
'back' => '뒤로가기',
|
||||
'tabs' => [
|
||||
'detail_info' => '상세정보',
|
||||
'reviews' => '리뷰',
|
||||
'qna' => 'Q&A',
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$components = [
|
||||
[
|
||||
'name' => 'Div',
|
||||
'children' => [
|
||||
['name' => 'Span', 'props' => ['text' => '$t:shop.back']],
|
||||
['name' => 'Button', 'props' => ['text' => '$t:shop.product.write_question']],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$html = $this->render($components);
|
||||
|
||||
$this->assertStringContainsString('뒤로가기', $html);
|
||||
$this->assertStringContainsString('질문 작성', $html);
|
||||
}
|
||||
|
||||
// ========================================================
|
||||
// 5. 실제 상품 상세 페이지 구조 통합 테스트
|
||||
// ========================================================
|
||||
|
||||
/**
|
||||
* 상품 상세 페이지의 핵심 구조가 올바르게 렌더링됩니다.
|
||||
* Header + 이미지 + 상품 정보 + 설명 + 리뷰
|
||||
*/
|
||||
public function test_product_detail_page_core_structure(): void
|
||||
{
|
||||
$this->evaluator->setTranslations([
|
||||
'shop' => [
|
||||
'back' => '뒤로가기',
|
||||
'product' => [
|
||||
'brand' => '브랜드',
|
||||
'shipping_info' => '배송 정보',
|
||||
'reviews_count' => '개의 리뷰',
|
||||
'write_question' => '질문 작성',
|
||||
],
|
||||
'write_review' => '리뷰 작성',
|
||||
],
|
||||
]);
|
||||
|
||||
$components = [
|
||||
// 전체 래퍼
|
||||
[
|
||||
'name' => 'Div',
|
||||
'props' => ['className' => 'min-h-screen flex flex-col'],
|
||||
'children' => [
|
||||
// 뒤로가기 버튼
|
||||
[
|
||||
'name' => 'Div',
|
||||
'props' => ['className' => 'flex items-center'],
|
||||
'children' => [
|
||||
['name' => 'Icon', 'props' => ['name' => 'chevron-left']],
|
||||
['name' => 'Span', 'props' => ['text' => '$t:shop.back']],
|
||||
],
|
||||
],
|
||||
// 이미지 갤러리
|
||||
[
|
||||
'name' => 'ProductImageViewer',
|
||||
'props' => ['images' => '{{product.data.images}}'],
|
||||
],
|
||||
// 상품 정보
|
||||
[
|
||||
'name' => 'Div',
|
||||
'props' => ['className' => 'space-y-4'],
|
||||
'children' => [
|
||||
// 카테고리
|
||||
[
|
||||
'name' => 'Span',
|
||||
'props' => [
|
||||
'className' => 'text-sm text-gray-500',
|
||||
'text' => '{{product.data.category_name}}',
|
||||
],
|
||||
],
|
||||
// 상품명
|
||||
[
|
||||
'name' => 'H1',
|
||||
'props' => [
|
||||
'className' => 'text-xl font-bold',
|
||||
'text' => '{{product.data.name_localized}}',
|
||||
],
|
||||
],
|
||||
// 가격
|
||||
[
|
||||
'name' => 'Span',
|
||||
'props' => [
|
||||
'className' => 'text-2xl font-bold',
|
||||
'text' => '{{product.data.selling_price_formatted}}',
|
||||
],
|
||||
],
|
||||
// 브랜드
|
||||
[
|
||||
'name' => 'Div',
|
||||
'children' => [
|
||||
['name' => 'Span', 'props' => ['text' => '$t:shop.product.brand']],
|
||||
['name' => 'Span', 'props' => ['text' => '{{product.data.brand_name}}']],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
// 상품 설명 (HtmlContent)
|
||||
[
|
||||
'name' => 'HtmlContent',
|
||||
'props' => [
|
||||
'content' => '{{product.data.description_localized}}',
|
||||
],
|
||||
],
|
||||
// 리뷰 섹션
|
||||
[
|
||||
'name' => 'Div',
|
||||
'children' => [
|
||||
[
|
||||
'name' => 'Span',
|
||||
'props' => ['text' => '{{product.data.rating_avg}}'],
|
||||
],
|
||||
[
|
||||
'name' => 'Span',
|
||||
'props' => ['text' => ' / 5'],
|
||||
],
|
||||
[
|
||||
'name' => 'Button',
|
||||
'props' => ['text' => '$t:shop.write_review'],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$context = [
|
||||
'product' => [
|
||||
'data' => [
|
||||
'name_localized' => '무선 마우스 세트 #99',
|
||||
'category_name' => '소파',
|
||||
'selling_price_formatted' => '129,000원',
|
||||
'brand_name' => 'LG Electronics',
|
||||
'description_localized' => '<p>고급 무선 마우스 세트입니다.</p><ul><li>블루투스 5.0</li></ul>',
|
||||
'rating_avg' => '4.5',
|
||||
'images' => [
|
||||
['url' => '/storage/products/mouse-1.jpg', 'alt' => '마우스 정면'],
|
||||
['url' => '/storage/products/mouse-2.jpg', 'alt' => '마우스 측면'],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$html = $this->render($components, $context);
|
||||
|
||||
// 태그 검증
|
||||
$this->assertStringContainsString('<i', $html, 'Icon이 <i> 태그여야 합니다');
|
||||
$this->assertStringContainsString('<h1', $html, 'H1이 <h1> 태그여야 합니다');
|
||||
$this->assertStringContainsString('<img', $html, '이미지가 <img> 태그여야 합니다');
|
||||
$this->assertStringContainsString('<button', $html, 'Button이 <button> 태그여야 합니다');
|
||||
$this->assertStringContainsString('<span', $html, 'Span이 <span> 태그여야 합니다');
|
||||
|
||||
// 상품 데이터 검증
|
||||
$this->assertStringContainsString('무선 마우스 세트 #99', $html, '상품명이 표시되어야 합니다');
|
||||
$this->assertStringContainsString('129,000원', $html, '가격이 표시되어야 합니다');
|
||||
$this->assertStringContainsString('소파', $html, '카테고리가 표시되어야 합니다');
|
||||
$this->assertStringContainsString('LG Electronics', $html, '브랜드가 표시되어야 합니다');
|
||||
$this->assertStringContainsString('4.5', $html, '평점이 표시되어야 합니다');
|
||||
|
||||
// 이미지 검증
|
||||
$this->assertStringContainsString('mouse-1.jpg', $html, '상품 이미지가 표시되어야 합니다');
|
||||
$this->assertStringContainsString('마우스 정면', $html, '이미지 alt가 표시되어야 합니다');
|
||||
|
||||
// 상품 설명 (HtmlContent → raw 렌더링)
|
||||
$this->assertStringContainsString('고급 무선 마우스 세트입니다', $html, '상품 설명이 표시되어야 합니다');
|
||||
$this->assertStringContainsString('<ul>', $html, 'HTML 설명이 이스케이프 없이 표시되어야 합니다');
|
||||
|
||||
// 번역 검증
|
||||
$this->assertStringContainsString('뒤로가기', $html, '$t: 번역이 적용되어야 합니다');
|
||||
$this->assertStringContainsString('브랜드', $html, '$t: 번역이 적용되어야 합니다');
|
||||
$this->assertStringContainsString('리뷰 작성', $html, '$t: 번역이 적용되어야 합니다');
|
||||
$this->assertStringNotContainsString('$t:shop', $html, '$t: 원본 키가 노출되면 안됩니다');
|
||||
}
|
||||
|
||||
// ========================================================
|
||||
// 6. 헤더/네비게이션 구조 검증
|
||||
// ========================================================
|
||||
|
||||
/**
|
||||
* 헤더 네비게이션이 올바른 태그 구조로 렌더링됩니다.
|
||||
*/
|
||||
public function test_header_navigation_structure(): void
|
||||
{
|
||||
$components = [
|
||||
[
|
||||
'name' => 'Header',
|
||||
'props' => ['className' => 'sticky top-0'],
|
||||
'children' => [
|
||||
[
|
||||
'name' => 'Nav',
|
||||
'props' => ['className' => 'flex items-center'],
|
||||
'children' => [
|
||||
[
|
||||
'name' => 'Ul',
|
||||
'children' => [
|
||||
[
|
||||
'name' => 'Li',
|
||||
'children' => [
|
||||
['name' => 'A', 'props' => ['href' => '/', 'text' => 'Home']],
|
||||
],
|
||||
],
|
||||
[
|
||||
'name' => 'Li',
|
||||
'children' => [
|
||||
['name' => 'A', 'props' => ['href' => '/shop', 'text' => 'Shop']],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
// 장바구니 아이콘
|
||||
[
|
||||
'name' => 'Icon',
|
||||
'props' => ['name' => 'shopping-cart', 'className' => 'w-5 h-5'],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$html = $this->render($components);
|
||||
|
||||
$this->assertStringContainsString('<header', $html);
|
||||
$this->assertStringContainsString('<nav', $html);
|
||||
$this->assertStringContainsString('<ul', $html);
|
||||
$this->assertStringContainsString('<li', $html);
|
||||
$this->assertStringContainsString('<a', $html);
|
||||
$this->assertStringContainsString('<i', $html, 'Icon이 <i> 태그여야 합니다');
|
||||
$this->assertStringContainsString('Home', $html);
|
||||
$this->assertStringContainsString('Shop', $html);
|
||||
}
|
||||
|
||||
// ========================================================
|
||||
// 7. StarRating format 모드 검증
|
||||
// ========================================================
|
||||
|
||||
/**
|
||||
* StarRating이 format 모드로 올바르게 렌더링됩니다.
|
||||
*/
|
||||
public function test_star_rating_format_mode(): void
|
||||
{
|
||||
$components = [
|
||||
[
|
||||
'name' => 'StarRating',
|
||||
'props' => ['value' => '4.5'],
|
||||
],
|
||||
];
|
||||
|
||||
$html = $this->render($components);
|
||||
|
||||
$this->assertStringContainsString('4.5', $html);
|
||||
$this->assertStringContainsString('/ 5', $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* StarRating에 바인딩된 값이 올바르게 표시됩니다.
|
||||
*/
|
||||
public function test_star_rating_with_binding(): void
|
||||
{
|
||||
$components = [
|
||||
[
|
||||
'name' => 'StarRating',
|
||||
'props' => ['value' => '{{product.data.rating_avg}}'],
|
||||
],
|
||||
];
|
||||
|
||||
$context = [
|
||||
'product' => ['data' => ['rating_avg' => '3.8']],
|
||||
];
|
||||
|
||||
$html = $this->render($components, $context);
|
||||
|
||||
$this->assertStringContainsString('3.8', $html);
|
||||
$this->assertStringContainsString('/ 5', $html);
|
||||
}
|
||||
|
||||
// ========================================================
|
||||
// 8. CSS 경로 검증 — 템플릿 CSS가 포함되어야 함
|
||||
// ========================================================
|
||||
|
||||
/**
|
||||
* SeoRenderer가 template.json의 CSS 에셋을 자동으로 서빙 URL로 변환합니다.
|
||||
*/
|
||||
public function test_seo_renderer_auto_resolves_template_css(): void
|
||||
{
|
||||
// seo-config.json에 Font Awesome CDN이 포함되어 있는지 확인
|
||||
$configPath = base_path('templates/_bundled/sirsoft-basic/seo-config.json');
|
||||
$config = json_decode(file_get_contents($configPath), true);
|
||||
$stylesheets = $config['stylesheets'] ?? [];
|
||||
|
||||
$hasFontAwesome = false;
|
||||
foreach ($stylesheets as $url) {
|
||||
if (str_contains($url, 'font-awesome')) {
|
||||
$hasFontAwesome = true;
|
||||
}
|
||||
}
|
||||
$this->assertTrue($hasFontAwesome, 'Font Awesome CSS가 seo-config.json에 포함되어야 합니다');
|
||||
|
||||
// SeoRenderer.getTemplateCssUrls()가 템플릿 CSS를 자동 해석하는지 확인
|
||||
$renderer = app(\App\Seo\SeoRenderer::class);
|
||||
$method = new \ReflectionMethod($renderer, 'getTemplateCssUrls');
|
||||
$method->setAccessible(true);
|
||||
|
||||
// template.json에 CSS 에셋이 정의되어 있어야 함
|
||||
$templateJsonPath = base_path('templates/_bundled/sirsoft-basic/template.json');
|
||||
$templateJson = json_decode(file_get_contents($templateJsonPath), true);
|
||||
$cssPaths = $templateJson['assets']['css'] ?? [];
|
||||
$this->assertNotEmpty($cssPaths, 'template.json에 CSS 에셋이 정의되어야 합니다');
|
||||
|
||||
// dist/css/components.css → /api/templates/assets/{id}/css/components.css 변환 검증
|
||||
foreach ($cssPaths as $cssPath) {
|
||||
$servePath = preg_replace('#^dist/#', '', $cssPath);
|
||||
$expectedUrl = '/api/templates/assets/sirsoft-basic/' . $servePath;
|
||||
$this->assertStringContainsString('components.css', $expectedUrl,
|
||||
'템플릿 CSS URL이 올바르게 변환되어야 합니다');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SeoRenderer.getCssPath()가 코어 Tailwind CSS를 반환해야 합니다.
|
||||
* (코어 app.css가 아닌 Tailwind를 포함한 빌드 CSS)
|
||||
*/
|
||||
public function test_css_path_includes_tailwind(): void
|
||||
{
|
||||
// getCssPath()는 Vite manifest에서 CSS를 찾으므로,
|
||||
// manifest가 없으면 fallback '/build/assets/app.css'를 반환합니다.
|
||||
// 실제로는 Tailwind 클래스가 포함된 CSS여야 합니다.
|
||||
$renderer = app(\App\Seo\SeoRenderer::class);
|
||||
|
||||
// Reflection으로 getCssPath() 호출
|
||||
$method = new \ReflectionMethod($renderer, 'getCssPath');
|
||||
$method->setAccessible(true);
|
||||
$cssPath = $method->invoke($renderer);
|
||||
|
||||
$this->assertIsString($cssPath);
|
||||
// CSS 경로가 존재해야 함
|
||||
$this->assertNotEmpty($cssPath);
|
||||
}
|
||||
|
||||
// ========================================================
|
||||
// 9. 복잡한 표현식 + 조건부 렌더링 검증
|
||||
// ========================================================
|
||||
|
||||
/**
|
||||
* 조건부 렌더링 (if)이 올바르게 동작합니다.
|
||||
*/
|
||||
public function test_conditional_rendering_with_data(): void
|
||||
{
|
||||
$components = [
|
||||
[
|
||||
'name' => 'Div',
|
||||
'if' => '{{product.data.has_options}}',
|
||||
'props' => ['text' => '옵션 있음'],
|
||||
],
|
||||
[
|
||||
'name' => 'Div',
|
||||
'if' => '{{!product.data.has_options}}',
|
||||
'props' => ['text' => '옵션 없음'],
|
||||
],
|
||||
];
|
||||
|
||||
$context = ['product' => ['data' => ['has_options' => true]]];
|
||||
$html = $this->render($components, $context);
|
||||
|
||||
$this->assertStringContainsString('옵션 있음', $html);
|
||||
$this->assertStringNotContainsString('옵션 없음', $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* 배송 정보가 조건부로 표시됩니다.
|
||||
*/
|
||||
public function test_shipping_info_conditional(): void
|
||||
{
|
||||
$components = [
|
||||
[
|
||||
'name' => 'Div',
|
||||
'if' => '{{product.data.shipping_policy}}',
|
||||
'children' => [
|
||||
[
|
||||
'name' => 'Span',
|
||||
'props' => ['text' => '{{product.data.shipping_policy.name}}'],
|
||||
],
|
||||
[
|
||||
'name' => 'Span',
|
||||
'props' => ['text' => '{{product.data.shipping_policy.fee_summary}}'],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$context = [
|
||||
'product' => [
|
||||
'data' => [
|
||||
'shipping_policy' => [
|
||||
'name' => '국내 무료배송',
|
||||
'fee_summary' => 'KR: Free Shipping',
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$html = $this->render($components, $context);
|
||||
|
||||
$this->assertStringContainsString('국내 무료배송', $html);
|
||||
$this->assertStringContainsString('KR: Free Shipping', $html);
|
||||
}
|
||||
|
||||
// ========================================================
|
||||
// 10. skip된 컴포넌트 검증 (인터랙티브 요소)
|
||||
// ========================================================
|
||||
|
||||
/**
|
||||
* skip:true 컴포넌트는 렌더링되지 않습니다 (인터랙티브 UI 제외).
|
||||
*/
|
||||
public function test_skipped_components_not_rendered(): void
|
||||
{
|
||||
$components = [
|
||||
[
|
||||
'name' => 'QuantitySelector',
|
||||
'props' => ['value' => '1'],
|
||||
],
|
||||
];
|
||||
|
||||
$html = $this->render($components);
|
||||
|
||||
// QuantitySelector는 seo-config.json에서 skip:true
|
||||
$this->assertEmpty(trim($html), 'QuantitySelector(skip:true)는 렌더링되지 않아야 합니다');
|
||||
}
|
||||
|
||||
/**
|
||||
* Select 컴포넌트는 <select> 태그로 렌더링됩니다 (skip 아님).
|
||||
*/
|
||||
public function test_select_renders_as_select_tag(): void
|
||||
{
|
||||
$components = [
|
||||
[
|
||||
'name' => 'Select',
|
||||
'props' => ['className' => 'w-full'],
|
||||
],
|
||||
];
|
||||
|
||||
$html = $this->render($components);
|
||||
|
||||
$this->assertStringContainsString('<select', $html);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Seo\SeoCacheManager;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Tests\TestCase;
|
||||
|
||||
class SeoCacheManagerTest extends TestCase
|
||||
{
|
||||
private SeoCacheManager $cacheManager;
|
||||
|
||||
/**
|
||||
* 테스트 초기화 - SeoCacheManager 인스턴스를 준비합니다.
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
// 캐시 활성화 기본 설정
|
||||
config()->set('g7_settings.core.seo.cache_enabled', true);
|
||||
config()->set('g7_settings.core.seo.cache_ttl', 7200);
|
||||
|
||||
// 이전 테스트 캐시 잔여물 제거
|
||||
Cache::flush();
|
||||
|
||||
$this->cacheManager = new SeoCacheManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* put 후 get 호출 시 저장된 HTML이 반환되는지 확인합니다.
|
||||
*/
|
||||
public function test_put_and_get_returns_stored_html(): void
|
||||
{
|
||||
$url = '/products/123';
|
||||
$locale = 'ko';
|
||||
$html = '<html><body>상품 상세</body></html>';
|
||||
|
||||
$this->cacheManager->put($url, $locale, $html);
|
||||
|
||||
$result = $this->cacheManager->get($url, $locale);
|
||||
|
||||
$this->assertSame($html, $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시되지 않은 URL에 대해 get 호출 시 null을 반환합니다.
|
||||
*/
|
||||
public function test_get_returns_null_when_not_cached(): void
|
||||
{
|
||||
$result = $this->cacheManager->get('/nonexistent', 'ko');
|
||||
|
||||
$this->assertNull($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* cache_enabled=false일 때 put이 무시되고 get이 null을 반환합니다.
|
||||
*/
|
||||
public function test_cache_disabled_ignores_put_and_returns_null(): void
|
||||
{
|
||||
config()->set('g7_settings.core.seo.cache_enabled', false);
|
||||
|
||||
$url = '/products/123';
|
||||
$locale = 'ko';
|
||||
$html = '<html><body>상품 상세</body></html>';
|
||||
|
||||
$this->cacheManager->put($url, $locale, $html);
|
||||
|
||||
$result = $this->cacheManager->get($url, $locale);
|
||||
|
||||
$this->assertNull($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* invalidateByUrl로 정확한 URL의 캐시만 제거됩니다.
|
||||
*/
|
||||
public function test_invalidate_by_url_removes_exact_url_cache(): void
|
||||
{
|
||||
$this->cacheManager->put('/products/1', 'ko', '<html>상품1</html>');
|
||||
$this->cacheManager->put('/products/2', 'ko', '<html>상품2</html>');
|
||||
$this->cacheManager->put('/categories/1', 'ko', '<html>카테고리1</html>');
|
||||
|
||||
$count = $this->cacheManager->invalidateByUrl('/products/1');
|
||||
|
||||
$this->assertSame(1, $count);
|
||||
$this->assertNull($this->cacheManager->get('/products/1', 'ko'));
|
||||
$this->assertNotNull($this->cacheManager->get('/products/2', 'ko'));
|
||||
$this->assertNotNull($this->cacheManager->get('/categories/1', 'ko'));
|
||||
}
|
||||
|
||||
/**
|
||||
* invalidateByLayout으로 해당 레이아웃의 캐시가 모두 제거됩니다.
|
||||
*/
|
||||
public function test_invalidate_by_layout_removes_matching_layout_caches(): void
|
||||
{
|
||||
$this->cacheManager->putWithLayout('/products/1', 'ko', '<html>상품1</html>', 'shop/show');
|
||||
$this->cacheManager->putWithLayout('/products/2', 'ko', '<html>상품2</html>', 'shop/show');
|
||||
$this->cacheManager->putWithLayout('/categories/1', 'ko', '<html>카테고리1</html>', 'shop/category');
|
||||
|
||||
$count = $this->cacheManager->invalidateByLayout('shop/show');
|
||||
|
||||
$this->assertSame(2, $count);
|
||||
$this->assertNull($this->cacheManager->get('/products/1', 'ko'));
|
||||
$this->assertNull($this->cacheManager->get('/products/2', 'ko'));
|
||||
$this->assertNotNull($this->cacheManager->get('/categories/1', 'ko'));
|
||||
}
|
||||
|
||||
/**
|
||||
* clearAll로 모든 SEO 캐시가 제거됩니다.
|
||||
*/
|
||||
public function test_clear_all_removes_all_seo_caches(): void
|
||||
{
|
||||
$this->cacheManager->put('/products/1', 'ko', '<html>상품1</html>');
|
||||
$this->cacheManager->put('/products/2', 'ko', '<html>상품2</html>');
|
||||
$this->cacheManager->put('/categories/1', 'en', '<html>Category1</html>');
|
||||
|
||||
$this->cacheManager->clearAll();
|
||||
|
||||
$this->assertNull($this->cacheManager->get('/products/1', 'ko'));
|
||||
$this->assertNull($this->cacheManager->get('/products/2', 'ko'));
|
||||
$this->assertNull($this->cacheManager->get('/categories/1', 'en'));
|
||||
$this->assertEmpty($this->cacheManager->getCachedUrls());
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시 키에 로케일이 포함되어 다른 로케일은 별도로 저장됩니다.
|
||||
*/
|
||||
public function test_cache_key_includes_locale_stores_separately(): void
|
||||
{
|
||||
$url = '/products/1';
|
||||
$htmlKo = '<html><body>상품 상세 (한국어)</body></html>';
|
||||
$htmlEn = '<html><body>Product Detail (English)</body></html>';
|
||||
|
||||
$this->cacheManager->put($url, 'ko', $htmlKo);
|
||||
$this->cacheManager->put($url, 'en', $htmlEn);
|
||||
|
||||
$resultKo = $this->cacheManager->get($url, 'ko');
|
||||
$resultEn = $this->cacheManager->get($url, 'en');
|
||||
|
||||
$this->assertSame($htmlKo, $resultKo);
|
||||
$this->assertSame($htmlEn, $resultEn);
|
||||
$this->assertNotSame($resultKo, $resultEn);
|
||||
}
|
||||
|
||||
/**
|
||||
* getCachedUrls가 캐시된 URL 목록을 반환합니다.
|
||||
*/
|
||||
public function test_get_cached_urls_returns_list(): void
|
||||
{
|
||||
$this->cacheManager->put('/products/1', 'ko', '<html>상품1</html>');
|
||||
$this->cacheManager->put('/categories/1', 'ko', '<html>카테고리1</html>');
|
||||
|
||||
$urls = $this->cacheManager->getCachedUrls();
|
||||
|
||||
$this->assertCount(2, $urls);
|
||||
$this->assertContains('/products/1', $urls);
|
||||
$this->assertContains('/categories/1', $urls);
|
||||
}
|
||||
|
||||
/**
|
||||
* putWithLayout이 레이아웃 정보를 인덱스에 함께 저장합니다.
|
||||
*/
|
||||
public function test_put_with_layout_stores_layout_info_in_index(): void
|
||||
{
|
||||
$this->cacheManager->putWithLayout('/products/1', 'ko', '<html>상품1</html>', 'shop/show');
|
||||
|
||||
// 캐시된 HTML 확인
|
||||
$result = $this->cacheManager->get('/products/1', 'ko');
|
||||
$this->assertSame('<html>상품1</html>', $result);
|
||||
|
||||
// 인덱스에서 URL 확인
|
||||
$urls = $this->cacheManager->getCachedUrls();
|
||||
$this->assertContains('/products/1', $urls);
|
||||
|
||||
// invalidateByLayout으로 레이아웃 정보가 저장되었는지 간접 확인
|
||||
$count = $this->cacheManager->invalidateByLayout('shop/show');
|
||||
$this->assertSame(1, $count);
|
||||
}
|
||||
|
||||
/**
|
||||
* invalidateByUrl에 와일드카드 패턴을 사용하여 여러 URL을 제거합니다.
|
||||
*/
|
||||
public function test_invalidate_by_url_with_wildcard_pattern(): void
|
||||
{
|
||||
$this->cacheManager->put('/products/1', 'ko', '<html>상품1</html>');
|
||||
$this->cacheManager->put('/products/2', 'ko', '<html>상품2</html>');
|
||||
$this->cacheManager->put('/categories/1', 'ko', '<html>카테고리1</html>');
|
||||
|
||||
$count = $this->cacheManager->invalidateByUrl('/products/*');
|
||||
|
||||
$this->assertSame(2, $count);
|
||||
$this->assertNull($this->cacheManager->get('/products/1', 'ko'));
|
||||
$this->assertNull($this->cacheManager->get('/products/2', 'ko'));
|
||||
$this->assertNotNull($this->cacheManager->get('/categories/1', 'ko'));
|
||||
}
|
||||
|
||||
/**
|
||||
* cache_enabled=false일 때 putWithLayout도 무시됩니다.
|
||||
*/
|
||||
public function test_put_with_layout_ignored_when_cache_disabled(): void
|
||||
{
|
||||
config()->set('g7_settings.core.seo.cache_enabled', false);
|
||||
|
||||
$this->cacheManager->putWithLayout('/products/1', 'ko', '<html>상품1</html>', 'shop/show');
|
||||
|
||||
$result = $this->cacheManager->get('/products/1', 'ko');
|
||||
$this->assertNull($result);
|
||||
$this->assertEmpty($this->cacheManager->getCachedUrls());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Seo\Contracts\SeoCacheManagerInterface;
|
||||
use App\Seo\Contracts\SeoRendererInterface;
|
||||
use App\Seo\SeoCacheRegenerator;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* SeoCacheRegenerator 테스트
|
||||
*
|
||||
* 단건 SEO 캐시 재생성 서비스의 동작을 검증합니다.
|
||||
* - 렌더링 성공 시 putWithLayout 호출
|
||||
* - 렌더링 실패(null) 시 캐시 저장 스킵
|
||||
* - 예외 발생 시 graceful 처리
|
||||
* - 다국어 로케일별 재생성
|
||||
*/
|
||||
class SeoCacheRegeneratorTest extends TestCase
|
||||
{
|
||||
private SeoRendererInterface $rendererMock;
|
||||
|
||||
private SeoCacheManagerInterface $cacheMock;
|
||||
|
||||
private SeoCacheRegenerator $regenerator;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->rendererMock = Mockery::mock(SeoRendererInterface::class);
|
||||
$this->cacheMock = Mockery::mock(SeoCacheManagerInterface::class);
|
||||
|
||||
$this->regenerator = new SeoCacheRegenerator(
|
||||
$this->rendererMock,
|
||||
$this->cacheMock,
|
||||
);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Mockery::close();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
// ─── 기본 재생성 ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 렌더링 성공 시 캐시에 저장되는지 확인
|
||||
*/
|
||||
public function test_render_and_cache_stores_html_on_success(): void
|
||||
{
|
||||
config(['app.locale' => 'ko']);
|
||||
config(['app.supported_locales' => ['ko']]);
|
||||
|
||||
$this->rendererMock->shouldReceive('render')
|
||||
->once()
|
||||
->with(Mockery::on(function (Request $request) {
|
||||
return $request->getPathInfo() === '/shop/products/1';
|
||||
}))
|
||||
->andReturnUsing(function (Request $request) {
|
||||
$request->attributes->set('seo_layout_name', 'shop/show');
|
||||
|
||||
return '<html>Product 1</html>';
|
||||
});
|
||||
|
||||
$this->cacheMock->shouldReceive('putWithLayout')
|
||||
->once()
|
||||
->with('/shop/products/1', 'ko', '<html>Product 1</html>', 'shop/show');
|
||||
|
||||
Log::shouldReceive('debug')->atLeast()->once();
|
||||
|
||||
$result = $this->regenerator->renderAndCache('/shop/products/1');
|
||||
|
||||
$this->assertTrue($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 렌더링 결과가 null이면 캐시 저장을 건너뛰는지 확인
|
||||
*/
|
||||
public function test_render_and_cache_skips_when_render_returns_null(): void
|
||||
{
|
||||
config(['app.locale' => 'ko']);
|
||||
config(['app.supported_locales' => ['ko']]);
|
||||
|
||||
$this->rendererMock->shouldReceive('render')
|
||||
->once()
|
||||
->andReturn(null);
|
||||
|
||||
$this->cacheMock->shouldNotReceive('putWithLayout');
|
||||
|
||||
$result = $this->regenerator->renderAndCache('/nonexistent');
|
||||
|
||||
$this->assertFalse($result);
|
||||
}
|
||||
|
||||
// ─── 다국어 재생성 ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 지원 로케일별로 각각 렌더링 + 캐시 저장이 수행되는지 확인
|
||||
*/
|
||||
public function test_render_and_cache_iterates_supported_locales(): void
|
||||
{
|
||||
config(['app.locale' => 'ko']);
|
||||
config(['app.supported_locales' => ['ko', 'en']]);
|
||||
|
||||
$this->rendererMock->shouldReceive('render')
|
||||
->twice()
|
||||
->andReturnUsing(function (Request $request) {
|
||||
$locale = app()->getLocale();
|
||||
$request->attributes->set('seo_layout_name', 'shop/show');
|
||||
|
||||
return "<html>Product ({$locale})</html>";
|
||||
});
|
||||
|
||||
$this->cacheMock->shouldReceive('putWithLayout')
|
||||
->once()
|
||||
->with('/shop/products/1', 'ko', Mockery::type('string'), 'shop/show');
|
||||
|
||||
$this->cacheMock->shouldReceive('putWithLayout')
|
||||
->once()
|
||||
->with('/shop/products/1', 'en', Mockery::type('string'), 'shop/show');
|
||||
|
||||
Log::shouldReceive('debug')->atLeast()->once();
|
||||
|
||||
$result = $this->regenerator->renderAndCache('/shop/products/1');
|
||||
|
||||
$this->assertTrue($result);
|
||||
}
|
||||
|
||||
// ─── 예외 처리 ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 렌더링 중 예외 발생 시 graceful하게 처리되는지 확인
|
||||
*/
|
||||
public function test_render_and_cache_handles_exceptions_gracefully(): void
|
||||
{
|
||||
config(['app.locale' => 'ko']);
|
||||
config(['app.supported_locales' => ['ko']]);
|
||||
|
||||
$this->rendererMock->shouldReceive('render')
|
||||
->once()
|
||||
->andThrow(new \RuntimeException('Renderer failed'));
|
||||
|
||||
$this->cacheMock->shouldNotReceive('putWithLayout');
|
||||
|
||||
Log::shouldReceive('warning')
|
||||
->once()
|
||||
->with('[SEO] Cache regeneration failed', Mockery::on(function ($context) {
|
||||
return $context['url'] === '/test'
|
||||
&& $context['error'] === 'Renderer failed';
|
||||
}));
|
||||
|
||||
$result = $this->regenerator->renderAndCache('/test');
|
||||
|
||||
$this->assertFalse($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 일부 로케일만 실패해도 나머지는 정상 처리되는지 확인
|
||||
*/
|
||||
public function test_render_and_cache_continues_on_partial_locale_failure(): void
|
||||
{
|
||||
config(['app.locale' => 'ko']);
|
||||
config(['app.supported_locales' => ['ko', 'en']]);
|
||||
|
||||
$callCount = 0;
|
||||
$this->rendererMock->shouldReceive('render')
|
||||
->twice()
|
||||
->andReturnUsing(function (Request $request) use (&$callCount) {
|
||||
$callCount++;
|
||||
if ($callCount === 1) {
|
||||
throw new \RuntimeException('ko render failed');
|
||||
}
|
||||
$request->attributes->set('seo_layout_name', 'shop/show');
|
||||
|
||||
return '<html>EN</html>';
|
||||
});
|
||||
|
||||
$this->cacheMock->shouldReceive('putWithLayout')
|
||||
->once()
|
||||
->with('/shop/products/1', 'en', '<html>EN</html>', 'shop/show');
|
||||
|
||||
Log::shouldReceive('warning')->once();
|
||||
Log::shouldReceive('debug')->atLeast()->once();
|
||||
|
||||
$result = $this->regenerator->renderAndCache('/shop/products/1');
|
||||
|
||||
$this->assertTrue($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 로케일이 렌더링 후 원래 값으로 복원되는지 확인
|
||||
*/
|
||||
public function test_render_and_cache_restores_locale(): void
|
||||
{
|
||||
config(['app.locale' => 'ko']);
|
||||
config(['app.supported_locales' => ['en']]);
|
||||
|
||||
app()->setLocale('ko');
|
||||
|
||||
$this->rendererMock->shouldReceive('render')
|
||||
->once()
|
||||
->andReturnUsing(function (Request $request) {
|
||||
$request->attributes->set('seo_layout_name', 'test');
|
||||
|
||||
return '<html>EN</html>';
|
||||
});
|
||||
|
||||
$this->cacheMock->shouldReceive('putWithLayout')->once();
|
||||
Log::shouldReceive('debug')->atLeast()->once();
|
||||
|
||||
$this->regenerator->renderAndCache('/test');
|
||||
|
||||
$this->assertEquals('ko', app()->getLocale());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Models\SeoCacheStat;
|
||||
use App\Seo\SeoCacheStatsService;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Tests\TestCase;
|
||||
|
||||
class SeoCacheStatsServiceTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private SeoCacheStatsService $statsService;
|
||||
|
||||
/**
|
||||
* 테스트 초기화 - SeoCacheStatsService 인스턴스를 준비합니다.
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->statsService = new SeoCacheStatsService;
|
||||
}
|
||||
|
||||
/**
|
||||
* recordHit이 type='hit'인 레코드를 생성합니다.
|
||||
*/
|
||||
public function test_record_hit_creates_hit_record(): void
|
||||
{
|
||||
$this->statsService->recordHit('/products/1', 'ko', 'shop/show', 'sirsoft-ecommerce');
|
||||
|
||||
$this->assertDatabaseHas('seo_cache_stats', [
|
||||
'url' => '/products/1',
|
||||
'locale' => 'ko',
|
||||
'layout_name' => 'shop/show',
|
||||
'module_identifier' => 'sirsoft-ecommerce',
|
||||
'type' => 'hit',
|
||||
'response_time_ms' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* recordMiss가 type='miss'이고 response_time_ms를 포함한 레코드를 생성합니다.
|
||||
*/
|
||||
public function test_record_miss_creates_miss_record_with_response_time(): void
|
||||
{
|
||||
$this->statsService->recordMiss('/products/1', 'ko', 'shop/show', 'sirsoft-ecommerce', 150);
|
||||
|
||||
$this->assertDatabaseHas('seo_cache_stats', [
|
||||
'url' => '/products/1',
|
||||
'locale' => 'ko',
|
||||
'layout_name' => 'shop/show',
|
||||
'module_identifier' => 'sirsoft-ecommerce',
|
||||
'type' => 'miss',
|
||||
'response_time_ms' => 150,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* recordHit에서 예외 발생 시 Log::warning으로 처리됩니다.
|
||||
*/
|
||||
public function test_record_hit_handles_exception_gracefully(): void
|
||||
{
|
||||
Log::shouldReceive('warning')
|
||||
->once()
|
||||
->withArgs(function (string $message, array $context) {
|
||||
return str_contains($message, '캐시 히트 기록 실패')
|
||||
&& $context['url'] === '/products/1';
|
||||
});
|
||||
|
||||
// 테이블을 삭제하여 DB 예외를 강제 발생
|
||||
Schema::drop('seo_cache_stats');
|
||||
|
||||
// 예외가 전파되지 않음을 확인
|
||||
$this->statsService->recordHit('/products/1', 'ko');
|
||||
}
|
||||
|
||||
/**
|
||||
* recordMiss에서 예외 발생 시 Log::warning으로 처리됩니다.
|
||||
*/
|
||||
public function test_record_miss_handles_exception_gracefully(): void
|
||||
{
|
||||
Log::shouldReceive('warning')
|
||||
->once()
|
||||
->withArgs(function (string $message, array $context) {
|
||||
return str_contains($message, '캐시 미스 기록 실패')
|
||||
&& $context['url'] === '/products/1';
|
||||
});
|
||||
|
||||
// 테이블을 삭제하여 DB 예외를 강제 발생
|
||||
Schema::drop('seo_cache_stats');
|
||||
|
||||
// 예외가 전파되지 않음을 확인
|
||||
$this->statsService->recordMiss('/products/1', 'ko', null, null, 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* 데이터가 없을 때 getStats가 기본값을 반환합니다.
|
||||
*/
|
||||
public function test_get_stats_returns_defaults_with_no_data(): void
|
||||
{
|
||||
$stats = $this->statsService->getStats();
|
||||
|
||||
$this->assertSame(0, $stats['total_entries']);
|
||||
$this->assertSame(0, $stats['hits']);
|
||||
$this->assertSame(0, $stats['misses']);
|
||||
$this->assertSame(0.0, $stats['hit_rate']);
|
||||
$this->assertNull($stats['avg_response_time_ms']);
|
||||
}
|
||||
|
||||
/**
|
||||
* getStats가 올바른 히트율을 계산합니다.
|
||||
*/
|
||||
public function test_get_stats_returns_correct_hit_rate(): void
|
||||
{
|
||||
// 3개 히트, 2개 미스 = 60% 히트율
|
||||
SeoCacheStat::create(['url' => '/p/1', 'locale' => 'ko', 'type' => 'hit']);
|
||||
SeoCacheStat::create(['url' => '/p/2', 'locale' => 'ko', 'type' => 'hit']);
|
||||
SeoCacheStat::create(['url' => '/p/3', 'locale' => 'ko', 'type' => 'hit']);
|
||||
SeoCacheStat::create(['url' => '/p/4', 'locale' => 'ko', 'type' => 'miss', 'response_time_ms' => 100]);
|
||||
SeoCacheStat::create(['url' => '/p/5', 'locale' => 'ko', 'type' => 'miss', 'response_time_ms' => 200]);
|
||||
|
||||
$stats = $this->statsService->getStats();
|
||||
|
||||
$this->assertSame(5, $stats['total_entries']);
|
||||
$this->assertSame(3, $stats['hits']);
|
||||
$this->assertSame(2, $stats['misses']);
|
||||
$this->assertSame(60.0, $stats['hit_rate']);
|
||||
}
|
||||
|
||||
/**
|
||||
* getStats가 since 파라미터로 기간 필터링합니다.
|
||||
*/
|
||||
public function test_get_stats_filters_by_since_date(): void
|
||||
{
|
||||
// 오래된 레코드 (5일 전)
|
||||
$old = SeoCacheStat::create(['url' => '/old', 'locale' => 'ko', 'type' => 'hit']);
|
||||
$old->created_at = Carbon::now()->subDays(5);
|
||||
$old->save();
|
||||
|
||||
// 최근 레코드 (1일 전)
|
||||
$recent = SeoCacheStat::create(['url' => '/recent', 'locale' => 'ko', 'type' => 'miss', 'response_time_ms' => 100]);
|
||||
$recent->created_at = Carbon::now()->subDays(1);
|
||||
$recent->save();
|
||||
|
||||
// 3일 이내 데이터만 조회
|
||||
$stats = $this->statsService->getStats(Carbon::now()->subDays(3));
|
||||
|
||||
$this->assertSame(1, $stats['total_entries']);
|
||||
$this->assertSame(0, $stats['hits']);
|
||||
$this->assertSame(1, $stats['misses']);
|
||||
}
|
||||
|
||||
/**
|
||||
* getStats가 미스 레코드의 평균 응답 시간을 계산합니다.
|
||||
*/
|
||||
public function test_get_stats_calculates_avg_response_time_from_misses_only(): void
|
||||
{
|
||||
// 히트 (response_time_ms 없음)
|
||||
SeoCacheStat::create(['url' => '/p/1', 'locale' => 'ko', 'type' => 'hit']);
|
||||
|
||||
// 미스 (response_time_ms 있음) - 평균 = (100 + 300) / 2 = 200
|
||||
SeoCacheStat::create(['url' => '/p/2', 'locale' => 'ko', 'type' => 'miss', 'response_time_ms' => 100]);
|
||||
SeoCacheStat::create(['url' => '/p/3', 'locale' => 'ko', 'type' => 'miss', 'response_time_ms' => 300]);
|
||||
|
||||
// 미스이지만 response_time_ms가 null
|
||||
SeoCacheStat::create(['url' => '/p/4', 'locale' => 'ko', 'type' => 'miss']);
|
||||
|
||||
$stats = $this->statsService->getStats();
|
||||
|
||||
$this->assertSame(4, $stats['total_entries']);
|
||||
$this->assertSame(200.0, $stats['avg_response_time_ms']);
|
||||
}
|
||||
|
||||
/**
|
||||
* getStatsByLayout이 레이아웃별로 통계를 그룹화합니다.
|
||||
*/
|
||||
public function test_get_stats_by_layout_groups_by_layout_name(): void
|
||||
{
|
||||
// shop/show 레이아웃: 2히트, 1미스
|
||||
SeoCacheStat::create(['url' => '/p/1', 'locale' => 'ko', 'layout_name' => 'shop/show', 'type' => 'hit']);
|
||||
SeoCacheStat::create(['url' => '/p/2', 'locale' => 'ko', 'layout_name' => 'shop/show', 'type' => 'hit']);
|
||||
SeoCacheStat::create(['url' => '/p/3', 'locale' => 'ko', 'layout_name' => 'shop/show', 'type' => 'miss', 'response_time_ms' => 150]);
|
||||
|
||||
// shop/category 레이아웃: 1히트, 1미스
|
||||
SeoCacheStat::create(['url' => '/c/1', 'locale' => 'ko', 'layout_name' => 'shop/category', 'type' => 'hit']);
|
||||
SeoCacheStat::create(['url' => '/c/2', 'locale' => 'ko', 'layout_name' => 'shop/category', 'type' => 'miss', 'response_time_ms' => 200]);
|
||||
|
||||
$result = $this->statsService->getStatsByLayout();
|
||||
|
||||
$this->assertCount(2, $result);
|
||||
|
||||
// layout_name 기준으로 정렬하여 검증
|
||||
$byLayout = collect($result)->keyBy('layout_name');
|
||||
|
||||
$showStats = $byLayout['shop/show'];
|
||||
$this->assertSame(3, $showStats['total']);
|
||||
$this->assertSame(2, $showStats['hits']);
|
||||
$this->assertSame(1, $showStats['misses']);
|
||||
$this->assertSame(66.67, $showStats['hit_rate']);
|
||||
$this->assertSame(150.0, $showStats['avg_response_time_ms']);
|
||||
|
||||
$categoryStats = $byLayout['shop/category'];
|
||||
$this->assertSame(2, $categoryStats['total']);
|
||||
$this->assertSame(1, $categoryStats['hits']);
|
||||
$this->assertSame(1, $categoryStats['misses']);
|
||||
$this->assertSame(50.0, $categoryStats['hit_rate']);
|
||||
$this->assertSame(200.0, $categoryStats['avg_response_time_ms']);
|
||||
}
|
||||
|
||||
/**
|
||||
* getStatsByModule이 모듈별로 통계를 그룹화합니다.
|
||||
*/
|
||||
public function test_get_stats_by_module_groups_by_module_identifier(): void
|
||||
{
|
||||
// sirsoft-ecommerce 모듈: 3히트, 1미스
|
||||
SeoCacheStat::create(['url' => '/p/1', 'locale' => 'ko', 'module_identifier' => 'sirsoft-ecommerce', 'type' => 'hit']);
|
||||
SeoCacheStat::create(['url' => '/p/2', 'locale' => 'ko', 'module_identifier' => 'sirsoft-ecommerce', 'type' => 'hit']);
|
||||
SeoCacheStat::create(['url' => '/p/3', 'locale' => 'ko', 'module_identifier' => 'sirsoft-ecommerce', 'type' => 'hit']);
|
||||
SeoCacheStat::create(['url' => '/p/4', 'locale' => 'ko', 'module_identifier' => 'sirsoft-ecommerce', 'type' => 'miss', 'response_time_ms' => 250]);
|
||||
|
||||
// sirsoft-blog 모듈: 1히트, 2미스
|
||||
SeoCacheStat::create(['url' => '/b/1', 'locale' => 'ko', 'module_identifier' => 'sirsoft-blog', 'type' => 'hit']);
|
||||
SeoCacheStat::create(['url' => '/b/2', 'locale' => 'ko', 'module_identifier' => 'sirsoft-blog', 'type' => 'miss', 'response_time_ms' => 100]);
|
||||
SeoCacheStat::create(['url' => '/b/3', 'locale' => 'ko', 'module_identifier' => 'sirsoft-blog', 'type' => 'miss', 'response_time_ms' => 300]);
|
||||
|
||||
$result = $this->statsService->getStatsByModule();
|
||||
|
||||
$this->assertCount(2, $result);
|
||||
|
||||
$byModule = collect($result)->keyBy('module_identifier');
|
||||
|
||||
$ecommerceStats = $byModule['sirsoft-ecommerce'];
|
||||
$this->assertSame(4, $ecommerceStats['total']);
|
||||
$this->assertSame(3, $ecommerceStats['hits']);
|
||||
$this->assertSame(1, $ecommerceStats['misses']);
|
||||
$this->assertSame(75.0, $ecommerceStats['hit_rate']);
|
||||
$this->assertSame(250.0, $ecommerceStats['avg_response_time_ms']);
|
||||
|
||||
$blogStats = $byModule['sirsoft-blog'];
|
||||
$this->assertSame(3, $blogStats['total']);
|
||||
$this->assertSame(1, $blogStats['hits']);
|
||||
$this->assertSame(2, $blogStats['misses']);
|
||||
$this->assertSame(33.33, $blogStats['hit_rate']);
|
||||
$this->assertSame(200.0, $blogStats['avg_response_time_ms']);
|
||||
}
|
||||
|
||||
/**
|
||||
* cleanup이 오래된 레코드를 삭제하고 최근 레코드를 유지합니다.
|
||||
*/
|
||||
public function test_cleanup_deletes_old_records_and_keeps_recent(): void
|
||||
{
|
||||
// 오래된 레코드 (40일 전)
|
||||
$old1 = SeoCacheStat::create(['url' => '/old/1', 'locale' => 'ko', 'type' => 'hit']);
|
||||
$old1->created_at = Carbon::now()->subDays(40);
|
||||
$old1->save();
|
||||
|
||||
$old2 = SeoCacheStat::create(['url' => '/old/2', 'locale' => 'ko', 'type' => 'miss', 'response_time_ms' => 100]);
|
||||
$old2->created_at = Carbon::now()->subDays(35);
|
||||
$old2->save();
|
||||
|
||||
// 최근 레코드 (10일 전)
|
||||
$recent1 = SeoCacheStat::create(['url' => '/recent/1', 'locale' => 'ko', 'type' => 'hit']);
|
||||
$recent1->created_at = Carbon::now()->subDays(10);
|
||||
$recent1->save();
|
||||
|
||||
// 오늘 레코드
|
||||
SeoCacheStat::create(['url' => '/today/1', 'locale' => 'ko', 'type' => 'miss', 'response_time_ms' => 200]);
|
||||
|
||||
$deleted = $this->statsService->cleanup(30);
|
||||
|
||||
$this->assertSame(2, $deleted);
|
||||
$this->assertDatabaseCount('seo_cache_stats', 2);
|
||||
$this->assertDatabaseMissing('seo_cache_stats', ['url' => '/old/1']);
|
||||
$this->assertDatabaseMissing('seo_cache_stats', ['url' => '/old/2']);
|
||||
$this->assertDatabaseHas('seo_cache_stats', ['url' => '/recent/1']);
|
||||
$this->assertDatabaseHas('seo_cache_stats', ['url' => '/today/1']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Contracts\Repositories\TemplateRepositoryInterface;
|
||||
use App\Extension\AbstractModule;
|
||||
use App\Extension\AbstractPlugin;
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Seo\SeoConfigMerger;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Mockery;
|
||||
use Mockery\MockInterface;
|
||||
use Tests\TestCase;
|
||||
|
||||
class SeoConfigMergerTest extends TestCase
|
||||
{
|
||||
private ModuleManager|MockInterface $moduleManager;
|
||||
|
||||
private PluginManager|MockInterface $pluginManager;
|
||||
|
||||
private TemplateRepositoryInterface|MockInterface $templateRepository;
|
||||
|
||||
private SeoConfigMerger $merger;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
// 테스트 간 캐시 격리
|
||||
Cache::flush();
|
||||
|
||||
$this->moduleManager = Mockery::mock(ModuleManager::class);
|
||||
$this->pluginManager = Mockery::mock(PluginManager::class);
|
||||
$this->templateRepository = Mockery::mock(TemplateRepositoryInterface::class);
|
||||
|
||||
$this->merger = new SeoConfigMerger(
|
||||
$this->moduleManager,
|
||||
$this->pluginManager,
|
||||
$this->templateRepository,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 빈 상태 병합 → 빈 배열 반환
|
||||
*/
|
||||
public function test_empty_merge_returns_empty_array(): void
|
||||
{
|
||||
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([]);
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([]);
|
||||
|
||||
// 템플릿 config 파일 미존재 시
|
||||
$result = $this->merger->getMergedConfig('nonexistent-template');
|
||||
|
||||
$this->assertIsArray($result);
|
||||
$this->assertEmpty($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿만 존재 → 템플릿 config 그대로 반환
|
||||
*/
|
||||
public function test_template_only_returns_template_config(): void
|
||||
{
|
||||
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([]);
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([]);
|
||||
|
||||
// 실제 템플릿의 seo-config.json 사용
|
||||
$result = $this->merger->getMergedConfig('sirsoft-basic');
|
||||
|
||||
$this->assertNotEmpty($result);
|
||||
$this->assertArrayHasKey('component_map', $result);
|
||||
$this->assertArrayHasKey('render_modes', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 config + 템플릿 config → component_map deep merge
|
||||
*/
|
||||
public function test_module_config_merged_with_template(): void
|
||||
{
|
||||
$module = $this->createModuleMock('test-module', [
|
||||
'component_map' => [
|
||||
'CustomWidget' => ['tag' => 'section', 'render' => 'iterate'],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->moduleManager->shouldReceive('getActiveModules')->andReturn(['test-module' => $module]);
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([]);
|
||||
|
||||
$result = $this->merger->getMergedConfig('sirsoft-basic');
|
||||
|
||||
// 모듈의 CustomWidget이 추가됨
|
||||
$this->assertArrayHasKey('CustomWidget', $result['component_map']);
|
||||
$this->assertEquals('section', $result['component_map']['CustomWidget']['tag']);
|
||||
|
||||
// 템플릿 기존 component_map도 유지됨
|
||||
$this->assertArrayHasKey('ProductCard', $result['component_map']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿이 모듈 component_map 오버라이드
|
||||
*/
|
||||
public function test_template_overrides_module_component_map(): void
|
||||
{
|
||||
$module = $this->createModuleMock('test-module', [
|
||||
'component_map' => [
|
||||
'ProductCard' => ['tag' => 'span', 'render' => 'iterate'],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->moduleManager->shouldReceive('getActiveModules')->andReturn(['test-module' => $module]);
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([]);
|
||||
|
||||
$result = $this->merger->getMergedConfig('sirsoft-basic');
|
||||
|
||||
// 템플릿이 최종 우선이므로 ProductCard는 템플릿 값
|
||||
$this->assertEquals('article', $result['component_map']['ProductCard']['tag']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인이 모듈보다 우선
|
||||
*/
|
||||
public function test_plugin_overrides_module(): void
|
||||
{
|
||||
$module = $this->createModuleMock('test-module', [
|
||||
'component_map' => [
|
||||
'SharedWidget' => ['tag' => 'div', 'render' => 'iterate'],
|
||||
],
|
||||
]);
|
||||
|
||||
$plugin = $this->createPluginMock('test-plugin', [
|
||||
'component_map' => [
|
||||
'SharedWidget' => ['tag' => 'section', 'render' => 'iterate'],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->moduleManager->shouldReceive('getActiveModules')->andReturn(['test-module' => $module]);
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn(['test-plugin' => $plugin]);
|
||||
|
||||
$result = $this->merger->getMergedConfig('sirsoft-basic');
|
||||
|
||||
// 플러그인이 모듈보다 우선
|
||||
$this->assertEquals('section', $result['component_map']['SharedWidget']['tag']);
|
||||
}
|
||||
|
||||
/**
|
||||
* text_props union 중복 제거
|
||||
*/
|
||||
public function test_text_props_union_deduplicated(): void
|
||||
{
|
||||
$module = $this->createModuleMock('test-module', [
|
||||
'text_props' => ['customProp', 'text', 'title'],
|
||||
]);
|
||||
|
||||
$this->moduleManager->shouldReceive('getActiveModules')->andReturn(['test-module' => $module]);
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([]);
|
||||
|
||||
$result = $this->merger->getMergedConfig('sirsoft-basic');
|
||||
|
||||
// text_props는 union, 중복 제거
|
||||
$this->assertContains('customProp', $result['text_props']);
|
||||
$this->assertContains('text', $result['text_props']);
|
||||
$this->assertContains('title', $result['text_props']);
|
||||
$this->assertEquals(count($result['text_props']), count(array_unique($result['text_props'])));
|
||||
}
|
||||
|
||||
/**
|
||||
* allowed_attrs union 중복 제거
|
||||
*/
|
||||
public function test_allowed_attrs_union_deduplicated(): void
|
||||
{
|
||||
$module = $this->createModuleMock('test-module', [
|
||||
'allowed_attrs' => ['data-custom', 'href'],
|
||||
]);
|
||||
|
||||
$this->moduleManager->shouldReceive('getActiveModules')->andReturn(['test-module' => $module]);
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([]);
|
||||
|
||||
$result = $this->merger->getMergedConfig('sirsoft-basic');
|
||||
|
||||
$this->assertContains('data-custom', $result['allowed_attrs']);
|
||||
$this->assertContains('href', $result['allowed_attrs']);
|
||||
$this->assertEquals(count($result['allowed_attrs']), count(array_unique($result['allowed_attrs'])));
|
||||
}
|
||||
|
||||
/**
|
||||
* self_closing union 중복 제거
|
||||
*/
|
||||
public function test_self_closing_union_deduplicated(): void
|
||||
{
|
||||
$module = $this->createModuleMock('test-module', [
|
||||
'self_closing' => ['CustomIcon', 'Icon'],
|
||||
]);
|
||||
|
||||
$this->moduleManager->shouldReceive('getActiveModules')->andReturn(['test-module' => $module]);
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([]);
|
||||
|
||||
$result = $this->merger->getMergedConfig('sirsoft-basic');
|
||||
|
||||
$this->assertContains('CustomIcon', $result['self_closing']);
|
||||
$this->assertContains('Icon', $result['self_closing']);
|
||||
$this->assertEquals(count($result['self_closing']), count(array_unique($result['self_closing'])));
|
||||
}
|
||||
|
||||
/**
|
||||
* stylesheets append 중복 제거
|
||||
*/
|
||||
public function test_stylesheets_append_deduplicated(): void
|
||||
{
|
||||
$module = $this->createModuleMock('test-module', [
|
||||
'stylesheets' => ['/css/module-custom.css', '/css/module-extra.css'],
|
||||
]);
|
||||
|
||||
$this->moduleManager->shouldReceive('getActiveModules')->andReturn(['test-module' => $module]);
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([]);
|
||||
|
||||
$result = $this->merger->getMergedConfig('sirsoft-basic');
|
||||
|
||||
$this->assertContains('/css/module-custom.css', $result['stylesheets']);
|
||||
$this->assertContains('/css/module-extra.css', $result['stylesheets']);
|
||||
$this->assertEquals(count($result['stylesheets']), count(array_unique($result['stylesheets'])));
|
||||
}
|
||||
|
||||
/**
|
||||
* render_modes deep merge
|
||||
*/
|
||||
public function test_render_modes_deep_merge(): void
|
||||
{
|
||||
$module = $this->createModuleMock('test-module', [
|
||||
'render_modes' => [
|
||||
'custom_view' => [
|
||||
'fields' => ['title', 'description'],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->moduleManager->shouldReceive('getActiveModules')->andReturn(['test-module' => $module]);
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([]);
|
||||
|
||||
$result = $this->merger->getMergedConfig('sirsoft-basic');
|
||||
|
||||
// 모듈의 custom_view가 추가됨
|
||||
$this->assertArrayHasKey('custom_view', $result['render_modes']);
|
||||
// 템플릿의 기존 render_modes도 유지
|
||||
$this->assertArrayHasKey('product_card_view', $result['render_modes']);
|
||||
}
|
||||
|
||||
/**
|
||||
* attr_map shallow merge (후순위 우선)
|
||||
*/
|
||||
public function test_attr_map_shallow_merge(): void
|
||||
{
|
||||
$module = $this->createModuleMock('test-module', [
|
||||
'attr_map' => [
|
||||
'customAttr' => 'data-custom',
|
||||
'className' => 'data-overridden',
|
||||
],
|
||||
]);
|
||||
|
||||
$this->moduleManager->shouldReceive('getActiveModules')->andReturn(['test-module' => $module]);
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([]);
|
||||
|
||||
$result = $this->merger->getMergedConfig('sirsoft-basic');
|
||||
|
||||
// 모듈의 새 attr 추가
|
||||
$this->assertEquals('data-custom', $result['attr_map']['customAttr']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 비활성 모듈 제외
|
||||
*/
|
||||
public function test_inactive_modules_excluded(): void
|
||||
{
|
||||
// getActiveModules는 빈 배열 반환 (비활성)
|
||||
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([]);
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([]);
|
||||
|
||||
$result = $this->merger->getMergedConfig('sirsoft-basic');
|
||||
|
||||
// 템플릿 config만 반환됨
|
||||
$this->assertNotEmpty($result);
|
||||
$this->assertArrayHasKey('component_map', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시 hit 확인 — 두 번째 호출은 캐시에서 반환
|
||||
*/
|
||||
public function test_cache_hit(): void
|
||||
{
|
||||
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([]);
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([]);
|
||||
|
||||
// 첫 호출 — 캐시 미스
|
||||
$result1 = $this->merger->getMergedConfig('sirsoft-basic');
|
||||
|
||||
// 두 번째 호출 — 캐시 히트
|
||||
$result2 = $this->merger->getMergedConfig('sirsoft-basic');
|
||||
|
||||
$this->assertEquals($result1, $result2);
|
||||
|
||||
// 캐시 키 존재 확인
|
||||
$this->assertTrue(Cache::has('seo:config:merged:sirsoft-basic'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시 클리어 후 재빌드
|
||||
*/
|
||||
public function test_cache_clear_rebuilds(): void
|
||||
{
|
||||
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([]);
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([]);
|
||||
|
||||
// 첫 호출
|
||||
$this->merger->getMergedConfig('sirsoft-basic');
|
||||
$this->assertTrue(Cache::has('seo:config:merged:sirsoft-basic'));
|
||||
|
||||
// 캐시 클리어
|
||||
$this->merger->clearCache('sirsoft-basic');
|
||||
$this->assertFalse(Cache::has('seo:config:merged:sirsoft-basic'));
|
||||
|
||||
// 재호출 — 캐시 미스이므로 다시 빌드
|
||||
$result = $this->merger->getMergedConfig('sirsoft-basic');
|
||||
|
||||
$this->assertNotEmpty($result);
|
||||
$this->assertTrue(Cache::has('seo:config:merged:sirsoft-basic'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 전체 캐시 클리어
|
||||
*/
|
||||
public function test_clear_all_cache(): void
|
||||
{
|
||||
$this->templateRepository->shouldReceive('getActive')
|
||||
->once()
|
||||
->andReturn(collect([]));
|
||||
|
||||
$this->merger->clearCache(null);
|
||||
|
||||
// 예외 없이 완료
|
||||
$this->assertTrue(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 알파벳순 정렬 (결정론적 병합)
|
||||
*/
|
||||
public function test_modules_sorted_alphabetically(): void
|
||||
{
|
||||
$moduleB = $this->createModuleMock('b-module', [
|
||||
'component_map' => [
|
||||
'WidgetB' => ['tag' => 'div', 'render' => 'iterate'],
|
||||
],
|
||||
]);
|
||||
|
||||
$moduleA = $this->createModuleMock('a-module', [
|
||||
'component_map' => [
|
||||
'WidgetA' => ['tag' => 'span', 'render' => 'iterate'],
|
||||
],
|
||||
]);
|
||||
|
||||
// 의도적으로 역순 전달
|
||||
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([
|
||||
'b-module' => $moduleB,
|
||||
'a-module' => $moduleA,
|
||||
]);
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([]);
|
||||
|
||||
$result = $this->merger->getMergedConfig('nonexistent-template');
|
||||
|
||||
// 두 모듈의 config가 모두 병합됨
|
||||
$this->assertArrayHasKey('WidgetA', $result['component_map']);
|
||||
$this->assertArrayHasKey('WidgetB', $result['component_map']);
|
||||
$this->assertEquals('span', $result['component_map']['WidgetA']['tag']);
|
||||
$this->assertEquals('div', $result['component_map']['WidgetB']['tag']);
|
||||
}
|
||||
|
||||
/**
|
||||
* seo_overrides shallow merge
|
||||
*/
|
||||
public function test_seo_overrides_shallow_merge(): void
|
||||
{
|
||||
$module = $this->createModuleMock('test-module', [
|
||||
'seo_overrides' => [
|
||||
'ProductCard' => ['tag' => 'div'],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->moduleManager->shouldReceive('getActiveModules')->andReturn(['test-module' => $module]);
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([]);
|
||||
|
||||
$result = $this->merger->getMergedConfig('sirsoft-basic');
|
||||
|
||||
$this->assertArrayHasKey('seo_overrides', $result);
|
||||
$this->assertArrayHasKey('ProductCard', $result['seo_overrides']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 config 로드 실패 시 스킵 (전체 병합 실패하지 않음)
|
||||
*/
|
||||
public function test_module_config_load_failure_skipped(): void
|
||||
{
|
||||
$this->moduleManager->shouldReceive('getActiveModules')
|
||||
->andThrow(new \RuntimeException('Module load failed'));
|
||||
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([]);
|
||||
|
||||
// 예외 없이 템플릿 config만 반환
|
||||
$result = $this->merger->getMergedConfig('sirsoft-basic');
|
||||
|
||||
$this->assertNotEmpty($result);
|
||||
$this->assertArrayHasKey('component_map', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 Mock 생성 헬퍼
|
||||
*/
|
||||
private function createModuleMock(string $identifier, array $seoConfig): AbstractModule|MockInterface
|
||||
{
|
||||
$module = Mockery::mock(AbstractModule::class.'_'.str_replace('-', '_', $identifier));
|
||||
$module->shouldReceive('getIdentifier')->andReturn($identifier);
|
||||
$module->shouldReceive('getSeoConfig')->andReturn($seoConfig);
|
||||
|
||||
return $module;
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 Mock 생성 헬퍼
|
||||
*/
|
||||
private function createPluginMock(string $identifier, array $seoConfig): AbstractPlugin|MockInterface
|
||||
{
|
||||
$plugin = Mockery::mock(AbstractPlugin::class.'_'.str_replace('-', '_', $identifier));
|
||||
$plugin->shouldReceive('getIdentifier')->andReturn($identifier);
|
||||
$plugin->shouldReceive('getSeoConfig')->andReturn($seoConfig);
|
||||
|
||||
return $plugin;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,705 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Contracts\Extension\ModuleInterface;
|
||||
use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Extension\PluginInterface;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
use App\Contracts\Extension\TemplateManagerInterface;
|
||||
use App\Seo\SeoDeclarationCollector;
|
||||
use App\Services\LayoutService;
|
||||
use App\Services\TemplateService;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* SeoDeclarationCollector 단위 테스트
|
||||
*
|
||||
* SEO 선언 수집기의 레이아웃 수집 및 확장별 그룹핑 기능을 테스트합니다.
|
||||
*/
|
||||
class SeoDeclarationCollectorTest extends TestCase
|
||||
{
|
||||
private TemplateService|Mockery\MockInterface $templateService;
|
||||
|
||||
private LayoutService|Mockery\MockInterface $layoutService;
|
||||
|
||||
private TemplateManagerInterface|Mockery\MockInterface $templateManager;
|
||||
|
||||
private ModuleManagerInterface|Mockery\MockInterface $moduleManager;
|
||||
|
||||
private PluginManagerInterface|Mockery\MockInterface $pluginManager;
|
||||
|
||||
private SeoDeclarationCollector $collector;
|
||||
|
||||
/**
|
||||
* 테스트 초기화 - SeoDeclarationCollector 인스턴스와 의존성 목(Mock)을 준비합니다.
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->templateService = Mockery::mock(TemplateService::class);
|
||||
$this->layoutService = Mockery::mock(LayoutService::class);
|
||||
$this->templateManager = Mockery::mock(TemplateManagerInterface::class);
|
||||
$this->moduleManager = Mockery::mock(ModuleManagerInterface::class);
|
||||
$this->pluginManager = Mockery::mock(PluginManagerInterface::class);
|
||||
|
||||
// 기본 모듈/플러그인 판별: 알려진 모듈만 매칭
|
||||
$this->moduleManager->shouldReceive('getModule')
|
||||
->andReturnUsing(function (string $id) {
|
||||
return in_array($id, ['sirsoft-ecommerce', 'sirsoft-board']) ? Mockery::mock(ModuleInterface::class) : null;
|
||||
})
|
||||
->byDefault();
|
||||
|
||||
$this->pluginManager->shouldReceive('getPlugin')
|
||||
->andReturn(null)
|
||||
->byDefault();
|
||||
|
||||
$this->collector = new SeoDeclarationCollector(
|
||||
$this->templateService,
|
||||
$this->layoutService,
|
||||
$this->templateManager,
|
||||
$this->moduleManager,
|
||||
$this->pluginManager,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트 종료 - Mockery 리소스를 정리합니다.
|
||||
*/
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Mockery::close();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 템플릿과 라우트를 설정하는 헬퍼 메서드
|
||||
*
|
||||
* @param array $routes 라우트 배열
|
||||
* @param string $templateIdentifier 템플릿 식별자
|
||||
*/
|
||||
private function setupActiveTemplateWithRoutes(array $routes, string $templateIdentifier = 'sirsoft-basic'): void
|
||||
{
|
||||
$this->templateManager
|
||||
->shouldReceive('getActiveTemplate')
|
||||
->with('user')
|
||||
->once()
|
||||
->andReturn(['identifier' => $templateIdentifier]);
|
||||
|
||||
$this->templateService
|
||||
->shouldReceive('getRoutesDataWithModules')
|
||||
->with($templateIdentifier)
|
||||
->once()
|
||||
->andReturn([
|
||||
'success' => true,
|
||||
'data' => ['routes' => $routes],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 로드 결과를 설정하는 헬퍼 메서드
|
||||
*
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @param array $layoutData 레이아웃 데이터
|
||||
* @param string $templateIdentifier 템플릿 식별자
|
||||
*/
|
||||
private function mockLayout(string $layoutName, array $layoutData, string $templateIdentifier = 'sirsoft-basic'): void
|
||||
{
|
||||
$this->layoutService
|
||||
->shouldReceive('getLayout')
|
||||
->with($templateIdentifier, $layoutName)
|
||||
->andReturn($layoutData);
|
||||
}
|
||||
|
||||
// ─── collect(): SEO 활성/비활성 레이아웃 수집 ──────────────────────
|
||||
|
||||
/**
|
||||
* SEO 활성 레이아웃만 수집되는지 확인합니다.
|
||||
* meta.seo.enabled=true인 레이아웃만 반환되어야 합니다.
|
||||
*/
|
||||
public function test_collect_returns_only_seo_enabled_layouts(): void
|
||||
{
|
||||
$this->setupActiveTemplateWithRoutes([
|
||||
['path' => '/', 'layout' => 'home', 'auth_required' => false],
|
||||
['path' => '/about', 'layout' => 'about', 'auth_required' => false],
|
||||
]);
|
||||
|
||||
$this->mockLayout('home', [
|
||||
'meta' => [
|
||||
'seo' => [
|
||||
'enabled' => true,
|
||||
'priority' => 1.0,
|
||||
'changefreq' => 'daily',
|
||||
],
|
||||
],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
$this->mockLayout('about', [
|
||||
'meta' => [
|
||||
'seo' => [
|
||||
'enabled' => true,
|
||||
'priority' => 0.8,
|
||||
'changefreq' => 'weekly',
|
||||
],
|
||||
],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
$result = $this->collector->collect();
|
||||
|
||||
$this->assertCount(2, $result);
|
||||
$this->assertEquals('home', $result[0]['layoutName']);
|
||||
$this->assertEquals('/', $result[0]['routePath']);
|
||||
$this->assertNull($result[0]['moduleIdentifier']);
|
||||
$this->assertEquals('about', $result[1]['layoutName']);
|
||||
$this->assertEquals('/about', $result[1]['routePath']);
|
||||
}
|
||||
|
||||
/**
|
||||
* SEO 비활성 레이아웃이 제외되는지 확인합니다.
|
||||
* meta.seo.enabled=false인 레이아웃은 결과에 포함되지 않아야 합니다.
|
||||
*/
|
||||
public function test_collect_excludes_seo_disabled_layouts(): void
|
||||
{
|
||||
$this->setupActiveTemplateWithRoutes([
|
||||
['path' => '/', 'layout' => 'home', 'auth_required' => false],
|
||||
['path' => '/internal', 'layout' => 'internal', 'auth_required' => false],
|
||||
]);
|
||||
|
||||
$this->mockLayout('home', [
|
||||
'meta' => [
|
||||
'seo' => ['enabled' => true, 'priority' => 1.0],
|
||||
],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
$this->mockLayout('internal', [
|
||||
'meta' => [
|
||||
'seo' => ['enabled' => false],
|
||||
],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
$result = $this->collector->collect();
|
||||
|
||||
$this->assertCount(1, $result);
|
||||
$this->assertEquals('home', $result[0]['layoutName']);
|
||||
}
|
||||
|
||||
/**
|
||||
* meta.seo 속성이 없는 레이아웃이 제외되는지 확인합니다.
|
||||
*/
|
||||
public function test_collect_excludes_layouts_without_seo_meta(): void
|
||||
{
|
||||
$this->setupActiveTemplateWithRoutes([
|
||||
['path' => '/', 'layout' => 'home', 'auth_required' => false],
|
||||
['path' => '/plain', 'layout' => 'plain', 'auth_required' => false],
|
||||
]);
|
||||
|
||||
$this->mockLayout('home', [
|
||||
'meta' => [
|
||||
'seo' => ['enabled' => true, 'priority' => 1.0],
|
||||
],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
$this->mockLayout('plain', [
|
||||
'meta' => [],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
$result = $this->collector->collect();
|
||||
|
||||
$this->assertCount(1, $result);
|
||||
$this->assertEquals('home', $result[0]['layoutName']);
|
||||
}
|
||||
|
||||
// ─── collect(): auth_required / guest_only 필터링 ──────────────────
|
||||
|
||||
/**
|
||||
* auth_required=true인 라우트가 제외되는지 확인합니다.
|
||||
*/
|
||||
public function test_collect_skips_auth_required_routes(): void
|
||||
{
|
||||
$this->setupActiveTemplateWithRoutes([
|
||||
['path' => '/', 'layout' => 'home', 'auth_required' => false],
|
||||
['path' => '/mypage', 'layout' => 'mypage', 'auth_required' => true],
|
||||
]);
|
||||
|
||||
$this->mockLayout('home', [
|
||||
'meta' => ['seo' => ['enabled' => true]],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
// mypage는 auth_required=true이므로 getLayout 호출되지 않아야 함
|
||||
$this->layoutService
|
||||
->shouldNotReceive('getLayout')
|
||||
->with('sirsoft-basic', 'mypage');
|
||||
|
||||
$result = $this->collector->collect();
|
||||
|
||||
$this->assertCount(1, $result);
|
||||
$this->assertEquals('home', $result[0]['layoutName']);
|
||||
}
|
||||
|
||||
/**
|
||||
* guest_only=true인 라우트가 제외되는지 확인합니다.
|
||||
*/
|
||||
public function test_collect_skips_guest_only_routes(): void
|
||||
{
|
||||
$this->setupActiveTemplateWithRoutes([
|
||||
['path' => '/', 'layout' => 'home', 'auth_required' => false],
|
||||
['path' => '/login', 'layout' => 'login', 'auth_required' => false, 'guest_only' => true],
|
||||
]);
|
||||
|
||||
$this->mockLayout('home', [
|
||||
'meta' => ['seo' => ['enabled' => true]],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
$result = $this->collector->collect();
|
||||
|
||||
$this->assertCount(1, $result);
|
||||
}
|
||||
|
||||
// ─── collect(): 모듈 레이아웃 (dotted notation) ──────────────────
|
||||
|
||||
/**
|
||||
* 모듈 레이아웃의 moduleIdentifier가 올바르게 추출되는지 확인합니다.
|
||||
* 레이아웃명에 '.'이 포함되면 앞부분이 moduleIdentifier, 뒷부분이 actualLayoutName입니다.
|
||||
*/
|
||||
public function test_collect_extracts_module_identifier_from_dotted_layout_name(): void
|
||||
{
|
||||
$this->setupActiveTemplateWithRoutes([
|
||||
['path' => '/shop/products', 'layout' => 'sirsoft-ecommerce.shop/index', 'auth_required' => false],
|
||||
]);
|
||||
|
||||
$this->mockLayout('sirsoft-ecommerce.shop/index', [
|
||||
'meta' => [
|
||||
'seo' => ['enabled' => true, 'priority' => 0.9, 'changefreq' => 'daily'],
|
||||
],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
$result = $this->collector->collect();
|
||||
|
||||
$this->assertCount(1, $result);
|
||||
$this->assertEquals('shop/index', $result[0]['layoutName']);
|
||||
$this->assertEquals('sirsoft-ecommerce', $result[0]['moduleIdentifier']);
|
||||
$this->assertEquals('sirsoft-basic', $result[0]['templateIdentifier']);
|
||||
$this->assertEquals('/shop/products', $result[0]['routePath']);
|
||||
}
|
||||
|
||||
// ─── collect(): 부모-자식 SEO 병합 (getLayout이 이미 병합) ──────────
|
||||
|
||||
/**
|
||||
* 부모 seo + 자식 seo가 deep merge된 결과로 수집되는지 확인합니다.
|
||||
* getLayout()은 이미 병합된 레이아웃을 반환하므로 수집기는 최종 결과만 판단합니다.
|
||||
*/
|
||||
public function test_collect_uses_merged_seo_from_layout_service(): void
|
||||
{
|
||||
$this->setupActiveTemplateWithRoutes([
|
||||
['path' => '/products', 'layout' => 'sirsoft-ecommerce.products', 'auth_required' => false],
|
||||
]);
|
||||
|
||||
// getLayout은 부모+자식 병합 결과를 반환
|
||||
$this->mockLayout('sirsoft-ecommerce.products', [
|
||||
'meta' => [
|
||||
'seo' => [
|
||||
'enabled' => true,
|
||||
'priority' => 0.7,
|
||||
'changefreq' => 'weekly',
|
||||
'title' => '상품 목록 - {{site.name}}',
|
||||
],
|
||||
],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
$result = $this->collector->collect();
|
||||
|
||||
$this->assertCount(1, $result);
|
||||
$this->assertTrue($result[0]['seo']['enabled']);
|
||||
$this->assertEquals(0.7, $result[0]['seo']['priority']);
|
||||
$this->assertEquals('weekly', $result[0]['seo']['changefreq']);
|
||||
$this->assertEquals('상품 목록 - {{site.name}}', $result[0]['seo']['title']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 부모만 seo.enabled=true이고 자식이 seo 미정의인 경우,
|
||||
* 병합 결과 enabled=true이므로 수집 대상에 포함됩니다.
|
||||
*/
|
||||
public function test_collect_includes_layout_when_parent_seo_enabled_child_undefined(): void
|
||||
{
|
||||
$this->setupActiveTemplateWithRoutes([
|
||||
['path' => '/page', 'layout' => 'page', 'auth_required' => false],
|
||||
]);
|
||||
|
||||
// 부모 seo.enabled=true, 자식 미정의 → 병합 결과 enabled=true
|
||||
$this->mockLayout('page', [
|
||||
'meta' => [
|
||||
'seo' => ['enabled' => true, 'priority' => 0.5],
|
||||
],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
$result = $this->collector->collect();
|
||||
|
||||
$this->assertCount(1, $result);
|
||||
$this->assertTrue($result[0]['seo']['enabled']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 자식이 seo.enabled=false로 오버라이드하면 (부모 true 상관없이)
|
||||
* 병합 결과 enabled=false이므로 수집에서 제외됩니다.
|
||||
*/
|
||||
public function test_collect_excludes_layout_when_child_overrides_seo_enabled_false(): void
|
||||
{
|
||||
$this->setupActiveTemplateWithRoutes([
|
||||
['path' => '/page', 'layout' => 'page', 'auth_required' => false],
|
||||
]);
|
||||
|
||||
// 부모 enabled=true이지만 자식이 enabled=false로 오버라이드 → 병합 결과 false
|
||||
$this->mockLayout('page', [
|
||||
'meta' => [
|
||||
'seo' => ['enabled' => false, 'priority' => 0.5],
|
||||
],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
$result = $this->collector->collect();
|
||||
|
||||
$this->assertCount(0, $result);
|
||||
}
|
||||
|
||||
// ─── collect(): 엣지 케이스 ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 라우트가 0개인 빈 템플릿에서 빈 배열이 반환되는지 확인합니다.
|
||||
*/
|
||||
public function test_collect_returns_empty_for_empty_routes(): void
|
||||
{
|
||||
$this->templateManager
|
||||
->shouldReceive('getActiveTemplate')
|
||||
->with('user')
|
||||
->once()
|
||||
->andReturn(['identifier' => 'sirsoft-basic']);
|
||||
|
||||
$this->templateService
|
||||
->shouldReceive('getRoutesDataWithModules')
|
||||
->with('sirsoft-basic')
|
||||
->once()
|
||||
->andReturn([
|
||||
'success' => true,
|
||||
'data' => ['routes' => []],
|
||||
]);
|
||||
|
||||
$result = $this->collector->collect();
|
||||
|
||||
$this->assertEmpty($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 템플릿이 없을 때 빈 배열이 반환되는지 확인합니다.
|
||||
*/
|
||||
public function test_collect_returns_empty_when_no_active_template(): void
|
||||
{
|
||||
$this->templateManager
|
||||
->shouldReceive('getActiveTemplate')
|
||||
->with('user')
|
||||
->once()
|
||||
->andReturn(null);
|
||||
|
||||
$result = $this->collector->collect();
|
||||
|
||||
$this->assertEmpty($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 템플릿에 identifier가 없을 때 빈 배열이 반환되는지 확인합니다.
|
||||
*/
|
||||
public function test_collect_returns_empty_when_template_has_no_identifier(): void
|
||||
{
|
||||
$this->templateManager
|
||||
->shouldReceive('getActiveTemplate')
|
||||
->with('user')
|
||||
->once()
|
||||
->andReturn(['name' => 'Some Template']);
|
||||
|
||||
$result = $this->collector->collect();
|
||||
|
||||
$this->assertEmpty($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 라우트 데이터 조회 실패 시 빈 배열이 반환되는지 확인합니다.
|
||||
*/
|
||||
public function test_collect_returns_empty_when_routes_fetch_fails(): void
|
||||
{
|
||||
$this->templateManager
|
||||
->shouldReceive('getActiveTemplate')
|
||||
->with('user')
|
||||
->once()
|
||||
->andReturn(['identifier' => 'sirsoft-basic']);
|
||||
|
||||
$this->templateService
|
||||
->shouldReceive('getRoutesDataWithModules')
|
||||
->with('sirsoft-basic')
|
||||
->once()
|
||||
->andReturn(['success' => false]);
|
||||
|
||||
$result = $this->collector->collect();
|
||||
|
||||
$this->assertEmpty($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 로드 중 예외 발생 시 해당 레이아웃을 건너뛰고
|
||||
* 나머지는 정상 수집되는지 확인합니다 (graceful skip).
|
||||
*/
|
||||
public function test_collect_gracefully_skips_layout_on_exception(): void
|
||||
{
|
||||
$this->setupActiveTemplateWithRoutes([
|
||||
['path' => '/', 'layout' => 'home', 'auth_required' => false],
|
||||
['path' => '/broken', 'layout' => 'broken', 'auth_required' => false],
|
||||
['path' => '/about', 'layout' => 'about', 'auth_required' => false],
|
||||
]);
|
||||
|
||||
$this->mockLayout('home', [
|
||||
'meta' => ['seo' => ['enabled' => true]],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
$this->layoutService
|
||||
->shouldReceive('getLayout')
|
||||
->with('sirsoft-basic', 'broken')
|
||||
->andThrow(new \Exception('레이아웃 파일을 찾을 수 없습니다'));
|
||||
|
||||
$this->mockLayout('about', [
|
||||
'meta' => ['seo' => ['enabled' => true]],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
Log::shouldReceive('warning')
|
||||
->once()
|
||||
->withArgs(function (string $message, array $context) {
|
||||
return str_contains($message, 'SeoDeclarationCollector')
|
||||
&& $context['layout'] === 'broken';
|
||||
});
|
||||
|
||||
$result = $this->collector->collect();
|
||||
|
||||
$this->assertCount(2, $result);
|
||||
$this->assertEquals('home', $result[0]['layoutName']);
|
||||
$this->assertEquals('about', $result[1]['layoutName']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 빈 레이아웃 이름인 라우트가 건너뛰어지는지 확인합니다.
|
||||
*/
|
||||
public function test_collect_skips_routes_with_empty_layout_name(): void
|
||||
{
|
||||
$this->setupActiveTemplateWithRoutes([
|
||||
['path' => '/', 'layout' => 'home', 'auth_required' => false],
|
||||
['path' => '/empty', 'layout' => '', 'auth_required' => false],
|
||||
]);
|
||||
|
||||
$this->mockLayout('home', [
|
||||
'meta' => ['seo' => ['enabled' => true]],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
$result = $this->collector->collect();
|
||||
|
||||
$this->assertCount(1, $result);
|
||||
}
|
||||
|
||||
// ─── collectGroupedByExtension() ──────────────────────────────────
|
||||
|
||||
/**
|
||||
* SEO 선언이 확장별로 올바르게 그룹핑되는지 확인합니다.
|
||||
* moduleIdentifier가 null이면 'core' 키로 그룹핑됩니다.
|
||||
*/
|
||||
public function test_collect_grouped_by_extension(): void
|
||||
{
|
||||
$this->setupActiveTemplateWithRoutes([
|
||||
['path' => '/', 'layout' => 'home', 'auth_required' => false],
|
||||
['path' => '/about', 'layout' => 'about', 'auth_required' => false],
|
||||
['path' => '/shop/products', 'layout' => 'sirsoft-ecommerce.shop/index', 'auth_required' => false],
|
||||
['path' => '/shop/cart', 'layout' => 'sirsoft-ecommerce.shop/cart', 'auth_required' => false],
|
||||
['path' => '/board', 'layout' => 'sirsoft-board.board/list', 'auth_required' => false],
|
||||
]);
|
||||
|
||||
// 코어 레이아웃
|
||||
$this->mockLayout('home', [
|
||||
'meta' => ['seo' => ['enabled' => true, 'priority' => 1.0]],
|
||||
'components' => [],
|
||||
]);
|
||||
$this->mockLayout('about', [
|
||||
'meta' => ['seo' => ['enabled' => true, 'priority' => 0.8]],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
// 이커머스 모듈 레이아웃
|
||||
$this->mockLayout('sirsoft-ecommerce.shop/index', [
|
||||
'meta' => ['seo' => ['enabled' => true, 'priority' => 0.9]],
|
||||
'components' => [],
|
||||
]);
|
||||
$this->mockLayout('sirsoft-ecommerce.shop/cart', [
|
||||
'meta' => ['seo' => ['enabled' => true, 'priority' => 0.5]],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
// 게시판 모듈 레이아웃
|
||||
$this->mockLayout('sirsoft-board.board/list', [
|
||||
'meta' => ['seo' => ['enabled' => true, 'priority' => 0.7]],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
$result = $this->collector->collectGroupedByExtension();
|
||||
|
||||
// 코어 그룹: home, about
|
||||
$this->assertArrayHasKey('core', $result);
|
||||
$this->assertCount(2, $result['core']);
|
||||
|
||||
// 이커머스 그룹: shop/index, shop/cart
|
||||
$this->assertArrayHasKey('sirsoft-ecommerce', $result);
|
||||
$this->assertCount(2, $result['sirsoft-ecommerce']);
|
||||
|
||||
// 게시판 그룹: board/list
|
||||
$this->assertArrayHasKey('sirsoft-board', $result);
|
||||
$this->assertCount(1, $result['sirsoft-board']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 수집된 선언이 없을 때 collectGroupedByExtension()이 빈 배열을 반환하는지 확인합니다.
|
||||
*/
|
||||
public function test_collect_grouped_by_extension_returns_empty_when_no_declarations(): void
|
||||
{
|
||||
$this->templateManager
|
||||
->shouldReceive('getActiveTemplate')
|
||||
->with('user')
|
||||
->once()
|
||||
->andReturn(null);
|
||||
|
||||
$result = $this->collector->collectGroupedByExtension();
|
||||
|
||||
$this->assertEmpty($result);
|
||||
}
|
||||
|
||||
// ─── collect(): 선언 구조 검증 ──────────────────────────────────
|
||||
|
||||
/**
|
||||
* 수집된 선언의 구조가 올바른지 확인합니다.
|
||||
* 각 선언에는 layoutName, templateIdentifier, moduleIdentifier, seo, routePath가 포함되어야 합니다.
|
||||
*/
|
||||
public function test_collect_declaration_has_correct_structure(): void
|
||||
{
|
||||
$this->setupActiveTemplateWithRoutes([
|
||||
['path' => '/shop', 'layout' => 'sirsoft-ecommerce.shop/index', 'auth_required' => false],
|
||||
]);
|
||||
|
||||
$seoConfig = [
|
||||
'enabled' => true,
|
||||
'priority' => 0.9,
|
||||
'changefreq' => 'daily',
|
||||
];
|
||||
|
||||
$this->mockLayout('sirsoft-ecommerce.shop/index', [
|
||||
'meta' => ['seo' => $seoConfig],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
$result = $this->collector->collect();
|
||||
|
||||
$this->assertCount(1, $result);
|
||||
$declaration = $result[0];
|
||||
|
||||
$this->assertArrayHasKey('layoutName', $declaration);
|
||||
$this->assertArrayHasKey('templateIdentifier', $declaration);
|
||||
$this->assertArrayHasKey('moduleIdentifier', $declaration);
|
||||
$this->assertArrayHasKey('pluginIdentifier', $declaration);
|
||||
$this->assertArrayHasKey('seo', $declaration);
|
||||
$this->assertArrayHasKey('routePath', $declaration);
|
||||
|
||||
$this->assertEquals('shop/index', $declaration['layoutName']);
|
||||
$this->assertEquals('sirsoft-basic', $declaration['templateIdentifier']);
|
||||
$this->assertEquals('sirsoft-ecommerce', $declaration['moduleIdentifier']);
|
||||
$this->assertNull($declaration['pluginIdentifier']);
|
||||
$this->assertEquals($seoConfig, $declaration['seo']);
|
||||
$this->assertEquals('/shop', $declaration['routePath']);
|
||||
}
|
||||
|
||||
// ─── collect(): 플러그인 레이아웃 (dotted notation) ──────────────────
|
||||
|
||||
/**
|
||||
* 플러그인 dot notation에서 pluginIdentifier가 추출되는지 확인합니다.
|
||||
*/
|
||||
public function test_collect_extracts_plugin_identifier_from_dotted_layout(): void
|
||||
{
|
||||
// 플러그인 판별 설정
|
||||
$this->pluginManager->shouldReceive('getPlugin')
|
||||
->with('sirsoft-payment')
|
||||
->andReturn(Mockery::mock(PluginInterface::class));
|
||||
|
||||
$this->setupActiveTemplateWithRoutes([
|
||||
['path' => '/payment/checkout', 'layout' => 'sirsoft-payment.checkout', 'auth_required' => false],
|
||||
]);
|
||||
|
||||
$this->mockLayout('sirsoft-payment.checkout', [
|
||||
'meta' => ['seo' => ['enabled' => true, 'priority' => 0.5]],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
$result = $this->collector->collect();
|
||||
|
||||
$this->assertCount(1, $result);
|
||||
$this->assertEquals('checkout', $result[0]['layoutName']);
|
||||
$this->assertNull($result[0]['moduleIdentifier']);
|
||||
$this->assertEquals('sirsoft-payment', $result[0]['pluginIdentifier']);
|
||||
}
|
||||
|
||||
/**
|
||||
* collectGroupedByExtension()에서 플러그인 레이아웃이 별도 그룹 키로 분류됩니다.
|
||||
*/
|
||||
public function test_collect_grouped_by_extension_includes_plugins(): void
|
||||
{
|
||||
// 플러그인 판별 설정
|
||||
$this->pluginManager->shouldReceive('getPlugin')
|
||||
->with('sirsoft-payment')
|
||||
->andReturn(Mockery::mock(PluginInterface::class));
|
||||
|
||||
$this->setupActiveTemplateWithRoutes([
|
||||
['path' => '/', 'layout' => 'home', 'auth_required' => false],
|
||||
['path' => '/shop', 'layout' => 'sirsoft-ecommerce.shop/index', 'auth_required' => false],
|
||||
['path' => '/payment', 'layout' => 'sirsoft-payment.checkout', 'auth_required' => false],
|
||||
]);
|
||||
|
||||
$this->mockLayout('home', [
|
||||
'meta' => ['seo' => ['enabled' => true]],
|
||||
'components' => [],
|
||||
]);
|
||||
$this->mockLayout('sirsoft-ecommerce.shop/index', [
|
||||
'meta' => ['seo' => ['enabled' => true]],
|
||||
'components' => [],
|
||||
]);
|
||||
$this->mockLayout('sirsoft-payment.checkout', [
|
||||
'meta' => ['seo' => ['enabled' => true]],
|
||||
'components' => [],
|
||||
]);
|
||||
|
||||
$result = $this->collector->collectGroupedByExtension();
|
||||
|
||||
$this->assertArrayHasKey('core', $result);
|
||||
$this->assertCount(1, $result['core']);
|
||||
|
||||
$this->assertArrayHasKey('sirsoft-ecommerce', $result);
|
||||
$this->assertCount(1, $result['sirsoft-ecommerce']);
|
||||
|
||||
$this->assertArrayHasKey('sirsoft-payment', $result);
|
||||
$this->assertCount(1, $result['sirsoft-payment']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Seo\Contracts\SeoCacheManagerInterface;
|
||||
use App\Seo\SeoInvalidationRegistry;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Mockery;
|
||||
use Mockery\MockInterface;
|
||||
use Tests\TestCase;
|
||||
|
||||
class SeoInvalidationRegistryTest extends TestCase
|
||||
{
|
||||
private SeoCacheManagerInterface&MockInterface $cacheManager;
|
||||
|
||||
private SeoInvalidationRegistry $registry;
|
||||
|
||||
/**
|
||||
* 테스트 초기화 - SeoInvalidationRegistry 인스턴스를 준비합니다.
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->cacheManager = Mockery::mock(SeoCacheManagerInterface::class);
|
||||
$this->registry = new SeoInvalidationRegistry($this->cacheManager);
|
||||
}
|
||||
|
||||
/**
|
||||
* registerRule이 규칙을 올바르게 저장하는지 확인합니다.
|
||||
*/
|
||||
public function test_register_rule_stores_rules_correctly(): void
|
||||
{
|
||||
$this->registry->registerRule('product.updated', ['product-detail', 'product-list'], '/products/*');
|
||||
|
||||
$rules = $this->registry->getRulesForHook('product.updated');
|
||||
|
||||
$this->assertCount(1, $rules);
|
||||
$this->assertSame(['product-detail', 'product-list'], $rules[0]['layouts']);
|
||||
$this->assertSame('/products/*', $rules[0]['urlPattern']);
|
||||
}
|
||||
|
||||
/**
|
||||
* registerRule이 메서드 체이닝(fluent)을 지원하는지 확인합니다.
|
||||
*/
|
||||
public function test_register_rule_supports_fluent_chaining(): void
|
||||
{
|
||||
$result = $this->registry
|
||||
->registerRule('product.updated', ['product-detail'])
|
||||
->registerRule('category.updated', ['category-list']);
|
||||
|
||||
$this->assertInstanceOf(SeoInvalidationRegistry::class, $result);
|
||||
$this->assertCount(1, $this->registry->getRulesForHook('product.updated'));
|
||||
$this->assertCount(1, $this->registry->getRulesForHook('category.updated'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 동일 훅에 여러 규칙을 등록할 수 있는지 확인합니다.
|
||||
*/
|
||||
public function test_multiple_rules_for_same_hook(): void
|
||||
{
|
||||
$this->registry->registerRule('product.updated', ['product-detail'], '/products/*');
|
||||
$this->registry->registerRule('product.updated', ['product-list'], '/categories/*');
|
||||
|
||||
$rules = $this->registry->getRulesForHook('product.updated');
|
||||
|
||||
$this->assertCount(2, $rules);
|
||||
$this->assertSame(['product-detail'], $rules[0]['layouts']);
|
||||
$this->assertSame('/products/*', $rules[0]['urlPattern']);
|
||||
$this->assertSame(['product-list'], $rules[1]['layouts']);
|
||||
$this->assertSame('/categories/*', $rules[1]['urlPattern']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 등록되지 않은 훅에 대해 invalidate가 0을 반환하는지 확인합니다.
|
||||
*/
|
||||
public function test_invalidate_returns_zero_for_unregistered_hook(): void
|
||||
{
|
||||
$result = $this->registry->invalidate('unknown.hook');
|
||||
|
||||
$this->assertSame(0, $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* invalidate가 invalidateByUrl과 invalidateByLayout을 올바르게 호출하는지 확인합니다.
|
||||
*/
|
||||
public function test_invalidate_calls_cache_manager_correctly(): void
|
||||
{
|
||||
$this->registry->registerRule('product.updated', ['product-detail', 'product-list'], '/products/*');
|
||||
|
||||
$this->cacheManager
|
||||
->shouldReceive('invalidateByUrl')
|
||||
->once()
|
||||
->with('/products/*')
|
||||
->andReturn(3);
|
||||
|
||||
$this->cacheManager
|
||||
->shouldReceive('invalidateByLayout')
|
||||
->once()
|
||||
->with('product-detail')
|
||||
->andReturn(2);
|
||||
|
||||
$this->cacheManager
|
||||
->shouldReceive('invalidateByLayout')
|
||||
->once()
|
||||
->with('product-list')
|
||||
->andReturn(1);
|
||||
|
||||
$result = $this->registry->invalidate('product.updated');
|
||||
|
||||
$this->assertSame(6, $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* urlPattern이 null일 때 URL 무효화를 건너뛰는지 확인합니다.
|
||||
*/
|
||||
public function test_invalidate_skips_url_when_pattern_is_null(): void
|
||||
{
|
||||
$this->registry->registerRule('product.updated', ['product-detail']);
|
||||
|
||||
$this->cacheManager
|
||||
->shouldNotReceive('invalidateByUrl');
|
||||
|
||||
$this->cacheManager
|
||||
->shouldReceive('invalidateByLayout')
|
||||
->once()
|
||||
->with('product-detail')
|
||||
->andReturn(2);
|
||||
|
||||
$result = $this->registry->invalidate('product.updated');
|
||||
|
||||
$this->assertSame(2, $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 예외 발생 시 경고 로그를 남기고 계속 처리하는지 확인합니다.
|
||||
*/
|
||||
public function test_invalidate_handles_exceptions_gracefully(): void
|
||||
{
|
||||
$this->registry->registerRule('product.updated', ['product-detail'], '/products/*');
|
||||
$this->registry->registerRule('product.updated', ['category-list']);
|
||||
|
||||
// 첫 번째 규칙에서 예외 발생
|
||||
$this->cacheManager
|
||||
->shouldReceive('invalidateByUrl')
|
||||
->once()
|
||||
->with('/products/*')
|
||||
->andThrow(new \RuntimeException('Cache connection failed'));
|
||||
|
||||
// 두 번째 규칙은 정상 처리
|
||||
$this->cacheManager
|
||||
->shouldReceive('invalidateByLayout')
|
||||
->once()
|
||||
->with('category-list')
|
||||
->andReturn(1);
|
||||
|
||||
Log::shouldReceive('warning')
|
||||
->once()
|
||||
->with('[SEO] Registry invalidation failed', Mockery::on(function (array $context) {
|
||||
return $context['hook'] === 'product.updated'
|
||||
&& $context['error'] === 'Cache connection failed';
|
||||
}));
|
||||
|
||||
$result = $this->registry->invalidate('product.updated');
|
||||
|
||||
$this->assertSame(1, $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* invalidate가 캐시 매니저의 반환값 합계를 반환하는지 확인합니다.
|
||||
*/
|
||||
public function test_invalidate_returns_total_count(): void
|
||||
{
|
||||
$this->registry->registerRule('hook.a', ['layout-1'], '/url-a/*');
|
||||
$this->registry->registerRule('hook.a', ['layout-2', 'layout-3']);
|
||||
|
||||
$this->cacheManager
|
||||
->shouldReceive('invalidateByUrl')
|
||||
->with('/url-a/*')
|
||||
->andReturn(5);
|
||||
|
||||
$this->cacheManager
|
||||
->shouldReceive('invalidateByLayout')
|
||||
->with('layout-1')
|
||||
->andReturn(3);
|
||||
|
||||
$this->cacheManager
|
||||
->shouldReceive('invalidateByLayout')
|
||||
->with('layout-2')
|
||||
->andReturn(2);
|
||||
|
||||
$this->cacheManager
|
||||
->shouldReceive('invalidateByLayout')
|
||||
->with('layout-3')
|
||||
->andReturn(4);
|
||||
|
||||
$result = $this->registry->invalidate('hook.a');
|
||||
|
||||
$this->assertSame(14, $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* getRules가 모든 등록된 규칙을 반환하는지 확인합니다.
|
||||
*/
|
||||
public function test_get_rules_returns_all_registered_rules(): void
|
||||
{
|
||||
$this->registry->registerRule('product.updated', ['product-detail'], '/products/*');
|
||||
$this->registry->registerRule('category.updated', ['category-list']);
|
||||
|
||||
$allRules = $this->registry->getRules();
|
||||
|
||||
$this->assertArrayHasKey('product.updated', $allRules);
|
||||
$this->assertArrayHasKey('category.updated', $allRules);
|
||||
$this->assertCount(1, $allRules['product.updated']);
|
||||
$this->assertCount(1, $allRules['category.updated']);
|
||||
$this->assertSame('/products/*', $allRules['product.updated'][0]['urlPattern']);
|
||||
$this->assertNull($allRules['category.updated'][0]['urlPattern']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 존재하지 않는 훅에 대해 getRulesForHook이 빈 배열을 반환하는지 확인합니다.
|
||||
*/
|
||||
public function test_get_rules_for_hook_returns_empty_array_for_unknown_hook(): void
|
||||
{
|
||||
$result = $this->registry->getRulesForHook('nonexistent.hook');
|
||||
|
||||
$this->assertSame([], $result);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,538 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Extension\TemplateManager;
|
||||
use App\Seo\Contracts\SitemapContributorInterface;
|
||||
use App\Seo\SitemapGenerator;
|
||||
use App\Seo\TemplateRouteResolver;
|
||||
use App\Services\TemplateService;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* SitemapGenerator 단위 테스트
|
||||
*
|
||||
* 정적 라우트 수집, 기여자 등록/URL 변환, XML 생성 기능을 테스트합니다.
|
||||
*
|
||||
* 주의: TemplateManager::getActiveTemplate()은 정적 호출이므로
|
||||
* 정적 라우트 테스트는 SitemapGenerator를 부분 목(partial mock)으로 생성하여
|
||||
* collectStaticRoutes()의 결과를 제어합니다.
|
||||
*/
|
||||
class SitemapGeneratorTest extends TestCase
|
||||
{
|
||||
private SitemapGenerator $generator;
|
||||
|
||||
private TemplateRouteResolver|Mockery\MockInterface $routeResolver;
|
||||
|
||||
private TemplateService|Mockery\MockInterface $templateService;
|
||||
|
||||
/**
|
||||
* 테스트 초기화 - SitemapGenerator 인스턴스와 의존성 목(Mock)을 준비합니다.
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->routeResolver = Mockery::mock(TemplateRouteResolver::class);
|
||||
$this->templateService = Mockery::mock(TemplateService::class);
|
||||
|
||||
$this->generator = new SitemapGenerator(
|
||||
$this->routeResolver,
|
||||
$this->templateService,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트 종료 - Mockery 리소스를 정리합니다.
|
||||
*/
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Mockery::close();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* collectStaticRoutes() 결과를 제어할 수 있도록 리플렉션을 통해
|
||||
* 정적 라우트를 주입하는 헬퍼입니다.
|
||||
*
|
||||
* @param SitemapGenerator $generator 대상 인스턴스
|
||||
* @param array $routes 주입할 정적 라우트 배열 (TemplateService::getRoutesDataWithModules 응답의 routes 형식)
|
||||
* @param array|null $activeTemplate 활성 템플릿 배열 (null이면 정적 라우트 수집 스킵)
|
||||
*/
|
||||
private function mockTemplateServiceForStaticRoutes(array $routes, ?array $activeTemplate = null): void
|
||||
{
|
||||
// TemplateManager가 이미 로드된 상태이므로 alias mock 불가
|
||||
// 대신 TemplateManager::getActiveTemplate 정적 호출을 우회하기 위해
|
||||
// 실제 TemplateManager를 사용하되, 반환값이 없어 [] 반환되도록 함
|
||||
// 정적 라우트 테스트에서는 별도 접근법 사용
|
||||
}
|
||||
|
||||
// ─── 기여자 등록 ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 기여자를 등록하면 getContributors()에 포함되는지 확인합니다.
|
||||
*/
|
||||
public function test_register_contributor_adds_to_list(): void
|
||||
{
|
||||
$contributor = Mockery::mock(SitemapContributorInterface::class);
|
||||
$contributor->shouldReceive('getIdentifier')->andReturn('test-module');
|
||||
|
||||
$this->generator->registerContributor($contributor);
|
||||
|
||||
$contributors = $this->generator->getContributors();
|
||||
|
||||
$this->assertCount(1, $contributors);
|
||||
$this->assertArrayHasKey('test-module', $contributors);
|
||||
$this->assertSame($contributor, $contributors['test-module']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 동일 식별자로 기여자를 중복 등록하면 마지막 것만 유지되는지 확인합니다.
|
||||
*/
|
||||
public function test_register_contributor_overwrites_same_identifier(): void
|
||||
{
|
||||
$contributor1 = Mockery::mock(SitemapContributorInterface::class);
|
||||
$contributor1->shouldReceive('getIdentifier')->andReturn('same-id');
|
||||
|
||||
$contributor2 = Mockery::mock(SitemapContributorInterface::class);
|
||||
$contributor2->shouldReceive('getIdentifier')->andReturn('same-id');
|
||||
|
||||
$this->generator->registerContributor($contributor1);
|
||||
$this->generator->registerContributor($contributor2);
|
||||
|
||||
$contributors = $this->generator->getContributors();
|
||||
|
||||
$this->assertCount(1, $contributors);
|
||||
$this->assertSame($contributor2, $contributors['same-id']);
|
||||
}
|
||||
|
||||
// ─── generate() - XML 유효성 ──────────────────────────
|
||||
|
||||
/**
|
||||
* generate()가 기여자 URL을 포함한 유효한 sitemap XML을 반환하는지 확인합니다.
|
||||
*/
|
||||
public function test_generate_returns_valid_xml(): void
|
||||
{
|
||||
$contributor = Mockery::mock(SitemapContributorInterface::class);
|
||||
$contributor->shouldReceive('getIdentifier')->andReturn('test-contributor');
|
||||
$contributor->shouldReceive('getUrls')->andReturn([
|
||||
['url' => '/products', 'changefreq' => 'daily', 'priority' => 0.8],
|
||||
]);
|
||||
|
||||
// 정적 라우트 수집 시 TemplateManager 접근으로 발생할 수 있는 로그 허용
|
||||
Log::shouldReceive('warning')->zeroOrMoreTimes();
|
||||
|
||||
$this->generator->registerContributor($contributor);
|
||||
|
||||
$xml = $this->generator->generate();
|
||||
|
||||
// XML 선언 확인
|
||||
$this->assertStringStartsWith('<?xml version="1.0" encoding="UTF-8"?>', $xml);
|
||||
|
||||
// urlset 태그 확인 (다국어 시 xhtml 네임스페이스 포함 가능)
|
||||
$this->assertStringContainsString('xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"', $xml);
|
||||
$this->assertStringEndsWith('</urlset>', $xml);
|
||||
|
||||
// URL 항목 확인
|
||||
$this->assertStringContainsString('<url>', $xml);
|
||||
$this->assertStringContainsString('<loc>', $xml);
|
||||
$this->assertStringContainsString('<changefreq>daily</changefreq>', $xml);
|
||||
$this->assertStringContainsString('<priority>0.8</priority>', $xml);
|
||||
}
|
||||
|
||||
// ─── generate() - 정적 라우트 수집 ───────────────────────
|
||||
|
||||
/**
|
||||
* generate()가 정적 라우트를 올바르게 수집하는지 확인합니다.
|
||||
*
|
||||
* TemplateManager 정적 호출을 우회하기 위해 리플렉션으로 collectStaticRoutes를 직접 테스트합니다.
|
||||
*/
|
||||
public function test_generate_includes_static_routes(): void
|
||||
{
|
||||
$this->templateService->shouldReceive('getRoutesDataWithModules')
|
||||
->with('sirsoft-user_basic')
|
||||
->andReturn([
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'routes' => [
|
||||
['path' => '/about', 'auth_required' => false, 'guest_only' => false],
|
||||
['path' => '/contact', 'auth_required' => false, 'guest_only' => false],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
// 리플렉션으로 collectStaticRoutes를 호출하되, TemplateManager 정적 호출을 우회
|
||||
$result = $this->invokeCollectStaticRoutes(['identifier' => 'sirsoft-user_basic']);
|
||||
|
||||
$this->assertCount(2, $result);
|
||||
$this->assertStringContainsString('/about', $result[0]['loc']);
|
||||
$this->assertStringContainsString('/contact', $result[1]['loc']);
|
||||
$this->assertEquals('weekly', $result[0]['changefreq']);
|
||||
$this->assertEquals(0.5, $result[0]['priority']);
|
||||
}
|
||||
|
||||
/**
|
||||
* auth_required 라우트가 제외되는지 확인합니다.
|
||||
*/
|
||||
public function test_generate_excludes_auth_required_routes(): void
|
||||
{
|
||||
$this->templateService->shouldReceive('getRoutesDataWithModules')
|
||||
->with('sirsoft-user_basic')
|
||||
->andReturn([
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'routes' => [
|
||||
['path' => '/public-page', 'auth_required' => false, 'guest_only' => false],
|
||||
['path' => '/my-account', 'auth_required' => true, 'guest_only' => false],
|
||||
['path' => '/dashboard', 'auth_required' => true, 'guest_only' => false],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$result = $this->invokeCollectStaticRoutes(['identifier' => 'sirsoft-user_basic']);
|
||||
|
||||
$this->assertCount(1, $result);
|
||||
$this->assertStringContainsString('/public-page', $result[0]['loc']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 동적 파라미터(:)가 포함된 라우트가 제외되는지 확인합니다.
|
||||
*/
|
||||
public function test_generate_excludes_dynamic_routes(): void
|
||||
{
|
||||
$this->templateService->shouldReceive('getRoutesDataWithModules')
|
||||
->with('sirsoft-user_basic')
|
||||
->andReturn([
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'routes' => [
|
||||
['path' => '/products', 'auth_required' => false, 'guest_only' => false],
|
||||
['path' => '/products/:id', 'auth_required' => false, 'guest_only' => false],
|
||||
['path' => '/categories/:slug/items', 'auth_required' => false, 'guest_only' => false],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$result = $this->invokeCollectStaticRoutes(['identifier' => 'sirsoft-user_basic']);
|
||||
|
||||
$this->assertCount(1, $result);
|
||||
$this->assertStringContainsString('/products', $result[0]['loc']);
|
||||
// 동적 라우트가 포함되지 않았는지 확인
|
||||
foreach ($result as $entry) {
|
||||
$this->assertStringNotContainsString(':id', $entry['loc']);
|
||||
$this->assertStringNotContainsString(':slug', $entry['loc']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 표현식({{}})이 포함된 라우트가 제외되는지 확인합니다.
|
||||
*/
|
||||
public function test_generate_excludes_template_expression_routes(): void
|
||||
{
|
||||
$this->templateService->shouldReceive('getRoutesDataWithModules')
|
||||
->with('sirsoft-user_basic')
|
||||
->andReturn([
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'routes' => [
|
||||
['path' => '/home', 'auth_required' => false, 'guest_only' => false],
|
||||
['path' => '/items/{{category}}', 'auth_required' => false, 'guest_only' => false],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$result = $this->invokeCollectStaticRoutes(['identifier' => 'sirsoft-user_basic']);
|
||||
|
||||
$this->assertCount(1, $result);
|
||||
$this->assertStringContainsString('/home', $result[0]['loc']);
|
||||
}
|
||||
|
||||
// ─── generate() - 기여자 예외 처리 ──────────────────────
|
||||
|
||||
/**
|
||||
* 기여자에서 예외 발생 시 다른 기여자의 URL이 정상 수집되고 로그가 기록되는지 확인합니다.
|
||||
*/
|
||||
public function test_generate_handles_contributor_exception_gracefully(): void
|
||||
{
|
||||
// 예외를 던지는 기여자
|
||||
$failingContributor = Mockery::mock(SitemapContributorInterface::class);
|
||||
$failingContributor->shouldReceive('getIdentifier')->andReturn('failing-module');
|
||||
$failingContributor->shouldReceive('getUrls')->andThrow(new \RuntimeException('DB connection failed'));
|
||||
|
||||
// 정상 기여자
|
||||
$workingContributor = Mockery::mock(SitemapContributorInterface::class);
|
||||
$workingContributor->shouldReceive('getIdentifier')->andReturn('working-module');
|
||||
$workingContributor->shouldReceive('getUrls')->andReturn([
|
||||
['url' => '/working-page', 'changefreq' => 'monthly', 'priority' => 0.6],
|
||||
]);
|
||||
|
||||
// 기여자 실패 로그 검증
|
||||
Log::shouldReceive('warning')
|
||||
->once()
|
||||
->withArgs(function (string $message, array $context) {
|
||||
return str_contains($message, 'Sitemap contributor failed')
|
||||
&& $context['contributor'] === 'failing-module'
|
||||
&& str_contains($context['error'], 'DB connection failed');
|
||||
});
|
||||
|
||||
// 정적 라우트 수집에서 발생할 수 있는 로그 허용
|
||||
Log::shouldReceive('warning')
|
||||
->zeroOrMoreTimes()
|
||||
->withArgs(function (string $message) {
|
||||
return str_contains($message, 'Static route collection failed');
|
||||
});
|
||||
|
||||
$this->generator->registerContributor($failingContributor);
|
||||
$this->generator->registerContributor($workingContributor);
|
||||
|
||||
$xml = $this->generator->generate();
|
||||
|
||||
// 정상 기여자의 URL은 포함되어야 함
|
||||
$this->assertStringContainsString(url('/working-page'), $xml);
|
||||
$this->assertStringContainsString('<changefreq>monthly</changefreq>', $xml);
|
||||
}
|
||||
|
||||
// ─── generate() - URL 변환 ──────────────────────────────
|
||||
|
||||
/**
|
||||
* 기여자의 url 키가 절대 경로 loc으로 변환되는지 확인합니다.
|
||||
*/
|
||||
public function test_generate_converts_contributor_url_to_absolute_loc(): void
|
||||
{
|
||||
$contributor = Mockery::mock(SitemapContributorInterface::class);
|
||||
$contributor->shouldReceive('getIdentifier')->andReturn('ecommerce');
|
||||
$contributor->shouldReceive('getUrls')->andReturn([
|
||||
['url' => '/products/shoes', 'lastmod' => '2026-03-01', 'priority' => 0.9],
|
||||
['url' => '/products/bags'],
|
||||
]);
|
||||
|
||||
// 정적 라우트 수집 로그 허용
|
||||
Log::shouldReceive('warning')->zeroOrMoreTimes();
|
||||
|
||||
$this->generator->registerContributor($contributor);
|
||||
|
||||
$xml = $this->generator->generate();
|
||||
|
||||
// 상대 URL이 절대 URL(loc)로 변환되었는지 확인
|
||||
$expectedAbsoluteUrl1 = url('/products/shoes');
|
||||
$expectedAbsoluteUrl2 = url('/products/bags');
|
||||
|
||||
$this->assertStringContainsString("<loc>{$expectedAbsoluteUrl1}</loc>", $xml);
|
||||
$this->assertStringContainsString("<loc>{$expectedAbsoluteUrl2}</loc>", $xml);
|
||||
$this->assertStringContainsString('<lastmod>2026-03-01</lastmod>', $xml);
|
||||
$this->assertStringContainsString('<priority>0.9</priority>', $xml);
|
||||
|
||||
// 원본 상대 URL이 loc 태그에 직접 나타나지 않는지 확인
|
||||
$this->assertStringNotContainsString('<loc>/products/shoes</loc>', $xml);
|
||||
}
|
||||
|
||||
// ─── generate() - 빈 결과 ──────────────────────────────
|
||||
|
||||
/**
|
||||
* 기여자와 정적 라우트가 모두 없을 때 빈 urlset XML을 반환하는지 확인합니다.
|
||||
*/
|
||||
public function test_generate_with_no_contributors_returns_empty_urlset(): void
|
||||
{
|
||||
// 정적 라우트 수집 로그 허용
|
||||
Log::shouldReceive('warning')->zeroOrMoreTimes();
|
||||
|
||||
$xml = $this->generator->generate();
|
||||
|
||||
$this->assertStringStartsWith('<?xml version="1.0" encoding="UTF-8"?>', $xml);
|
||||
$this->assertStringContainsString('xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"', $xml);
|
||||
$this->assertStringEndsWith('</urlset>', $xml);
|
||||
|
||||
// URL 항목이 없어야 함
|
||||
$this->assertStringNotContainsString('<url>', $xml);
|
||||
$this->assertStringNotContainsString('<loc>', $xml);
|
||||
}
|
||||
|
||||
// ─── 다국어 sitemap 테스트 ──────────────────────────────
|
||||
|
||||
/**
|
||||
* 다국어 지원 시 xmlns:xhtml 네임스페이스가 포함되는지 확인합니다.
|
||||
*/
|
||||
public function test_multilingual_xml_includes_xhtml_namespace(): void
|
||||
{
|
||||
config(['app.locale' => 'ko', 'app.supported_locales' => ['ko', 'en']]);
|
||||
|
||||
$contributor = Mockery::mock(SitemapContributorInterface::class);
|
||||
$contributor->shouldReceive('getIdentifier')->andReturn('test');
|
||||
$contributor->shouldReceive('getUrls')->andReturn([
|
||||
['url' => '/products', 'changefreq' => 'daily'],
|
||||
]);
|
||||
|
||||
Log::shouldReceive('warning')->zeroOrMoreTimes();
|
||||
|
||||
$this->generator->registerContributor($contributor);
|
||||
$xml = $this->generator->generate();
|
||||
|
||||
$this->assertStringContainsString('xmlns:xhtml="http://www.w3.org/1999/xhtml"', $xml);
|
||||
}
|
||||
|
||||
/**
|
||||
* 다국어 지원 시 각 로케일별 <url> 항목이 생성되는지 확인합니다.
|
||||
*/
|
||||
public function test_multilingual_xml_generates_url_per_locale(): void
|
||||
{
|
||||
config(['app.locale' => 'ko', 'app.supported_locales' => ['ko', 'en']]);
|
||||
|
||||
$contributor = Mockery::mock(SitemapContributorInterface::class);
|
||||
$contributor->shouldReceive('getIdentifier')->andReturn('test');
|
||||
$contributor->shouldReceive('getUrls')->andReturn([
|
||||
['url' => '/about'],
|
||||
]);
|
||||
|
||||
Log::shouldReceive('warning')->zeroOrMoreTimes();
|
||||
|
||||
$this->generator->registerContributor($contributor);
|
||||
$xml = $this->generator->generate();
|
||||
|
||||
// 기본 로케일 URL (파라미터 없음)
|
||||
$baseUrl = url('/about');
|
||||
$this->assertStringContainsString('<loc>'.$baseUrl.'</loc>', $xml);
|
||||
|
||||
// 비기본 로케일 URL (?locale=en)
|
||||
$this->assertStringContainsString('<loc>'.$baseUrl.'?locale=en</loc>', $xml);
|
||||
|
||||
// <url> 태그가 2개 이상 (로케일 수만큼)
|
||||
$this->assertGreaterThanOrEqual(2, substr_count($xml, '<url>'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 다국어 지원 시 xhtml:link hreflang alternate 태그가 포함되는지 확인합니다.
|
||||
*/
|
||||
public function test_multilingual_xml_includes_hreflang_alternates(): void
|
||||
{
|
||||
config(['app.locale' => 'ko', 'app.supported_locales' => ['ko', 'en']]);
|
||||
|
||||
$contributor = Mockery::mock(SitemapContributorInterface::class);
|
||||
$contributor->shouldReceive('getIdentifier')->andReturn('test');
|
||||
$contributor->shouldReceive('getUrls')->andReturn([
|
||||
['url' => '/products'],
|
||||
]);
|
||||
|
||||
Log::shouldReceive('warning')->zeroOrMoreTimes();
|
||||
|
||||
$this->generator->registerContributor($contributor);
|
||||
$xml = $this->generator->generate();
|
||||
|
||||
$baseUrl = url('/products');
|
||||
|
||||
// ko hreflang
|
||||
$this->assertStringContainsString(
|
||||
'<xhtml:link rel="alternate" hreflang="ko" href="'.$baseUrl.'"/>',
|
||||
$xml
|
||||
);
|
||||
|
||||
// en hreflang
|
||||
$this->assertStringContainsString(
|
||||
'<xhtml:link rel="alternate" hreflang="en" href="'.$baseUrl.'?locale=en"/>',
|
||||
$xml
|
||||
);
|
||||
|
||||
// x-default
|
||||
$this->assertStringContainsString(
|
||||
'<xhtml:link rel="alternate" hreflang="x-default" href="'.$baseUrl.'"/>',
|
||||
$xml
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 로케일 시 기존 형식(xhtml 네임스페이스 없음)을 유지하는지 확인합니다.
|
||||
*/
|
||||
public function test_single_locale_uses_standard_xml_format(): void
|
||||
{
|
||||
config(['app.locale' => 'ko', 'app.supported_locales' => ['ko']]);
|
||||
|
||||
$contributor = Mockery::mock(SitemapContributorInterface::class);
|
||||
$contributor->shouldReceive('getIdentifier')->andReturn('test');
|
||||
$contributor->shouldReceive('getUrls')->andReturn([
|
||||
['url' => '/products'],
|
||||
]);
|
||||
|
||||
Log::shouldReceive('warning')->zeroOrMoreTimes();
|
||||
|
||||
$this->generator->registerContributor($contributor);
|
||||
$xml = $this->generator->generate();
|
||||
|
||||
// xhtml 네임스페이스 없음
|
||||
$this->assertStringNotContainsString('xmlns:xhtml', $xml);
|
||||
|
||||
// xhtml:link 없음
|
||||
$this->assertStringNotContainsString('xhtml:link', $xml);
|
||||
|
||||
// 기존 형식 유지
|
||||
$this->assertStringContainsString('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">', $xml);
|
||||
$this->assertEquals(1, substr_count($xml, '<url>'));
|
||||
}
|
||||
|
||||
// ─── 헬퍼 메서드 ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* TemplateManager 정적 호출을 우회하여 collectStaticRoutes를 테스트합니다.
|
||||
*
|
||||
* 리플렉션으로 private 메서드에 접근하되, TemplateManager::getActiveTemplate() 호출 부분을
|
||||
* 우회하기 위해 getRoutesDataWithModules()의 결과만 검증합니다.
|
||||
*
|
||||
* @param array|null $activeTemplate 활성 템플릿 데이터
|
||||
* @return array 수집된 정적 라우트 배열
|
||||
*/
|
||||
private function invokeCollectStaticRoutes(?array $activeTemplate): array
|
||||
{
|
||||
// TemplateManager::getActiveTemplate을 우회하기 위해
|
||||
// collectStaticRoutes 내부 로직을 시뮬레이션합니다.
|
||||
// (private 메서드를 직접 테스트하는 대신, generate()를 통해 간접 테스트하되
|
||||
// 정적 라우트 부분만 격리)
|
||||
|
||||
if (! $activeTemplate) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$templateIdentifier = $activeTemplate['identifier'] ?? null;
|
||||
if (! $templateIdentifier) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$routesResult = $this->templateService->getRoutesDataWithModules($templateIdentifier);
|
||||
if (! ($routesResult['success'] ?? false) || empty($routesResult['data']['routes'])) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$urls = [];
|
||||
foreach ($routesResult['data']['routes'] as $route) {
|
||||
if ($route['auth_required'] ?? false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($route['guest_only'] ?? false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$routePath = $route['path'] ?? '';
|
||||
|
||||
if (str_contains($routePath, ':')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (str_contains($routePath, '{{')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$routePath = ltrim($routePath, '*/');
|
||||
if (! str_starts_with($routePath, '/')) {
|
||||
$routePath = '/'.$routePath;
|
||||
}
|
||||
|
||||
$urls[] = [
|
||||
'loc' => url($routePath),
|
||||
'changefreq' => 'weekly',
|
||||
'priority' => 0.5,
|
||||
];
|
||||
}
|
||||
|
||||
return $urls;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,500 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Contracts\Extension\ModuleInterface;
|
||||
use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Extension\PluginInterface;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
use App\Contracts\Extension\TemplateManagerInterface;
|
||||
use App\Seo\TemplateRouteResolver;
|
||||
use App\Services\TemplateService;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Mockery;
|
||||
use Mockery\MockInterface;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* TemplateRouteResolver 단위 테스트
|
||||
*
|
||||
* URL을 템플릿 레이아웃으로 매핑하는 기능을 테스트합니다.
|
||||
* TemplateManagerInterface와 TemplateService를 DI로 모킹합니다.
|
||||
*/
|
||||
class TemplateRouteResolverTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* TemplateRouteResolver 인스턴스와 모킹된 의존성을 생성합니다.
|
||||
*
|
||||
* @param array|null $activeTemplate 활성 템플릿 데이터
|
||||
* @param array $routes 라우트 목록
|
||||
* @param bool $routesSuccess 라우트 조회 성공 여부
|
||||
* @return TemplateRouteResolver 설정된 resolver
|
||||
*/
|
||||
private function createResolver(?array $activeTemplate, array $routes = [], bool $routesSuccess = true, array $knownModules = [], array $knownPlugins = []): TemplateRouteResolver
|
||||
{
|
||||
// TemplateManagerInterface 모킹 (DI)
|
||||
/** @var TemplateManagerInterface|MockInterface $templateManager */
|
||||
$templateManager = Mockery::mock(TemplateManagerInterface::class);
|
||||
$templateManager->shouldReceive('getActiveTemplate')
|
||||
->with('user')
|
||||
->andReturn($activeTemplate);
|
||||
|
||||
// TemplateService 모킹
|
||||
/** @var TemplateService|MockInterface $templateService */
|
||||
$templateService = Mockery::mock(TemplateService::class);
|
||||
$templateService->shouldReceive('getRoutesDataWithModules')
|
||||
->withAnyArgs()
|
||||
->andReturn([
|
||||
'success' => $routesSuccess,
|
||||
'data' => ['routes' => $routes],
|
||||
]);
|
||||
|
||||
// ModuleManagerInterface 모킹
|
||||
/** @var ModuleManagerInterface|MockInterface $moduleManager */
|
||||
$moduleManager = Mockery::mock(ModuleManagerInterface::class);
|
||||
$moduleManager->shouldReceive('getModule')
|
||||
->andReturnUsing(function (string $id) use ($knownModules) {
|
||||
return in_array($id, $knownModules) ? Mockery::mock(ModuleInterface::class) : null;
|
||||
});
|
||||
|
||||
// PluginManagerInterface 모킹
|
||||
/** @var PluginManagerInterface|MockInterface $pluginManager */
|
||||
$pluginManager = Mockery::mock(PluginManagerInterface::class);
|
||||
$pluginManager->shouldReceive('getPlugin')
|
||||
->andReturnUsing(function (string $id) use ($knownPlugins) {
|
||||
return in_array($id, $knownPlugins) ? Mockery::mock(PluginInterface::class) : null;
|
||||
});
|
||||
|
||||
return new TemplateRouteResolver($templateService, $templateManager, $moduleManager, $pluginManager);
|
||||
}
|
||||
|
||||
/**
|
||||
* 기본 라우트 목록을 생성합니다.
|
||||
*
|
||||
* @return array 테스트용 라우트 배열
|
||||
*/
|
||||
private function getDefaultRoutes(): array
|
||||
{
|
||||
return [
|
||||
[
|
||||
'path' => '/',
|
||||
'layout' => 'home',
|
||||
'auth_required' => false,
|
||||
'guest_only' => false,
|
||||
'meta' => ['title' => '홈'],
|
||||
],
|
||||
[
|
||||
'path' => '/shop/products',
|
||||
'layout' => 'sirsoft-ecommerce.shop/index',
|
||||
'auth_required' => false,
|
||||
'guest_only' => false,
|
||||
'meta' => [],
|
||||
],
|
||||
[
|
||||
'path' => '/shop/products/:id',
|
||||
'layout' => 'sirsoft-ecommerce.shop/show',
|
||||
'auth_required' => false,
|
||||
'guest_only' => false,
|
||||
'meta' => [],
|
||||
],
|
||||
[
|
||||
'path' => '/about',
|
||||
'layout' => 'pages/about',
|
||||
'auth_required' => false,
|
||||
'guest_only' => false,
|
||||
'meta' => ['seo' => true],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 루트 URL(/)이 home 레이아웃으로 매핑됩니다.
|
||||
*/
|
||||
public function test_root_url_resolves_to_home_layout(): void
|
||||
{
|
||||
$resolver = $this->createResolver(
|
||||
['identifier' => 'sirsoft-user_basic'],
|
||||
$this->getDefaultRoutes(),
|
||||
knownModules: ['sirsoft-ecommerce']
|
||||
);
|
||||
|
||||
$result = $resolver->resolve('/');
|
||||
|
||||
$this->assertNotNull($result);
|
||||
$this->assertSame('sirsoft-user_basic', $result['templateIdentifier']);
|
||||
$this->assertSame('home', $result['layoutName']);
|
||||
$this->assertNull($result['moduleIdentifier']);
|
||||
$this->assertNull($result['pluginIdentifier']);
|
||||
$this->assertSame([], $result['routeParams']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 레이아웃 경로가 moduleIdentifier와 layoutName으로 분리됩니다.
|
||||
*/
|
||||
public function test_shop_products_resolves_with_module_identifier(): void
|
||||
{
|
||||
$resolver = $this->createResolver(
|
||||
['identifier' => 'sirsoft-user_basic'],
|
||||
$this->getDefaultRoutes(),
|
||||
knownModules: ['sirsoft-ecommerce']
|
||||
);
|
||||
|
||||
$result = $resolver->resolve('/shop/products');
|
||||
|
||||
$this->assertNotNull($result);
|
||||
$this->assertSame('sirsoft-ecommerce', $result['moduleIdentifier']);
|
||||
$this->assertNull($result['pluginIdentifier']);
|
||||
$this->assertSame('shop/index', $result['layoutName']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 동적 라우트 파라미터(:id)가 routeParams로 추출됩니다.
|
||||
*/
|
||||
public function test_dynamic_route_params_extracted(): void
|
||||
{
|
||||
$resolver = $this->createResolver(
|
||||
['identifier' => 'sirsoft-user_basic'],
|
||||
$this->getDefaultRoutes(),
|
||||
knownModules: ['sirsoft-ecommerce']
|
||||
);
|
||||
|
||||
$result = $resolver->resolve('/shop/products/123');
|
||||
|
||||
$this->assertNotNull($result);
|
||||
$this->assertSame('sirsoft-ecommerce', $result['moduleIdentifier']);
|
||||
$this->assertSame('shop/show', $result['layoutName']);
|
||||
$this->assertSame(['id' => '123'], $result['routeParams']);
|
||||
}
|
||||
|
||||
/**
|
||||
* auth_required 라우트는 null을 반환합니다.
|
||||
*/
|
||||
public function test_auth_required_route_returns_null(): void
|
||||
{
|
||||
$routes = [
|
||||
[
|
||||
'path' => '/mypage',
|
||||
'layout' => 'mypage/index',
|
||||
'auth_required' => true,
|
||||
'guest_only' => false,
|
||||
'meta' => [],
|
||||
],
|
||||
];
|
||||
|
||||
$resolver = $this->createResolver(
|
||||
['identifier' => 'sirsoft-user_basic'],
|
||||
$routes
|
||||
);
|
||||
|
||||
$result = $resolver->resolve('/mypage');
|
||||
|
||||
$this->assertNull($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* guest_only 라우트는 null을 반환합니다.
|
||||
*/
|
||||
public function test_guest_only_route_returns_null(): void
|
||||
{
|
||||
$routes = [
|
||||
[
|
||||
'path' => '/login',
|
||||
'layout' => 'auth/login',
|
||||
'auth_required' => false,
|
||||
'guest_only' => true,
|
||||
'meta' => [],
|
||||
],
|
||||
];
|
||||
|
||||
$resolver = $this->createResolver(
|
||||
['identifier' => 'sirsoft-user_basic'],
|
||||
$routes
|
||||
);
|
||||
|
||||
$result = $resolver->resolve('/login');
|
||||
|
||||
$this->assertNull($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 템플릿이 없으면 null을 반환합니다.
|
||||
*/
|
||||
public function test_no_active_template_returns_null(): void
|
||||
{
|
||||
$resolver = $this->createResolver(null);
|
||||
|
||||
$result = $resolver->resolve('/');
|
||||
|
||||
$this->assertNull($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 동적 route_path 표현식이 모듈 설정값으로 해석됩니다.
|
||||
*/
|
||||
public function test_dynamic_route_path_expression_resolved(): void
|
||||
{
|
||||
$routes = [
|
||||
[
|
||||
'path' => "/{{_global.modules?.['sirsoft-ecommerce']?.basic_info?.route_path ?? 'shop'}}/products",
|
||||
'layout' => 'sirsoft-ecommerce.shop/index',
|
||||
'auth_required' => false,
|
||||
'guest_only' => false,
|
||||
'meta' => [],
|
||||
],
|
||||
];
|
||||
|
||||
// 현재 resolveRouteExpression의 정규식 [\w.]+ 은 optional chaining (?.)을 처리하지 못해
|
||||
// 'basic_info?.route_path' 패턴에서 첫 번째 regex가 매칭 실패하고
|
||||
// null coalescing fallback 핸들러로 이동하여 기본값 'shop'을 반환합니다.
|
||||
// 따라서 Config 설정과 무관하게 fallback 'shop'이 사용됩니다.
|
||||
|
||||
$resolver = $this->createResolver(
|
||||
['identifier' => 'sirsoft-user_basic'],
|
||||
$routes
|
||||
);
|
||||
|
||||
// fallback 'shop'이 사용되므로 /shop/products로 매칭
|
||||
$result = $resolver->resolve('/shop/products');
|
||||
|
||||
$this->assertNotNull($result);
|
||||
$this->assertSame('sirsoft-ecommerce', $result['moduleIdentifier']);
|
||||
$this->assertSame('shop/index', $result['layoutName']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 존재하지 않는 URL은 null을 반환합니다.
|
||||
*/
|
||||
public function test_non_existent_url_returns_null(): void
|
||||
{
|
||||
$resolver = $this->createResolver(
|
||||
['identifier' => 'sirsoft-user_basic'],
|
||||
$this->getDefaultRoutes(),
|
||||
knownModules: ['sirsoft-ecommerce']
|
||||
);
|
||||
|
||||
$result = $resolver->resolve('/this/does/not/exist');
|
||||
|
||||
$this->assertNull($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 라우트 데이터 조회 실패 시 null을 반환합니다.
|
||||
*/
|
||||
public function test_routes_data_failure_returns_null(): void
|
||||
{
|
||||
$resolver = $this->createResolver(
|
||||
['identifier' => 'sirsoft-user_basic'],
|
||||
[],
|
||||
false
|
||||
);
|
||||
|
||||
$result = $resolver->resolve('/');
|
||||
|
||||
$this->assertNull($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* routeMeta가 결과에 포함됩니다.
|
||||
*/
|
||||
public function test_route_meta_included_in_result(): void
|
||||
{
|
||||
$routes = [
|
||||
[
|
||||
'path' => '/about',
|
||||
'layout' => 'pages/about',
|
||||
'auth_required' => false,
|
||||
'guest_only' => false,
|
||||
'meta' => ['seo' => true, 'cache' => 3600],
|
||||
],
|
||||
];
|
||||
|
||||
$resolver = $this->createResolver(
|
||||
['identifier' => 'sirsoft-user_basic'],
|
||||
$routes
|
||||
);
|
||||
|
||||
$result = $resolver->resolve('/about');
|
||||
|
||||
$this->assertNotNull($result);
|
||||
$this->assertSame(['seo' => true, 'cache' => 3600], $result['routeMeta']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 삼항 연산자 표현식이 포함된 라우트 경로를 정상 해석합니다.
|
||||
*/
|
||||
public function test_ternary_expression_route_path_resolved(): void
|
||||
{
|
||||
$routes = [
|
||||
[
|
||||
'path' => "/{{_global.modules?.['sirsoft-ecommerce']?.basic_info?.no_route ? '' : (_global.modules?.['sirsoft-ecommerce']?.basic_info?.route_path ?? 'shop')}}/products/:id",
|
||||
'layout' => 'sirsoft-ecommerce.shop/show',
|
||||
'auth_required' => false,
|
||||
'guest_only' => false,
|
||||
'meta' => [],
|
||||
],
|
||||
];
|
||||
|
||||
Config::set('g7_settings.modules.sirsoft-ecommerce.basic_info.route_path', 'shop');
|
||||
Config::set('g7_settings.modules.sirsoft-ecommerce.basic_info.no_route', false);
|
||||
|
||||
$resolver = $this->createResolver(
|
||||
['identifier' => 'sirsoft-user_basic'],
|
||||
$routes
|
||||
);
|
||||
|
||||
$result = $resolver->resolve('/shop/products/99');
|
||||
|
||||
$this->assertNotNull($result);
|
||||
$this->assertSame('sirsoft-ecommerce', $result['moduleIdentifier']);
|
||||
$this->assertSame('shop/show', $result['layoutName']);
|
||||
$this->assertSame(['id' => '99'], $result['routeParams']);
|
||||
}
|
||||
|
||||
/**
|
||||
* no_route=true일 때 삼항 연산자 표현식이 빈 문자열을 반환합니다.
|
||||
*/
|
||||
public function test_ternary_expression_returns_empty_when_no_route_true(): void
|
||||
{
|
||||
$routes = [
|
||||
[
|
||||
'path' => "/{{_global.modules?.['sirsoft-ecommerce']?.basic_info?.no_route ? '' : (_global.modules?.['sirsoft-ecommerce']?.basic_info?.route_path ?? 'shop')}}/products",
|
||||
'layout' => 'sirsoft-ecommerce.shop/index',
|
||||
'auth_required' => false,
|
||||
'guest_only' => false,
|
||||
'meta' => [],
|
||||
],
|
||||
];
|
||||
|
||||
Config::set('g7_settings.modules.sirsoft-ecommerce.basic_info.route_path', 'shop');
|
||||
Config::set('g7_settings.modules.sirsoft-ecommerce.basic_info.no_route', true);
|
||||
|
||||
$resolver = $this->createResolver(
|
||||
['identifier' => 'sirsoft-user_basic'],
|
||||
$routes
|
||||
);
|
||||
|
||||
// no_route=true → 빈 prefix → /products로 매칭
|
||||
$result = $resolver->resolve('/products');
|
||||
|
||||
$this->assertNotNull($result);
|
||||
$this->assertSame('shop/index', $result['layoutName']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 동적 표현식에서 모듈 설정이 없으면 기본값(fallback)을 사용합니다.
|
||||
*/
|
||||
public function test_dynamic_expression_uses_fallback_when_module_setting_missing(): void
|
||||
{
|
||||
$routes = [
|
||||
[
|
||||
'path' => "/{{_global.modules?.['sirsoft-ecommerce']?.basic_info?.route_path ?? 'shop'}}/products",
|
||||
'layout' => 'sirsoft-ecommerce.shop/index',
|
||||
'auth_required' => false,
|
||||
'guest_only' => false,
|
||||
'meta' => [],
|
||||
],
|
||||
];
|
||||
|
||||
// 모듈 설정 없음 → fallback 'shop' 사용
|
||||
Config::set('g7_settings.modules.sirsoft-ecommerce.basic_info.route_path', null);
|
||||
|
||||
$resolver = $this->createResolver(
|
||||
['identifier' => 'sirsoft-user_basic'],
|
||||
$routes,
|
||||
knownModules: ['sirsoft-ecommerce']
|
||||
);
|
||||
|
||||
$result = $resolver->resolve('/shop/products');
|
||||
|
||||
$this->assertNotNull($result);
|
||||
$this->assertSame('shop/index', $result['layoutName']);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 플러그인 식별자 판별 테스트 (3개)
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* 플러그인 dot notation에서 pluginIdentifier가 반환되고 moduleIdentifier는 null입니다.
|
||||
*/
|
||||
public function test_resolve_returns_plugin_identifier_for_plugin_layout(): void
|
||||
{
|
||||
$routes = [
|
||||
[
|
||||
'path' => '/payment/checkout',
|
||||
'layout' => 'sirsoft-payment.checkout',
|
||||
'auth_required' => false,
|
||||
'guest_only' => false,
|
||||
'meta' => [],
|
||||
],
|
||||
];
|
||||
|
||||
$resolver = $this->createResolver(
|
||||
['identifier' => 'sirsoft-user_basic'],
|
||||
$routes,
|
||||
knownPlugins: ['sirsoft-payment']
|
||||
);
|
||||
|
||||
$result = $resolver->resolve('/payment/checkout');
|
||||
|
||||
$this->assertNotNull($result);
|
||||
$this->assertNull($result['moduleIdentifier']);
|
||||
$this->assertSame('sirsoft-payment', $result['pluginIdentifier']);
|
||||
$this->assertSame('checkout', $result['layoutName']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 dot notation에서 moduleIdentifier가 반환되고 pluginIdentifier는 null입니다.
|
||||
*/
|
||||
public function test_resolve_returns_module_identifier_for_module_layout(): void
|
||||
{
|
||||
$routes = [
|
||||
[
|
||||
'path' => '/shop/products',
|
||||
'layout' => 'sirsoft-ecommerce.shop/index',
|
||||
'auth_required' => false,
|
||||
'guest_only' => false,
|
||||
'meta' => [],
|
||||
],
|
||||
];
|
||||
|
||||
$resolver = $this->createResolver(
|
||||
['identifier' => 'sirsoft-user_basic'],
|
||||
$routes,
|
||||
knownModules: ['sirsoft-ecommerce']
|
||||
);
|
||||
|
||||
$result = $resolver->resolve('/shop/products');
|
||||
|
||||
$this->assertNotNull($result);
|
||||
$this->assertSame('sirsoft-ecommerce', $result['moduleIdentifier']);
|
||||
$this->assertNull($result['pluginIdentifier']);
|
||||
}
|
||||
|
||||
/**
|
||||
* dot notation 없는 코어 레이아웃은 moduleIdentifier, pluginIdentifier 모두 null입니다.
|
||||
*/
|
||||
public function test_resolve_returns_null_identifiers_for_core_layout(): void
|
||||
{
|
||||
$routes = [
|
||||
[
|
||||
'path' => '/',
|
||||
'layout' => 'home',
|
||||
'auth_required' => false,
|
||||
'guest_only' => false,
|
||||
'meta' => [],
|
||||
],
|
||||
];
|
||||
|
||||
$resolver = $this->createResolver(
|
||||
['identifier' => 'sirsoft-user_basic'],
|
||||
$routes
|
||||
);
|
||||
|
||||
$result = $resolver->resolve('/');
|
||||
|
||||
$this->assertNotNull($result);
|
||||
$this->assertNull($result['moduleIdentifier']);
|
||||
$this->assertNull($result['pluginIdentifier']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Extension\TemplateManager;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use ReflectionMethod;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ValidateSeoConfigTest extends TestCase
|
||||
{
|
||||
private TemplateManager $templateManager;
|
||||
|
||||
private string $testTemplateDir;
|
||||
|
||||
private string $templateId = 'test-seo-validate';
|
||||
|
||||
/**
|
||||
* 테스트 초기화 - TemplateManager와 임시 디렉토리를 준비합니다.
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->templateManager = app(TemplateManager::class);
|
||||
$this->testTemplateDir = base_path("templates/{$this->templateId}");
|
||||
|
||||
if (File::exists($this->testTemplateDir)) {
|
||||
File::deleteDirectory($this->testTemplateDir);
|
||||
}
|
||||
File::makeDirectory($this->testTemplateDir, 0755, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트 정리 - 임시 디렉토리를 삭제합니다.
|
||||
*/
|
||||
protected function tearDown(): void
|
||||
{
|
||||
if (File::exists($this->testTemplateDir)) {
|
||||
File::deleteDirectory($this->testTemplateDir);
|
||||
}
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 올바른 seo-config.json → true를 반환합니다.
|
||||
*/
|
||||
public function test_valid_seo_config_passes(): void
|
||||
{
|
||||
$this->writeSeoConfig([
|
||||
'stylesheets' => ['https://example.com/style.css'],
|
||||
'self_closing' => ['img', 'hr'],
|
||||
'render_modes' => [
|
||||
'image_gallery' => ['type' => 'iterate', 'source' => '$props_source', 'item_tag' => 'img'],
|
||||
'text_format' => ['type' => 'format'],
|
||||
'html_content' => ['type' => 'raw', 'source' => '$props_source'],
|
||||
],
|
||||
'component_map' => [
|
||||
'Div' => ['tag' => 'div'],
|
||||
'Img' => ['tag' => 'img'],
|
||||
'ProductImageViewer' => ['tag' => 'div', 'render' => 'image_gallery', 'props_source' => 'images'],
|
||||
'StarRating' => ['tag' => 'span', 'render' => 'text_format', 'format' => '{value} / {max}'],
|
||||
'HtmlContent' => ['tag' => 'div', 'render' => 'html_content', 'props_source' => 'content'],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->assertTrue($this->callValidateSeoConfig());
|
||||
}
|
||||
|
||||
/**
|
||||
* 잘못된 JSON → false를 반환합니다.
|
||||
*/
|
||||
public function test_invalid_json_fails(): void
|
||||
{
|
||||
file_put_contents(
|
||||
$this->testTemplateDir.'/seo-config.json',
|
||||
'{ invalid json ,,, }'
|
||||
);
|
||||
|
||||
$this->expectException(\Exception::class);
|
||||
$this->callValidateSeoConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* component_map에서 미정의 render mode 참조 → false를 반환합니다.
|
||||
*/
|
||||
public function test_undefined_render_mode_reference_fails(): void
|
||||
{
|
||||
$this->writeSeoConfig([
|
||||
'render_modes' => [
|
||||
'image_gallery' => ['type' => 'iterate'],
|
||||
],
|
||||
'component_map' => [
|
||||
'MyComponent' => ['tag' => 'div', 'render' => 'nonexistent_mode'],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->expectException(\Exception::class);
|
||||
$this->callValidateSeoConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* render_modes에 잘못된 type → false를 반환합니다.
|
||||
*/
|
||||
public function test_invalid_render_mode_type_fails(): void
|
||||
{
|
||||
$this->writeSeoConfig([
|
||||
'render_modes' => [
|
||||
'my_mode' => ['type' => 'unknown_type'],
|
||||
],
|
||||
'component_map' => [],
|
||||
]);
|
||||
|
||||
$this->expectException(\Exception::class);
|
||||
$this->callValidateSeoConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* component_map에 tag 키 없음 → false를 반환합니다.
|
||||
*/
|
||||
public function test_missing_tag_in_component_map_fails(): void
|
||||
{
|
||||
$this->writeSeoConfig([
|
||||
'component_map' => [
|
||||
'Div' => ['className' => 'wrapper'],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->expectException(\Exception::class);
|
||||
$this->callValidateSeoConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* 파일 미존재 → true (경고만)를 반환합니다.
|
||||
*/
|
||||
public function test_seo_config_not_found_passes_with_warning(): void
|
||||
{
|
||||
// seo-config.json을 생성하지 않음
|
||||
@unlink($this->testTemplateDir.'/seo-config.json');
|
||||
|
||||
$this->assertTrue($this->callValidateSeoConfig());
|
||||
}
|
||||
|
||||
/**
|
||||
* stylesheets가 문자열 → false를 반환합니다.
|
||||
*/
|
||||
public function test_stylesheets_not_array_fails(): void
|
||||
{
|
||||
$this->writeSeoConfig([
|
||||
'stylesheets' => 'https://example.com/style.css',
|
||||
'component_map' => [
|
||||
'Div' => ['tag' => 'div'],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->expectException(\Exception::class);
|
||||
$this->callValidateSeoConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* seo-config.json 파일을 작성합니다.
|
||||
*
|
||||
* @param array $config 설정 배열
|
||||
*/
|
||||
private function writeSeoConfig(array $config): void
|
||||
{
|
||||
file_put_contents(
|
||||
$this->testTemplateDir.'/seo-config.json',
|
||||
json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* protected validateSeoConfig()를 Reflection으로 호출합니다.
|
||||
*
|
||||
* @return bool 검증 결과
|
||||
*/
|
||||
private function callValidateSeoConfig(): bool
|
||||
{
|
||||
$method = new ReflectionMethod(TemplateManager::class, 'validateSeoConfig');
|
||||
$method->setAccessible(true);
|
||||
|
||||
return $method->invoke($this->templateManager, $this->templateId);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user