v7.0.0-beta.4 release
This commit is contained in:
1 parent
05db17887d
commit
1db039ff34
1545 files changed
+136783
-11634
No files matched your search
@@ -0,0 +1,148 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\TestFixtures\Listeners {
|
||||
|
||||
use App\ActivityLog\Traits\ResolvesActivityLogType;
|
||||
|
||||
/**
|
||||
* 모듈 namespace 의 fake listener.
|
||||
*
|
||||
* `ExtensionManager::resolveExtensionByFqcn()` 가 본 FQCN 을
|
||||
* `sirsoft-ecommerce` 로 해석하는 것을 활용하여 trait 의 origin 자동 주입을 검증.
|
||||
*/
|
||||
class FakeEcommerceListener
|
||||
{
|
||||
use ResolvesActivityLogType;
|
||||
|
||||
public function fire(string $action, array $context = []): void
|
||||
{
|
||||
$this->logActivity($action, $context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace App\TestFixtures\CoreListeners {
|
||||
|
||||
use App\ActivityLog\Traits\ResolvesActivityLogType;
|
||||
|
||||
/**
|
||||
* 코어 namespace 의 fake listener — origin 미주입 검증용.
|
||||
*/
|
||||
class FakeCoreListener
|
||||
{
|
||||
use ResolvesActivityLogType;
|
||||
|
||||
public function fire(string $action, array $context = []): void
|
||||
{
|
||||
$this->logActivity($action, $context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace Tests\Unit\ActivityLog {
|
||||
|
||||
use App\TestFixtures\CoreListeners\FakeCoreListener;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Mockery;
|
||||
use Modules\Sirsoft\Ecommerce\TestFixtures\Listeners\FakeEcommerceListener;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* ResolvesActivityLogType trait 의 properties.extension_origin 자동 주입 검증.
|
||||
*
|
||||
* 호출 클래스 FQCN 이 모듈/플러그인 namespace 일 때만 origin 이 주입되며,
|
||||
* 코어 클래스는 주입하지 않음 (코어 lang fallback 으로 충분).
|
||||
*/
|
||||
class ResolvesActivityLogTypeOriginTest extends TestCase
|
||||
{
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Mockery::close();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_module_listener_injects_extension_origin_into_properties(): void
|
||||
{
|
||||
$captured = null;
|
||||
|
||||
$logChannel = Mockery::mock(LoggerInterface::class);
|
||||
Log::shouldReceive('channel')->with('activity')->andReturn($logChannel);
|
||||
$logChannel->shouldReceive('info')
|
||||
->once()
|
||||
->withArgs(function (string $action, array $context) use (&$captured) {
|
||||
$captured = $context;
|
||||
|
||||
return $action === 'mileage.earn';
|
||||
});
|
||||
|
||||
(new FakeEcommerceListener)->fire('mileage.earn');
|
||||
|
||||
$this->assertIsArray($captured);
|
||||
$this->assertSame('sirsoft-ecommerce', $captured['properties']['extension_origin']);
|
||||
}
|
||||
|
||||
public function test_core_listener_does_not_inject_extension_origin(): void
|
||||
{
|
||||
$captured = null;
|
||||
|
||||
$logChannel = Mockery::mock(LoggerInterface::class);
|
||||
Log::shouldReceive('channel')->with('activity')->andReturn($logChannel);
|
||||
$logChannel->shouldReceive('info')
|
||||
->once()
|
||||
->withArgs(function (string $action, array $context) use (&$captured) {
|
||||
$captured = $context;
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
(new FakeCoreListener)->fire('user.create');
|
||||
|
||||
$this->assertIsArray($captured);
|
||||
$this->assertArrayNotHasKey('extension_origin', $captured['properties'] ?? []);
|
||||
}
|
||||
|
||||
public function test_explicit_extension_origin_is_preserved(): void
|
||||
{
|
||||
$captured = null;
|
||||
|
||||
$logChannel = Mockery::mock(LoggerInterface::class);
|
||||
Log::shouldReceive('channel')->with('activity')->andReturn($logChannel);
|
||||
$logChannel->shouldReceive('info')
|
||||
->once()
|
||||
->withArgs(function (string $action, array $context) use (&$captured) {
|
||||
$captured = $context;
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
(new FakeEcommerceListener)->fire('mileage.earn', [
|
||||
'properties' => ['extension_origin' => 'manual-override'],
|
||||
]);
|
||||
|
||||
$this->assertSame('manual-override', $captured['properties']['extension_origin']);
|
||||
}
|
||||
|
||||
public function test_module_listener_preserves_existing_properties(): void
|
||||
{
|
||||
$captured = null;
|
||||
|
||||
$logChannel = Mockery::mock(LoggerInterface::class);
|
||||
Log::shouldReceive('channel')->with('activity')->andReturn($logChannel);
|
||||
$logChannel->shouldReceive('info')
|
||||
->once()
|
||||
->withArgs(function (string $action, array $context) use (&$captured) {
|
||||
$captured = $context;
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
(new FakeEcommerceListener)->fire('mileage.earn', [
|
||||
'properties' => ['extra' => 'value'],
|
||||
]);
|
||||
|
||||
$this->assertSame('sirsoft-ecommerce', $captured['properties']['extension_origin']);
|
||||
$this->assertSame('value', $captured['properties']['extra']);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Concerns\Seeder;
|
||||
|
||||
use App\Concerns\Seeder\HasTranslatableSeeder;
|
||||
use App\Contracts\Seeder\TranslatableSeederInterface;
|
||||
use App\Extension\HookManager;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* HasTranslatableSeeder Trait 단위 테스트.
|
||||
*
|
||||
* 검증 시나리오:
|
||||
* 1. 확장 식별자가 있을 때 필터명이 `seed.{ext}.{entity}.translations` 로 조립됨
|
||||
* 2. 확장 식별자가 빈 문자열일 때 필터명이 `seed.{entity}.translations` 로 조립됨
|
||||
* 3. 등록된 필터가 없으면 getDefaults() 결과가 그대로 반환됨
|
||||
* 4. 등록된 필터가 있으면 활성 lang pack 키가 머지된 결과가 반환됨
|
||||
* 5. 매칭 키 (code/slug/key) 가 entry 보강 시 사용되는지 — 필터 콜백 인자로 정확히 전달됨
|
||||
*/
|
||||
class HasTranslatableSeederTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* 테스트용 anonymous 시더 — interface + trait 사용.
|
||||
*/
|
||||
private function makeSeeder(string $extension, string $entity, string $matchKey, array $defaults): TranslatableSeederInterface
|
||||
{
|
||||
return new class($extension, $entity, $matchKey, $defaults) implements TranslatableSeederInterface
|
||||
{
|
||||
use HasTranslatableSeeder;
|
||||
|
||||
public function __construct(
|
||||
private string $extension,
|
||||
private string $entity,
|
||||
private string $matchKey,
|
||||
private array $defaults,
|
||||
) {}
|
||||
|
||||
public function getExtensionIdentifier(): string
|
||||
{
|
||||
return $this->extension;
|
||||
}
|
||||
|
||||
public function getTranslatableEntity(): string
|
||||
{
|
||||
return $this->entity;
|
||||
}
|
||||
|
||||
public function getMatchKey(): string
|
||||
{
|
||||
return $this->matchKey;
|
||||
}
|
||||
|
||||
public function getDefaults(): array
|
||||
{
|
||||
return $this->defaults;
|
||||
}
|
||||
|
||||
public function exposeFilterName(): string
|
||||
{
|
||||
return $this->resolveTranslationFilterName();
|
||||
}
|
||||
|
||||
public function exposeResolved(): array
|
||||
{
|
||||
return $this->resolveTranslatedDefaults();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public function test_filter_name_for_extension_scope(): void
|
||||
{
|
||||
$seeder = $this->makeSeeder('sirsoft-ecommerce', 'shipping_carriers', 'code', []);
|
||||
|
||||
$this->assertSame(
|
||||
'seed.sirsoft-ecommerce.shipping_carriers.translations',
|
||||
$seeder->exposeFilterName(),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_filter_name_for_core_scope_when_extension_empty(): void
|
||||
{
|
||||
$seeder = $this->makeSeeder('', 'notifications', 'type', []);
|
||||
|
||||
$this->assertSame(
|
||||
'seed.notifications.translations',
|
||||
$seeder->exposeFilterName(),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_returns_defaults_when_no_filter_registered(): void
|
||||
{
|
||||
$defaults = [
|
||||
['code' => 'cj', 'name' => ['ko' => 'CJ대한통운', 'en' => 'CJ Logistics']],
|
||||
];
|
||||
|
||||
$seeder = $this->makeSeeder('sirsoft-ecommerce', 'shipping_carriers_unfiltered_'.uniqid(), 'code', $defaults);
|
||||
|
||||
$this->assertSame($defaults, $seeder->exposeResolved());
|
||||
}
|
||||
|
||||
public function test_returns_filtered_defaults_with_lang_pack_merge(): void
|
||||
{
|
||||
$entity = 'shipping_carriers_filtered_'.uniqid();
|
||||
$filterName = "seed.sirsoft-ecommerce.{$entity}.translations";
|
||||
|
||||
$defaults = [
|
||||
['code' => 'cj', 'name' => ['ko' => 'CJ대한통운', 'en' => 'CJ Logistics']],
|
||||
['code' => 'hanjin', 'name' => ['ko' => '한진택배', 'en' => 'Hanjin Express']],
|
||||
];
|
||||
|
||||
// 활성 ja lang pack 의 seed/{entity}.json 머지를 모사 — code 매칭으로 ja 키 보강
|
||||
$jaSeed = [
|
||||
['code' => 'cj', 'name' => ['ja' => 'CJ大韓通運']],
|
||||
['code' => 'hanjin', 'name' => ['ja' => 'ハンジン宅配']],
|
||||
];
|
||||
|
||||
HookManager::addFilter($filterName, function (array $entries) use ($jaSeed): array {
|
||||
foreach ($entries as &$entry) {
|
||||
foreach ($jaSeed as $patch) {
|
||||
if ($entry['code'] === $patch['code']) {
|
||||
$entry['name'] = array_merge($entry['name'], $patch['name']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $entries;
|
||||
});
|
||||
|
||||
$seeder = $this->makeSeeder('sirsoft-ecommerce', $entity, 'code', $defaults);
|
||||
$resolved = $seeder->exposeResolved();
|
||||
|
||||
$this->assertCount(2, $resolved);
|
||||
$this->assertSame('CJ대한통운', $resolved[0]['name']['ko']);
|
||||
$this->assertSame('CJ Logistics', $resolved[0]['name']['en']);
|
||||
$this->assertSame('CJ大韓通運', $resolved[0]['name']['ja']);
|
||||
$this->assertSame('ハンジン宅配', $resolved[1]['name']['ja']);
|
||||
}
|
||||
|
||||
public function test_match_key_passes_through_to_filter_callback(): void
|
||||
{
|
||||
$entity = 'board_types_'.uniqid();
|
||||
$filterName = "seed.sirsoft-board.{$entity}.translations";
|
||||
|
||||
$defaults = [
|
||||
['slug' => 'basic', 'name' => ['ko' => '기본형']],
|
||||
];
|
||||
|
||||
$captured = null;
|
||||
HookManager::addFilter($filterName, function (array $entries) use (&$captured): array {
|
||||
$captured = $entries;
|
||||
|
||||
return $entries;
|
||||
});
|
||||
|
||||
$seeder = $this->makeSeeder('sirsoft-board', $entity, 'slug', $defaults);
|
||||
$seeder->exposeResolved();
|
||||
|
||||
$this->assertSame($defaults, $captured);
|
||||
$this->assertSame('slug', $seeder->getMatchKey());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Config;
|
||||
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* config/database.php 의 PHP 8.5+ deprecation 회피 회귀 테스트
|
||||
*
|
||||
* PHP 8.5 에서 PDO::MYSQL_ATTR_SSL_CA 상수가 deprecated 되었으므로
|
||||
* config 로드 시 E_DEPRECATED 가 트리거되지 않아야 한다.
|
||||
*
|
||||
* 검증 방식:
|
||||
* 1. 동적: config 파일을 재include 하여 발생한 PDO 관련 deprecation 캡처 (PHP 8.5+ 에서만 트리거)
|
||||
* 2. 정적: 파일 텍스트에서 가드 없는 PDO::MYSQL_ATTR_SSL_CA 직접 참조 패턴 검출 (모든 PHP 버전)
|
||||
*
|
||||
* 정적 검사는 PHP 8.4 이하 CI 에서도 회귀를 차단하기 위함이다.
|
||||
*
|
||||
* @see https://github.com/gnuboard/g7/issues/23
|
||||
*/
|
||||
class DatabaseConfigDeprecationTest extends TestCase
|
||||
{
|
||||
public function test_mysql_options_does_not_trigger_pdo_deprecation(): void
|
||||
{
|
||||
$deprecations = $this->captureDeprecations(function () {
|
||||
// Laravel 부팅 후 config 파일을 재include — database_path() 등 헬퍼 사용 가능
|
||||
$config = require config_path('database.php');
|
||||
$mysqlOptions = $config['connections']['mysql']['options'];
|
||||
$mariadbOptions = $config['connections']['mariadb']['options'];
|
||||
|
||||
// array_filter 결과를 실제로 순회하여 키 상수 평가 강제
|
||||
foreach ($mysqlOptions as $k => $v) {
|
||||
$unused = $k;
|
||||
}
|
||||
foreach ($mariadbOptions as $k => $v) {
|
||||
$unused = $k;
|
||||
}
|
||||
});
|
||||
|
||||
$this->assertEmpty(
|
||||
$deprecations,
|
||||
'config/database.php emitted PHP deprecation: '
|
||||
. json_encode($deprecations, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)
|
||||
);
|
||||
}
|
||||
|
||||
public function test_config_file_does_not_reference_unguarded_deprecated_pdo_constant(): void
|
||||
{
|
||||
$file = file_get_contents(config_path('database.php'));
|
||||
|
||||
// 가드 패턴: PHP_VERSION_ID >= 80500 ternary 안에서만 PDO::MYSQL_ATTR_SSL_CA 사용 허용
|
||||
$guardedPattern = '/PHP_VERSION_ID\s*>=\s*80500.*?Pdo\\\\Mysql::ATTR_SSL_CA.*?PDO::MYSQL_ATTR_SSL_CA/s';
|
||||
$hasGuard = (bool) preg_match($guardedPattern, $file);
|
||||
|
||||
// 직접 참조 횟수
|
||||
$directReferences = preg_match_all('/PDO::MYSQL_ATTR_SSL_CA/', $file);
|
||||
|
||||
if ($directReferences > 0 && ! $hasGuard) {
|
||||
$this->fail(
|
||||
"config/database.php references PDO::MYSQL_ATTR_SSL_CA without a "
|
||||
. "PHP_VERSION_ID >= 80500 ternary guard. This causes E_DEPRECATED "
|
||||
. "on PHP 8.5+. Use \\Pdo\\Mysql::ATTR_SSL_CA when PHP_VERSION_ID >= 80500."
|
||||
);
|
||||
}
|
||||
|
||||
$this->assertTrue(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable $fn 실행 중 발생한 deprecation 을 수집할 콜백
|
||||
* @return array<int, array{message: string, file: string, line: int}>
|
||||
*/
|
||||
private function captureDeprecations(callable $fn): array
|
||||
{
|
||||
$deprecations = [];
|
||||
|
||||
set_error_handler(function ($severity, $message, $file, $line) use (&$deprecations) {
|
||||
if ($severity === E_DEPRECATED || $severity === E_USER_DEPRECATED) {
|
||||
if (str_contains($message, 'PDO::') || str_contains($message, 'MYSQL_ATTR_')) {
|
||||
$deprecations[] = compact('message', 'file', 'line');
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}, E_DEPRECATED | E_USER_DEPRECATED);
|
||||
|
||||
try {
|
||||
$fn();
|
||||
} finally {
|
||||
restore_error_handler();
|
||||
}
|
||||
|
||||
return $deprecations;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Console;
|
||||
|
||||
use App\Services\LanguagePackService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* language-pack:check-updates 콘솔 커맨드 회귀 테스트.
|
||||
*
|
||||
* 본 커맨드는 LanguagePackService::checkUpdates() 에 위임하므로 위임 동작과
|
||||
* 출력 포맷이 회귀 없이 유지되는지 검증합니다.
|
||||
*/
|
||||
class CheckLanguagePackUpdatesCommandTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* 테스트 정리.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Mockery::close();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_outputs_no_packs_message_when_empty(): void
|
||||
{
|
||||
$service = Mockery::mock(LanguagePackService::class);
|
||||
$service->shouldReceive('checkUpdates')
|
||||
->once()
|
||||
->with(null)
|
||||
->andReturn(['checked' => 0, 'updates' => 0, 'details' => []]);
|
||||
$this->app->instance(LanguagePackService::class, $service);
|
||||
|
||||
$this->artisan('language-pack:check-updates')
|
||||
->expectsOutputToContain('GitHub 기반 언어팩이 없습니다')
|
||||
->assertSuccessful();
|
||||
}
|
||||
|
||||
public function test_renders_each_detail_line(): void
|
||||
{
|
||||
$service = Mockery::mock(LanguagePackService::class);
|
||||
$service->shouldReceive('checkUpdates')
|
||||
->once()
|
||||
->with(null)
|
||||
->andReturn([
|
||||
'checked' => 2,
|
||||
'updates' => 1,
|
||||
'details' => [
|
||||
['identifier' => 'foo-core-ja', 'current' => '1.0.0', 'latest' => '1.1.0', 'has_update' => true, 'error' => null],
|
||||
['identifier' => 'foo-core-de', 'current' => '1.0.0', 'latest' => '1.0.0', 'has_update' => false, 'error' => null],
|
||||
],
|
||||
]);
|
||||
$this->app->instance(LanguagePackService::class, $service);
|
||||
|
||||
$this->artisan('language-pack:check-updates')
|
||||
->expectsOutputToContain('foo-core-ja')
|
||||
->expectsOutputToContain('foo-core-de')
|
||||
->assertSuccessful();
|
||||
}
|
||||
|
||||
public function test_passes_identifier_option(): void
|
||||
{
|
||||
$service = Mockery::mock(LanguagePackService::class);
|
||||
$service->shouldReceive('checkUpdates')
|
||||
->once()
|
||||
->with('foo-core-ja')
|
||||
->andReturn(['checked' => 0, 'updates' => 0, 'details' => []]);
|
||||
$this->app->instance(LanguagePackService::class, $service);
|
||||
|
||||
$this->artisan('language-pack:check-updates', ['--identifier' => 'foo-core-ja'])
|
||||
->assertSuccessful();
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,10 @@ class BroadcastDashboardResourcesTest extends TestCase
|
||||
|
||||
public function test_command_broadcasts_resources_update(): void
|
||||
{
|
||||
// HookManager::broadcast 는 null/log 드라이버 또는 host 미설정 시 dispatch 스킵
|
||||
config(['broadcasting.default' => 'reverb']);
|
||||
config(['broadcasting.connections.reverb.options.host' => 'localhost']);
|
||||
|
||||
Event::fake([GenericBroadcastEvent::class]);
|
||||
|
||||
$this->artisan('dashboard:broadcast-resources')
|
||||
@@ -35,6 +39,10 @@ class BroadcastDashboardResourcesTest extends TestCase
|
||||
|
||||
public function test_command_sends_correct_resource_data(): void
|
||||
{
|
||||
// HookManager::broadcast 는 null/log 드라이버 또는 host 미설정 시 dispatch 스킵
|
||||
config(['broadcasting.default' => 'reverb']);
|
||||
config(['broadcasting.connections.reverb.options.host' => 'localhost']);
|
||||
|
||||
Event::fake([GenericBroadcastEvent::class]);
|
||||
|
||||
$this->artisan('dashboard:broadcast-resources')
|
||||
|
||||
@@ -5,13 +5,14 @@ namespace Tests\Unit\Console\Commands;
|
||||
use App\Jobs\GenerateSitemapJob;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Bus;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* SeoGenerateSitemapCommand 유닛 테스트
|
||||
*
|
||||
* seo:generate-sitemap 커맨드의 큐 디스패치, 동기 실행, 출력 메시지를 검증합니다.
|
||||
* seo:generate-sitemap 커맨드의 큐 드라이버 분기, 강제 동기, 출력 메시지를 검증합니다.
|
||||
*/
|
||||
class SeoGenerateSitemapCommandTest extends TestCase
|
||||
{
|
||||
@@ -22,52 +23,48 @@ class SeoGenerateSitemapCommandTest extends TestCase
|
||||
}
|
||||
|
||||
/**
|
||||
* --sync 없이 실행 시 잡이 큐에 디스패치되는지 확인합니다.
|
||||
* 큐 드라이버가 sync 가 아닐 때 비동기 디스패치되는지 확인합니다.
|
||||
*/
|
||||
public function test_command_dispatches_job_to_queue(): void
|
||||
public function test_command_dispatches_async_when_queue_driver_is_not_sync(): void
|
||||
{
|
||||
Config::set('queue.default', 'database');
|
||||
Bus::fake([GenerateSitemapJob::class]);
|
||||
|
||||
$this->artisan('seo:generate-sitemap')
|
||||
->expectsOutput('Sitemap 생성이 큐에 디스패치되었습니다.')
|
||||
->assertExitCode(Command::SUCCESS);
|
||||
|
||||
Bus::assertDispatched(GenerateSitemapJob::class);
|
||||
Bus::assertNotDispatchedSync(GenerateSitemapJob::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* --sync 옵션으로 실행 시 잡이 동기적으로 디스패치되는지 확인합니다.
|
||||
* 큐 드라이버가 sync 일 때 옵션 없이도 동기 실행되는지 확인합니다.
|
||||
*/
|
||||
public function test_command_dispatches_job_sync(): void
|
||||
public function test_command_dispatches_sync_when_queue_driver_is_sync(): void
|
||||
{
|
||||
Config::set('queue.default', 'sync');
|
||||
Bus::fake([GenerateSitemapJob::class]);
|
||||
|
||||
$this->artisan('seo:generate-sitemap', ['--sync' => true])
|
||||
$this->artisan('seo:generate-sitemap')
|
||||
->expectsOutput('Sitemap이 생성되었습니다.')
|
||||
->assertExitCode(Command::SUCCESS);
|
||||
|
||||
Bus::assertDispatchedSync(GenerateSitemapJob::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 큐 디스패치 시 올바른 출력 메시지를 확인합니다.
|
||||
* --sync 옵션은 큐 드라이버와 무관하게 동기 실행을 강제합니다.
|
||||
*/
|
||||
public function test_command_outputs_queue_dispatch_message(): void
|
||||
{
|
||||
Bus::fake([GenerateSitemapJob::class]);
|
||||
|
||||
$this->artisan('seo:generate-sitemap')
|
||||
->expectsOutput('Sitemap 생성이 큐에 디스패치되었습니다.')
|
||||
->assertExitCode(Command::SUCCESS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 동기 실행 시 올바른 출력 메시지를 확인합니다.
|
||||
*/
|
||||
public function test_command_outputs_sync_success_message(): void
|
||||
public function test_command_forces_sync_when_option_provided(): void
|
||||
{
|
||||
Config::set('queue.default', 'database');
|
||||
Bus::fake([GenerateSitemapJob::class]);
|
||||
|
||||
$this->artisan('seo:generate-sitemap', ['--sync' => true])
|
||||
->expectsOutput('Sitemap이 생성되었습니다.')
|
||||
->assertExitCode(Command::SUCCESS);
|
||||
|
||||
Bus::assertDispatchedSync(GenerateSitemapJob::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Console\Commands\Traits;
|
||||
|
||||
use App\Console\Commands\Traits\HasUnifiedConfirm;
|
||||
use Illuminate\Console\Command;
|
||||
use Symfony\Component\Console\Tester\CommandTester;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* HasUnifiedConfirm trait 단위 테스트.
|
||||
*
|
||||
* Symfony QuestionHelper 를 거치므로 CommandTester 의 setInputs() 로 STDIN 시뮬레이션,
|
||||
* --no-interaction 시 default 즉시 반환을 검증한다.
|
||||
*/
|
||||
class HasUnifiedConfirmTest extends TestCase
|
||||
{
|
||||
public function test_returns_default_when_non_interactive_default_false(): void
|
||||
{
|
||||
$tester = $this->makeTester(false);
|
||||
|
||||
$tester->execute([], ['interactive' => false]);
|
||||
|
||||
$this->assertSame('false', trim($tester->getDisplay()));
|
||||
}
|
||||
|
||||
public function test_returns_default_when_non_interactive_default_true(): void
|
||||
{
|
||||
$tester = $this->makeTester(true);
|
||||
|
||||
$tester->execute([], ['interactive' => false]);
|
||||
|
||||
$this->assertSame('true', trim($tester->getDisplay()));
|
||||
}
|
||||
|
||||
public function test_resolves_immediately_on_yes_input(): void
|
||||
{
|
||||
$tester = $this->makeTester(false);
|
||||
$tester->setInputs(['yes']);
|
||||
|
||||
$tester->execute([]);
|
||||
|
||||
$display = $tester->getDisplay();
|
||||
$this->assertStringEndsWith('true', trim($display));
|
||||
$this->assertStringNotContainsString('yes, y, no, n', $display);
|
||||
}
|
||||
|
||||
public function test_resolves_immediately_on_no_input(): void
|
||||
{
|
||||
$tester = $this->makeTester(true);
|
||||
$tester->setInputs(['no']);
|
||||
|
||||
$tester->execute([]);
|
||||
|
||||
$this->assertStringEndsWith('false', trim($tester->getDisplay()));
|
||||
}
|
||||
|
||||
public function test_resolves_on_y_short_input(): void
|
||||
{
|
||||
$tester = $this->makeTester(false);
|
||||
$tester->setInputs(['y']);
|
||||
|
||||
$tester->execute([]);
|
||||
|
||||
$this->assertStringEndsWith('true', trim($tester->getDisplay()));
|
||||
}
|
||||
|
||||
public function test_returns_default_on_empty_input(): void
|
||||
{
|
||||
$tester = $this->makeTester(true);
|
||||
$tester->setInputs(['']);
|
||||
|
||||
$tester->execute([]);
|
||||
|
||||
$this->assertStringEndsWith('true', trim($tester->getDisplay()));
|
||||
}
|
||||
|
||||
public function test_loops_on_invalid_input_then_resolves(): void
|
||||
{
|
||||
$tester = $this->makeTester(false);
|
||||
$tester->setInputs(['abc', 'y']);
|
||||
|
||||
$tester->execute([]);
|
||||
|
||||
$display = $tester->getDisplay();
|
||||
$this->assertStringContainsString('yes, y, no, n 중 하나로 입력해 주세요.', $display);
|
||||
$this->assertStringEndsWith('true', trim($display));
|
||||
}
|
||||
|
||||
public function test_loops_multiple_times_on_invalid_input(): void
|
||||
{
|
||||
$tester = $this->makeTester(true);
|
||||
$tester->setInputs(['abc', 'foo', 'no']);
|
||||
|
||||
$tester->execute([]);
|
||||
|
||||
$display = $tester->getDisplay();
|
||||
$this->assertSame(2, substr_count($display, 'yes, y, no, n 중 하나로 입력해 주세요.'));
|
||||
$this->assertStringEndsWith('false', trim($display));
|
||||
}
|
||||
|
||||
/**
|
||||
* Symfony QuestionHelper 가 default 값을 자동 표시하는 `[default]` 가
|
||||
* 우리가 직접 그린 `[yes]` / `[no]` 옆에 빈 `[]` 로 중복 출력되지 않아야 한다.
|
||||
*
|
||||
* 회귀 시나리오 (이전): `진행할까요? (yes/no) [no] []:`
|
||||
* 정상: `진행할까요? (yes/no) [no]:`
|
||||
*/
|
||||
public function test_prompt_does_not_show_duplicate_empty_default_brackets(): void
|
||||
{
|
||||
$tester = $this->makeTester(false);
|
||||
$tester->setInputs(['no']);
|
||||
|
||||
$tester->execute([]);
|
||||
|
||||
$display = $tester->getDisplay();
|
||||
// `[no] []` 또는 `[yes] []` 같은 중복 default 표시가 없어야 함
|
||||
$this->assertStringNotContainsString('[no] []', $display);
|
||||
$this->assertStringNotContainsString('[yes] []', $display);
|
||||
$this->assertStringNotContainsString('[]', $display);
|
||||
// 정상 prompt 형식 확인
|
||||
$this->assertStringContainsString('진행할까요? (yes/no) [no]:', $display);
|
||||
}
|
||||
|
||||
public function test_prompt_does_not_show_duplicate_brackets_when_default_yes(): void
|
||||
{
|
||||
$tester = $this->makeTester(true);
|
||||
$tester->setInputs(['yes']);
|
||||
|
||||
$tester->execute([]);
|
||||
|
||||
$display = $tester->getDisplay();
|
||||
$this->assertStringNotContainsString('[]', $display);
|
||||
$this->assertStringContainsString('진행할까요? (yes/no) [yes]:', $display);
|
||||
}
|
||||
|
||||
private function makeTester(bool $default): CommandTester
|
||||
{
|
||||
$command = new class($default) extends Command
|
||||
{
|
||||
use HasUnifiedConfirm;
|
||||
|
||||
protected $signature = 'test:unified-confirm';
|
||||
|
||||
public function __construct(private bool $defaultValue)
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$result = $this->unifiedConfirm('진행할까요?', $this->defaultValue);
|
||||
$this->line($result ? 'true' : 'false');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
};
|
||||
|
||||
$command->setLaravel($this->app);
|
||||
|
||||
return new CommandTester($command);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Console\Helpers;
|
||||
|
||||
use App\Console\Helpers\ConsoleConfirm;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* ConsoleConfirm 헬퍼 단위 테스트.
|
||||
*
|
||||
* - parse(): 입력 정규화 규칙 (대소문자/공백/empty/유효값/무효값)
|
||||
* - ask(): STDIN 루프 동작 (1회 결정/재질문/EOF/non-tty)
|
||||
*/
|
||||
class ConsoleConfirmTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* @return array<string, array{string, bool, bool|null}>
|
||||
*/
|
||||
public static function parseCases(): array
|
||||
{
|
||||
return [
|
||||
'empty + default true' => ['', true, true],
|
||||
'empty + default false' => ['', false, false],
|
||||
'yes lowercase' => ['yes', false, true],
|
||||
'y short' => ['y', false, true],
|
||||
'Y uppercase' => ['Y', false, true],
|
||||
'YES uppercase' => ['YES', false, true],
|
||||
'yes with surrounding whitespace' => [' yes ', false, true],
|
||||
'yes with newline (fgets style)' => ["\nyes\n", false, true],
|
||||
'no lowercase' => ['no', true, false],
|
||||
'n short' => ['n', true, false],
|
||||
'N uppercase + default true' => ['N', true, false],
|
||||
'NO uppercase' => ['NO', true, false],
|
||||
'invalid - yell_no (default false)' => ['yell_no', false, null],
|
||||
'invalid - nope (default true)' => ['nope', true, null],
|
||||
'invalid - yeah (y로 시작이지만 무관)' => ['yeah', false, null],
|
||||
'invalid - 1 (numeric truthy)' => ['1', false, null],
|
||||
'invalid - 0 (numeric falsy)' => ['0', false, null],
|
||||
'invalid - true literal' => ['true', false, null],
|
||||
'invalid - false literal' => ['false', false, null],
|
||||
'invalid - 한글 예 (비ASCII)' => ['예', false, null],
|
||||
'invalid - 한글 네 (비ASCII)' => ['네', false, null],
|
||||
'whitespace-only → empty → default' => [" \t \n", true, true],
|
||||
];
|
||||
}
|
||||
|
||||
#[DataProvider('parseCases')]
|
||||
public function test_parse_normalizes_input(string $raw, bool $default, ?bool $expected): void
|
||||
{
|
||||
$this->assertSame($expected, ConsoleConfirm::parse($raw, $default));
|
||||
}
|
||||
|
||||
public function test_ask_returns_immediately_on_first_valid_input(): void
|
||||
{
|
||||
$stdin = $this->makeStdin(["yes\n"]);
|
||||
$output = '';
|
||||
|
||||
$result = ConsoleConfirm::ask(
|
||||
'진행할까요?',
|
||||
false,
|
||||
$stdin,
|
||||
function (string $text) use (&$output) {
|
||||
$output .= $text;
|
||||
},
|
||||
);
|
||||
|
||||
$this->assertTrue($result);
|
||||
$this->assertStringContainsString('진행할까요? (yes/no) [no]: ', $output);
|
||||
$this->assertStringNotContainsString('yes, y, no, n', $output);
|
||||
}
|
||||
|
||||
public function test_ask_loops_on_invalid_input_then_resolves(): void
|
||||
{
|
||||
$stdin = $this->makeStdin(["abc\n", "y\n"]);
|
||||
$output = '';
|
||||
|
||||
$result = ConsoleConfirm::ask(
|
||||
'진행할까요?',
|
||||
false,
|
||||
$stdin,
|
||||
function (string $text) use (&$output) {
|
||||
$output .= $text;
|
||||
},
|
||||
);
|
||||
|
||||
$this->assertTrue($result);
|
||||
$this->assertStringContainsString('yes, y, no, n 중 하나로 입력해 주세요.', $output);
|
||||
// 질문이 정확히 2회 출력되어야 함
|
||||
$this->assertSame(2, substr_count($output, '진행할까요? (yes/no) [no]: '));
|
||||
}
|
||||
|
||||
public function test_ask_loops_multiple_times_on_invalid_input(): void
|
||||
{
|
||||
$stdin = $this->makeStdin(["a\n", "b\n", "no\n"]);
|
||||
$output = '';
|
||||
|
||||
$result = ConsoleConfirm::ask(
|
||||
'진행할까요?',
|
||||
true,
|
||||
$stdin,
|
||||
function (string $text) use (&$output) {
|
||||
$output .= $text;
|
||||
},
|
||||
);
|
||||
|
||||
$this->assertFalse($result);
|
||||
$this->assertSame(2, substr_count($output, 'yes, y, no, n 중 하나로 입력해 주세요.'));
|
||||
$this->assertSame(3, substr_count($output, '진행할까요? (yes/no) [yes]: '));
|
||||
}
|
||||
|
||||
public function test_ask_returns_default_on_eof(): void
|
||||
{
|
||||
$stdin = $this->makeStdin([]);
|
||||
|
||||
$resultDefaultTrue = ConsoleConfirm::ask('Q?', true, $stdin, fn () => null);
|
||||
$this->assertTrue($resultDefaultTrue);
|
||||
|
||||
$stdin2 = $this->makeStdin([]);
|
||||
$resultDefaultFalse = ConsoleConfirm::ask('Q?', false, $stdin2, fn () => null);
|
||||
$this->assertFalse($resultDefaultFalse);
|
||||
}
|
||||
|
||||
public function test_ask_returns_default_on_empty_input(): void
|
||||
{
|
||||
$stdin = $this->makeStdin(["\n"]);
|
||||
|
||||
$result = ConsoleConfirm::ask('Q?', true, $stdin, fn () => null);
|
||||
|
||||
$this->assertTrue($result);
|
||||
}
|
||||
|
||||
public function test_ask_uses_yes_hint_when_default_true(): void
|
||||
{
|
||||
$stdin = $this->makeStdin(["yes\n"]);
|
||||
$output = '';
|
||||
|
||||
ConsoleConfirm::ask('Q?', true, $stdin, function (string $text) use (&$output) {
|
||||
$output .= $text;
|
||||
});
|
||||
|
||||
$this->assertStringContainsString('Q? (yes/no) [yes]: ', $output);
|
||||
}
|
||||
|
||||
public function test_ask_uses_no_hint_when_default_false(): void
|
||||
{
|
||||
$stdin = $this->makeStdin(["no\n"]);
|
||||
$output = '';
|
||||
|
||||
ConsoleConfirm::ask('Q?', false, $stdin, function (string $text) use (&$output) {
|
||||
$output .= $text;
|
||||
});
|
||||
|
||||
$this->assertStringContainsString('Q? (yes/no) [no]: ', $output);
|
||||
}
|
||||
|
||||
/**
|
||||
* 메모리 기반 STDIN 리소스 생성.
|
||||
*
|
||||
* @param array<string> $lines fgets() 가 차례로 반환할 줄 (개행 포함 권장)
|
||||
* @return resource
|
||||
*/
|
||||
private function makeStdin(array $lines)
|
||||
{
|
||||
$stream = fopen('php://memory', 'r+');
|
||||
foreach ($lines as $line) {
|
||||
fwrite($stream, $line);
|
||||
}
|
||||
rewind($stream);
|
||||
|
||||
return $stream;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Contracts;
|
||||
|
||||
use App\Contracts\Extension\IdentityVerificationInterface;
|
||||
use App\Extension\IdentityVerification\Providers\MailIdentityProvider;
|
||||
use ReflectionClass;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* IdentityVerificationInterface 계약 테스트.
|
||||
*
|
||||
* 모든 구현체가 계약의 공개 메서드를 빠짐없이 구현하고,
|
||||
* 반환 타입이 계약과 일치하는지 검증합니다.
|
||||
*/
|
||||
class IdentityVerificationInterfaceContractTest extends TestCase
|
||||
{
|
||||
public function test_interface_defines_required_methods(): void
|
||||
{
|
||||
$reflection = new ReflectionClass(IdentityVerificationInterface::class);
|
||||
$methods = array_map(fn ($m) => $m->getName(), $reflection->getMethods());
|
||||
|
||||
foreach ([
|
||||
'getId',
|
||||
'getLabel',
|
||||
'getChannels',
|
||||
'getRenderHint',
|
||||
'supportsPurpose',
|
||||
'isAvailable',
|
||||
'requestChallenge',
|
||||
'verify',
|
||||
'cancel',
|
||||
'getSettingsSchema',
|
||||
'withConfig',
|
||||
] as $expected) {
|
||||
$this->assertContains($expected, $methods, "Interface must declare {$expected}().");
|
||||
}
|
||||
}
|
||||
|
||||
public function test_mail_provider_fulfills_contract(): void
|
||||
{
|
||||
$provider = $this->app->make(MailIdentityProvider::class);
|
||||
|
||||
$this->assertInstanceOf(IdentityVerificationInterface::class, $provider);
|
||||
$this->assertIsString($provider->getId());
|
||||
$this->assertIsString($provider->getLabel());
|
||||
$this->assertIsArray($provider->getChannels());
|
||||
$this->assertIsString($provider->getRenderHint());
|
||||
$this->assertIsBool($provider->supportsPurpose('signup'));
|
||||
$this->assertIsBool($provider->isAvailable());
|
||||
$this->assertIsArray($provider->getSettingsSchema());
|
||||
}
|
||||
|
||||
public function test_with_config_returns_new_instance(): void
|
||||
{
|
||||
$provider = $this->app->make(MailIdentityProvider::class);
|
||||
$configured = $provider->withConfig(['code_length' => 8]);
|
||||
|
||||
$this->assertInstanceOf(IdentityVerificationInterface::class, $configured);
|
||||
$this->assertNotSame($provider, $configured);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Enums;
|
||||
|
||||
use App\Enums\IdentityMessageScopeType;
|
||||
use App\Enums\IdentityOriginType;
|
||||
use App\Enums\IdentityPolicyAppliesTo;
|
||||
use App\Enums\IdentityPolicyFailMode;
|
||||
use App\Enums\IdentityPolicyScope;
|
||||
use App\Enums\IdentityPolicySourceType;
|
||||
use App\Enums\IdentityVerificationChannel;
|
||||
use App\Enums\IdentityVerificationPurpose;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* IDV 도메인 Enum 8종 단위 테스트.
|
||||
*
|
||||
* 케이스 누락/추가 회귀, tryFrom 안전성, label 다국어 키 존재를 검증합니다.
|
||||
*/
|
||||
class IdentityDomainEnumsTest extends TestCase
|
||||
{
|
||||
// ========================================================================
|
||||
// IdentityVerificationPurpose
|
||||
// ========================================================================
|
||||
|
||||
public function test_verification_purpose_has_four_core_cases(): void
|
||||
{
|
||||
$this->assertCount(4, IdentityVerificationPurpose::cases());
|
||||
$this->assertSame(
|
||||
['signup', 'password_reset', 'self_update', 'sensitive_action'],
|
||||
IdentityVerificationPurpose::values(),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_verification_purpose_is_core_check(): void
|
||||
{
|
||||
$this->assertTrue(IdentityVerificationPurpose::isCore('signup'));
|
||||
$this->assertFalse(IdentityVerificationPurpose::isCore('module_declared'));
|
||||
}
|
||||
|
||||
public function test_verification_purpose_try_from_safety(): void
|
||||
{
|
||||
$this->assertSame(IdentityVerificationPurpose::Signup, IdentityVerificationPurpose::tryFrom('signup'));
|
||||
$this->assertNull(IdentityVerificationPurpose::tryFrom('invalid'));
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// IdentityVerificationChannel
|
||||
// ========================================================================
|
||||
|
||||
public function test_verification_channel_has_email(): void
|
||||
{
|
||||
$this->assertContains(IdentityVerificationChannel::Email, IdentityVerificationChannel::cases());
|
||||
$this->assertSame('email', IdentityVerificationChannel::Email->value);
|
||||
}
|
||||
|
||||
public function test_verification_channel_is_core(): void
|
||||
{
|
||||
$this->assertTrue(IdentityVerificationChannel::isCore('email'));
|
||||
$this->assertFalse(IdentityVerificationChannel::isCore('sms'));
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// IdentityOriginType
|
||||
// ========================================================================
|
||||
|
||||
public function test_origin_type_has_seven_cases(): void
|
||||
{
|
||||
$this->assertCount(7, IdentityOriginType::cases());
|
||||
$this->assertSame(
|
||||
['route', 'hook', 'policy', 'middleware', 'api', 'custom', 'system'],
|
||||
IdentityOriginType::values(),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_origin_type_try_from_safety(): void
|
||||
{
|
||||
$this->assertSame(IdentityOriginType::Route, IdentityOriginType::tryFrom('route'));
|
||||
$this->assertNull(IdentityOriginType::tryFrom('not_a_type'));
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// IdentityPolicyScope
|
||||
// ========================================================================
|
||||
|
||||
public function test_policy_scope_has_three_cases(): void
|
||||
{
|
||||
$this->assertCount(3, IdentityPolicyScope::cases());
|
||||
$this->assertSame(['route', 'hook', 'custom'], IdentityPolicyScope::values());
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// IdentityPolicyFailMode
|
||||
// ========================================================================
|
||||
|
||||
public function test_policy_fail_mode_has_two_cases(): void
|
||||
{
|
||||
$this->assertCount(2, IdentityPolicyFailMode::cases());
|
||||
$this->assertSame(['block', 'log_only'], IdentityPolicyFailMode::values());
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// IdentityPolicyAppliesTo
|
||||
// ========================================================================
|
||||
|
||||
public function test_policy_applies_to_has_three_cases(): void
|
||||
{
|
||||
$this->assertCount(3, IdentityPolicyAppliesTo::cases());
|
||||
$this->assertSame(['self', 'admin', 'both'], IdentityPolicyAppliesTo::values());
|
||||
// 'self' 는 PHP 예약어이므로 case 이름은 Self_ 로 정의됨.
|
||||
$this->assertSame('self', IdentityPolicyAppliesTo::Self_->value);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// IdentityPolicySourceType
|
||||
// ========================================================================
|
||||
|
||||
public function test_policy_source_type_has_four_cases(): void
|
||||
{
|
||||
$this->assertCount(4, IdentityPolicySourceType::cases());
|
||||
$this->assertSame(['core', 'module', 'plugin', 'admin'], IdentityPolicySourceType::values());
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// IdentityMessageScopeType
|
||||
// ========================================================================
|
||||
|
||||
public function test_message_scope_type_has_three_cases(): void
|
||||
{
|
||||
$this->assertCount(3, IdentityMessageScopeType::cases());
|
||||
$this->assertSame(
|
||||
['provider_default', 'purpose', 'policy'],
|
||||
IdentityMessageScopeType::values(),
|
||||
);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// 다국어 라벨 — 모든 enum 의 label() 이 다국어 키로부터 비어있지 않은 문자열을 반환해야 함
|
||||
// ========================================================================
|
||||
|
||||
public function test_all_enum_labels_are_translated(): void
|
||||
{
|
||||
app()->setLocale('ko');
|
||||
|
||||
$samples = [
|
||||
IdentityVerificationPurpose::Signup,
|
||||
IdentityVerificationChannel::Email,
|
||||
IdentityOriginType::Route,
|
||||
IdentityPolicyScope::Route,
|
||||
IdentityPolicyFailMode::Block,
|
||||
IdentityPolicyAppliesTo::Self_,
|
||||
IdentityPolicySourceType::Core,
|
||||
IdentityMessageScopeType::Purpose,
|
||||
];
|
||||
|
||||
foreach ($samples as $case) {
|
||||
$label = $case->label();
|
||||
$this->assertIsString($label);
|
||||
$this->assertNotSame('', $label);
|
||||
// 다국어 키 미정의 시 Laravel 은 키 자체를 반환하므로 키 prefix 가 그대로면 fail.
|
||||
$this->assertStringNotContainsString('identity.', $label, sprintf(
|
||||
'%s::%s label has untranslated key: %s',
|
||||
$case::class,
|
||||
$case->name,
|
||||
$label,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Enums;
|
||||
|
||||
use App\Enums\LanguagePackOrigin;
|
||||
use App\Enums\LanguagePackSourceType;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* LanguagePackOrigin Enum + LanguagePackSourceType ↔ LanguagePackOrigin 매핑 회귀 테스트.
|
||||
*/
|
||||
class LanguagePackOriginTest extends TestCase
|
||||
{
|
||||
public function test_from_source_type_built_in_group(): void
|
||||
{
|
||||
$this->assertSame(
|
||||
LanguagePackOrigin::BuiltIn,
|
||||
LanguagePackOrigin::fromSourceType(LanguagePackSourceType::BuiltIn)
|
||||
);
|
||||
$this->assertSame(
|
||||
LanguagePackOrigin::BuiltIn,
|
||||
LanguagePackOrigin::fromSourceType(LanguagePackSourceType::BundledWithExtension)
|
||||
);
|
||||
}
|
||||
|
||||
public function test_from_source_type_bundled_group(): void
|
||||
{
|
||||
$this->assertSame(
|
||||
LanguagePackOrigin::Bundled,
|
||||
LanguagePackOrigin::fromSourceType(LanguagePackSourceType::Bundled)
|
||||
);
|
||||
}
|
||||
|
||||
public function test_from_source_type_user_installed_group(): void
|
||||
{
|
||||
foreach ([
|
||||
LanguagePackSourceType::Github,
|
||||
LanguagePackSourceType::Url,
|
||||
LanguagePackSourceType::Upload,
|
||||
LanguagePackSourceType::Zip,
|
||||
] as $external) {
|
||||
$this->assertSame(
|
||||
LanguagePackOrigin::UserInstalled,
|
||||
LanguagePackOrigin::fromSourceType($external),
|
||||
"{$external->value} 는 user_installed 로 매핑되어야 함"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_from_source_type_value_handles_null_and_invalid(): void
|
||||
{
|
||||
$this->assertNull(LanguagePackOrigin::fromSourceTypeValue(null));
|
||||
$this->assertNull(LanguagePackOrigin::fromSourceTypeValue('invalid_xxx'));
|
||||
$this->assertSame(
|
||||
LanguagePackOrigin::Bundled,
|
||||
LanguagePackOrigin::fromSourceTypeValue('bundled')
|
||||
);
|
||||
}
|
||||
|
||||
public function test_values_returns_all_3_origins(): void
|
||||
{
|
||||
$this->assertSame(
|
||||
['built_in', 'bundled', 'user_installed'],
|
||||
LanguagePackOrigin::values()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enum 누락 가드 — `LanguagePackSourceType` 의 모든 case 가 origin 매핑에서
|
||||
* 처리되는지 (match 누락 시 UnhandledMatchError) 검증.
|
||||
*/
|
||||
public function test_all_source_types_are_mapped(): void
|
||||
{
|
||||
foreach (LanguagePackSourceType::cases() as $source) {
|
||||
$origin = LanguagePackOrigin::fromSourceType($source);
|
||||
$this->assertContains(
|
||||
$origin,
|
||||
LanguagePackOrigin::cases(),
|
||||
"{$source->value} 는 LanguagePackOrigin 의 한 case 로 매핑되어야 함"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
-16
@@ -2,15 +2,15 @@
|
||||
|
||||
namespace Tests\Unit\Enums;
|
||||
|
||||
use App\Enums\MailSendStatus;
|
||||
use App\Enums\NotificationLogStatus;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* MailSendStatus Enum 테스트
|
||||
* NotificationLogStatus Enum 테스트
|
||||
*
|
||||
* 메일 발송 상태 Enum의 값과 동작을 검증합니다.
|
||||
*/
|
||||
class MailSendStatusTest extends TestCase
|
||||
class NotificationLogStatusTest extends TestCase
|
||||
{
|
||||
// ========================================================================
|
||||
// 케이스 값 테스트
|
||||
@@ -18,27 +18,27 @@ class MailSendStatusTest extends TestCase
|
||||
|
||||
public function test_sent_case_has_correct_value(): void
|
||||
{
|
||||
$this->assertSame('sent', MailSendStatus::Sent->value);
|
||||
$this->assertSame('sent', NotificationLogStatus::Sent->value);
|
||||
}
|
||||
|
||||
public function test_failed_case_has_correct_value(): void
|
||||
{
|
||||
$this->assertSame('failed', MailSendStatus::Failed->value);
|
||||
$this->assertSame('failed', NotificationLogStatus::Failed->value);
|
||||
}
|
||||
|
||||
public function test_skipped_case_has_correct_value(): void
|
||||
{
|
||||
$this->assertSame('skipped', MailSendStatus::Skipped->value);
|
||||
$this->assertSame('skipped', NotificationLogStatus::Skipped->value);
|
||||
}
|
||||
|
||||
public function test_cases_returns_all_statuses(): void
|
||||
{
|
||||
$cases = MailSendStatus::cases();
|
||||
$cases = NotificationLogStatus::cases();
|
||||
|
||||
$this->assertCount(3, $cases);
|
||||
$this->assertContains(MailSendStatus::Sent, $cases);
|
||||
$this->assertContains(MailSendStatus::Failed, $cases);
|
||||
$this->assertContains(MailSendStatus::Skipped, $cases);
|
||||
$this->assertContains(NotificationLogStatus::Sent, $cases);
|
||||
$this->assertContains(NotificationLogStatus::Failed, $cases);
|
||||
$this->assertContains(NotificationLogStatus::Skipped, $cases);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
@@ -47,25 +47,25 @@ class MailSendStatusTest extends TestCase
|
||||
|
||||
public function test_from_returns_correct_enum_for_valid_value(): void
|
||||
{
|
||||
$this->assertSame(MailSendStatus::Sent, MailSendStatus::from('sent'));
|
||||
$this->assertSame(MailSendStatus::Failed, MailSendStatus::from('failed'));
|
||||
$this->assertSame(MailSendStatus::Skipped, MailSendStatus::from('skipped'));
|
||||
$this->assertSame(NotificationLogStatus::Sent, NotificationLogStatus::from('sent'));
|
||||
$this->assertSame(NotificationLogStatus::Failed, NotificationLogStatus::from('failed'));
|
||||
$this->assertSame(NotificationLogStatus::Skipped, NotificationLogStatus::from('skipped'));
|
||||
}
|
||||
|
||||
public function test_from_throws_exception_for_invalid_value(): void
|
||||
{
|
||||
$this->expectException(\ValueError::class);
|
||||
|
||||
MailSendStatus::from('invalid');
|
||||
NotificationLogStatus::from('invalid');
|
||||
}
|
||||
|
||||
public function test_try_from_returns_null_for_invalid_value(): void
|
||||
{
|
||||
$this->assertNull(MailSendStatus::tryFrom('invalid'));
|
||||
$this->assertNull(NotificationLogStatus::tryFrom('invalid'));
|
||||
}
|
||||
|
||||
public function test_try_from_returns_enum_for_valid_value(): void
|
||||
{
|
||||
$this->assertSame(MailSendStatus::Sent, MailSendStatus::tryFrom('sent'));
|
||||
$this->assertSame(NotificationLogStatus::Sent, NotificationLogStatus::tryFrom('sent'));
|
||||
}
|
||||
}
|
||||
@@ -29,8 +29,12 @@ class CoreBackupHelperTest extends TestCase
|
||||
$this->testBasePath = storage_path('app/test_core_backup');
|
||||
$this->backupsBasePath = storage_path('app/core_backups');
|
||||
|
||||
// 테스트용 디렉토리 구조 생성
|
||||
// 테스트용 디렉토리 구조 생성 + 기존 backup 산출물(이전 테스트/실제 코어 업데이트
|
||||
// 흔적) 으로 인한 카운트 오염 차단
|
||||
File::ensureDirectoryExists($this->testBasePath);
|
||||
if (File::isDirectory($this->backupsBasePath)) {
|
||||
File::deleteDirectory($this->backupsBasePath);
|
||||
}
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
@@ -270,9 +274,16 @@ class CoreBackupHelperTest extends TestCase
|
||||
|
||||
$backups = CoreBackupHelper::listBackups();
|
||||
|
||||
$this->assertCount(2, $backups);
|
||||
$this->assertArrayHasKey('path', $backups[0]);
|
||||
$this->assertArrayHasKey('name', $backups[0]);
|
||||
$this->assertArrayHasKey('created_at', $backups[0]);
|
||||
// Windows 환경에서 setUp 의 deleteDirectory 가 file lock 으로 일부 실패할 수 있으므로
|
||||
// 테스트가 명시적으로 만든 fixture 만 필터링하여 검증 (격리 우회).
|
||||
$fixtureBackups = array_values(array_filter($backups, fn ($b) => str_starts_with(
|
||||
$b['name'] ?? '',
|
||||
'core_2026010'
|
||||
)));
|
||||
|
||||
$this->assertCount(2, $fixtureBackups);
|
||||
$this->assertArrayHasKey('path', $fixtureBackups[0]);
|
||||
$this->assertArrayHasKey('name', $fixtureBackups[0]);
|
||||
$this->assertArrayHasKey('created_at', $fixtureBackups[0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Extension;
|
||||
|
||||
use App\Enums\DeactivationReason;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* DeactivationReason Enum 단위 테스트.
|
||||
*
|
||||
* 사용자 수동 / 시스템 자동 비활성화 사유의 Enum 값 도메인과 헬퍼 메서드
|
||||
* (label, isSystemTriggered, values, isValid) 동작을 검증합니다.
|
||||
*/
|
||||
class DeactivationReasonTest extends TestCase
|
||||
{
|
||||
public function test_enum_values_match_db_string_domain(): void
|
||||
{
|
||||
$this->assertSame('manual', DeactivationReason::Manual->value);
|
||||
$this->assertSame('incompatible_core', DeactivationReason::IncompatibleCore->value);
|
||||
}
|
||||
|
||||
public function test_label_returns_korean_fallback(): void
|
||||
{
|
||||
$this->assertSame('사용자 수동 비활성화', DeactivationReason::Manual->label());
|
||||
$this->assertSame('코어 버전 호환성', DeactivationReason::IncompatibleCore->label());
|
||||
}
|
||||
|
||||
public function test_is_system_triggered_distinguishes_manual_vs_incompatible(): void
|
||||
{
|
||||
$this->assertFalse(DeactivationReason::Manual->isSystemTriggered());
|
||||
$this->assertTrue(DeactivationReason::IncompatibleCore->isSystemTriggered());
|
||||
}
|
||||
|
||||
public function test_values_returns_complete_string_array(): void
|
||||
{
|
||||
$values = DeactivationReason::values();
|
||||
$this->assertCount(2, $values);
|
||||
$this->assertContains('manual', $values);
|
||||
$this->assertContains('incompatible_core', $values);
|
||||
}
|
||||
|
||||
public function test_is_valid_accepts_known_and_rejects_unknown(): void
|
||||
{
|
||||
$this->assertTrue(DeactivationReason::isValid('manual'));
|
||||
$this->assertTrue(DeactivationReason::isValid('incompatible_core'));
|
||||
$this->assertFalse(DeactivationReason::isValid('unknown'));
|
||||
$this->assertFalse(DeactivationReason::isValid(''));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Extension;
|
||||
|
||||
use App\Extension\ExtensionManager;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* ExtensionManager::resolveExtensionByFqcn() 단위 테스트
|
||||
*
|
||||
* FQCN → 모듈/플러그인 식별자 역변환 동작을 검증합니다.
|
||||
* directoryToNamespace() 의 역연산이며, 모듈 lang fallback 의 origin 식별 SSoT.
|
||||
*/
|
||||
class ExtensionManagerResolveByFqcnTest extends TestCase
|
||||
{
|
||||
public function test_resolves_module_fqcn_to_kebab_identifier(): void
|
||||
{
|
||||
$this->assertSame(
|
||||
'sirsoft-ecommerce',
|
||||
ExtensionManager::resolveExtensionByFqcn('Modules\\Sirsoft\\Ecommerce\\Models\\Order'),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_resolves_plugin_fqcn_to_kebab_identifier(): void
|
||||
{
|
||||
$this->assertSame(
|
||||
'sirsoft-payment',
|
||||
ExtensionManager::resolveExtensionByFqcn('Plugins\\Sirsoft\\Payment\\Services\\PaymentService'),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_preserves_underscore_for_pascal_case_with_internal_word_boundary(): void
|
||||
{
|
||||
$this->assertSame(
|
||||
'sirsoft-daum_postcode',
|
||||
ExtensionManager::resolveExtensionByFqcn('Modules\\Sirsoft\\DaumPostcode\\Models\\Address'),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_returns_null_for_core_app_namespace(): void
|
||||
{
|
||||
$this->assertNull(ExtensionManager::resolveExtensionByFqcn('App\\Models\\User'));
|
||||
}
|
||||
|
||||
public function test_returns_null_for_unknown_namespace(): void
|
||||
{
|
||||
$this->assertNull(ExtensionManager::resolveExtensionByFqcn('Vendor\\Anything\\Foo'));
|
||||
}
|
||||
|
||||
public function test_returns_null_for_short_module_namespace(): void
|
||||
{
|
||||
// 'Modules\Foo' 만으로는 vendor-name 두 세그먼트 부족
|
||||
$this->assertNull(ExtensionManager::resolveExtensionByFqcn('Modules\\Foo'));
|
||||
}
|
||||
|
||||
public function test_handles_leading_backslash(): void
|
||||
{
|
||||
$this->assertSame(
|
||||
'sirsoft-ecommerce',
|
||||
ExtensionManager::resolveExtensionByFqcn('\\Modules\\Sirsoft\\Ecommerce\\Models\\Order'),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_returns_null_for_empty_string(): void
|
||||
{
|
||||
$this->assertNull(ExtensionManager::resolveExtensionByFqcn(''));
|
||||
}
|
||||
|
||||
public function test_round_trip_with_directory_to_namespace(): void
|
||||
{
|
||||
// directoryToNamespace 의 정확한 역연산 검증
|
||||
$identifier = 'sirsoft-ecommerce';
|
||||
$namespace = 'Modules\\'.ExtensionManager::directoryToNamespace($identifier).'\\Models\\Foo';
|
||||
$this->assertSame($identifier, ExtensionManager::resolveExtensionByFqcn($namespace));
|
||||
}
|
||||
}
|
||||
@@ -422,6 +422,168 @@ class ExtensionMenuSyncHelperTest extends TestCase
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* config 정의의 is_active=false 가 신규 메뉴 생성 시 그대로 적용되는지 테스트
|
||||
*
|
||||
* 회귀: ExtensionMenuSyncHelper 가 hardcoded `is_active=true` 로 강제하여 개발 중인
|
||||
* 메뉴(예: config/core.php 의 admin-schedules `is_active: false`) 가 운영 환경에서
|
||||
* 자동 활성화되던 결함 차단.
|
||||
*/
|
||||
public function test_sync_menu_honors_is_active_false_from_definition_on_create(): void
|
||||
{
|
||||
$this->menuRepository
|
||||
->shouldReceive('findBySlugAndExtension')
|
||||
->once()
|
||||
->andReturn(null);
|
||||
|
||||
$newMenu = $this->createModelMock(Menu::class, ['id' => 1]);
|
||||
|
||||
$this->menuRepository
|
||||
->shouldReceive('updateOrCreate')
|
||||
->once()
|
||||
->with(
|
||||
Mockery::any(),
|
||||
Mockery::on(fn ($values) => $values['is_active'] === false)
|
||||
)
|
||||
->andReturn($newMenu);
|
||||
|
||||
$this->helper->syncMenu(
|
||||
slug: 'admin-schedules',
|
||||
extensionType: ExtensionOwnerType::Core,
|
||||
extensionIdentifier: 'core',
|
||||
newAttributes: [
|
||||
'name' => ['ko' => '스케쥴 관리', 'en' => 'Schedule Management'],
|
||||
'icon' => 'fas fa-clock',
|
||||
'order' => 12,
|
||||
'url' => '/admin/schedules',
|
||||
'is_active' => false,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* config 정의의 is_active=false 가 기존 메뉴 업데이트 시에도 적용되는지 테스트
|
||||
*
|
||||
* 운영자가 user_overrides 로 마킹하지 않았다면 정의값이 우선.
|
||||
*/
|
||||
public function test_sync_menu_honors_is_active_false_from_definition_on_update(): void
|
||||
{
|
||||
$existingMenu = $this->createModelMock(Menu::class, [
|
||||
'id' => 1,
|
||||
'is_active' => true, // 이전 동기화 때 잘못 활성화된 상태
|
||||
'user_overrides' => [],
|
||||
]);
|
||||
|
||||
$this->menuRepository
|
||||
->shouldReceive('findBySlugAndExtension')
|
||||
->once()
|
||||
->andReturn($existingMenu);
|
||||
|
||||
$this->menuRepository
|
||||
->shouldReceive('update')
|
||||
->once()
|
||||
->with(
|
||||
$existingMenu,
|
||||
Mockery::on(fn ($data) => array_key_exists('is_active', $data)
|
||||
&& $data['is_active'] === false)
|
||||
)
|
||||
->andReturn(true);
|
||||
|
||||
$existingMenu->shouldReceive('fresh')->once()->andReturn($existingMenu);
|
||||
|
||||
$this->helper->syncMenu(
|
||||
slug: 'admin-schedules',
|
||||
extensionType: ExtensionOwnerType::Core,
|
||||
extensionIdentifier: 'core',
|
||||
newAttributes: [
|
||||
'name' => ['ko' => '스케쥴 관리', 'en' => 'Schedule Management'],
|
||||
'icon' => 'fas fa-clock',
|
||||
'order' => 12,
|
||||
'url' => '/admin/schedules',
|
||||
'is_active' => false,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 운영자가 user_overrides 에 is_active 를 마킹한 경우 정의값이 무시되고 기존 상태가 보존되는지 테스트
|
||||
*
|
||||
* 시나리오: 정의는 is_active=false 지만 운영자가 UI 에서 활성화 후 user_overrides 에 마킹.
|
||||
* 재시드 시 운영자 선택이 보존되어야 한다.
|
||||
*/
|
||||
public function test_sync_menu_preserves_user_overridden_is_active(): void
|
||||
{
|
||||
$existingMenu = $this->createModelMock(Menu::class, [
|
||||
'id' => 1,
|
||||
'is_active' => true, // 운영자가 활성화
|
||||
'user_overrides' => ['is_active'],
|
||||
]);
|
||||
|
||||
$this->menuRepository
|
||||
->shouldReceive('findBySlugAndExtension')
|
||||
->once()
|
||||
->andReturn($existingMenu);
|
||||
|
||||
$this->menuRepository
|
||||
->shouldReceive('update')
|
||||
->once()
|
||||
->with(
|
||||
$existingMenu,
|
||||
Mockery::on(fn ($data) => ! array_key_exists('is_active', $data))
|
||||
)
|
||||
->andReturn(true);
|
||||
|
||||
$existingMenu->shouldReceive('fresh')->once()->andReturn($existingMenu);
|
||||
|
||||
$this->helper->syncMenu(
|
||||
slug: 'admin-schedules',
|
||||
extensionType: ExtensionOwnerType::Core,
|
||||
extensionIdentifier: 'core',
|
||||
newAttributes: [
|
||||
'name' => ['ko' => '스케쥴 관리', 'en' => 'Schedule Management'],
|
||||
'icon' => 'fas fa-clock',
|
||||
'order' => 12,
|
||||
'url' => '/admin/schedules',
|
||||
'is_active' => false, // 정의는 false 지만 user_overrides 가 우선
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* syncMenuRecursive 가 menuData 의 is_active 를 newAttributes 로 전달하는지 테스트
|
||||
*/
|
||||
public function test_sync_menu_recursive_passes_is_active_to_sync_menu(): void
|
||||
{
|
||||
$newMenu = $this->createModelMock(Menu::class, ['id' => 1]);
|
||||
|
||||
$this->menuRepository
|
||||
->shouldReceive('findBySlugAndExtension')
|
||||
->once()
|
||||
->andReturn(null);
|
||||
|
||||
$this->menuRepository
|
||||
->shouldReceive('updateOrCreate')
|
||||
->once()
|
||||
->with(
|
||||
Mockery::any(),
|
||||
Mockery::on(fn ($values) => $values['is_active'] === false)
|
||||
)
|
||||
->andReturn($newMenu);
|
||||
|
||||
$this->helper->syncMenuRecursive(
|
||||
menuData: [
|
||||
'slug' => 'admin-schedules',
|
||||
'name' => ['ko' => '스케쥴 관리', 'en' => 'Schedule Management'],
|
||||
'icon' => 'fas fa-clock',
|
||||
'order' => 12,
|
||||
'url' => '/admin/schedules',
|
||||
'is_active' => false,
|
||||
],
|
||||
extensionType: ExtensionOwnerType::Core,
|
||||
extensionIdentifier: 'core',
|
||||
);
|
||||
}
|
||||
|
||||
// ========== syncMenuRecursive 테스트 ==========
|
||||
|
||||
/**
|
||||
|
||||
@@ -346,8 +346,10 @@ class GithubHelperTest extends TestCase
|
||||
#[Test]
|
||||
public function resolveArchiveUrl_v접두사_태그_200이면_해당_URL을_반환합니다(): void
|
||||
{
|
||||
// resolveArchiveUrl 은 git/refs/tags/{tag} 로 태그 존재 여부를 먼저 검증한 뒤
|
||||
// zipball URL 을 반환 (codeload 404 불가시 실패 방지 — GithubHelper.php 참조)
|
||||
Http::fake([
|
||||
'api.github.com/repos/owner/repo/zipball/v1.0.0' => Http::response('', 200),
|
||||
'api.github.com/repos/owner/repo/git/refs/tags/v1.0.0' => Http::response('', 200),
|
||||
]);
|
||||
|
||||
$url = GithubHelper::resolveArchiveUrl('owner', 'repo', '1.0.0');
|
||||
@@ -359,8 +361,8 @@ class GithubHelperTest extends TestCase
|
||||
public function resolveArchiveUrl_v접두사_404이면_순수버전으로_폴백합니다(): void
|
||||
{
|
||||
Http::fake([
|
||||
'api.github.com/repos/owner/repo/zipball/v1.0.0' => Http::response('', 404),
|
||||
'api.github.com/repos/owner/repo/zipball/1.0.0' => Http::response('', 200),
|
||||
'api.github.com/repos/owner/repo/git/refs/tags/v1.0.0' => Http::response('', 404),
|
||||
'api.github.com/repos/owner/repo/git/refs/tags/1.0.0' => Http::response('', 200),
|
||||
]);
|
||||
|
||||
$url = GithubHelper::resolveArchiveUrl('owner', 'repo', '1.0.0');
|
||||
@@ -383,8 +385,10 @@ class GithubHelperTest extends TestCase
|
||||
#[Test]
|
||||
public function resolveArchiveUrl_302이면_해당_URL을_반환합니다(): void
|
||||
{
|
||||
// 리디렉션 상황: 태그 존재 확인(GET git/refs/tags)만 성공하면 zipball URL 반환.
|
||||
// zipball 실제 호출은 다운로드 시점에 발생 (resolveArchiveUrl 은 태그 검증 + URL 조립만 수행)
|
||||
Http::fake([
|
||||
'api.github.com/repos/owner/repo/zipball/v1.0.0' => Http::response('', 302),
|
||||
'api.github.com/repos/owner/repo/git/refs/tags/v1.0.0' => Http::response('', 200),
|
||||
]);
|
||||
|
||||
$url = GithubHelper::resolveArchiveUrl('owner', 'repo', '1.0.0');
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Extension\Helpers;
|
||||
|
||||
use App\Extension\Helpers\IdentityPolicySyncHelper;
|
||||
use App\Models\IdentityPolicy;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* IdentityPolicySyncHelper 테스트.
|
||||
*
|
||||
* 알림 시스템 NotificationSyncHelper 동형 — upsert + user_overrides 보존 + cleanupStale 을 검증.
|
||||
*/
|
||||
class IdentityPolicySyncHelperTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private IdentityPolicySyncHelper $helper;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->helper = $this->app->make(IdentityPolicySyncHelper::class);
|
||||
}
|
||||
|
||||
public function test_sync_policy_creates_new_policy_on_first_run(): void
|
||||
{
|
||||
$policy = $this->helper->syncPolicy([
|
||||
'key' => 'test.p1',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.test.one',
|
||||
'purpose' => 'sensitive_action',
|
||||
'grace_minutes' => 0,
|
||||
'enabled' => true,
|
||||
'source_type' => 'core',
|
||||
'source_identifier' => 'core',
|
||||
]);
|
||||
|
||||
$this->assertSame('test.p1', $policy->key);
|
||||
$this->assertSame('route', $policy->scope->value);
|
||||
$this->assertTrue($policy->enabled);
|
||||
}
|
||||
|
||||
public function test_sync_policy_updates_fields_not_in_user_overrides(): void
|
||||
{
|
||||
$this->helper->syncPolicy([
|
||||
'key' => 'test.p2',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.test.two',
|
||||
'purpose' => 'sensitive_action',
|
||||
'grace_minutes' => 0,
|
||||
'enabled' => true,
|
||||
'source_type' => 'core',
|
||||
'source_identifier' => 'core',
|
||||
]);
|
||||
|
||||
// 운영자가 enabled 를 수정했다고 가정 — user_overrides 에 기록
|
||||
$policy = IdentityPolicy::where('key', 'test.p2')->first();
|
||||
$policy->user_overrides = ['enabled'];
|
||||
$policy->enabled = false;
|
||||
$policy->save();
|
||||
|
||||
// 재시딩 — enabled 는 user_overrides 에 있으므로 보존, target 은 갱신
|
||||
$this->helper->syncPolicy([
|
||||
'key' => 'test.p2',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.test.two_changed',
|
||||
'purpose' => 'sensitive_action',
|
||||
'grace_minutes' => 0,
|
||||
'enabled' => true, // 여기서 true 로 재설정해도
|
||||
'source_type' => 'core',
|
||||
'source_identifier' => 'core',
|
||||
]);
|
||||
|
||||
$policy->refresh();
|
||||
$this->assertSame('api.test.two_changed', $policy->target, 'target 은 갱신되어야 함');
|
||||
$this->assertFalse($policy->enabled, 'enabled 는 user_overrides 에 있어 보존되어야 함');
|
||||
}
|
||||
|
||||
/**
|
||||
* conditions 운영자 편집값 보존 (B안 리팩토링).
|
||||
*
|
||||
* 회원가입 단계 등 정책 조건은 운영자가 화면에서 수정 후 user_overrides 에 'conditions' 가 추가되며,
|
||||
* 모듈 재sync 시 declared default 가 운영자 값을 덮어쓰지 않아야 한다.
|
||||
*/
|
||||
public function test_sync_policy_preserves_conditions_in_user_overrides(): void
|
||||
{
|
||||
$this->helper->syncPolicy([
|
||||
'key' => 'test.signup.before_submit',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.auth.register',
|
||||
'purpose' => 'signup',
|
||||
'conditions' => ['signup_stage' => 'before_submit'],
|
||||
'source_type' => 'module',
|
||||
'source_identifier' => 'sirsoft-board',
|
||||
]);
|
||||
|
||||
$policy = IdentityPolicy::where('key', 'test.signup.before_submit')->first();
|
||||
$policy->user_overrides = ['conditions'];
|
||||
$policy->conditions = ['signup_stage' => 'after_create'];
|
||||
$policy->save();
|
||||
|
||||
$this->helper->syncPolicy([
|
||||
'key' => 'test.signup.before_submit',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.auth.register',
|
||||
'purpose' => 'signup',
|
||||
'conditions' => ['signup_stage' => 'before_submit'],
|
||||
'source_type' => 'module',
|
||||
'source_identifier' => 'sirsoft-board',
|
||||
]);
|
||||
|
||||
$policy->refresh();
|
||||
$this->assertSame(
|
||||
['signup_stage' => 'after_create'],
|
||||
$policy->conditions,
|
||||
'conditions 는 user_overrides 에 등록되어 있어 declared default 로 덮어써지면 안 됨',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* trackable 5필드(enabled / grace_minutes / provider_id / fail_mode / conditions) 각각에 대해
|
||||
* user_overrides 등록 시 syncPolicy 가 운영자 값을 보존하는지 매트릭스 검증.
|
||||
*
|
||||
* @dataProvider trackableFieldProvider
|
||||
*/
|
||||
public function test_sync_preserves_each_trackable_field_in_user_overrides(string $field, mixed $declared, mixed $override): void
|
||||
{
|
||||
$key = "test.matrix.{$field}";
|
||||
$base = [
|
||||
'key' => $key,
|
||||
'scope' => 'route',
|
||||
'target' => "api.test.{$field}",
|
||||
'purpose' => 'sensitive_action',
|
||||
'grace_minutes' => 0,
|
||||
'enabled' => true,
|
||||
'provider_id' => null,
|
||||
'fail_mode' => 'block',
|
||||
'conditions' => null,
|
||||
'source_type' => 'module',
|
||||
'source_identifier' => 'sirsoft-board',
|
||||
];
|
||||
$base[$field] = $declared;
|
||||
|
||||
$this->helper->syncPolicy($base);
|
||||
|
||||
// 운영자 변경 시뮬레이션
|
||||
$policy = IdentityPolicy::where('key', $key)->first();
|
||||
$policy->user_overrides = [$field];
|
||||
$policy->{$field} = $override;
|
||||
$policy->save();
|
||||
|
||||
// 재시딩 — declared 가 운영자 값을 덮어쓰면 안 됨
|
||||
$this->helper->syncPolicy($base);
|
||||
|
||||
$policy->refresh();
|
||||
$actual = $field === 'conditions' ? $policy->conditions : $policy->{$field};
|
||||
// enum cast 된 분류 컬럼은 enum 객체이므로 ->value 비교
|
||||
if ($actual instanceof \BackedEnum) {
|
||||
$actual = $actual->value;
|
||||
}
|
||||
$this->assertSame(
|
||||
$override,
|
||||
$actual,
|
||||
"trackable 필드 '{$field}' 가 user_overrides 에 등록되어 있어 declared default 로 덮어써지면 안 됨",
|
||||
);
|
||||
}
|
||||
|
||||
public static function trackableFieldProvider(): array
|
||||
{
|
||||
return [
|
||||
'enabled' => ['enabled', true, false],
|
||||
'grace_minutes' => ['grace_minutes', 0, 60],
|
||||
'provider_id' => ['provider_id', null, 'g7:core.mail'],
|
||||
'fail_mode' => ['fail_mode', 'block', 'log_only'],
|
||||
'conditions' => ['conditions', null, ['signup_stage' => 'after_create']],
|
||||
];
|
||||
}
|
||||
|
||||
public function test_cleanup_stale_removes_policies_not_in_current_keys(): void
|
||||
{
|
||||
$this->helper->syncPolicy([
|
||||
'key' => 'test.stale.a',
|
||||
'scope' => 'route',
|
||||
'target' => 'a',
|
||||
'purpose' => 'sensitive_action',
|
||||
'source_type' => 'module',
|
||||
'source_identifier' => 'some-module',
|
||||
]);
|
||||
$this->helper->syncPolicy([
|
||||
'key' => 'test.stale.b',
|
||||
'scope' => 'route',
|
||||
'target' => 'b',
|
||||
'purpose' => 'sensitive_action',
|
||||
'source_type' => 'module',
|
||||
'source_identifier' => 'some-module',
|
||||
]);
|
||||
|
||||
// b 만 현재 선언 — a 는 stale 로 삭제되어야 함
|
||||
$removed = $this->helper->cleanupStalePolicies('module', 'some-module', ['test.stale.b']);
|
||||
|
||||
$this->assertSame(1, $removed);
|
||||
$this->assertNull(IdentityPolicy::where('key', 'test.stale.a')->first());
|
||||
$this->assertNotNull(IdentityPolicy::where('key', 'test.stale.b')->first());
|
||||
}
|
||||
|
||||
public function test_cleanup_stale_preserves_other_sources(): void
|
||||
{
|
||||
$this->helper->syncPolicy([
|
||||
'key' => 'test.admin.one',
|
||||
'scope' => 'route',
|
||||
'target' => 'a',
|
||||
'purpose' => 'sensitive_action',
|
||||
'source_type' => 'admin',
|
||||
'source_identifier' => 'admin',
|
||||
]);
|
||||
|
||||
// core source cleanup 은 admin source 정책에 영향 없어야 함
|
||||
$this->helper->cleanupStalePolicies('core', 'core', []);
|
||||
|
||||
$this->assertNotNull(IdentityPolicy::where('key', 'test.admin.one')->first());
|
||||
}
|
||||
}
|
||||
@@ -104,4 +104,124 @@ class HookArgumentSerializerTest extends TestCase
|
||||
$this->assertEquals(['extra' => 'data'], $deserialized[2]);
|
||||
$this->assertEquals(42, $deserialized[3]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Backed Enum (string) 이 직렬화/역직렬화되는지 검증합니다.
|
||||
*
|
||||
* 회귀 차단 (이슈 #204):
|
||||
* 큐 디스패치된 hook listener 가 enum 인자를 받을 때 deserialize 가 null 로 떨어져
|
||||
* TypeError 발생 (예: OrderActivityLogListener::handleOrderOptionAfterStatusChange 의
|
||||
* OrderStatusEnum 인자). HookArgumentSerializer 가 BackedEnum 을 처리하지 않는 사각지대.
|
||||
*/
|
||||
public function test_backed_string_enum_serialization(): void
|
||||
{
|
||||
$enum = HookSerializerStringBackedEnumFixture::ACTIVE;
|
||||
|
||||
$serialized = HookArgumentSerializer::serialize([$enum]);
|
||||
|
||||
$this->assertTrue($serialized[0]['__hook_enum__']);
|
||||
$this->assertSame(HookSerializerStringBackedEnumFixture::class, $serialized[0]['class']);
|
||||
$this->assertSame('active', $serialized[0]['value']);
|
||||
|
||||
$deserialized = HookArgumentSerializer::deserialize($serialized);
|
||||
|
||||
$this->assertInstanceOf(HookSerializerStringBackedEnumFixture::class, $deserialized[0]);
|
||||
$this->assertSame(HookSerializerStringBackedEnumFixture::ACTIVE, $deserialized[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Backed Enum (int) 이 직렬화/역직렬화되는지 검증합니다.
|
||||
*/
|
||||
public function test_backed_int_enum_serialization(): void
|
||||
{
|
||||
$enum = HookSerializerIntBackedEnumFixture::HIGH;
|
||||
|
||||
$serialized = HookArgumentSerializer::serialize([$enum]);
|
||||
$deserialized = HookArgumentSerializer::deserialize($serialized);
|
||||
|
||||
$this->assertSame(HookSerializerIntBackedEnumFixture::HIGH, $deserialized[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure (Unit) Enum 이 직렬화/역직렬화되는지 검증합니다.
|
||||
*/
|
||||
public function test_unit_enum_serialization(): void
|
||||
{
|
||||
$enum = HookSerializerUnitEnumFixture::FIRST;
|
||||
|
||||
$serialized = HookArgumentSerializer::serialize([$enum]);
|
||||
$deserialized = HookArgumentSerializer::deserialize($serialized);
|
||||
|
||||
$this->assertSame(HookSerializerUnitEnumFixture::FIRST, $deserialized[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hard delete 된 모델도 deserialize 시 attributes 스냅샷으로 in-memory 복원되는지 검증.
|
||||
*
|
||||
* 회귀 차단 (이슈 #204):
|
||||
* Order/Product 등 hard-delete 후 after_delete 훅이 큐 워커에서 dispatch 될 때
|
||||
* find($id) 가 null 반환 → listener TypeError. SoftDeletes 처리(40d98e2a7) 의 사각지대.
|
||||
* 직렬화 시 attributes 도 함께 저장하고, find() 가 null 이면 attributes 로 모델 재생성.
|
||||
*/
|
||||
public function test_hard_deleted_model_restores_via_attributes_snapshot(): void
|
||||
{
|
||||
$user = User::factory()->create(['name' => 'TestUser', 'email' => 'snap@test.local']);
|
||||
|
||||
// 직렬화 시 user 가 살아있는 상태에서 attributes 캡처
|
||||
$serialized = HookArgumentSerializer::serialize([$user]);
|
||||
|
||||
// attributes 가 직렬화 결과에 포함되어 있는지 확인
|
||||
$this->assertArrayHasKey('attributes', $serialized[0]);
|
||||
$this->assertSame('TestUser', $serialized[0]['attributes']['name']);
|
||||
|
||||
// 모델을 hard delete 하여 DB 에서 제거
|
||||
$userId = $user->id;
|
||||
$user->forceDelete();
|
||||
|
||||
$this->assertNull(User::find($userId), '실제로 삭제되어 find 결과 null');
|
||||
|
||||
// 역직렬화: find 가 null 이지만 attributes snapshot 으로 복원되어야 함
|
||||
$deserialized = HookArgumentSerializer::deserialize($serialized);
|
||||
|
||||
$this->assertInstanceOf(User::class, $deserialized[0], 'hard-deleted 모델도 in-memory 복원');
|
||||
$this->assertSame('TestUser', $deserialized[0]->name);
|
||||
$this->assertSame('snap@test.local', $deserialized[0]->email);
|
||||
$this->assertSame($userId, $deserialized[0]->id);
|
||||
$this->assertFalse($deserialized[0]->exists, 'in-memory 복원이므로 exists=false');
|
||||
}
|
||||
|
||||
/**
|
||||
* 혼합 인자 배열에 enum 이 포함되어 정상 통과하는지 검증.
|
||||
*/
|
||||
public function test_mixed_arguments_including_enum(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$args = [$user, HookSerializerStringBackedEnumFixture::ACTIVE, 'note'];
|
||||
|
||||
$serialized = HookArgumentSerializer::serialize($args);
|
||||
$deserialized = HookArgumentSerializer::deserialize($serialized);
|
||||
|
||||
$this->assertInstanceOf(User::class, $deserialized[0]);
|
||||
$this->assertSame(HookSerializerStringBackedEnumFixture::ACTIVE, $deserialized[1]);
|
||||
$this->assertSame('note', $deserialized[2]);
|
||||
}
|
||||
}
|
||||
|
||||
enum HookSerializerStringBackedEnumFixture: string
|
||||
{
|
||||
case ACTIVE = 'active';
|
||||
case PENDING = 'pending';
|
||||
}
|
||||
|
||||
enum HookSerializerIntBackedEnumFixture: int
|
||||
{
|
||||
case LOW = 1;
|
||||
case HIGH = 9;
|
||||
}
|
||||
|
||||
enum HookSerializerUnitEnumFixture
|
||||
{
|
||||
case FIRST;
|
||||
case SECOND;
|
||||
}
|
||||
@@ -23,11 +23,13 @@ class HookListenerRegistrarTest extends TestCase
|
||||
{
|
||||
parent::setUp();
|
||||
HookManager::resetAll();
|
||||
HookListenerRegistrar::clear();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
HookManager::resetAll();
|
||||
HookListenerRegistrar::clear();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
@@ -109,6 +111,103 @@ class HookListenerRegistrarTest extends TestCase
|
||||
Queue::assertNotPushed(DispatchHookListenerJob::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 동일 listener 를 동일 source 로 2회 등록해도 hook callback 이 1번만 추가되는지 검증합니다.
|
||||
*
|
||||
* 회귀 차단 (이슈 #204):
|
||||
* 테스트 환경에서 매 setUp 시 ServiceProvider boot 가 다시 호출되며 ModuleManager
|
||||
* loadModules → registerModuleHookListeners → HookListenerRegistrar::register 가
|
||||
* 매번 호출되어, HookManager::$hooks 에 동일 listener callback 이 누적됨.
|
||||
* 100+ 테스트 누적 시 hook 카운트 폭증으로 doAction 가 hang 발생.
|
||||
*
|
||||
* register() 가 process-wide idempotency 를 보장해야 한다.
|
||||
*/
|
||||
public function test_register_is_idempotent_per_source_and_listener(): void
|
||||
{
|
||||
HookListenerRegistrar::clear();
|
||||
|
||||
// 1차 등록
|
||||
HookListenerRegistrar::register(StubSyncListener::class, 'test-source');
|
||||
|
||||
$countAfterFirst = $this->countRegisteredCallbacks('test.registrar.sync');
|
||||
$this->assertSame(1, $countAfterFirst, '첫 등록 후 callback 은 1개');
|
||||
|
||||
// 동일 source + 동일 listener 로 2차 등록
|
||||
HookListenerRegistrar::register(StubSyncListener::class, 'test-source');
|
||||
|
||||
$countAfterSecond = $this->countRegisteredCallbacks('test.registrar.sync');
|
||||
$this->assertSame(1, $countAfterSecond, '동일 source 로 재등록해도 callback 은 1개 (누적 차단)');
|
||||
|
||||
// 동일 source + 동일 listener 로 100차 등록
|
||||
for ($i = 0; $i < 100; $i++) {
|
||||
HookListenerRegistrar::register(StubSyncListener::class, 'test-source');
|
||||
}
|
||||
|
||||
$countAfter100 = $this->countRegisteredCallbacks('test.registrar.sync');
|
||||
$this->assertSame(1, $countAfter100, '100회 재등록해도 callback 은 1개');
|
||||
}
|
||||
|
||||
/**
|
||||
* 다른 source 로 같은 listener 를 등록하면 별개로 등록되는지 검증합니다.
|
||||
*
|
||||
* 모듈/플러그인이 동일 listener 클래스를 공유하는 경우는 드물지만,
|
||||
* 가능성을 열어두기 위해 source 별로 idempotency cache 분리.
|
||||
*/
|
||||
public function test_register_allows_same_listener_for_different_sources(): void
|
||||
{
|
||||
HookListenerRegistrar::clear();
|
||||
|
||||
HookListenerRegistrar::register(StubSyncListener::class, 'source-a');
|
||||
HookListenerRegistrar::register(StubSyncListener::class, 'source-b');
|
||||
|
||||
$count = $this->countRegisteredCallbacks('test.registrar.sync');
|
||||
$this->assertSame(2, $count, '서로 다른 source 는 별개로 등록');
|
||||
}
|
||||
|
||||
/**
|
||||
* clear() 호출 후 다시 등록 가능한지 검증합니다.
|
||||
*
|
||||
* 모듈 install/uninstall 테스트 시나리오에서 listener 재등록을 허용하기 위함.
|
||||
*/
|
||||
public function test_clear_allows_reregistration(): void
|
||||
{
|
||||
HookListenerRegistrar::clear();
|
||||
|
||||
HookListenerRegistrar::register(StubSyncListener::class, 'test-source');
|
||||
HookListenerRegistrar::register(StubSyncListener::class, 'test-source');
|
||||
$this->assertSame(1, $this->countRegisteredCallbacks('test.registrar.sync'));
|
||||
|
||||
// 캐시 클리어 + HookManager 도 클리어 (모듈 uninstall 시뮬)
|
||||
HookListenerRegistrar::clear();
|
||||
HookManager::resetAll();
|
||||
|
||||
// 재등록 시 callback 이 다시 추가되어야 함
|
||||
HookListenerRegistrar::register(StubSyncListener::class, 'test-source');
|
||||
$this->assertSame(1, $this->countRegisteredCallbacks('test.registrar.sync'));
|
||||
}
|
||||
|
||||
/**
|
||||
* HookManager::$hooks 에서 특정 hookName 의 callback 수를 합산합니다.
|
||||
*/
|
||||
private function countRegisteredCallbacks(string $hookName): int
|
||||
{
|
||||
$ref = new \ReflectionClass(HookManager::class);
|
||||
$hooksProp = $ref->getProperty('hooks');
|
||||
$hooksProp->setAccessible(true);
|
||||
$hooks = $hooksProp->getValue();
|
||||
|
||||
if (! isset($hooks[$hookName])) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$count = 0;
|
||||
foreach ($hooks[$hookName] as $perPriority) {
|
||||
$count += count($perPriority);
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* 우선순위가 HookManager에 정확히 전달되는지 검증합니다.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Extension\IdentityVerification;
|
||||
|
||||
use App\Contracts\Extension\IdentityVerificationInterface;
|
||||
use App\Extension\HookManager;
|
||||
use App\Extension\IdentityVerification\DTO\VerificationChallenge;
|
||||
use App\Extension\IdentityVerification\DTO\VerificationResult;
|
||||
use App\Extension\IdentityVerification\IdentityVerificationManager;
|
||||
use App\Models\User;
|
||||
use Carbon\Carbon;
|
||||
use InvalidArgumentException;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* IdentityVerificationManager 테스트.
|
||||
*
|
||||
* 프로바이더 등록/해제/resolveForPurpose/필터 훅 통과 후 병합 동작을 검증.
|
||||
*/
|
||||
class IdentityVerificationManagerTest extends TestCase
|
||||
{
|
||||
private IdentityVerificationManager $manager;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
HookManager::resetAll();
|
||||
$this->manager = new IdentityVerificationManager();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
HookManager::resetAll();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_register_and_get_provider(): void
|
||||
{
|
||||
$provider = $this->makeProvider('dummy', true, true);
|
||||
$this->manager->register($provider);
|
||||
|
||||
$this->assertTrue($this->manager->has('dummy'));
|
||||
$this->assertSame($provider, $this->manager->get('dummy'));
|
||||
}
|
||||
|
||||
public function test_unregister_removes_provider(): void
|
||||
{
|
||||
$provider = $this->makeProvider('dummy', true, true);
|
||||
$this->manager->register($provider);
|
||||
$this->manager->unregister('dummy');
|
||||
|
||||
$this->assertFalse($this->manager->has('dummy'));
|
||||
}
|
||||
|
||||
public function test_get_unknown_throws(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->manager->get('nonexistent');
|
||||
}
|
||||
|
||||
public function test_all_runs_through_filter_hook(): void
|
||||
{
|
||||
$mail = $this->makeProvider('g7:core.mail', true, true);
|
||||
$this->manager->register($mail);
|
||||
|
||||
$injected = $this->makeProvider('plugin:fake', true, true);
|
||||
HookManager::addFilter('core.identity.registered_providers', function (array $providers) use ($injected) {
|
||||
$providers[$injected->getId()] = $injected;
|
||||
|
||||
return $providers;
|
||||
});
|
||||
|
||||
$all = $this->manager->all();
|
||||
|
||||
$this->assertArrayHasKey('g7:core.mail', $all);
|
||||
$this->assertArrayHasKey('plugin:fake', $all);
|
||||
}
|
||||
|
||||
public function test_resolve_for_purpose_returns_provider_supporting_purpose(): void
|
||||
{
|
||||
$mail = $this->makeProvider('g7:core.mail', true, true);
|
||||
$this->manager->register($mail);
|
||||
|
||||
$resolved = $this->manager->resolveForPurpose('signup');
|
||||
|
||||
$this->assertSame('g7:core.mail', $resolved->getId());
|
||||
}
|
||||
|
||||
public function test_resolve_for_purpose_falls_back_when_default_unsupported(): void
|
||||
{
|
||||
$unsupported = $this->makeProvider('g7:core.mail', true, false);
|
||||
$supporter = $this->makeProvider('plugin:kcp', true, true);
|
||||
|
||||
$this->manager->register($unsupported);
|
||||
$this->manager->register($supporter);
|
||||
|
||||
$resolved = $this->manager->resolveForPurpose('signup');
|
||||
|
||||
$this->assertSame('plugin:kcp', $resolved->getId());
|
||||
}
|
||||
|
||||
/**
|
||||
* IdentityVerificationInterface 더블을 생성합니다.
|
||||
*/
|
||||
private function makeProvider(string $id, bool $available, bool $supportsAll): IdentityVerificationInterface
|
||||
{
|
||||
return new class($id, $available, $supportsAll) implements IdentityVerificationInterface
|
||||
{
|
||||
public function __construct(
|
||||
private string $id,
|
||||
private bool $available,
|
||||
private bool $supportsAll,
|
||||
) {}
|
||||
|
||||
public function getId(): string
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getChannels(): array
|
||||
{
|
||||
return ['email'];
|
||||
}
|
||||
|
||||
public function getRenderHint(): string
|
||||
{
|
||||
return 'text_code';
|
||||
}
|
||||
|
||||
public function supportsPurpose(string $purpose): bool
|
||||
{
|
||||
return $this->supportsAll;
|
||||
}
|
||||
|
||||
public function isAvailable(): bool
|
||||
{
|
||||
return $this->available;
|
||||
}
|
||||
|
||||
public function requestChallenge(User|array $target, array $context = []): VerificationChallenge
|
||||
{
|
||||
return new VerificationChallenge(
|
||||
id: 'dummy-id',
|
||||
providerId: $this->id,
|
||||
purpose: $context['purpose'] ?? 'sensitive_action',
|
||||
channel: 'email',
|
||||
targetHash: str_repeat('0', 64),
|
||||
expiresAt: Carbon::now()->addMinutes(15),
|
||||
renderHint: 'text_code',
|
||||
);
|
||||
}
|
||||
|
||||
public function verify(string $challengeId, array $input, array $context = []): VerificationResult
|
||||
{
|
||||
return VerificationResult::success(
|
||||
challengeId: $challengeId,
|
||||
providerId: $this->id,
|
||||
verifiedAt: Carbon::now(),
|
||||
);
|
||||
}
|
||||
|
||||
public function cancel(string $challengeId): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function getSettingsSchema(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function withConfig(array $config): static
|
||||
{
|
||||
return $this;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Extension\IdentityVerification\Providers;
|
||||
|
||||
use App\Contracts\Repositories\IdentityVerificationLogRepositoryInterface;
|
||||
use App\Enums\IdentityVerificationStatus;
|
||||
use App\Extension\IdentityVerification\Providers\MailIdentityProvider;
|
||||
use App\Models\IdentityVerificationLog;
|
||||
use Database\Seeders\IdentityMessageDefinitionSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* MailIdentityProvider 테스트.
|
||||
*
|
||||
* Challenge 발행 / 검증 성공 / 잘못된 코드 / 만료 / 재시도 초과 / 취소 경로를 검증합니다.
|
||||
*/
|
||||
class MailIdentityProviderTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private MailIdentityProvider $provider;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
Notification::fake();
|
||||
Mail::fake();
|
||||
// dispatchMessage 가 IdentityMessageDefinition/Template 을 조회하므로 시더 필수.
|
||||
$this->seed(IdentityMessageDefinitionSeeder::class);
|
||||
$this->provider = $this->app->make(MailIdentityProvider::class);
|
||||
}
|
||||
|
||||
public function test_provider_metadata(): void
|
||||
{
|
||||
$this->assertSame('g7:core.mail', $this->provider->getId());
|
||||
$this->assertContains('email', $this->provider->getChannels());
|
||||
$this->assertTrue($this->provider->supportsPurpose('signup'));
|
||||
$this->assertTrue($this->provider->supportsPurpose('sensitive_action'));
|
||||
}
|
||||
|
||||
public function test_request_challenge_creates_log_and_sends_notification(): void
|
||||
{
|
||||
$challenge = $this->provider->requestChallenge(
|
||||
['email' => 'user@example.com'],
|
||||
['purpose' => 'signup', 'ip_address' => '127.0.0.1'],
|
||||
);
|
||||
|
||||
$this->assertSame('g7:core.mail', $challenge->providerId);
|
||||
$this->assertSame('email', $challenge->channel);
|
||||
$this->assertSame('text_code', $challenge->renderHint);
|
||||
$this->assertSame(hash('sha256', 'user@example.com'), $challenge->targetHash);
|
||||
|
||||
$log = IdentityVerificationLog::find($challenge->id);
|
||||
$this->assertNotNull($log);
|
||||
$this->assertSame(IdentityVerificationStatus::Sent, $log->status);
|
||||
$this->assertArrayHasKey('code_hash', $log->metadata ?? []);
|
||||
}
|
||||
|
||||
public function test_request_challenge_password_reset_uses_link_render_hint(): void
|
||||
{
|
||||
$challenge = $this->provider->requestChallenge(
|
||||
['email' => 'user@example.com'],
|
||||
['purpose' => 'password_reset'],
|
||||
);
|
||||
|
||||
$this->assertSame('link', $challenge->renderHint);
|
||||
|
||||
$log = IdentityVerificationLog::find($challenge->id);
|
||||
$this->assertArrayHasKey('link_token_hash', $log->metadata ?? []);
|
||||
}
|
||||
|
||||
public function test_verify_with_correct_code_succeeds(): void
|
||||
{
|
||||
/** @var IdentityVerificationLogRepositoryInterface $repo */
|
||||
$repo = $this->app->make(IdentityVerificationLogRepositoryInterface::class);
|
||||
|
||||
$challenge = $this->provider->requestChallenge(
|
||||
['email' => 'user@example.com'],
|
||||
['purpose' => 'sensitive_action'],
|
||||
);
|
||||
|
||||
// 테스트 목적으로 메타데이터에서 알려진 코드의 해시를 직접 주입
|
||||
$knownCode = '123456';
|
||||
$repo->updateById($challenge->id, [
|
||||
'metadata' => ['code_hash' => password_hash($knownCode, PASSWORD_BCRYPT)],
|
||||
'status' => IdentityVerificationStatus::Sent->value,
|
||||
]);
|
||||
|
||||
$result = $this->provider->verify($challenge->id, ['code' => $knownCode]);
|
||||
|
||||
$this->assertTrue($result->success);
|
||||
$this->assertNotNull($result->verifiedAt);
|
||||
|
||||
$log = IdentityVerificationLog::find($challenge->id);
|
||||
$this->assertSame(IdentityVerificationStatus::Verified, $log->status);
|
||||
$this->assertNotNull($log->verification_token);
|
||||
}
|
||||
|
||||
public function test_verify_with_wrong_code_increments_attempts(): void
|
||||
{
|
||||
/** @var IdentityVerificationLogRepositoryInterface $repo */
|
||||
$repo = $this->app->make(IdentityVerificationLogRepositoryInterface::class);
|
||||
|
||||
$challenge = $this->provider->requestChallenge(
|
||||
['email' => 'user@example.com'],
|
||||
['purpose' => 'sensitive_action'],
|
||||
);
|
||||
|
||||
$repo->updateById($challenge->id, [
|
||||
'metadata' => ['code_hash' => password_hash('123456', PASSWORD_BCRYPT)],
|
||||
'status' => IdentityVerificationStatus::Sent->value,
|
||||
]);
|
||||
|
||||
$result = $this->provider->verify($challenge->id, ['code' => '999999']);
|
||||
|
||||
$this->assertFalse($result->success);
|
||||
$this->assertSame('INVALID_CODE', $result->failureCode);
|
||||
|
||||
$log = IdentityVerificationLog::find($challenge->id);
|
||||
$this->assertSame(1, $log->attempts);
|
||||
}
|
||||
|
||||
public function test_cancel_marks_status_as_cancelled(): void
|
||||
{
|
||||
$challenge = $this->provider->requestChallenge(
|
||||
['email' => 'user@example.com'],
|
||||
['purpose' => 'sensitive_action'],
|
||||
);
|
||||
|
||||
$this->assertTrue($this->provider->cancel($challenge->id));
|
||||
|
||||
$log = IdentityVerificationLog::find($challenge->id);
|
||||
$this->assertSame(IdentityVerificationStatus::Cancelled, $log->status);
|
||||
}
|
||||
|
||||
public function test_request_challenge_fails_without_email(): void
|
||||
{
|
||||
$this->expectException(\InvalidArgumentException::class);
|
||||
$this->provider->requestChallenge([], ['purpose' => 'signup']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Extension;
|
||||
|
||||
use App\Extension\IdentityVerification\IdentityVerificationManager;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* IdentityVerificationManager purpose 레지스트리 계약 테스트.
|
||||
*
|
||||
* 2026-04-24 설계 변경 — AbstractModule/AbstractPlugin::getIdentityPurposes()
|
||||
* getter 로 선언된 purpose 가 Manager 레지스트리에 병합되는지 검증합니다.
|
||||
*/
|
||||
class IdentityVerificationManagerPurposeRegistryTest extends TestCase
|
||||
{
|
||||
public function test_core_default_purposes_are_returned(): void
|
||||
{
|
||||
$manager = new IdentityVerificationManager();
|
||||
$purposes = $manager->getAllPurposes();
|
||||
|
||||
$this->assertArrayHasKey('signup', $purposes);
|
||||
$this->assertArrayHasKey('password_reset', $purposes);
|
||||
$this->assertArrayHasKey('self_update', $purposes);
|
||||
$this->assertArrayHasKey('sensitive_action', $purposes);
|
||||
}
|
||||
|
||||
public function test_registerDeclaredPurposes_merges_extension_purposes(): void
|
||||
{
|
||||
$manager = new IdentityVerificationManager();
|
||||
|
||||
$manager->registerDeclaredPurposes([
|
||||
'checkout_verification' => [
|
||||
'label' => ['ko' => '결제 인증', 'en' => 'Checkout Verification'],
|
||||
'default_provider' => null,
|
||||
'allowed_channels' => ['email', 'sms'],
|
||||
],
|
||||
]);
|
||||
|
||||
$purposes = $manager->getAllPurposes();
|
||||
|
||||
$this->assertArrayHasKey('checkout_verification', $purposes);
|
||||
$this->assertArrayHasKey('signup', $purposes, '코어 기본 purpose 도 함께 유지되어야 한다');
|
||||
}
|
||||
|
||||
public function test_registerPurpose_single_key(): void
|
||||
{
|
||||
$manager = new IdentityVerificationManager();
|
||||
$manager->registerPurpose('adult_verification', [
|
||||
'label' => 'Adult Verification',
|
||||
'allowed_channels' => ['ipin'],
|
||||
]);
|
||||
|
||||
$this->assertTrue($manager->hasPurpose('adult_verification'));
|
||||
}
|
||||
|
||||
public function test_declared_purposes_can_override_core_entries(): void
|
||||
{
|
||||
$manager = new IdentityVerificationManager();
|
||||
$manager->registerPurpose('signup', [
|
||||
'label' => '커스텀 signup',
|
||||
'allowed_channels' => ['sms'],
|
||||
]);
|
||||
|
||||
$purposes = $manager->getAllPurposes();
|
||||
|
||||
$this->assertSame('커스텀 signup', $purposes['signup']['label']);
|
||||
}
|
||||
|
||||
public function test_invalid_payload_entries_are_ignored(): void
|
||||
{
|
||||
$manager = new IdentityVerificationManager();
|
||||
$manager->registerDeclaredPurposes([
|
||||
'' => ['label' => 'empty key'],
|
||||
'valid_key' => ['label' => 'OK'],
|
||||
'broken_key' => 'not-an-array',
|
||||
]);
|
||||
|
||||
$purposes = $manager->getAllPurposes();
|
||||
|
||||
$this->assertArrayHasKey('valid_key', $purposes);
|
||||
$this->assertArrayNotHasKey('', $purposes);
|
||||
$this->assertArrayNotHasKey('broken_key', $purposes);
|
||||
}
|
||||
|
||||
public function test_hasPurpose_reflects_core_and_registered_entries(): void
|
||||
{
|
||||
$manager = new IdentityVerificationManager();
|
||||
|
||||
$this->assertTrue($manager->hasPurpose('signup'));
|
||||
$this->assertFalse($manager->hasPurpose('checkout_verification'));
|
||||
|
||||
$manager->registerPurpose('checkout_verification', ['label' => 'test']);
|
||||
|
||||
$this->assertTrue($manager->hasPurpose('checkout_verification'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Extension;
|
||||
|
||||
use App\Extension\IdentityVerification\IdentityVerificationManager;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* IdentityVerificationManager — purpose source 정보 보존 회귀 테스트.
|
||||
*
|
||||
* 회귀 사례 (#297):
|
||||
* - 본인인증 정책 화면(코어/모듈)에서 "본인인증 목적" 을 일관되게 표기하려면
|
||||
* `getAllPurposes()` 응답에서 각 purpose 가 어느 source(코어/모듈/플러그인)에 의해
|
||||
* 선언되었는지 식별 가능해야 한다.
|
||||
* - 이전 구현은 declaredPurposes 에 source 정보 없이 meta 만 병합해 코어/모듈 화면이
|
||||
* 동일 데이터를 클라이언트 측 하드코딩 분기로만 구분할 수 있었다.
|
||||
*
|
||||
* 계약:
|
||||
* - 코어 기본 4종은 source_type='core', source_identifier='core'
|
||||
* - 모듈/플러그인이 선언한 purpose 는 source_type='module'|'plugin', source_identifier=확장 식별자
|
||||
* - source 가 미명시된 등록 (admin override / filter 훅 등) 은 source_type='admin'
|
||||
*/
|
||||
class IdentityVerificationManagerPurposeSourceTest extends TestCase
|
||||
{
|
||||
public function test_core_purposes_are_marked_with_core_source(): void
|
||||
{
|
||||
$manager = new IdentityVerificationManager();
|
||||
$purposes = $manager->getAllPurposes();
|
||||
|
||||
foreach (['signup', 'password_reset', 'self_update', 'sensitive_action'] as $key) {
|
||||
$this->assertArrayHasKey($key, $purposes);
|
||||
$this->assertSame('core', $purposes[$key]['source_type'] ?? null,
|
||||
"코어 기본 purpose {$key} 는 source_type=core 여야 함");
|
||||
$this->assertSame('core', $purposes[$key]['source_identifier'] ?? null,
|
||||
"코어 기본 purpose {$key} 는 source_identifier=core 여야 함");
|
||||
}
|
||||
}
|
||||
|
||||
public function test_registerDeclaredPurposes_marks_module_source(): void
|
||||
{
|
||||
$manager = new IdentityVerificationManager();
|
||||
|
||||
$manager->registerDeclaredPurposes([
|
||||
'checkout_verification' => [
|
||||
'label' => ['ko' => '결제 인증', 'en' => 'Checkout Verification'],
|
||||
'allowed_channels' => ['email', 'sms', 'ipin'],
|
||||
],
|
||||
], 'module', 'sirsoft-ecommerce');
|
||||
|
||||
$purposes = $manager->getAllPurposes();
|
||||
$this->assertArrayHasKey('checkout_verification', $purposes);
|
||||
$this->assertSame('module', $purposes['checkout_verification']['source_type'] ?? null);
|
||||
$this->assertSame('sirsoft-ecommerce', $purposes['checkout_verification']['source_identifier'] ?? null);
|
||||
}
|
||||
|
||||
public function test_registerDeclaredPurposes_marks_plugin_source(): void
|
||||
{
|
||||
$manager = new IdentityVerificationManager();
|
||||
|
||||
$manager->registerDeclaredPurposes([
|
||||
'adult_verification' => [
|
||||
'label' => ['ko' => '성인 인증', 'en' => 'Adult Verification'],
|
||||
'allowed_channels' => ['ipin'],
|
||||
],
|
||||
], 'plugin', 'sirsoft-adult-cert');
|
||||
|
||||
$purposes = $manager->getAllPurposes();
|
||||
$this->assertArrayHasKey('adult_verification', $purposes);
|
||||
$this->assertSame('plugin', $purposes['adult_verification']['source_type'] ?? null);
|
||||
$this->assertSame('sirsoft-adult-cert', $purposes['adult_verification']['source_identifier'] ?? null);
|
||||
}
|
||||
|
||||
public function test_registerPurpose_without_source_defaults_to_admin(): void
|
||||
{
|
||||
$manager = new IdentityVerificationManager();
|
||||
$manager->registerPurpose('runtime_purpose', [
|
||||
'label' => 'Runtime',
|
||||
'allowed_channels' => ['email'],
|
||||
]);
|
||||
|
||||
$purposes = $manager->getAllPurposes();
|
||||
$this->assertSame('admin', $purposes['runtime_purpose']['source_type'] ?? null);
|
||||
$this->assertSame('admin', $purposes['runtime_purpose']['source_identifier'] ?? null);
|
||||
}
|
||||
|
||||
public function test_module_can_override_core_purpose_and_source_changes(): void
|
||||
{
|
||||
$manager = new IdentityVerificationManager();
|
||||
$manager->registerDeclaredPurposes([
|
||||
'signup' => ['label' => '커스텀 signup', 'allowed_channels' => ['sms']],
|
||||
], 'module', 'sirsoft-ecommerce');
|
||||
|
||||
$purposes = $manager->getAllPurposes();
|
||||
$this->assertSame('module', $purposes['signup']['source_type'] ?? null);
|
||||
$this->assertSame('sirsoft-ecommerce', $purposes['signup']['source_identifier'] ?? null);
|
||||
}
|
||||
}
|
||||
@@ -262,14 +262,20 @@ class ModuleCleanupStaleEntriesTest extends TestCase
|
||||
$body = substr($source, $start, $end - $start);
|
||||
|
||||
$autoloadPos = strpos($body, '$this->extensionManager->updateComposerAutoload();');
|
||||
// updateModule 은 cleanupStaleModuleEntries 를 직접 호출하거나 syncDeclarativeArtifacts
|
||||
// 위임으로 호출한다 (위임이 내부적으로 cleanup 실행). 어느 형태든 해당 호출이
|
||||
// updateComposerAutoload 이후에 위치해야 한다.
|
||||
$cleanupPos = strpos($body, '$this->cleanupStaleModuleEntries(');
|
||||
if ($cleanupPos === false) {
|
||||
$cleanupPos = strpos($body, '$this->syncDeclarativeArtifacts(');
|
||||
}
|
||||
|
||||
$this->assertNotFalse($autoloadPos, 'updateComposerAutoload 호출을 찾을 수 없습니다.');
|
||||
$this->assertNotFalse($cleanupPos, 'cleanupStaleModuleEntries 호출을 찾을 수 없습니다.');
|
||||
$this->assertNotFalse($cleanupPos, 'cleanupStaleModuleEntries 또는 syncDeclarativeArtifacts 호출을 찾을 수 없습니다.');
|
||||
$this->assertLessThan(
|
||||
$cleanupPos,
|
||||
$autoloadPos,
|
||||
'updateComposerAutoload 는 cleanupStaleModuleEntries 보다 먼저 호출되어야 한다. '
|
||||
'updateComposerAutoload 는 cleanupStale (또는 syncDeclarativeArtifacts 위임) 보다 먼저 호출되어야 한다. '
|
||||
.'(동적 hook 의 모듈 클래스 autoload 보장)'
|
||||
);
|
||||
}
|
||||
@@ -293,13 +299,16 @@ class ModuleCleanupStaleEntriesTest extends TestCase
|
||||
|
||||
$autoloadPos = strpos($body, '$this->extensionManager->updateComposerAutoload();');
|
||||
$cleanupPos = strpos($body, '$this->cleanupStalePluginEntries(');
|
||||
if ($cleanupPos === false) {
|
||||
$cleanupPos = strpos($body, '$this->syncDeclarativeArtifacts(');
|
||||
}
|
||||
|
||||
$this->assertNotFalse($autoloadPos);
|
||||
$this->assertNotFalse($cleanupPos);
|
||||
$this->assertLessThan(
|
||||
$cleanupPos,
|
||||
$autoloadPos,
|
||||
'updateComposerAutoload 는 cleanupStalePluginEntries 보다 먼저 호출되어야 한다.'
|
||||
'updateComposerAutoload 는 cleanupStale (또는 syncDeclarativeArtifacts 위임) 보다 먼저 호출되어야 한다.'
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Extension;
|
||||
|
||||
use App\Exceptions\CoreVersionMismatchException;
|
||||
use App\Extension\CoreVersionChecker;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 모듈 코어 버전 호환성 검증 단위 테스트.
|
||||
*
|
||||
* ModuleManager 가 활성화/업데이트 경로에서 사용하는 검증 헬퍼
|
||||
* (CoreVersionChecker::validateExtension / isCompatible) 의 결과 도메인을
|
||||
* 모듈 컨텍스트에서 검증합니다.
|
||||
*/
|
||||
class ModuleManagerVersionCheckTest extends TestCase
|
||||
{
|
||||
private ?string $originalEnvVersion = null;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->originalEnvVersion = $_ENV['APP_VERSION'] ?? null;
|
||||
unset($_ENV['APP_VERSION'], $_SERVER['APP_VERSION']);
|
||||
putenv('APP_VERSION');
|
||||
config()->set('app.version', '7.0.0-beta.1');
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
unset($_ENV['APP_VERSION'], $_SERVER['APP_VERSION']);
|
||||
if ($this->originalEnvVersion !== null) {
|
||||
$_ENV['APP_VERSION'] = $this->originalEnvVersion;
|
||||
$_SERVER['APP_VERSION'] = $this->originalEnvVersion;
|
||||
putenv('APP_VERSION='.$this->originalEnvVersion);
|
||||
} else {
|
||||
putenv('APP_VERSION');
|
||||
}
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_incompatible_required_version_throws_with_module_payload(): void
|
||||
{
|
||||
try {
|
||||
CoreVersionChecker::validateExtension('>=7.5.0', 'sirsoft-ecommerce', 'module');
|
||||
$this->fail('CoreVersionMismatchException 이 발생해야 합니다.');
|
||||
} catch (CoreVersionMismatchException $e) {
|
||||
$payload = $e->getPayload();
|
||||
$this->assertSame('module', $payload['extension_type']);
|
||||
$this->assertSame('sirsoft-ecommerce', $payload['identifier']);
|
||||
$this->assertSame('>=7.5.0', $payload['required_core_version']);
|
||||
$this->assertSame('7.0.0-beta.1', $payload['current_core_version']);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_compatible_when_required_constraint_satisfied(): void
|
||||
{
|
||||
config()->set('app.version', '7.0.0');
|
||||
$this->assertTrue(CoreVersionChecker::isCompatible('>=7.0.0'));
|
||||
}
|
||||
|
||||
public function test_null_required_version_skips_validation(): void
|
||||
{
|
||||
$this->assertTrue(CoreVersionChecker::isCompatible(null));
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,7 @@ class ModuleUpdateI18nTest extends TestCase
|
||||
['modules.errors.extracted_dir_not_found'],
|
||||
['modules.errors.reload_failed'],
|
||||
['modules.errors.delete_directory_failed'],
|
||||
['modules.errors.downgrade_blocked'],
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Extension;
|
||||
|
||||
use App\Exceptions\CoreVersionMismatchException;
|
||||
use App\Extension\CoreVersionChecker;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 플러그인 코어 버전 호환성 검증 단위 테스트.
|
||||
*
|
||||
* PluginManager 가 활성화/업데이트 경로에서 사용하는 검증 헬퍼
|
||||
* (CoreVersionChecker::validateExtension / isCompatible) 의 결과 도메인을
|
||||
* 플러그인 컨텍스트에서 검증합니다.
|
||||
*
|
||||
* 케이스:
|
||||
* 1. 현재 코어 < 요구 → 예외 + payload(extension_type=plugin, identifier, required, current, guide_url)
|
||||
* 2. 현재 코어 == 요구 → true 통과
|
||||
* 3. 현재 코어 > 요구 (caret) → true 통과
|
||||
* 4. requireVersion=null → 검증 생략 true 통과
|
||||
*/
|
||||
class PluginManagerVersionCheckTest extends TestCase
|
||||
{
|
||||
private ?string $originalEnvVersion = null;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->originalEnvVersion = $_ENV['APP_VERSION'] ?? null;
|
||||
unset($_ENV['APP_VERSION'], $_SERVER['APP_VERSION']);
|
||||
putenv('APP_VERSION');
|
||||
config()->set('app.version', '7.0.0-beta.1');
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
unset($_ENV['APP_VERSION'], $_SERVER['APP_VERSION']);
|
||||
if ($this->originalEnvVersion !== null) {
|
||||
$_ENV['APP_VERSION'] = $this->originalEnvVersion;
|
||||
$_SERVER['APP_VERSION'] = $this->originalEnvVersion;
|
||||
putenv('APP_VERSION='.$this->originalEnvVersion);
|
||||
} else {
|
||||
putenv('APP_VERSION');
|
||||
}
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_incompatible_required_version_throws_with_plugin_payload(): void
|
||||
{
|
||||
try {
|
||||
CoreVersionChecker::validateExtension('>=7.1.0', 'sirsoft-payment', 'plugin');
|
||||
$this->fail('CoreVersionMismatchException 이 발생해야 합니다.');
|
||||
} catch (CoreVersionMismatchException $e) {
|
||||
$payload = $e->getPayload();
|
||||
$this->assertSame('plugin', $payload['extension_type']);
|
||||
$this->assertSame('sirsoft-payment', $payload['identifier']);
|
||||
$this->assertSame('>=7.1.0', $payload['required_core_version']);
|
||||
$this->assertSame('7.0.0-beta.1', $payload['current_core_version']);
|
||||
$this->assertSame('/admin/core/update', $payload['guide_url']);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_compatible_when_required_constraint_is_satisfied_loose(): void
|
||||
{
|
||||
config()->set('app.version', '7.1.0');
|
||||
$this->assertTrue(CoreVersionChecker::isCompatible('>=7.0.0'));
|
||||
$this->assertTrue(CoreVersionChecker::validateExtension('>=7.0.0', 'sirsoft-payment', 'plugin'));
|
||||
}
|
||||
|
||||
public function test_compatible_when_caret_constraint_with_higher_patch(): void
|
||||
{
|
||||
config()->set('app.version', '7.0.5');
|
||||
$this->assertTrue(CoreVersionChecker::isCompatible('^7.0.0'));
|
||||
}
|
||||
|
||||
public function test_null_required_version_skips_validation(): void
|
||||
{
|
||||
$this->assertTrue(CoreVersionChecker::isCompatible(null));
|
||||
$this->assertTrue(CoreVersionChecker::validateExtension(null, 'sirsoft-payment', 'plugin'));
|
||||
}
|
||||
|
||||
public function test_env_app_version_overrides_config_for_plugin_check(): void
|
||||
{
|
||||
config()->set('app.version', '7.0.0-beta.1');
|
||||
$_ENV['APP_VERSION'] = '7.2.0';
|
||||
|
||||
$this->assertTrue(CoreVersionChecker::isCompatible('>=7.1.0'));
|
||||
}
|
||||
}
|
||||
@@ -230,4 +230,41 @@ class ModuleStorageDriverTest extends TestCase
|
||||
// Then: null 반환
|
||||
$this->assertNull($response);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// 트랙 2-A — `.preserve-ownership` 마커 자동 작성 (코어 7.0.0-beta.4+)
|
||||
//
|
||||
// ModuleStorageDriver 가 첫 디렉토리 생성 시 마커 파일을 자동으로 작성하여
|
||||
// 미래 코어 update 의 chownRecursive 가 storage/app/modules/{id}/ 트리를
|
||||
// 자동 skip 하도록 함. 시드 시점 owner/perms 영구 보존.
|
||||
// ========================================================================
|
||||
|
||||
#[Test]
|
||||
public function it_writes_preservation_marker_on_first_put(): void
|
||||
{
|
||||
// When: 첫 파일 저장 (디렉토리 자동 생성)
|
||||
$this->driver->put('images', 'product/img.jpg', 'image-data');
|
||||
|
||||
// Then: 모듈 루트에 .preserve-ownership 마커 자동 생성
|
||||
$markerPath = 'test-module/.preserve-ownership';
|
||||
$this->assertTrue(
|
||||
Storage::disk('modules')->exists($markerPath),
|
||||
'ModuleStorageDriver 가 첫 사용 시 .preserve-ownership 마커를 자동 작성해야 함 '
|
||||
.'(미래 chownRecursive 가드 트리거)',
|
||||
);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_does_not_overwrite_existing_marker(): void
|
||||
{
|
||||
// Given: 마커 사전 작성 (운영자 커스텀 내용)
|
||||
Storage::disk('modules')->put('test-module/.preserve-ownership', 'custom marker');
|
||||
|
||||
// When: 추가 파일 저장
|
||||
$this->driver->put('images', 'test.jpg', 'data');
|
||||
|
||||
// Then: 기존 마커 내용 보존 (멱등)
|
||||
$content = Storage::disk('modules')->get('test-module/.preserve-ownership');
|
||||
$this->assertSame('custom marker', $content, '기존 마커 내용 무변경 (멱등)');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Extension;
|
||||
|
||||
use App\Exceptions\CoreVersionMismatchException;
|
||||
use App\Extension\CoreVersionChecker;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 템플릿 코어 버전 호환성 검증 단위 테스트.
|
||||
*
|
||||
* TemplateManager 가 활성화/업데이트 경로에서 사용하는 검증 헬퍼
|
||||
* (CoreVersionChecker::validateExtension / isCompatible) 의 결과 도메인을
|
||||
* 템플릿 컨텍스트에서 검증합니다.
|
||||
*/
|
||||
class TemplateManagerVersionCheckTest extends TestCase
|
||||
{
|
||||
private ?string $originalEnvVersion = null;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->originalEnvVersion = $_ENV['APP_VERSION'] ?? null;
|
||||
unset($_ENV['APP_VERSION'], $_SERVER['APP_VERSION']);
|
||||
putenv('APP_VERSION');
|
||||
config()->set('app.version', '7.0.0-beta.1');
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
unset($_ENV['APP_VERSION'], $_SERVER['APP_VERSION']);
|
||||
if ($this->originalEnvVersion !== null) {
|
||||
$_ENV['APP_VERSION'] = $this->originalEnvVersion;
|
||||
$_SERVER['APP_VERSION'] = $this->originalEnvVersion;
|
||||
putenv('APP_VERSION='.$this->originalEnvVersion);
|
||||
} else {
|
||||
putenv('APP_VERSION');
|
||||
}
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_incompatible_required_version_throws_with_template_payload(): void
|
||||
{
|
||||
try {
|
||||
CoreVersionChecker::validateExtension('>=8.0.0', 'sirsoft-admin_basic', 'template');
|
||||
$this->fail('CoreVersionMismatchException 이 발생해야 합니다.');
|
||||
} catch (CoreVersionMismatchException $e) {
|
||||
$payload = $e->getPayload();
|
||||
$this->assertSame('template', $payload['extension_type']);
|
||||
$this->assertSame('sirsoft-admin_basic', $payload['identifier']);
|
||||
$this->assertSame('>=8.0.0', $payload['required_core_version']);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_compatible_for_template_when_constraint_passes(): void
|
||||
{
|
||||
config()->set('app.version', '7.2.0');
|
||||
$this->assertTrue(CoreVersionChecker::isCompatible('^7.0.0'));
|
||||
}
|
||||
}
|
||||
@@ -367,4 +367,179 @@ class FilePermissionHelperTest extends TestCase
|
||||
$this->assertSame(0720, fileperms($file) & 0777, 'g+w 만 추가, 다른 비트 무변경');
|
||||
$this->assertSame(1, $changed);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// chownRecursiveDetailed / syncGroupWritabilityDetailed — Stage 3
|
||||
// 권한 정상화 실패 항목 누적 반환 검증
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* chownRecursiveDetailed — chown 미지원 환경 (Windows) 에서는 supported=false.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_chown_recursive_detailed_returns_supported_false_when_chown_missing(): void
|
||||
{
|
||||
if (function_exists('chown')) {
|
||||
$this->markTestSkipped('chown 지원 환경 — supported=false 케이스 검증 불가');
|
||||
}
|
||||
|
||||
$root = $this->createTempDir();
|
||||
$report = FilePermissionHelper::chownRecursiveDetailed($root, 0, false);
|
||||
|
||||
$this->assertFalse($report['supported']);
|
||||
$this->assertSame(0, $report['changed']);
|
||||
$this->assertSame([], $report['failed_paths']);
|
||||
}
|
||||
|
||||
/**
|
||||
* chownRecursiveDetailed — POSIX 환경에서 자기 자신을 owner 로 호출 시 changed=0, failed=0.
|
||||
*
|
||||
* 자기 소유자와 일치하면 chown 호출 자체가 발생하지 않으므로 멱등.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_chown_recursive_detailed_idempotent_when_owner_matches(): void
|
||||
{
|
||||
$this->assertPosixOrSkip();
|
||||
|
||||
$root = $this->createTempDir();
|
||||
$owner = fileowner($root);
|
||||
$this->assertNotFalse($owner);
|
||||
|
||||
$report = FilePermissionHelper::chownRecursiveDetailed($root, $owner, false);
|
||||
|
||||
$this->assertTrue($report['supported']);
|
||||
$this->assertSame(0, $report['changed']);
|
||||
$this->assertSame(0, $report['failed']);
|
||||
$this->assertSame([], $report['failed_paths']);
|
||||
}
|
||||
|
||||
/**
|
||||
* syncGroupWritabilityDetailed — 루트 g-w 환경은 skipped=true 로 보고.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_sync_group_writability_detailed_skipped_when_root_no_group_write(): void
|
||||
{
|
||||
$this->assertPosixOrSkip();
|
||||
|
||||
$root = $this->createTempDir();
|
||||
chmod($root, 0755);
|
||||
|
||||
$report = FilePermissionHelper::syncGroupWritabilityDetailed($root);
|
||||
|
||||
$this->assertTrue($report['skipped']);
|
||||
$this->assertSame(0, $report['changed']);
|
||||
$this->assertSame(0, $report['failed']);
|
||||
}
|
||||
|
||||
/**
|
||||
* syncGroupWritabilityDetailed — 정상 승격 시 changed>0, failed=0, skipped=false.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_sync_group_writability_detailed_reports_changed(): void
|
||||
{
|
||||
$this->assertPosixOrSkip();
|
||||
|
||||
$root = $this->createTempDir();
|
||||
chmod($root, 0775);
|
||||
|
||||
$child = $root.DIRECTORY_SEPARATOR.'sub';
|
||||
mkdir($child, 0755);
|
||||
|
||||
$report = FilePermissionHelper::syncGroupWritabilityDetailed($root);
|
||||
|
||||
$this->assertFalse($report['skipped']);
|
||||
$this->assertSame(1, $report['changed']);
|
||||
$this->assertSame(0, $report['failed']);
|
||||
$this->assertSame([], $report['failed_paths']);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// 트랙 2-A — `.preserve-ownership` 마커 + chownRecursiveDetailed 가드
|
||||
// (코어 7.0.0-beta.4+)
|
||||
//
|
||||
// 사용자 데이터 디렉토리 (storage/app/{modules,plugins,attachments,...}) 가
|
||||
// 마커 파일을 보유하면, sudo update 의 chownRecursive 가 그 서브트리 전체를
|
||||
// 자동 skip 하여 시드 시점 owner/perms 보존. 미래 release transition 의
|
||||
// 권한 회귀를 구조적으로 차단.
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* `chownRecursiveDetailed` 가 `respectPreservationMarker` 옵션을 지원해야 함.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_chown_recursive_detailed_supports_respect_preservation_marker_option(): void
|
||||
{
|
||||
$reflection = new \ReflectionMethod(FilePermissionHelper::class, 'chownRecursiveDetailed');
|
||||
$params = $reflection->getParameters();
|
||||
$names = array_map(fn ($p) => $p->getName(), $params);
|
||||
|
||||
$this->assertContains(
|
||||
'respectPreservationMarker',
|
||||
$names,
|
||||
'chownRecursiveDetailed 가 respectPreservationMarker 옵션을 받아야 함 (마커 인식 가드)',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 마커가 있는 디렉토리 트리는 chownRecursiveDetailed 가 skip — 자기 자신/하위 모두 chown 안 함.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_chown_recursive_detailed_skips_subtree_when_preservation_marker_present(): void
|
||||
{
|
||||
$this->assertPosixOrSkip();
|
||||
|
||||
$root = $this->createTempDir();
|
||||
$protectedDir = $root.DIRECTORY_SEPARATOR.'modules';
|
||||
mkdir($protectedDir, 0755);
|
||||
$imageDir = $protectedDir.DIRECTORY_SEPARATOR.'images';
|
||||
mkdir($imageDir, 0700);
|
||||
file_put_contents($imageDir.DIRECTORY_SEPARATOR.'test.jpg', 'data');
|
||||
|
||||
// 마커 파일 작성 → protectedDir 전체 chown 비대상
|
||||
file_put_contents($protectedDir.DIRECTORY_SEPARATOR.'.preserve-ownership', '');
|
||||
|
||||
$ownerBefore = fileowner($protectedDir);
|
||||
$imageDirOwnerBefore = fileowner($imageDir);
|
||||
|
||||
// 자기 자신 owner 로 호출 (실제 chown 시도 — 일반 user 권한 환경에서도 호출 가능)
|
||||
// 그러나 마커 가드로 skip 되어야 함. owner 가 동일해도 changed 카운트가 마커 가드 분기 검증
|
||||
$owner = $ownerBefore;
|
||||
$report = FilePermissionHelper::chownRecursiveDetailed(
|
||||
$root,
|
||||
$owner,
|
||||
false,
|
||||
respectPreservationMarker: true,
|
||||
);
|
||||
|
||||
$this->assertTrue($report['supported']);
|
||||
$this->assertSame($ownerBefore, fileowner($protectedDir), '마커 디렉토리 owner 무변경');
|
||||
$this->assertSame($imageDirOwnerBefore, fileowner($imageDir), '마커 하위 owner 무변경');
|
||||
$this->assertArrayHasKey('skipped_subtrees', $report, 'skipped_subtrees 카운트 보고');
|
||||
$this->assertGreaterThanOrEqual(1, $report['skipped_subtrees'], '최소 1개 서브트리 skip');
|
||||
}
|
||||
|
||||
/**
|
||||
* 마커 옵션이 false 이면 (기본값) — 기존 동작 그대로 (호환성 유지).
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_chown_recursive_detailed_backward_compatible_without_marker_option(): void
|
||||
{
|
||||
$this->assertPosixOrSkip();
|
||||
|
||||
$root = $this->createTempDir();
|
||||
$owner = fileowner($root);
|
||||
|
||||
// respectPreservationMarker 인자 없이 호출 → 기존 동작 (default false)
|
||||
$report = FilePermissionHelper::chownRecursiveDetailed($root, $owner, false);
|
||||
|
||||
$this->assertTrue($report['supported']);
|
||||
$this->assertSame(0, $report['failed']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Helpers;
|
||||
|
||||
use App\Extension\Helpers\IdentityMessageSyncHelper;
|
||||
use App\Models\IdentityMessageDefinition;
|
||||
use App\Models\IdentityMessageTemplate;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* IdentityMessageSyncHelper 단위 테스트.
|
||||
*
|
||||
* 정의/템플릿 syncOrCreate, user_overrides 보존, stale cleanup 검증.
|
||||
*/
|
||||
class IdentityMessageSyncHelperTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private IdentityMessageSyncHelper $helper;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->helper = app(IdentityMessageSyncHelper::class);
|
||||
}
|
||||
|
||||
public function test_sync_definition_creates_new_record(): void
|
||||
{
|
||||
$definition = $this->helper->syncDefinition($this->definitionData('signup'));
|
||||
|
||||
$this->assertSame('g7:core.mail', $definition->provider_id);
|
||||
$this->assertSame('purpose', $definition->scope_type->value);
|
||||
$this->assertSame('signup', $definition->scope_value);
|
||||
$this->assertTrue($definition->is_active);
|
||||
}
|
||||
|
||||
public function test_sync_definition_preserves_user_overrides_on_reseed(): void
|
||||
{
|
||||
$definition = $this->helper->syncDefinition($this->definitionData('signup'));
|
||||
|
||||
$definition->update(['name' => ['ko' => '운영자 변경 이름', 'en' => 'Custom Name']]);
|
||||
$definition->refresh();
|
||||
$this->assertContains('name', $definition->user_overrides ?? []);
|
||||
|
||||
$reseeded = $this->helper->syncDefinition($this->definitionData('signup'));
|
||||
|
||||
$this->assertSame('운영자 변경 이름', $reseeded->name['ko']);
|
||||
}
|
||||
|
||||
public function test_sync_template_creates_and_links_to_definition(): void
|
||||
{
|
||||
$definition = $this->helper->syncDefinition($this->definitionData('signup'));
|
||||
|
||||
$template = $this->helper->syncTemplate($definition->id, [
|
||||
'channel' => 'mail',
|
||||
'subject' => ['ko' => '제목', 'en' => 'Subject'],
|
||||
'body' => ['ko' => '본문', 'en' => 'Body'],
|
||||
]);
|
||||
|
||||
$this->assertSame($definition->id, $template->definition_id);
|
||||
$this->assertSame('mail', $template->channel);
|
||||
}
|
||||
|
||||
public function test_cleanup_stale_definitions_deletes_unmapped_records(): void
|
||||
{
|
||||
$signup = $this->helper->syncDefinition($this->definitionData('signup'));
|
||||
$reset = $this->helper->syncDefinition($this->definitionData('password_reset'));
|
||||
$extra = $this->helper->syncDefinition($this->definitionData('legacy'));
|
||||
|
||||
// signup, password_reset 만 유지 → legacy 삭제 대상
|
||||
$deleted = $this->helper->cleanupStaleDefinitions('core', 'core', [
|
||||
['provider_id' => 'g7:core.mail', 'scope_type' => 'purpose', 'scope_value' => 'signup'],
|
||||
['provider_id' => 'g7:core.mail', 'scope_type' => 'purpose', 'scope_value' => 'password_reset'],
|
||||
]);
|
||||
|
||||
$this->assertSame(1, $deleted);
|
||||
$this->assertNotNull(IdentityMessageDefinition::find($signup->id));
|
||||
$this->assertNotNull(IdentityMessageDefinition::find($reset->id));
|
||||
$this->assertNull(IdentityMessageDefinition::find($extra->id));
|
||||
}
|
||||
|
||||
public function test_cleanup_stale_definitions_cascade_deletes_templates(): void
|
||||
{
|
||||
$extra = $this->helper->syncDefinition($this->definitionData('legacy'));
|
||||
$this->helper->syncTemplate($extra->id, [
|
||||
'channel' => 'mail',
|
||||
'subject' => ['ko' => '제목'],
|
||||
'body' => ['ko' => '본문'],
|
||||
]);
|
||||
|
||||
$this->helper->cleanupStaleDefinitions('core', 'core', []);
|
||||
|
||||
$this->assertSame(0, IdentityMessageTemplate::where('definition_id', $extra->id)->count());
|
||||
}
|
||||
|
||||
public function test_cleanup_stale_templates_only_removes_unmapped_channels(): void
|
||||
{
|
||||
$definition = $this->helper->syncDefinition($this->definitionData('signup'));
|
||||
$this->helper->syncTemplate($definition->id, [
|
||||
'channel' => 'mail',
|
||||
'subject' => ['ko' => 'mail'],
|
||||
'body' => ['ko' => 'mail body'],
|
||||
]);
|
||||
$this->helper->syncTemplate($definition->id, [
|
||||
'channel' => 'sms',
|
||||
'subject' => ['ko' => 'sms'],
|
||||
'body' => ['ko' => 'sms body'],
|
||||
]);
|
||||
|
||||
$deleted = $this->helper->cleanupStaleTemplates($definition->id, ['mail']);
|
||||
|
||||
$this->assertSame(1, $deleted);
|
||||
$this->assertSame(1, IdentityMessageTemplate::where('definition_id', $definition->id)->count());
|
||||
$this->assertNotNull(IdentityMessageTemplate::where('definition_id', $definition->id)->where('channel', 'mail')->first());
|
||||
}
|
||||
|
||||
private function definitionData(string $scopeValue): array
|
||||
{
|
||||
return [
|
||||
'provider_id' => 'g7:core.mail',
|
||||
'scope_type' => 'purpose',
|
||||
'scope_value' => $scopeValue,
|
||||
'extension_type' => 'core',
|
||||
'extension_identifier' => 'core',
|
||||
'name' => ['ko' => '시드 이름 '.$scopeValue, 'en' => 'Seed Name '.$scopeValue],
|
||||
'channels' => ['mail'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Helpers;
|
||||
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* `localized_label()` / `localized_payload()` helper 단위 테스트.
|
||||
*
|
||||
* 우선순위 검증:
|
||||
* 1. nameKey __() 우선 (registry payload 패턴)
|
||||
* 2. value[locale] (settings JSON 패턴)
|
||||
* 3. fallbackKey __() (settings JSON 의 lang pack fallback)
|
||||
* 4. value[fallback_locale] / value 첫 키 (최종 fallback)
|
||||
*/
|
||||
class LocalizedLabelTest extends TestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
// 테스트용 lang 라인 등록 (translator 의 in-memory loader 활용)
|
||||
app('translator')->addLines([
|
||||
'test_helper.foo' => '폴백 키 KO',
|
||||
'test_helper.bar' => '네임 키 KO',
|
||||
], 'ko');
|
||||
app('translator')->addLines([
|
||||
'test_helper.foo' => 'Fallback Key EN',
|
||||
'test_helper.bar' => 'Name Key EN',
|
||||
], 'en');
|
||||
}
|
||||
|
||||
public function test_name_key_resolves_first_when_present(): void
|
||||
{
|
||||
app()->setLocale('ko');
|
||||
$this->assertSame(
|
||||
'네임 키 KO',
|
||||
localized_label(
|
||||
value: ['ko' => 'value-ko', 'en' => 'value-en'],
|
||||
nameKey: 'test_helper.bar',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_value_locale_used_when_name_key_absent(): void
|
||||
{
|
||||
app()->setLocale('en');
|
||||
$this->assertSame(
|
||||
'value-en',
|
||||
localized_label(value: ['ko' => 'value-ko', 'en' => 'value-en']),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_fallback_key_used_when_value_locale_missing(): void
|
||||
{
|
||||
app()->setLocale('ko');
|
||||
$this->assertSame(
|
||||
'폴백 키 KO',
|
||||
localized_label(
|
||||
value: ['en' => 'only-en'],
|
||||
fallbackKey: 'test_helper.foo',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_value_fallback_locale_used_when_no_keys(): void
|
||||
{
|
||||
app()->setLocale('ja');
|
||||
config(['app.fallback_locale' => 'ko']);
|
||||
$this->assertSame(
|
||||
'value-ko',
|
||||
localized_label(value: ['ko' => 'value-ko', 'en' => 'value-en']),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_returns_empty_string_when_all_sources_empty(): void
|
||||
{
|
||||
app()->setLocale('ko');
|
||||
$this->assertSame('', localized_label());
|
||||
$this->assertSame('', localized_label(value: null, nameKey: null, fallbackKey: null));
|
||||
}
|
||||
|
||||
public function test_localized_payload_with_name_key_field(): void
|
||||
{
|
||||
app()->setLocale('en');
|
||||
$entry = [
|
||||
'id' => 'mail',
|
||||
'name_key' => 'test_helper.bar',
|
||||
'name' => ['ko' => 'fallback-ko', 'en' => 'fallback-en'],
|
||||
];
|
||||
$this->assertSame('Name Key EN', localized_payload($entry, 'name'));
|
||||
}
|
||||
|
||||
public function test_localized_payload_falls_back_to_value_when_name_key_unresolved(): void
|
||||
{
|
||||
app()->setLocale('ko');
|
||||
$entry = [
|
||||
'id' => 'foo',
|
||||
'name' => ['ko' => 'value-ko', 'en' => 'value-en'],
|
||||
];
|
||||
$this->assertSame('value-ko', localized_payload($entry, 'name'));
|
||||
}
|
||||
|
||||
public function test_localized_payload_returns_empty_when_field_absent(): void
|
||||
{
|
||||
$entry = ['id' => 'foo'];
|
||||
$this->assertSame('', localized_payload($entry, 'name'));
|
||||
}
|
||||
|
||||
public function test_locale_argument_overrides_app_locale(): void
|
||||
{
|
||||
app()->setLocale('ko');
|
||||
$this->assertSame(
|
||||
'Name Key EN',
|
||||
localized_label(nameKey: 'test_helper.bar', locale: 'en'),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Helpers;
|
||||
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* g7_meta_generator_tag() 헬퍼 단위 테스트.
|
||||
*
|
||||
* 코어 SEO 설정(`seo.generator_enabled`, `seo.generator_content`)에 따라
|
||||
* `<meta name="generator">` 태그를 생성하는 동작을 검증합니다.
|
||||
*/
|
||||
class MetaGeneratorTagTest extends TestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
Config::set('app.version', '7.0.0-test');
|
||||
}
|
||||
|
||||
public function test_disabled_returns_empty_string(): void
|
||||
{
|
||||
Config::set('g7_settings.core.seo.generator_enabled', false);
|
||||
Config::set('g7_settings.core.seo.generator_content', 'Anything');
|
||||
|
||||
$this->assertSame('', g7_meta_generator_tag());
|
||||
}
|
||||
|
||||
public function test_enabled_with_empty_content_falls_back_to_version_default(): void
|
||||
{
|
||||
Config::set('g7_settings.core.seo.generator_enabled', true);
|
||||
Config::set('g7_settings.core.seo.generator_content', '');
|
||||
|
||||
$this->assertSame(
|
||||
'<meta name="generator" content="GnuBoard7 7.0.0-test">',
|
||||
g7_meta_generator_tag()
|
||||
);
|
||||
}
|
||||
|
||||
public function test_enabled_with_custom_content_uses_custom_value(): void
|
||||
{
|
||||
Config::set('g7_settings.core.seo.generator_enabled', true);
|
||||
Config::set('g7_settings.core.seo.generator_content', 'GnuBoard7');
|
||||
|
||||
$this->assertSame(
|
||||
'<meta name="generator" content="GnuBoard7">',
|
||||
g7_meta_generator_tag()
|
||||
);
|
||||
}
|
||||
|
||||
public function test_content_is_escaped_to_prevent_xss(): void
|
||||
{
|
||||
Config::set('g7_settings.core.seo.generator_enabled', true);
|
||||
Config::set('g7_settings.core.seo.generator_content', '"><script>alert(1)</script>');
|
||||
|
||||
$tag = g7_meta_generator_tag();
|
||||
|
||||
$this->assertStringNotContainsString('<script>', $tag);
|
||||
$this->assertStringContainsString('<script>', $tag);
|
||||
$this->assertStringContainsString('"', $tag);
|
||||
}
|
||||
|
||||
public function test_default_when_setting_missing_is_enabled_with_version(): void
|
||||
{
|
||||
// 설정 키 자체가 없을 때 헬퍼는 enabled=true 폴백 + 버전 메시지 출력
|
||||
Config::offsetUnset('g7_settings');
|
||||
|
||||
$this->assertSame(
|
||||
'<meta name="generator" content="GnuBoard7 7.0.0-test">',
|
||||
g7_meta_generator_tag()
|
||||
);
|
||||
}
|
||||
|
||||
public function test_whitespace_only_content_falls_back_to_default(): void
|
||||
{
|
||||
Config::set('g7_settings.core.seo.generator_enabled', true);
|
||||
Config::set('g7_settings.core.seo.generator_content', ' ');
|
||||
|
||||
$this->assertSame(
|
||||
'<meta name="generator" content="GnuBoard7 7.0.0-test">',
|
||||
g7_meta_generator_tag()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace Tests\Unit\Helpers;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use Illuminate\Support\Facades\App;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
@@ -258,4 +259,39 @@ class ResponseHelperTest extends TestCase
|
||||
|
||||
return $this->createDeepException($depth - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀: ResponseHelper::trans() 가 App::getLocale() 결과를 그대로 사용한다.
|
||||
*
|
||||
* 이전 구현은 자체 화이트리스트 ['ko', 'en'] 으로 ja 를 거부하고
|
||||
* config('app.locale') fallback 으로 떨어뜨렸다. 이 회귀 테스트는
|
||||
* SetLocale 미들웨어가 이미 set 한 App::getLocale() 결과(ja 등)가
|
||||
* 다국어 응답에 반영됨을 보장한다.
|
||||
*/
|
||||
public function test_trans_uses_current_app_locale_not_hardcoded_whitelist(): void
|
||||
{
|
||||
// 임시 키를 ko/ja 양쪽에 등록 (lang/ja/* 는 활성 언어팩이 폴백 등록)
|
||||
App::setLocale('ja');
|
||||
app('translator')->addLines(['testdomain.greet' => 'こんにちは'], 'ja');
|
||||
app('translator')->addLines(['testdomain.greet' => '안녕'], 'ko');
|
||||
|
||||
$response = ResponseHelper::success('testdomain.greet');
|
||||
$data = $response->getData(true);
|
||||
|
||||
$this->assertSame('こんにちは', $data['message']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀: App::getLocale() 가 빌트인 ko/en 외 로케일이어도 ResponseHelper 가 그 값을 신뢰한다.
|
||||
*/
|
||||
public function test_trans_respects_non_builtin_locale_when_app_locale_set(): void
|
||||
{
|
||||
App::setLocale('zh-CN');
|
||||
app('translator')->addLines(['testdomain.welcome' => '欢迎'], 'zh-CN');
|
||||
|
||||
$response = ResponseHelper::success('testdomain.welcome');
|
||||
$data = $response->getData(true);
|
||||
|
||||
$this->assertSame('欢迎', $data['message']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Helpers;
|
||||
|
||||
use App\Extension\Helpers\FilePermissionHelper;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* SettingsMigrator owner 상속 회귀 테스트.
|
||||
*
|
||||
* sudo update 흐름에서 모듈/플러그인 upgrade step 이 root 로 실행될 때
|
||||
* `SettingsMigrator::writeJsonFile` 가 만드는 *.json 파일이 root 소유로 영구 잔존하는
|
||||
* 회귀 차단:
|
||||
*
|
||||
* - 변경 1 로 storage/app/{modules,plugins} 가 chown 비대상이 된 후, settings *.json
|
||||
* 파일에 후속 PHP-FPM 이 update 시도 시 쓰기 실패하는 케이스 차단
|
||||
* - writeJsonFile 후 부모 디렉토리(예: storage/app/modules/{id}/settings/) 의 owner/group
|
||||
* 을 상속하여 PHP-FPM 시드 시점 owner 가 PHP-FPM 이라면 자동 일치
|
||||
*
|
||||
* 본 테스트는 `FilePermissionHelper::inheritOwnershipFromParent` 가 public static 으로
|
||||
* 노출되어 외부(SettingsMigrator) 가 호출 가능한지 검증.
|
||||
*/
|
||||
class SettingsMigratorOwnershipTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* @var array<int, string>
|
||||
*/
|
||||
private array $tempDirs = [];
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
foreach ($this->tempDirs as $dir) {
|
||||
if (File::isDirectory($dir)) {
|
||||
File::deleteDirectory($dir);
|
||||
}
|
||||
}
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function createTempDir(): string
|
||||
{
|
||||
$dir = storage_path('test_settings_owner_'.uniqid());
|
||||
File::ensureDirectoryExists($dir);
|
||||
$this->tempDirs[] = $dir;
|
||||
|
||||
return $dir;
|
||||
}
|
||||
|
||||
/**
|
||||
* inheritOwnershipFromParent 가 public static 으로 노출되어야 함.
|
||||
*
|
||||
* 변경 7-(a): `SettingsMigrator::writeJsonFile` 같은 외부 호출처가 본 helper 를
|
||||
* 사용해 부모 owner/group 을 상속하도록 노출.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_inherit_ownership_from_parent_is_public(): void
|
||||
{
|
||||
$reflection = new \ReflectionMethod(FilePermissionHelper::class, 'inheritOwnershipFromParent');
|
||||
|
||||
$this->assertTrue(
|
||||
$reflection->isPublic(),
|
||||
'FilePermissionHelper::inheritOwnershipFromParent 가 public 이어야 외부 호출 가능 (SettingsMigrator 등)',
|
||||
);
|
||||
$this->assertTrue($reflection->isStatic(), 'static 메서드여야 함');
|
||||
}
|
||||
|
||||
/**
|
||||
* inheritOwnershipFromParent — 부모 디렉토리 stat 기반으로 owner/group 적용.
|
||||
*
|
||||
* POSIX 환경 전용. 일반 user 권한에서는 다른 user 로 chown 시도가 실패할 수 있으나,
|
||||
* 자기 자신 owner 인 경우 chown 자체가 발생하지 않으므로 멱등.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_inherit_ownership_from_parent_idempotent_for_self_owner(): void
|
||||
{
|
||||
if (DIRECTORY_SEPARATOR !== '/' || ! function_exists('chown')) {
|
||||
$this->markTestSkipped('POSIX 환경 전용 (Windows 자동 스킵)');
|
||||
}
|
||||
|
||||
$parent = $this->createTempDir();
|
||||
$child = $parent.'/child.json';
|
||||
file_put_contents($child, '{}');
|
||||
|
||||
$parentOwnerBefore = fileowner($parent);
|
||||
$childOwnerBefore = fileowner($child);
|
||||
|
||||
// 자기 자신 owner 면 부모와 자식 owner 가 동일 → 멱등
|
||||
FilePermissionHelper::inheritOwnershipFromParent($child);
|
||||
|
||||
$this->assertSame($parentOwnerBefore, fileowner($parent));
|
||||
$this->assertSame($childOwnerBefore, fileowner($child));
|
||||
$this->assertSame($parentOwnerBefore, fileowner($child), '자식 owner 가 부모와 동일');
|
||||
}
|
||||
|
||||
/**
|
||||
* SettingsMigrator::writeJsonFile 호출 후 *.json 의 owner 가 부모와 일치.
|
||||
*
|
||||
* `SettingsMigrator` 는 protected 메서드 + non-static 이라 직접 호출이 어려우므로,
|
||||
* 핵심 통합 보장 = "writeJsonFile 메서드 안에서 inheritOwnershipFromParent 호출" 을
|
||||
* reflection 으로 검증.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_settings_migrator_write_json_file_invokes_inherit_ownership(): void
|
||||
{
|
||||
$reflection = new \ReflectionClass(\App\Extension\Helpers\SettingsMigrator::class);
|
||||
$method = $reflection->getMethod('writeJsonFile');
|
||||
$body = file_get_contents($method->getFileName());
|
||||
|
||||
// writeJsonFile 메서드 내부에 inheritOwnershipFromParent 호출이 존재해야 함
|
||||
$startLine = $method->getStartLine();
|
||||
$endLine = $method->getEndLine();
|
||||
$methodBody = implode("\n", array_slice(
|
||||
explode("\n", $body),
|
||||
$startLine - 1,
|
||||
$endLine - $startLine + 1
|
||||
));
|
||||
|
||||
$this->assertStringContainsString(
|
||||
'inheritOwnershipFromParent',
|
||||
$methodBody,
|
||||
'SettingsMigrator::writeJsonFile 가 sudo update 시 root 로 만든 *.json 의 owner 를 부모로 상속해야 함 (FilePermissionHelper::inheritOwnershipFromParent 호출)',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Http\Controllers\Concerns;
|
||||
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Http\Controllers\Concerns\OrchestratesCascadeInstall;
|
||||
use App\Services\ModuleService;
|
||||
use App\Services\PluginService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Mockery;
|
||||
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* cascade 의존 확장 설치 흐름의 상태별 처리 검증.
|
||||
*
|
||||
* 일반 설치(웹/CLI 단독)는 install 만 하지만, cascade 흐름은 본 확장 install 직후
|
||||
* `checkDependencies` 가 active 상태를 요구하므로 install + activate 를 묶어 수행한다.
|
||||
*
|
||||
* 회귀 시나리오: 템플릿 설치 시 의존 모듈이 "이미 설치됨 + 비활성" 상태인 경우
|
||||
* cascade 가 activate 를 호출하지 않으면 "필수 의존성 충족되지 않음" 으로 실패한다.
|
||||
*/
|
||||
class OrchestratesCascadeInstallTest extends TestCase
|
||||
{
|
||||
use MockeryPHPUnitIntegration;
|
||||
use RefreshDatabase;
|
||||
|
||||
private object $harness;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
// OrchestratesCascadeInstall trait 의 protected 메서드 호출용 무명 클래스
|
||||
$this->harness = new class {
|
||||
use OrchestratesCascadeInstall {
|
||||
installSelectedDependencies as public;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Mockery::close();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_inactive_installed_module_only_activates_no_reinstall(): void
|
||||
{
|
||||
$moduleService = Mockery::mock(ModuleService::class);
|
||||
$moduleService->shouldReceive('getModuleInfo')
|
||||
->with('foo-module')
|
||||
->andReturn([
|
||||
'is_installed' => true,
|
||||
'status' => ExtensionStatus::Inactive->value,
|
||||
]);
|
||||
$moduleService->shouldNotReceive('installModule');
|
||||
$moduleService->shouldReceive('activateModule')
|
||||
->once()
|
||||
->with('foo-module');
|
||||
$this->app->instance(ModuleService::class, $moduleService);
|
||||
|
||||
$this->harness->installSelectedDependencies([
|
||||
['type' => 'module', 'identifier' => 'foo-module'],
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_uninstalled_module_installs_then_activates(): void
|
||||
{
|
||||
$moduleService = Mockery::mock(ModuleService::class);
|
||||
$moduleService->shouldReceive('getModuleInfo')
|
||||
->with('bar-module')
|
||||
->andReturn([
|
||||
'is_installed' => false,
|
||||
'status' => 'uninstalled',
|
||||
]);
|
||||
$moduleService->shouldReceive('installModule')->once()->with('bar-module', \Mockery::any());
|
||||
$moduleService->shouldReceive('activateModule')->once()->with('bar-module');
|
||||
$this->app->instance(ModuleService::class, $moduleService);
|
||||
|
||||
$this->harness->installSelectedDependencies([
|
||||
['type' => 'module', 'identifier' => 'bar-module'],
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_active_module_is_skipped(): void
|
||||
{
|
||||
$moduleService = Mockery::mock(ModuleService::class);
|
||||
$moduleService->shouldReceive('getModuleInfo')
|
||||
->with('baz-module')
|
||||
->andReturn([
|
||||
'is_installed' => true,
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
$moduleService->shouldNotReceive('installModule');
|
||||
$moduleService->shouldNotReceive('activateModule');
|
||||
$this->app->instance(ModuleService::class, $moduleService);
|
||||
|
||||
$this->harness->installSelectedDependencies([
|
||||
['type' => 'module', 'identifier' => 'baz-module'],
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_inactive_installed_plugin_only_activates(): void
|
||||
{
|
||||
$pluginService = Mockery::mock(PluginService::class);
|
||||
$pluginService->shouldReceive('getPluginInfo')
|
||||
->with('foo-plugin')
|
||||
->andReturn([
|
||||
'is_installed' => true,
|
||||
'status' => ExtensionStatus::Inactive->value,
|
||||
]);
|
||||
$pluginService->shouldNotReceive('installPlugin');
|
||||
$pluginService->shouldReceive('activatePlugin')->once()->with('foo-plugin');
|
||||
$this->app->instance(PluginService::class, $pluginService);
|
||||
|
||||
$this->harness->installSelectedDependencies([
|
||||
['type' => 'plugin', 'identifier' => 'foo-plugin'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -148,7 +148,9 @@ class ActivityLogIndexRequestTest extends TestCase
|
||||
|
||||
public function test_actor_exceeding_max_length_fails(): void
|
||||
{
|
||||
$validator = $this->makeValidator(['actor' => str_repeat('a', 256)]);
|
||||
// actor 필드는 rules 에 존재하지 않으므로 크기 제한 검증이 없다.
|
||||
// 최신 구현은 created_by 필드로 검증하며, max:36 적용됨.
|
||||
$validator = $this->makeValidator(['created_by' => str_repeat('a', 37)]);
|
||||
$this->assertTrue($validator->fails());
|
||||
}
|
||||
|
||||
|
||||
@@ -542,9 +542,10 @@ class ActivityLogResourceTest extends TestCase
|
||||
public function test_resource_resolves_unreplaced_count_from_bulk_changes(): void
|
||||
{
|
||||
$locale = app()->getLocale();
|
||||
// namespaced key ('vendor::group.key') 는 addLines 의 3번째 인자 namespace 로 전달해야 함
|
||||
app('translator')->addLines([
|
||||
'sirsoft-ecommerce::activity_log.description.order_bulk_status_update' => '주문 일괄 상태 변경 (:count건)',
|
||||
], $locale);
|
||||
'activity_log.description.order_bulk_status_update' => '주문 일괄 상태 변경 (:count건)',
|
||||
], $locale, 'sirsoft-ecommerce');
|
||||
|
||||
$bulkChanges = [
|
||||
101 => [
|
||||
@@ -579,8 +580,8 @@ class ActivityLogResourceTest extends TestCase
|
||||
{
|
||||
$locale = app()->getLocale();
|
||||
app('translator')->addLines([
|
||||
'sirsoft-ecommerce::activity_log.description.order_bulk_status_update' => '주문 일괄 상태 변경 (:count건)',
|
||||
], $locale);
|
||||
'activity_log.description.order_bulk_status_update' => '주문 일괄 상태 변경 (:count건)',
|
||||
], $locale, 'sirsoft-ecommerce');
|
||||
|
||||
$bulkChanges = [
|
||||
101 => [
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Installer;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use ReflectionClass;
|
||||
use ValidationApi;
|
||||
|
||||
/**
|
||||
* 인스톨러 Composer/PHP 경로 검증 보안 회귀 테스트
|
||||
*
|
||||
* 사용자 입력으로 들어온 Composer/PHP 바이너리 경로가 shell 명령으로 그대로
|
||||
* 실행되던 결함(공백 분기 + escape 부재) 의 패치를 보장한다.
|
||||
*
|
||||
* 검증 축:
|
||||
* - shell 메타문자(공백, 세미콜론, 백틱 등) 포함 입력 → exec 도달 전 차단
|
||||
* - 존재하지 않는 경로 → exec 도달 전 차단
|
||||
* - 빈 입력 (시스템 기본 'composer' / 'php') → 통과 (실행은 환경 의존)
|
||||
* - 정상 .phar 경로 + 잘못된 phpPath → exec 도달 전 차단
|
||||
*/
|
||||
class ComposerPathValidationTest extends TestCase
|
||||
{
|
||||
private static bool $loaded = false;
|
||||
|
||||
public static function setUpBeforeClass(): void
|
||||
{
|
||||
if (self::$loaded) {
|
||||
return;
|
||||
}
|
||||
|
||||
// ValidationApi 는 글로벌 네임스페이스이므로 \lang() 으로 조회됨 →
|
||||
// 글로벌 스코프에 정의된 스텁이 필요.
|
||||
require_once __DIR__ . '/stubs/lang_stub.php';
|
||||
|
||||
if (! defined('MIN_PHP_VERSION')) {
|
||||
define('MIN_PHP_VERSION', '8.2.0');
|
||||
}
|
||||
|
||||
if (! defined('CHECK_CONFIGURATION_LIBRARY')) {
|
||||
define('CHECK_CONFIGURATION_LIBRARY', true);
|
||||
}
|
||||
|
||||
require_once dirname(__DIR__, 3) . '/public/install/api/check-configuration.php';
|
||||
self::$loaded = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* private 메서드 호출 헬퍼.
|
||||
*/
|
||||
private function invoke(string $method, array $args): array
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$ref = new ReflectionClass($api);
|
||||
$m = $ref->getMethod($method);
|
||||
|
||||
// PHP 8.1+ 부터 ReflectionMethod 가 자동으로 private 접근 가능 — setAccessible 미호출.
|
||||
return $m->invokeArgs($api, $args);
|
||||
}
|
||||
|
||||
public function test_composer_path_with_shell_injection_is_rejected_before_exec(): void
|
||||
{
|
||||
$marker = sys_get_temp_dir() . '/g7_kve_test_' . bin2hex(random_bytes(4));
|
||||
$payload = 'sh -c "id > ' . $marker . '"';
|
||||
|
||||
$result = $this->invoke('validateComposerPath', [$payload, 'php']);
|
||||
|
||||
$this->assertFalse($result['valid'], '공백 포함 임의 명령 입력은 valid=false 여야 함');
|
||||
$this->assertNull($result['version']);
|
||||
$this->assertFileDoesNotExist($marker, '검증 단계에서 exec 가 실행되지 않아야 함 (RCE 차단)');
|
||||
}
|
||||
|
||||
public function test_composer_path_with_semicolon_injection_is_rejected(): void
|
||||
{
|
||||
$marker = sys_get_temp_dir() . '/g7_kve_test_' . bin2hex(random_bytes(4));
|
||||
$payload = '/bin/sh; touch ' . $marker;
|
||||
|
||||
$result = $this->invoke('validateComposerPath', [$payload, 'php']);
|
||||
|
||||
$this->assertFalse($result['valid']);
|
||||
$this->assertFileDoesNotExist($marker);
|
||||
}
|
||||
|
||||
public function test_composer_path_pointing_to_nonexistent_file_is_rejected(): void
|
||||
{
|
||||
$result = $this->invoke('validateComposerPath', ['/nonexistent/path/to/composer', 'php']);
|
||||
|
||||
$this->assertFalse($result['valid']);
|
||||
$this->assertNull($result['version']);
|
||||
}
|
||||
|
||||
public function test_composer_path_pointing_to_directory_is_rejected(): void
|
||||
{
|
||||
$result = $this->invoke('validateComposerPath', [sys_get_temp_dir(), 'php']);
|
||||
|
||||
$this->assertFalse($result['valid']);
|
||||
}
|
||||
|
||||
public function test_phar_path_with_invalid_php_path_is_rejected_before_exec(): void
|
||||
{
|
||||
$marker = sys_get_temp_dir() . '/g7_kve_test_' . bin2hex(random_bytes(4));
|
||||
|
||||
$tmpPhar = tempnam(sys_get_temp_dir(), 'g7-fake-composer-') . '.phar';
|
||||
file_put_contents($tmpPhar, '');
|
||||
chmod($tmpPhar, 0755);
|
||||
|
||||
try {
|
||||
$payload = 'sh -c "id > ' . $marker . '"';
|
||||
$result = $this->invoke('validateComposerPath', [$tmpPhar, $payload]);
|
||||
|
||||
$this->assertFalse($result['valid']);
|
||||
$this->assertFileDoesNotExist($marker);
|
||||
} finally {
|
||||
@unlink($tmpPhar);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_php_path_with_shell_injection_is_rejected_before_exec(): void
|
||||
{
|
||||
$marker = sys_get_temp_dir() . '/g7_kve_test_' . bin2hex(random_bytes(4));
|
||||
$payload = 'sh -c "id > ' . $marker . '"';
|
||||
|
||||
$result = $this->invoke('validatePhpPath', [$payload]);
|
||||
|
||||
$this->assertFalse($result['valid']);
|
||||
$this->assertFileDoesNotExist($marker);
|
||||
}
|
||||
|
||||
public function test_php_path_pointing_to_nonexistent_file_is_rejected(): void
|
||||
{
|
||||
$result = $this->invoke('validatePhpPath', ['/nonexistent/path/to/php']);
|
||||
|
||||
$this->assertFalse($result['valid']);
|
||||
}
|
||||
|
||||
public function test_empty_composer_path_falls_back_to_system_composer(): void
|
||||
{
|
||||
// 빈 입력은 'composer' 시스템 기본으로 시도 (실행 자체는 환경 의존)
|
||||
// 핵심은 validation 단계에서 거부되지 않고 exec 까지 도달한다는 것.
|
||||
$result = $this->invoke('validateComposerPath', ['', 'php']);
|
||||
|
||||
// composer 미설치 환경: exec 실패로 valid=false + error_composer_exec_failed 메시지
|
||||
// composer 설치 환경: valid=true
|
||||
// 두 경우 모두 "사전 거부" 와는 다른 메시지를 반환해야 한다.
|
||||
$this->assertContains($result['valid'], [true, false]);
|
||||
// 사전 거부 메시지("error_composer_exec_failed") 가 path='composer' 로 매핑되거나 성공.
|
||||
// shell injection 메시지 패턴이 들어가지 않는지 확인.
|
||||
$this->assertIsString($result['message']);
|
||||
}
|
||||
}
|
||||
@@ -43,9 +43,9 @@ class DeleteDirectoryTest extends TestCase
|
||||
define('INSTALLER_BASE_URL', '/install');
|
||||
}
|
||||
|
||||
// 인스톨러 함수 로드
|
||||
require_once base_path('public/install/includes/functions.php');
|
||||
require_once base_path('public/install/api/rollback-functions.php');
|
||||
// 인스톨러 함수 로드 (pure PHPUnit TestCase 라서 Laravel base_path() 사용 불가 — BASE_PATH 상수 사용)
|
||||
require_once BASE_PATH . '/public/install/includes/functions.php';
|
||||
require_once BASE_PATH . '/public/install/api/rollback-functions.php';
|
||||
|
||||
// 임시 디렉토리 생성
|
||||
$this->tempDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'g7_test_delete_' . uniqid();
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Installer;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* existing_db_action 변경 시 db_cleanup 재실행 보장 회귀 테스트
|
||||
*
|
||||
* 회귀 시나리오 (이슈 #319 부수 발견):
|
||||
* - 첫 시도에서 사용자가 'skip' 으로 진행 → db_cleanup 이 즉시 completed 마킹
|
||||
* - db_migrate 가 잔존 테이블에 막혀 fail
|
||||
* - 재시도에서 사용자가 'drop_tables' 동의
|
||||
* - install-process.php 가 state['existing_db_action']='drop_tables' 로 갱신
|
||||
* 하지만 completed_tasks 의 'db_cleanup' 마커가 그대로 남아 cleanup 함수가
|
||||
* 다시 호출되지 않음 → drop 안 됨 → db_migrate 가 동일 1050 에러로 fail
|
||||
*
|
||||
* 수정 가드: 사용자가 'drop_tables' 로 새로 동의하면 (이전과 다르면)
|
||||
* db_cleanup 마커를 completed_tasks 에서 제거하여 재실행 보장.
|
||||
*/
|
||||
class ExistingDbActionGuardTest extends TestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
if (! defined('BASE_PATH')) {
|
||||
define('BASE_PATH', sys_get_temp_dir() . '/g7-existing-db-action-test-' . bin2hex(random_bytes(4)));
|
||||
mkdir(BASE_PATH . '/storage', 0755, true);
|
||||
}
|
||||
|
||||
require_once dirname(__DIR__, 3) . '/public/install/includes/installer-state.php';
|
||||
}
|
||||
|
||||
public function test_drop_tables_resets_db_cleanup_when_previous_was_skip(): void
|
||||
{
|
||||
$state = [
|
||||
'existing_db_action' => 'skip',
|
||||
'completed_tasks' => ['composer_check', 'env_update', 'db_cleanup', 'db_migrate'],
|
||||
];
|
||||
|
||||
$guarded = applyExistingDbActionStateGuard($state, 'drop_tables');
|
||||
|
||||
$this->assertNotContains('db_cleanup', $guarded['completed_tasks']);
|
||||
$this->assertContains('composer_check', $guarded['completed_tasks']); // 다른 task 보존
|
||||
$this->assertContains('env_update', $guarded['completed_tasks']);
|
||||
}
|
||||
|
||||
public function test_drop_tables_resets_db_cleanup_when_previous_was_null(): void
|
||||
{
|
||||
$state = [
|
||||
'completed_tasks' => ['composer_check', 'db_cleanup'],
|
||||
];
|
||||
|
||||
$guarded = applyExistingDbActionStateGuard($state, 'drop_tables');
|
||||
|
||||
$this->assertNotContains('db_cleanup', $guarded['completed_tasks']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 시나리오 ③ (SSE → 폴링 이어서):
|
||||
* - 사용자가 drop_tables 동의 후 SSE 시작
|
||||
* - SSE 워커가 db_cleanup → db_migrate 일부 진행 중 SSE 구동 실패
|
||||
* - 폴링 모드로 재진입 시 install-process.php 가 동일 'drop_tables' 동의 받음
|
||||
* - state['existing_db_action']='drop_tables' (이전과 같음)
|
||||
* - 가드가 db_cleanup + db_migrate 마커를 모두 제거해야 cleanup 재실행 → 잔존
|
||||
* 테이블(이전 SSE 가 일부 만든 것 포함) drop → migrate 처음부터 → 1050 에러 회피
|
||||
*/
|
||||
public function test_drop_tables_resets_db_cleanup_and_migrate_even_when_already_drop_tables(): void
|
||||
{
|
||||
$state = [
|
||||
'existing_db_action' => 'drop_tables',
|
||||
'completed_tasks' => ['composer_check', 'db_cleanup', 'db_migrate'],
|
||||
];
|
||||
|
||||
$guarded = applyExistingDbActionStateGuard($state, 'drop_tables');
|
||||
|
||||
$this->assertNotContains('db_cleanup', $guarded['completed_tasks']);
|
||||
$this->assertNotContains('db_migrate', $guarded['completed_tasks']);
|
||||
$this->assertContains('composer_check', $guarded['completed_tasks']); // db 외 task 보존
|
||||
}
|
||||
|
||||
public function test_drop_tables_resets_db_seed_marker_too(): void
|
||||
{
|
||||
$state = [
|
||||
'completed_tasks' => ['db_cleanup', 'db_migrate', 'db_seed'],
|
||||
];
|
||||
|
||||
$guarded = applyExistingDbActionStateGuard($state, 'drop_tables');
|
||||
|
||||
$this->assertNotContains('db_cleanup', $guarded['completed_tasks']);
|
||||
$this->assertNotContains('db_migrate', $guarded['completed_tasks']);
|
||||
$this->assertNotContains('db_seed', $guarded['completed_tasks']);
|
||||
}
|
||||
|
||||
public function test_skip_does_not_reset_anything(): void
|
||||
{
|
||||
$state = [
|
||||
'existing_db_action' => 'drop_tables',
|
||||
'completed_tasks' => ['db_cleanup'],
|
||||
];
|
||||
|
||||
$guarded = applyExistingDbActionStateGuard($state, 'skip');
|
||||
|
||||
// skip 으로 변경해도 cleanup 마커 보존 (이미 drop 했음)
|
||||
$this->assertContains('db_cleanup', $guarded['completed_tasks']);
|
||||
}
|
||||
|
||||
public function test_handles_missing_completed_tasks_gracefully(): void
|
||||
{
|
||||
$state = ['existing_db_action' => 'skip'];
|
||||
|
||||
$guarded = applyExistingDbActionStateGuard($state, 'drop_tables');
|
||||
|
||||
$this->assertSame([], $guarded['completed_tasks']);
|
||||
}
|
||||
|
||||
public function test_returns_array_values_so_keys_are_sequential(): void
|
||||
{
|
||||
$state = [
|
||||
'existing_db_action' => 'skip',
|
||||
'completed_tasks' => ['composer_check', 'db_cleanup', 'env_update'],
|
||||
];
|
||||
|
||||
$guarded = applyExistingDbActionStateGuard($state, 'drop_tables');
|
||||
|
||||
// array_filter 후 array_values 적용으로 순차 키 보장
|
||||
$this->assertSame([0, 1], array_keys($guarded['completed_tasks']));
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀: 다른 워커가 활성 진행 중이면 db_* 마커 reset 금지.
|
||||
*
|
||||
* 시나리오:
|
||||
* - SSE 워커가 db_cleanup/db_migrate/db_seed 완료 후 module/plugin 진행 중
|
||||
* - 클라이언트가 폴링 fallback 시도 → install-process.php 호출
|
||||
* - install-process.php 가 applyExistingDbActionStateGuard('drop_tables') 호출
|
||||
* - 그 시점 active_worker_id 는 SSE 워커, last_heartbeat 는 fresh
|
||||
* - 가드가 db_* 마커 제거하면 그 후 SSE 워커가 module 완료 markTaskCompleted 시
|
||||
* state.json 에는 db_* 가 빠진 채로 module_* 만 추가됨 (UI 에 DB pending 표시 회귀)
|
||||
*
|
||||
* 의도: 다른 워커가 살아있으면 state 변경 금지 (race 회피). worker 가 죽었을 때만
|
||||
* (heartbeat stale 또는 active_worker_id 부재) reset 하여 폴링 재진입 케이스 커버.
|
||||
*/
|
||||
public function test_drop_tables_does_not_reset_when_other_worker_is_active(): void
|
||||
{
|
||||
$state = [
|
||||
'existing_db_action' => 'drop_tables',
|
||||
'completed_tasks' => ['db_cleanup', 'db_migrate', 'db_seed', 'module_install:sirsoft-board'],
|
||||
'active_worker_id' => 'abc123',
|
||||
'last_heartbeat' => time(), // fresh heartbeat
|
||||
];
|
||||
|
||||
$guarded = applyExistingDbActionStateGuard($state, 'drop_tables');
|
||||
|
||||
// 다른 워커 진행 중이므로 db_* 마커 보존 (race 회피)
|
||||
$this->assertContains('db_cleanup', $guarded['completed_tasks']);
|
||||
$this->assertContains('db_migrate', $guarded['completed_tasks']);
|
||||
$this->assertContains('db_seed', $guarded['completed_tasks']);
|
||||
$this->assertContains('module_install:sirsoft-board', $guarded['completed_tasks']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀: stale 워커 (heartbeat 15초 초과) 인 경우엔 reset 정상 동작 — 죽은 워커가
|
||||
* cleanup 만 진행 후 끊긴 케이스를 폴링이 takeover 할 수 있어야 한다.
|
||||
*/
|
||||
public function test_drop_tables_resets_when_other_worker_is_stale(): void
|
||||
{
|
||||
$state = [
|
||||
'existing_db_action' => 'drop_tables',
|
||||
'completed_tasks' => ['db_cleanup', 'db_migrate'],
|
||||
'active_worker_id' => 'abc123',
|
||||
'last_heartbeat' => time() - 60, // stale heartbeat (60초 전)
|
||||
];
|
||||
|
||||
$guarded = applyExistingDbActionStateGuard($state, 'drop_tables');
|
||||
|
||||
// worker 가 죽었으므로 reset 진행 (기존 의도된 동작)
|
||||
$this->assertNotContains('db_cleanup', $guarded['completed_tasks']);
|
||||
$this->assertNotContains('db_migrate', $guarded['completed_tasks']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀: active_worker_id 부재 시 reset 정상 동작 — 처음 진입하는 폴링 워커는
|
||||
* race 우려가 없으므로 기존 동작 보존.
|
||||
*/
|
||||
public function test_drop_tables_resets_when_no_active_worker(): void
|
||||
{
|
||||
$state = [
|
||||
'existing_db_action' => 'drop_tables',
|
||||
'completed_tasks' => ['db_cleanup', 'db_migrate'],
|
||||
// active_worker_id 키 자체가 없음
|
||||
];
|
||||
|
||||
$guarded = applyExistingDbActionStateGuard($state, 'drop_tables');
|
||||
|
||||
$this->assertNotContains('db_cleanup', $guarded['completed_tasks']);
|
||||
$this->assertNotContains('db_migrate', $guarded['completed_tasks']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Installer;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* 인스톨러 진입 가드 회귀 테스트
|
||||
*
|
||||
* 설치 완료 후 public/install/api/ 하위 모든 엔드포인트가 비즈니스 로직 진입 전
|
||||
* HTTP 410 으로 차단되어야 하는 정책의 단위 검증.
|
||||
*
|
||||
* 판정 신호:
|
||||
* 1. {BASE_PATH}/storage/app/g7_installed 락 파일 존재
|
||||
* 2. .env 의 INSTALLER_COMPLETED=true (또는 1, yes)
|
||||
*
|
||||
* exit/header 동작은 단위 테스트 내에서 직접 검증할 수 없으므로
|
||||
* installer_is_completed() 의 결정론적 판정 결과만 검증한다.
|
||||
* 410 응답 본문은 PoC 매뉴얼 검증 영역.
|
||||
*/
|
||||
class InstallerGuardTest extends TestCase
|
||||
{
|
||||
private static string $tempBase = '';
|
||||
|
||||
public static function setUpBeforeClass(): void
|
||||
{
|
||||
self::$tempBase = sys_get_temp_dir() . '/g7-installer-guard-test-' . bin2hex(random_bytes(4));
|
||||
mkdir(self::$tempBase . '/storage/app', 0755, true);
|
||||
|
||||
// BASE_PATH 가 다른 테스트에서 이미 정의되었을 수 있다.
|
||||
// 그 경우 폴백 (installer_resolve_base_path) 가 본 파일 위치 기준으로 결정되므로
|
||||
// 본 테스트는 정의된 BASE_PATH 를 그대로 사용하고, 그 안에 격리 디렉토리를 만든다.
|
||||
if (! defined('BASE_PATH')) {
|
||||
define('BASE_PATH', self::$tempBase);
|
||||
} else {
|
||||
// 다른 테스트의 BASE_PATH 와 공존 — 그 디렉토리 안에 lock/.env 를 두고 정리.
|
||||
self::$tempBase = BASE_PATH;
|
||||
if (! is_dir(BASE_PATH . '/storage/app')) {
|
||||
@mkdir(BASE_PATH . '/storage/app', 0755, true);
|
||||
}
|
||||
}
|
||||
|
||||
require_once dirname(__DIR__, 3) . '/public/install/api/_guard.php';
|
||||
}
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->cleanup();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->cleanup();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function cleanup(): void
|
||||
{
|
||||
@unlink(BASE_PATH . '/storage/app/g7_installed');
|
||||
@unlink(BASE_PATH . '/.env');
|
||||
}
|
||||
|
||||
public function test_no_signals_means_not_completed(): void
|
||||
{
|
||||
$this->assertFalse(installer_is_completed());
|
||||
}
|
||||
|
||||
public function test_lock_file_only_marks_completed(): void
|
||||
{
|
||||
file_put_contents(BASE_PATH . '/storage/app/g7_installed', '');
|
||||
|
||||
$this->assertTrue(installer_is_completed());
|
||||
}
|
||||
|
||||
public function test_env_flag_only_marks_completed(): void
|
||||
{
|
||||
file_put_contents(BASE_PATH . '/.env', "APP_ENV=local\nINSTALLER_COMPLETED=true\n");
|
||||
|
||||
$this->assertTrue(installer_is_completed());
|
||||
}
|
||||
|
||||
public function test_env_flag_accepts_quoted_true(): void
|
||||
{
|
||||
file_put_contents(BASE_PATH . '/.env', 'INSTALLER_COMPLETED="true"' . "\n");
|
||||
|
||||
$this->assertTrue(installer_is_completed());
|
||||
}
|
||||
|
||||
public function test_env_flag_accepts_one(): void
|
||||
{
|
||||
file_put_contents(BASE_PATH . '/.env', 'INSTALLER_COMPLETED=1' . "\n");
|
||||
|
||||
$this->assertTrue(installer_is_completed());
|
||||
}
|
||||
|
||||
public function test_env_flag_false_does_not_mark_completed(): void
|
||||
{
|
||||
file_put_contents(BASE_PATH . '/.env', "APP_ENV=local\nINSTALLER_COMPLETED=false\n");
|
||||
|
||||
$this->assertFalse(installer_is_completed());
|
||||
}
|
||||
|
||||
public function test_env_flag_missing_does_not_mark_completed(): void
|
||||
{
|
||||
file_put_contents(BASE_PATH . '/.env', "APP_ENV=local\n");
|
||||
|
||||
$this->assertFalse(installer_is_completed());
|
||||
}
|
||||
|
||||
public function test_both_signals_present_marks_completed(): void
|
||||
{
|
||||
file_put_contents(BASE_PATH . '/storage/app/g7_installed', '');
|
||||
file_put_contents(BASE_PATH . '/.env', 'INSTALLER_COMPLETED=true' . "\n");
|
||||
|
||||
$this->assertTrue(installer_is_completed());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Installer;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* 인스톨러 런타임 헬퍼 단위 테스트
|
||||
*
|
||||
* public/install/includes/installer-runtime.php 의 헬퍼 함수들을 검증한다.
|
||||
* 인스톨러는 Laravel 외부에서 동작하므로 BASE_PATH 상수와 헬퍼 인클루드를
|
||||
* 테스트 setUp 단계에서 직접 처리한다.
|
||||
*
|
||||
* @see https://github.com/gnuboard/g7/issues/23
|
||||
*/
|
||||
class InstallerRuntimeHelperTest extends TestCase
|
||||
{
|
||||
private string $tempBase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
// 격리된 BASE_PATH — 운영 환경 storage/installer 와 충돌 방지
|
||||
$this->tempBase = sys_get_temp_dir() . '/g7-installer-runtime-test-' . bin2hex(random_bytes(4));
|
||||
mkdir($this->tempBase . '/storage/installer', 0755, true);
|
||||
|
||||
if (! defined('BASE_PATH')) {
|
||||
define('BASE_PATH', $this->tempBase);
|
||||
}
|
||||
|
||||
// INSTALLER_RUNTIME_PATH 는 BASE_PATH 기반으로 한 번만 정의되므로,
|
||||
// 첫 테스트가 끝까지 책임진다 (BASE_PATH 자체가 const 라 재정의 불가).
|
||||
// installer-runtime.php 자체에 escapeEnvValue polyfill 이 있어 functions.php
|
||||
// 미로드 환경에서도 mergeRuntimeIntoEnv 가 정상 동작한다.
|
||||
require_once dirname(__DIR__, 3) . '/public/install/includes/installer-runtime.php';
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
// INSTALLER_RUNTIME_PATH 는 첫 정의된 BASE_PATH 에 묶여있으므로
|
||||
// 그 파일만 정리하고, 임시 디렉토리는 시스템 temp cleaner 에 위임
|
||||
if (defined('INSTALLER_RUNTIME_PATH') && is_file(INSTALLER_RUNTIME_PATH)) {
|
||||
@unlink(INSTALLER_RUNTIME_PATH);
|
||||
}
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_read_returns_null_when_file_absent(): void
|
||||
{
|
||||
$this->assertFileDoesNotExist(INSTALLER_RUNTIME_PATH);
|
||||
$this->assertNull(readInstallerRuntime());
|
||||
}
|
||||
|
||||
public function test_write_creates_file_atomically(): void
|
||||
{
|
||||
$data = [
|
||||
'db' => ['write' => ['host' => '127.0.0.1', 'port' => '3306']],
|
||||
'app' => ['key' => 'base64:abc'],
|
||||
];
|
||||
|
||||
$this->assertTrue(writeInstallerRuntime($data));
|
||||
$this->assertFileExists(INSTALLER_RUNTIME_PATH);
|
||||
|
||||
$read = readInstallerRuntime();
|
||||
$this->assertSame($data['db']['write']['host'], $read['db']['write']['host']);
|
||||
$this->assertSame('base64:abc', $read['app']['key']);
|
||||
}
|
||||
|
||||
public function test_write_then_delete_round_trip(): void
|
||||
{
|
||||
writeInstallerRuntime(['app' => ['key' => 'base64:xyz']]);
|
||||
$this->assertFileExists(INSTALLER_RUNTIME_PATH);
|
||||
|
||||
$this->assertTrue(deleteInstallerRuntime());
|
||||
$this->assertFileDoesNotExist(INSTALLER_RUNTIME_PATH);
|
||||
|
||||
// 멱등성 — 부재 상태에서 재호출 OK
|
||||
$this->assertTrue(deleteInstallerRuntime());
|
||||
}
|
||||
|
||||
public function test_read_returns_null_for_corrupted_file(): void
|
||||
{
|
||||
file_put_contents(INSTALLER_RUNTIME_PATH, "<?php\nreturn 'not-an-array';\n");
|
||||
|
||||
$this->assertNull(readInstallerRuntime());
|
||||
}
|
||||
|
||||
public function test_generate_app_key_inline_produces_valid_laravel_format(): void
|
||||
{
|
||||
$key = generateAppKeyInline();
|
||||
|
||||
$this->assertStringStartsWith('base64:', $key);
|
||||
|
||||
$raw = base64_decode(substr($key, 7), true);
|
||||
$this->assertNotFalse($raw, 'base64 portion must decode');
|
||||
$this->assertSame(32, strlen($raw), 'AES-256-CBC requires 32-byte key');
|
||||
|
||||
// 매 호출마다 다른 값
|
||||
$this->assertNotSame($key, generateAppKeyInline());
|
||||
}
|
||||
|
||||
public function test_build_runtime_preserves_existing_app_key(): void
|
||||
{
|
||||
$existingKey = generateAppKeyInline();
|
||||
writeInstallerRuntime(['app' => ['key' => $existingKey]]);
|
||||
|
||||
$built = buildInstallerRuntimeFromState([
|
||||
'db_write_host' => 'localhost',
|
||||
'db_write_database' => 'g7',
|
||||
'db_write_username' => 'root',
|
||||
]);
|
||||
|
||||
// 재시도 시 키 보존 — 새 키로 덮어쓰지 않음
|
||||
$this->assertSame($existingKey, $built['app']['key']);
|
||||
}
|
||||
|
||||
public function test_build_runtime_generates_new_app_key_when_absent(): void
|
||||
{
|
||||
$this->assertFileDoesNotExist(INSTALLER_RUNTIME_PATH);
|
||||
|
||||
$built = buildInstallerRuntimeFromState([
|
||||
'db_write_host' => 'localhost',
|
||||
'db_write_database' => 'g7',
|
||||
'db_write_username' => 'root',
|
||||
]);
|
||||
|
||||
$this->assertStringStartsWith('base64:', $built['app']['key']);
|
||||
$this->assertSame(32, strlen(base64_decode(substr($built['app']['key'], 7), true)));
|
||||
}
|
||||
|
||||
public function test_build_runtime_includes_separate_read_when_specified(): void
|
||||
{
|
||||
$built = buildInstallerRuntimeFromState([
|
||||
'db_write_host' => 'write-host',
|
||||
'db_write_database' => 'g7',
|
||||
'db_read_host' => 'read-host',
|
||||
'db_read_database' => 'g7_replica',
|
||||
]);
|
||||
|
||||
$this->assertArrayHasKey('read', $built['db']);
|
||||
$this->assertSame('read-host', $built['db']['read']['host']);
|
||||
$this->assertSame('g7_replica', $built['db']['read']['database']);
|
||||
}
|
||||
|
||||
public function test_build_runtime_omits_read_when_same_as_write(): void
|
||||
{
|
||||
$built = buildInstallerRuntimeFromState([
|
||||
'db_write_host' => 'localhost',
|
||||
'db_read_host' => 'localhost', // 동일 호스트 → 별도 read 불필요
|
||||
]);
|
||||
|
||||
$this->assertArrayNotHasKey('read', $built['db']);
|
||||
}
|
||||
|
||||
public function test_build_runtime_falls_back_to_legacy_db_keys(): void
|
||||
{
|
||||
// 일부 인스톨러 경로가 db_host/db_database 등 prefix 없는 키를 사용
|
||||
$built = buildInstallerRuntimeFromState([
|
||||
'db_host' => 'legacy-host',
|
||||
'db_database' => 'g7',
|
||||
'db_username' => 'admin',
|
||||
]);
|
||||
|
||||
$this->assertSame('legacy-host', $built['db']['write']['host']);
|
||||
$this->assertSame('g7', $built['db']['write']['database']);
|
||||
$this->assertSame('admin', $built['db']['write']['username']);
|
||||
}
|
||||
|
||||
public function test_merge_replaces_app_key_line_in_env_content(): void
|
||||
{
|
||||
$envContent = "APP_NAME=Test\nAPP_KEY=\nDB_HOST=localhost\n";
|
||||
$runtime = ['app' => ['key' => 'base64:abc']];
|
||||
|
||||
$merged = mergeRuntimeIntoEnv($envContent, $runtime);
|
||||
|
||||
$this->assertStringContainsString('APP_KEY=base64:abc', $merged);
|
||||
$this->assertStringNotContainsString("APP_KEY=\n", $merged);
|
||||
$this->assertStringContainsString('DB_HOST=localhost', $merged); // 다른 라인 보존
|
||||
}
|
||||
|
||||
public function test_merge_appends_app_key_when_not_present(): void
|
||||
{
|
||||
$envContent = "APP_NAME=Test\nDB_HOST=localhost\n";
|
||||
$runtime = ['app' => ['key' => 'base64:xyz']];
|
||||
|
||||
$merged = mergeRuntimeIntoEnv($envContent, $runtime);
|
||||
|
||||
$this->assertStringContainsString('APP_KEY=base64:xyz', $merged);
|
||||
}
|
||||
|
||||
public function test_merge_appends_installer_completed_flag(): void
|
||||
{
|
||||
$envContent = "APP_KEY=base64:test\n";
|
||||
$runtime = ['app' => ['key' => 'base64:test']];
|
||||
|
||||
$merged = mergeRuntimeIntoEnv($envContent, $runtime);
|
||||
|
||||
$this->assertStringContainsString('INSTALLER_COMPLETED=true', $merged);
|
||||
$this->assertStringContainsString('# Installation Status', $merged);
|
||||
}
|
||||
|
||||
public function test_merge_does_not_duplicate_installer_completed(): void
|
||||
{
|
||||
$envContent = "APP_KEY=base64:test\n\nINSTALLER_COMPLETED=true\n";
|
||||
$runtime = ['app' => ['key' => 'base64:test']];
|
||||
|
||||
$merged = mergeRuntimeIntoEnv($envContent, $runtime);
|
||||
|
||||
// 정확히 1회만 등장
|
||||
$count = substr_count($merged, 'INSTALLER_COMPLETED=true');
|
||||
$this->assertSame(1, $count, 'INSTALLER_COMPLETED 가 중복되지 않아야 함');
|
||||
}
|
||||
|
||||
public function test_merge_skips_app_key_when_invalid_format(): void
|
||||
{
|
||||
$envContent = "APP_KEY=existing\n";
|
||||
$runtime = ['app' => ['key' => 'not-base64-format']];
|
||||
|
||||
$merged = mergeRuntimeIntoEnv($envContent, $runtime);
|
||||
|
||||
// base64: prefix 가 없으면 치환하지 않음
|
||||
$this->assertStringContainsString('APP_KEY=existing', $merged);
|
||||
$this->assertStringNotContainsString('APP_KEY=not-base64', $merged);
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀 테스트: state.json 결손 시에도 runtime 의 DB 정보로 .env 가 완성되어야 한다.
|
||||
*
|
||||
* 회귀 시나리오: setInstallationCompleteSSE 가 state.json 을 finalize 호출 전에
|
||||
* 삭제 → finalize 가 generateEnvContent() 호출 시 state.config 를 못 읽어 .env.example
|
||||
* 의 placeholder 값(127.0.0.1 / g7 / root / 빈 비밀번호) 으로 .env 가 작성되던 회귀.
|
||||
*/
|
||||
public function test_merge_replaces_db_credentials_with_runtime_values(): void
|
||||
{
|
||||
$envContent = <<<'ENV'
|
||||
DB_WRITE_HOST=127.0.0.1
|
||||
DB_WRITE_PORT=3306
|
||||
DB_WRITE_DATABASE=g7
|
||||
DB_WRITE_USERNAME=root
|
||||
DB_WRITE_PASSWORD=
|
||||
DB_PREFIX=g7_
|
||||
APP_KEY=
|
||||
ENV;
|
||||
|
||||
$runtime = [
|
||||
'db' => [
|
||||
'write' => [
|
||||
'host' => 'real-host.example.com',
|
||||
'port' => '3307',
|
||||
'database' => 'real_db',
|
||||
'username' => 'real_user',
|
||||
'password' => 'real_pass',
|
||||
],
|
||||
'prefix' => 'real_',
|
||||
],
|
||||
'app' => ['key' => 'base64:' . base64_encode(str_repeat('a', 32))],
|
||||
];
|
||||
|
||||
$merged = mergeRuntimeIntoEnv($envContent, $runtime);
|
||||
|
||||
$this->assertStringContainsString('DB_WRITE_HOST=real-host.example.com', $merged);
|
||||
$this->assertStringContainsString('DB_WRITE_PORT=3307', $merged);
|
||||
$this->assertStringContainsString('DB_WRITE_DATABASE=real_db', $merged);
|
||||
$this->assertStringContainsString('DB_WRITE_USERNAME=real_user', $merged);
|
||||
$this->assertStringContainsString('DB_WRITE_PASSWORD="real_pass"', $merged);
|
||||
$this->assertStringContainsString('DB_PREFIX=real_', $merged);
|
||||
|
||||
// Read 라인도 write 와 동기화되어 치환되어야 함
|
||||
$this->assertStringNotContainsString('DB_WRITE_HOST=127.0.0.1', $merged);
|
||||
$this->assertStringNotContainsString('DB_WRITE_DATABASE=g7' . PHP_EOL, $merged);
|
||||
}
|
||||
|
||||
public function test_merge_syncs_read_with_write_when_read_not_specified(): void
|
||||
{
|
||||
$envContent = "DB_READ_HOST=127.0.0.1\nDB_READ_DATABASE=g7\nDB_READ_USERNAME=root\nDB_READ_PASSWORD=\n";
|
||||
|
||||
$runtime = [
|
||||
'db' => [
|
||||
'write' => [
|
||||
'host' => 'w-host',
|
||||
'port' => '3306',
|
||||
'database' => 'wdb',
|
||||
'username' => 'wu',
|
||||
'password' => 'wp',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$merged = mergeRuntimeIntoEnv($envContent, $runtime);
|
||||
|
||||
// read 미지정 시 write 값으로 동기
|
||||
$this->assertStringContainsString('DB_READ_HOST=w-host', $merged);
|
||||
$this->assertStringContainsString('DB_READ_DATABASE=wdb', $merged);
|
||||
$this->assertStringContainsString('DB_READ_USERNAME=wu', $merged);
|
||||
$this->assertStringContainsString('DB_READ_PASSWORD="wp"', $merged);
|
||||
}
|
||||
|
||||
public function test_merge_uses_separate_read_when_specified(): void
|
||||
{
|
||||
$envContent = "DB_READ_HOST=\nDB_READ_DATABASE=\n";
|
||||
|
||||
$runtime = [
|
||||
'db' => [
|
||||
'write' => ['host' => 'w-host', 'database' => 'wdb', 'username' => 'wu', 'password' => 'wp'],
|
||||
'read' => ['host' => 'r-host', 'database' => 'rdb', 'username' => 'ru', 'password' => 'rp'],
|
||||
],
|
||||
];
|
||||
|
||||
$merged = mergeRuntimeIntoEnv($envContent, $runtime);
|
||||
|
||||
$this->assertStringContainsString('DB_READ_HOST=r-host', $merged);
|
||||
$this->assertStringContainsString('DB_READ_DATABASE=rdb', $merged);
|
||||
}
|
||||
|
||||
public function test_merge_appends_db_lines_when_absent_from_template(): void
|
||||
{
|
||||
$envContent = "APP_NAME=Test\n";
|
||||
|
||||
$runtime = [
|
||||
'db' => [
|
||||
'write' => [
|
||||
'host' => 'h',
|
||||
'port' => '3306',
|
||||
'database' => 'd',
|
||||
'username' => 'u',
|
||||
'password' => 'p',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$merged = mergeRuntimeIntoEnv($envContent, $runtime);
|
||||
|
||||
// .env.example 에 라인이 없는 비표준 케이스 — 끝에 추가
|
||||
$this->assertStringContainsString('DB_WRITE_HOST=h', $merged);
|
||||
$this->assertStringContainsString('DB_WRITE_DATABASE=d', $merged);
|
||||
}
|
||||
|
||||
public function test_merge_preserves_db_lines_when_runtime_has_no_db(): void
|
||||
{
|
||||
$envContent = "DB_WRITE_HOST=user-input.com\nAPP_KEY=\n";
|
||||
|
||||
// runtime 에 db 키 자체가 없는 케이스 (이상 상태) — 기존 .env 값 보존
|
||||
$runtime = ['app' => ['key' => 'base64:' . base64_encode(str_repeat('x', 32))]];
|
||||
|
||||
$merged = mergeRuntimeIntoEnv($envContent, $runtime);
|
||||
|
||||
$this->assertStringContainsString('DB_WRITE_HOST=user-input.com', $merged);
|
||||
}
|
||||
|
||||
public function test_merge_escapes_password_with_special_characters(): void
|
||||
{
|
||||
$envContent = "DB_WRITE_PASSWORD=\n";
|
||||
|
||||
$runtime = [
|
||||
'db' => [
|
||||
'write' => [
|
||||
'host' => 'h',
|
||||
'database' => 'd',
|
||||
'username' => 'u',
|
||||
'password' => 'p@ss"with$pecial',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$merged = mergeRuntimeIntoEnv($envContent, $runtime);
|
||||
|
||||
// escapeEnvValue 가 큰따옴표/백슬래시 escape + 큰따옴표 wrapping
|
||||
$this->assertStringContainsString('DB_WRITE_PASSWORD="p@ss\\"with$pecial"', $merged);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Installer;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use ReflectionClass;
|
||||
use ValidationApi;
|
||||
|
||||
/**
|
||||
* 인스톨러 추가 보안 강화 회귀 테스트
|
||||
*
|
||||
* 후속 감사로 추가 발견된 5개 이슈에 대한 회귀 가드:
|
||||
* - getComposerCommand/Display 의 공백 분기 RCE
|
||||
* - save-extensions 식별자 셸 주입
|
||||
* - checkCorePendingPath 경로 traversal/정보 노출
|
||||
* - escapeEnvValue 개행 라인 주입
|
||||
* - PDO DSN 파라미터 주입
|
||||
*/
|
||||
class InstallerSecurityHardeningTest extends TestCase
|
||||
{
|
||||
private static bool $loaded = false;
|
||||
private static string $tempBase = '';
|
||||
|
||||
public static function setUpBeforeClass(): void
|
||||
{
|
||||
if (self::$loaded) {
|
||||
return;
|
||||
}
|
||||
|
||||
require_once __DIR__ . '/stubs/lang_stub.php';
|
||||
|
||||
if (! defined('MIN_PHP_VERSION')) {
|
||||
define('MIN_PHP_VERSION', '8.2.0');
|
||||
}
|
||||
if (! defined('CHECK_CONFIGURATION_LIBRARY')) {
|
||||
define('CHECK_CONFIGURATION_LIBRARY', true);
|
||||
}
|
||||
|
||||
self::$tempBase = sys_get_temp_dir() . '/g7-installer-hardening-' . bin2hex(random_bytes(4));
|
||||
@mkdir(self::$tempBase . '/storage/app', 0755, true);
|
||||
|
||||
if (! defined('BASE_PATH')) {
|
||||
define('BASE_PATH', self::$tempBase);
|
||||
} else {
|
||||
self::$tempBase = BASE_PATH;
|
||||
@mkdir(BASE_PATH . '/storage/app', 0755, true);
|
||||
}
|
||||
|
||||
if (! defined('STATE_PATH')) {
|
||||
define('STATE_PATH', BASE_PATH . '/storage/installer-state.json');
|
||||
}
|
||||
|
||||
require_once dirname(__DIR__, 3) . '/public/install/api/check-configuration.php';
|
||||
require_once dirname(__DIR__, 3) . '/public/install/includes/installer-state.php';
|
||||
require_once dirname(__DIR__, 3) . '/public/install/includes/functions.php';
|
||||
require_once dirname(__DIR__, 3) . '/public/install/includes/task-runner.php';
|
||||
|
||||
self::$loaded = true;
|
||||
}
|
||||
|
||||
private function invokePrivate(object $obj, string $method, array $args)
|
||||
{
|
||||
$ref = new ReflectionClass($obj);
|
||||
$m = $ref->getMethod($method);
|
||||
return $m->invokeArgs($obj, $args);
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트가 도중 종료되어도 PO 작업 디렉토리에 state.json 잔여물이 남지 않도록 항상 정리.
|
||||
* BASE_PATH 가 다른 테스트 인프라에 의해 프로젝트 루트로 바인딩되는 경우를 대비해
|
||||
* 프로젝트 루트의 storage/installer-state.json 도 함께 정리.
|
||||
*/
|
||||
protected function tearDown(): void
|
||||
{
|
||||
@unlink(STATE_PATH);
|
||||
$projectStateFile = dirname(__DIR__, 3) . '/storage/installer-state.json';
|
||||
@unlink($projectStateFile);
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트별 임시 state.json 작성/삭제 도우미.
|
||||
*/
|
||||
private function writeState(array $config): void
|
||||
{
|
||||
$state = ['config' => $config];
|
||||
@file_put_contents(STATE_PATH, json_encode($state));
|
||||
}
|
||||
|
||||
private function clearState(): void
|
||||
{
|
||||
@unlink(STATE_PATH);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Critical-1 — getComposerCommand 공백 분기 RCE 차단
|
||||
// ========================================================================
|
||||
|
||||
public function test_getComposerCommand_rejects_space_containing_input_falls_back_to_composer(): void
|
||||
{
|
||||
$this->writeState(['composer_binary' => 'sh -c "id > /tmp/g7_should_not_run"']);
|
||||
|
||||
$cmd = getComposerCommand();
|
||||
|
||||
$this->assertSame('composer', $cmd, '공백 포함 입력은 시스템 기본 composer 로 폴백');
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommand_rejects_shell_metachars_falls_back_to_composer(): void
|
||||
{
|
||||
foreach ([
|
||||
'/bin/sh; touch /tmp/x',
|
||||
'/bin/composer && id',
|
||||
'$(id)',
|
||||
'`id`',
|
||||
"/bin/composer\nrm -rf /",
|
||||
] as $payload) {
|
||||
$this->writeState(['composer_binary' => $payload]);
|
||||
$cmd = getComposerCommand();
|
||||
$this->assertSame('composer', $cmd, "셸 메타문자 포함 입력 거부 (입력: {$payload})");
|
||||
}
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommand_rejects_nonexistent_path(): void
|
||||
{
|
||||
$this->writeState(['composer_binary' => '/nonexistent/path/to/composer']);
|
||||
|
||||
$cmd = getComposerCommand();
|
||||
|
||||
$this->assertSame('composer', $cmd);
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommand_empty_returns_default(): void
|
||||
{
|
||||
$this->writeState(['composer_binary' => '']);
|
||||
|
||||
$this->assertSame('composer', getComposerCommand());
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_getComposerCommandForDisplay_does_not_leak_shell_payload(): void
|
||||
{
|
||||
$this->writeState(['composer_binary' => 'rm -rf /']);
|
||||
|
||||
$display = getComposerCommandForDisplay();
|
||||
|
||||
$this->assertSame('composer', $display, '셸 페이로드는 디스플레이에도 노출되지 않음');
|
||||
$this->assertStringNotContainsString('rm', $display);
|
||||
$this->clearState();
|
||||
}
|
||||
|
||||
public function test_isInstallerExecutablePath_rejects_metachars(): void
|
||||
{
|
||||
foreach (['foo bar', 'a;b', 'a`b', 'a$b', 'a|b', "a\nb", 'a"b', "a'b", 'a\\b'] as $bad) {
|
||||
$this->assertFalse(isInstallerExecutablePath($bad), "메타문자 거부: {$bad}");
|
||||
}
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// High-2 — checkCorePendingPath traversal 차단
|
||||
// ========================================================================
|
||||
|
||||
public function test_checkCorePendingPath_rejects_parent_traversal(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
|
||||
foreach (['../../../etc', '..', 'foo/../bar', 'foo/..\\bar'] as $bad) {
|
||||
$_GET = ['path' => $bad];
|
||||
ob_start();
|
||||
$this->invokePrivate($api, 'checkCorePendingPath', []);
|
||||
$body = ob_get_clean();
|
||||
$decoded = json_decode($body, true);
|
||||
|
||||
$this->assertIsArray($decoded);
|
||||
$this->assertFalse($decoded['success'], "traversal 거부: {$bad}");
|
||||
// 단일 통일 메시지로 enumeration 신호 차단
|
||||
$this->assertSame('error_core_pending_path_invalid', $decoded['message']);
|
||||
}
|
||||
$_GET = [];
|
||||
}
|
||||
|
||||
public function test_checkCorePendingPath_rejects_null_byte(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$_GET = ['path' => "valid\0../etc"];
|
||||
ob_start();
|
||||
$this->invokePrivate($api, 'checkCorePendingPath', []);
|
||||
$body = ob_get_clean();
|
||||
$decoded = json_decode($body, true);
|
||||
|
||||
$this->assertFalse($decoded['success']);
|
||||
$_GET = [];
|
||||
}
|
||||
|
||||
public function test_checkCorePendingPath_returns_uniform_message_for_nonexistent(): void
|
||||
{
|
||||
$api = new ValidationApi();
|
||||
$_GET = ['path' => '/nonexistent/g7-test-' . bin2hex(random_bytes(4))];
|
||||
ob_start();
|
||||
$this->invokePrivate($api, 'checkCorePendingPath', []);
|
||||
$body = ob_get_clean();
|
||||
$decoded = json_decode($body, true);
|
||||
|
||||
$this->assertFalse($decoded['success']);
|
||||
// 존재 여부/타입 차이를 응답에 노출하지 않음
|
||||
$this->assertSame('error_core_pending_path_invalid', $decoded['message']);
|
||||
$_GET = [];
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Medium-1 — escapeEnvValue 개행 제거
|
||||
// ========================================================================
|
||||
|
||||
public function test_escapeEnvValue_strips_newlines(): void
|
||||
{
|
||||
$payload = "secret\nINJECTED=true";
|
||||
$result = escapeEnvValue($payload);
|
||||
|
||||
// 핵심 보안 속성: 결과에 개행 문자가 없어야 한다 (라인 주입 차단).
|
||||
// INJECTED=true 가 따옴표 내부 일부로 포함되는 것은 문제 아님 — .env 파서는
|
||||
// 따옴표 닫힘 전까지 단일 값으로만 해석.
|
||||
$this->assertStringNotContainsString("\n", $result, 'LF 가 결과에 포함되면 안 됨');
|
||||
$this->assertStringNotContainsString("\r", $result);
|
||||
// 결과는 따옴표로 시작/종료 (라인 주입이 성립하려면 따옴표가 닫힌 뒤 개행이 와야 하나 개행이 제거됨)
|
||||
$this->assertStringStartsWith('"', $result);
|
||||
$this->assertStringEndsWith('"', $result);
|
||||
}
|
||||
|
||||
public function test_escapeEnvValue_strips_crlf(): void
|
||||
{
|
||||
$result = escapeEnvValue("a\r\nb");
|
||||
|
||||
$this->assertSame('"ab"', $result);
|
||||
}
|
||||
|
||||
public function test_escapeEnvValue_preserves_normal_password(): void
|
||||
{
|
||||
$result = escapeEnvValue('p@ssw0rd!#$%');
|
||||
|
||||
$this->assertSame('"p@ssw0rd!#$%"', $result);
|
||||
}
|
||||
|
||||
public function test_escapeEnvValue_escapes_quotes_and_backslashes(): void
|
||||
{
|
||||
$result = escapeEnvValue('a"b\\c');
|
||||
|
||||
$this->assertSame('"a\\"b\\\\c"', $result);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Medium-2 — PDO DSN 파라미터 sanitize
|
||||
// ========================================================================
|
||||
|
||||
public function test_getDatabaseConnection_rejects_semicolon_in_host(): void
|
||||
{
|
||||
$this->expectException(\PDOException::class);
|
||||
|
||||
getDatabaseConnection([
|
||||
'db_write_host' => 'localhost;injected=evil',
|
||||
'db_write_port' => '3306',
|
||||
'db_write_database' => 'testdb',
|
||||
'db_write_username' => 'root',
|
||||
'db_write_password' => '',
|
||||
], false);
|
||||
}
|
||||
|
||||
public function test_getDatabaseConnection_rejects_equals_in_database(): void
|
||||
{
|
||||
$this->expectException(\PDOException::class);
|
||||
|
||||
getDatabaseConnection([
|
||||
'db_write_host' => 'localhost',
|
||||
'db_write_port' => '3306',
|
||||
'db_write_database' => 'test=evil',
|
||||
'db_write_username' => 'root',
|
||||
'db_write_password' => '',
|
||||
], false);
|
||||
}
|
||||
|
||||
public function test_getDatabaseConnection_rejects_newline_in_port(): void
|
||||
{
|
||||
$this->expectException(\PDOException::class);
|
||||
|
||||
getDatabaseConnection([
|
||||
'db_write_host' => 'localhost',
|
||||
'db_write_port' => "3306\nfoo=bar",
|
||||
'db_write_database' => 'testdb',
|
||||
'db_write_username' => 'root',
|
||||
'db_write_password' => '',
|
||||
], false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Installer;
|
||||
|
||||
use PHPUnit\Framework\Attributes\PreserveGlobalState;
|
||||
use PHPUnit\Framework\Attributes\RunClassInSeparateProcess;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* 인스톨러 상태 스키마 단위 테스트.
|
||||
*
|
||||
* `public/install/includes/config.php` 의 `DEFAULT_INSTALLATION_STATE` 와
|
||||
* `installer-state.php` 의 `saveInstallationState`/`getInstallationState`
|
||||
* 라운드트립이 신규 `selected_extensions.language_packs` 키를 보존하는지 검증.
|
||||
*
|
||||
* BASE_PATH 는 PHP 상수로 클래스 라이프사이클 단위 단 한 번 정의 (setUpBeforeClass).
|
||||
*/
|
||||
#[RunClassInSeparateProcess]
|
||||
#[PreserveGlobalState(false)]
|
||||
class InstallerStateSchemaTest extends TestCase
|
||||
{
|
||||
private static string $sharedBase = '';
|
||||
|
||||
private static string $skipReason = '';
|
||||
|
||||
public static function setUpBeforeClass(): void
|
||||
{
|
||||
parent::setUpBeforeClass();
|
||||
|
||||
// 안전 가드: BASE_PATH 가 시스템 temp 하위가 아니면 (= 다른 테스트가 프로젝트 루트로 박은 경우)
|
||||
// setUp/tearDown 의 storage/installer-state.json @unlink 가 실제 설치 상태를 파괴할 수 있으므로 skip.
|
||||
$tempPrefix = realpath(sys_get_temp_dir()) ?: sys_get_temp_dir();
|
||||
if (defined('BASE_PATH')) {
|
||||
$resolved = realpath((string) BASE_PATH) ?: (string) BASE_PATH;
|
||||
if (strpos($resolved, $tempPrefix) !== 0) {
|
||||
self::$skipReason = 'BASE_PATH ('.$resolved.') 가 시스템 temp 하위가 아님 — '.
|
||||
'다른 Installer 테스트의 BASE_PATH 정의가 선행됨. 격리 실행 필요: '.
|
||||
'php vendor/bin/phpunit --filter=InstallerStateSchemaTest';
|
||||
|
||||
return;
|
||||
}
|
||||
self::$sharedBase = (string) BASE_PATH;
|
||||
} else {
|
||||
self::$sharedBase = sys_get_temp_dir().'/g7-installer-state-test-'.bin2hex(random_bytes(4));
|
||||
define('BASE_PATH', self::$sharedBase);
|
||||
}
|
||||
|
||||
$storageDir = self::$sharedBase.'/storage';
|
||||
if (! is_dir($storageDir)) {
|
||||
mkdir($storageDir, 0755, true);
|
||||
}
|
||||
|
||||
// config.php 의 INSTALLER_BASE_URL 계산이 $_SERVER['SCRIPT_NAME'] 에 의존
|
||||
if (! isset($_SERVER['SCRIPT_NAME'])) {
|
||||
$_SERVER['SCRIPT_NAME'] = '/install/index.php';
|
||||
}
|
||||
|
||||
require_once dirname(__DIR__, 3).'/public/install/includes/config.php';
|
||||
require_once dirname(__DIR__, 3).'/public/install/includes/installer-state.php';
|
||||
}
|
||||
|
||||
public static function tearDownAfterClass(): void
|
||||
{
|
||||
// skipReason 이 설정되어 있으면 sharedBase 가 미초기화 — destructive cleanup 회피
|
||||
if (self::$skipReason === '' && self::$sharedBase !== '') {
|
||||
$statePath = self::$sharedBase.'/storage/installer-state.json';
|
||||
if (file_exists($statePath)) {
|
||||
@unlink($statePath);
|
||||
}
|
||||
}
|
||||
parent::tearDownAfterClass();
|
||||
}
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
if (self::$skipReason !== '') {
|
||||
$this->markTestSkipped(self::$skipReason);
|
||||
}
|
||||
|
||||
// 각 테스트 시작 시 state.json 초기화
|
||||
$statePath = self::$sharedBase.'/storage/installer-state.json';
|
||||
if (file_exists($statePath)) {
|
||||
@unlink($statePath);
|
||||
}
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function default_state_includes_language_packs_empty_array(): void
|
||||
{
|
||||
$default = DEFAULT_INSTALLATION_STATE;
|
||||
$this->assertArrayHasKey('selected_extensions', $default);
|
||||
$this->assertArrayHasKey('language_packs', $default['selected_extensions']);
|
||||
$this->assertSame([], $default['selected_extensions']['language_packs']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function get_state_returns_language_packs_when_state_file_missing(): void
|
||||
{
|
||||
$state = getInstallationState();
|
||||
$this->assertArrayHasKey('selected_extensions', $state);
|
||||
$this->assertArrayHasKey('language_packs', $state['selected_extensions']);
|
||||
$this->assertSame([], $state['selected_extensions']['language_packs']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function save_and_get_roundtrip_preserves_language_packs(): void
|
||||
{
|
||||
$state = getInstallationState();
|
||||
$state['selected_extensions'] = [
|
||||
'admin_templates' => ['sirsoft-admin_basic'],
|
||||
'user_templates' => ['sirsoft-basic'],
|
||||
'modules' => ['sirsoft-board'],
|
||||
'plugins' => [],
|
||||
'language_packs' => ['g7-core-ja', 'g7-module-sirsoft-board-ja'],
|
||||
];
|
||||
|
||||
$saved = saveInstallationState($state);
|
||||
$this->assertTrue($saved, 'state.json 저장이 성공해야 함');
|
||||
|
||||
$reloaded = getInstallationState();
|
||||
$this->assertSame(
|
||||
['g7-core-ja', 'g7-module-sirsoft-board-ja'],
|
||||
$reloaded['selected_extensions']['language_packs'],
|
||||
'language_packs 배열이 라운드트립에서 보존되어야 함'
|
||||
);
|
||||
$this->assertSame(
|
||||
['sirsoft-board'],
|
||||
$reloaded['selected_extensions']['modules'],
|
||||
'기존 modules 키도 함께 보존되어야 함 (회귀 가드)'
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -98,10 +98,13 @@ class InstallerWindowsCommandsTest extends TestCase
|
||||
|
||||
/**
|
||||
* getPermissionFixCommand()가 Windows에서 icacls 명령어를 반환하는지 확인합니다.
|
||||
*
|
||||
* 현재 시그니처: getPermissionFixCommand(string $pathList, string $mode = 'ownership')
|
||||
* (이전 (owner, path, mode) 3-arg 에서 리팩토링되어 owner 인자 제거됨)
|
||||
*/
|
||||
public function test_get_permission_fix_command_ownership_mode(): void
|
||||
{
|
||||
$command = getPermissionFixCommand('www-data', '/var/www/storage', 'ownership');
|
||||
$command = getPermissionFixCommand('/var/www/storage', 'ownership');
|
||||
|
||||
if (isWindows()) {
|
||||
$this->assertStringContainsString('icacls', $command);
|
||||
@@ -109,8 +112,7 @@ class InstallerWindowsCommandsTest extends TestCase
|
||||
$this->assertStringContainsString('Everyone:(OI)(CI)F', $command);
|
||||
$this->assertStringContainsString('/T', $command);
|
||||
} else {
|
||||
$this->assertStringContainsString('sudo chown -R www-data:www-data', $command);
|
||||
$this->assertStringContainsString('sudo chmod -R 2770', $command);
|
||||
$this->assertStringContainsString('chmod -R 755 /var/www/storage', $command);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,15 +121,14 @@ class InstallerWindowsCommandsTest extends TestCase
|
||||
*/
|
||||
public function test_get_permission_fix_command_file_mode(): void
|
||||
{
|
||||
$command = getPermissionFixCommand('www-data', '/var/www/.env', 'file');
|
||||
$command = getPermissionFixCommand('/var/www/.env', 'file');
|
||||
|
||||
if (isWindows()) {
|
||||
$this->assertStringContainsString('icacls', $command);
|
||||
$this->assertStringContainsString('Everyone:F', $command);
|
||||
$this->assertStringNotContainsString('/T', $command);
|
||||
} else {
|
||||
$this->assertStringContainsString('sudo chown www-data:www-data', $command);
|
||||
$this->assertStringContainsString('sudo chmod 660', $command);
|
||||
$this->assertStringContainsString('chmod 644 /var/www/.env', $command);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,7 +141,7 @@ class InstallerWindowsCommandsTest extends TestCase
|
||||
$this->markTestSkipped('Windows 전용 테스트');
|
||||
}
|
||||
|
||||
$command = getPermissionFixCommand('www-data', '/var/www/storage', 'ownership');
|
||||
$command = getPermissionFixCommand('/var/www/storage', 'ownership');
|
||||
$this->assertStringContainsString('\\var\\www\\storage', $command);
|
||||
$this->assertStringNotContainsString('/var/', $command);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Installer;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* 폴링 모드 응답 즉시 flush 회귀 테스트 (PHP 8.5 + mod_fcgid/Apache)
|
||||
*
|
||||
* 시나리오: 사용자가 폴링 모드로 설치 시작 시 install-process.php 가 응답 JSON 을
|
||||
* echo 하고 워커를 인라인 실행한다. 응답이 즉시 클라이언트에 도달해야 브라우저가
|
||||
* 1초 폴링 (state-management.php?action=get) 을 시작할 수 있다.
|
||||
*
|
||||
* 회귀: PHP 8.5 환경에서 install-process.php 의 폴링 분기가 출력 버퍼 / gzip 압축
|
||||
* 비활성화 처리를 누락하여, php.ini 또는 Apache 의 compression 이 활성화된 경우
|
||||
* Content-Length 헤더와 wire body 가 불일치 → 브라우저 fetch 가 워커 종료 시점
|
||||
* (최대 10분) 까지 hang. 결과로 폴링 모니터가 시작조차 못 하고 설치 완료 시점에서야
|
||||
* 모든 진행 상황이 한꺼번에 표시됨.
|
||||
*
|
||||
* SSE 분기 (install-worker.php) 는 동일 환경에서 정상 작동하는데, 그 분기는 다음
|
||||
* 처리를 명시한다:
|
||||
* @ini_set('output_buffering', 'off')
|
||||
* @ini_set('zlib.output_compression', false)
|
||||
* @apache_setenv('no-gzip', 1)
|
||||
* while (ob_get_level() > 0) ob_end_clean();
|
||||
*
|
||||
* 본 테스트는 install-process.php 의 폴링 분기에 동일한 출력 처리 비활성화가 echo
|
||||
* 이전에 존재하는지 정적 검증한다. PHP 8.3 에서는 회귀하지 않으므로 정적 검사로만
|
||||
* 회귀 차단 가능 (런타임 검사는 SAPI 종속이라 PHPUnit 환경에서 불가).
|
||||
*/
|
||||
class PollingResponseFlushTest extends TestCase
|
||||
{
|
||||
private string $sourcePath;
|
||||
private string $source;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->sourcePath = dirname(__DIR__, 3) . '/public/install/api/install-process.php';
|
||||
$this->assertFileExists($this->sourcePath, 'install-process.php 가 존재해야 한다.');
|
||||
|
||||
$this->source = (string) file_get_contents($this->sourcePath);
|
||||
$this->assertNotSame('', $this->source);
|
||||
}
|
||||
|
||||
public function test_polling_branch_disables_zlib_output_compression(): void
|
||||
{
|
||||
$pollingBranch = $this->extractPollingBranch();
|
||||
|
||||
$this->assertMatchesRegularExpression(
|
||||
'/@?ini_set\(\s*[\'"]zlib\.output_compression[\'"]\s*,\s*(false|[\'"]\s*off\s*[\'"]|0)\s*\)/i',
|
||||
$pollingBranch,
|
||||
'폴링 분기는 echo 이전에 zlib.output_compression 을 비활성화해야 한다 — '
|
||||
. 'PHP 8.5 + mod_deflate/zlib 환경에서 Content-Length 와 wire body 불일치로 fetch 가 hang.'
|
||||
);
|
||||
}
|
||||
|
||||
public function test_polling_branch_disables_output_buffering_ini(): void
|
||||
{
|
||||
$pollingBranch = $this->extractPollingBranch();
|
||||
|
||||
$this->assertMatchesRegularExpression(
|
||||
'/@?ini_set\(\s*[\'"]output_buffering[\'"]\s*,\s*[\'"]\s*off\s*[\'"]\s*\)/i',
|
||||
$pollingBranch,
|
||||
'폴링 분기는 echo 이전에 output_buffering ini 를 off 로 설정해야 한다 — '
|
||||
. 'php.ini output_buffering 이 활성화된 SAPI 환경에서 응답 즉시 송신 보장.'
|
||||
);
|
||||
}
|
||||
|
||||
public function test_polling_branch_disables_apache_gzip(): void
|
||||
{
|
||||
$pollingBranch = $this->extractPollingBranch();
|
||||
|
||||
$this->assertMatchesRegularExpression(
|
||||
'/apache_setenv\(\s*[\'"]no-gzip[\'"]\s*,\s*1\s*\)/i',
|
||||
$pollingBranch,
|
||||
'폴링 분기는 echo 이전에 apache_setenv(no-gzip, 1) 를 호출해야 한다 — '
|
||||
. 'Apache mod_deflate 가 응답을 압축하면 Content-Length 가 무력화됨.'
|
||||
);
|
||||
}
|
||||
|
||||
public function test_polling_branch_emits_padding_to_force_fcgid_flush(): void
|
||||
{
|
||||
$pollingBranch = $this->extractPollingBranch();
|
||||
|
||||
$this->assertMatchesRegularExpression(
|
||||
'/str_repeat\(\s*[\'"]\s*[\'"]\s*,\s*(6553[6-9]|65[6-9]\d{2}|6[6-9]\d{3}|[789]\d{4}|[1-9]\d{5,})\s*\)/',
|
||||
$pollingBranch,
|
||||
'폴링 분기는 echo 직후 65536 바이트 이상의 padding(str_repeat(공백)) 을 출력해야 한다 — '
|
||||
. 'mod_fcgid (FcgidOutputBufferSize default 64KB) 가 응답을 즉시 flush 하도록 강제. '
|
||||
. '워커가 10분간 인라인 실행되는 동안 install-process.php 응답이 클라이언트에 도달하지 못해 '
|
||||
. 'PollingMonitor 가 시작조차 못 하는 회귀를 차단.'
|
||||
);
|
||||
}
|
||||
|
||||
public function test_padding_position_is_after_json_echo_and_before_flush(): void
|
||||
{
|
||||
$pollingBranch = $this->extractPollingBranch();
|
||||
|
||||
$echoPos = strpos($pollingBranch, 'echo $responseJson;');
|
||||
$this->assertNotFalse($echoPos);
|
||||
|
||||
$hasMatch = preg_match(
|
||||
'/str_repeat\(\s*[\'"]\s*[\'"]\s*,\s*\d+\s*\)/',
|
||||
$pollingBranch,
|
||||
$matches,
|
||||
PREG_OFFSET_CAPTURE
|
||||
);
|
||||
$this->assertSame(1, $hasMatch, 'padding str_repeat 호출이 분기 내에 존재해야 한다.');
|
||||
$paddingPos = $matches[0][1];
|
||||
|
||||
$flushPos = strpos($pollingBranch, '@flush()', $echoPos);
|
||||
$this->assertNotFalse($flushPos);
|
||||
|
||||
$this->assertGreaterThan(
|
||||
$echoPos,
|
||||
$paddingPos,
|
||||
'padding 은 echo $responseJson 이후에 출력되어야 한다 (그래야 응답 본문이 먼저 wire 에 들어감).'
|
||||
);
|
||||
$this->assertLessThan(
|
||||
$flushPos,
|
||||
$paddingPos,
|
||||
'padding 은 flush() 이전에 출력되어야 한다 (flush 시점에 64KB 임계 도달해야 mod_fcgid 가 송출).'
|
||||
);
|
||||
}
|
||||
|
||||
public function test_content_length_remains_json_byte_count_only(): void
|
||||
{
|
||||
$pollingBranch = $this->extractPollingBranch();
|
||||
|
||||
// padding 은 wire 에는 들어가지만 Content-Length 는 JSON 바이트 수만 명시해야 한다.
|
||||
// 그래야 브라우저가 Content-Length 만큼만 읽고 fetch resolve 후 padding 은 무시.
|
||||
$this->assertMatchesRegularExpression(
|
||||
'/header\(\s*[\'"]Content-Length:\s*[\'"]\s*\.\s*strlen\(\s*\$responseJson\s*\)\s*\)/',
|
||||
$pollingBranch,
|
||||
'Content-Length 헤더는 padding 을 제외한 $responseJson 의 바이트 수만 명시해야 한다.'
|
||||
);
|
||||
}
|
||||
|
||||
public function test_output_disable_calls_precede_echo_response(): void
|
||||
{
|
||||
$pollingBranch = $this->extractPollingBranch();
|
||||
|
||||
$echoPos = strpos($pollingBranch, 'echo $responseJson;');
|
||||
$this->assertNotFalse($echoPos, '폴링 분기에 `echo $responseJson;` 문장이 존재해야 한다.');
|
||||
|
||||
// zlib.output_compression 비활성화 위치
|
||||
$hasMatch = preg_match(
|
||||
'/@?ini_set\(\s*[\'"]zlib\.output_compression[\'"]/',
|
||||
$pollingBranch,
|
||||
$matches,
|
||||
PREG_OFFSET_CAPTURE
|
||||
);
|
||||
$this->assertSame(1, $hasMatch, 'zlib.output_compression 비활성화가 분기 내에 존재해야 한다.');
|
||||
$zlibPos = $matches[0][1];
|
||||
$this->assertLessThan(
|
||||
$echoPos,
|
||||
$zlibPos,
|
||||
'zlib.output_compression 비활성화는 echo 이전에 실행되어야 한다.'
|
||||
);
|
||||
|
||||
// apache_setenv(no-gzip)
|
||||
$hasMatch = preg_match(
|
||||
'/apache_setenv\(\s*[\'"]no-gzip[\'"]/',
|
||||
$pollingBranch,
|
||||
$matches,
|
||||
PREG_OFFSET_CAPTURE
|
||||
);
|
||||
$this->assertSame(1, $hasMatch, 'apache_setenv(no-gzip) 가 분기 내에 존재해야 한다.');
|
||||
$noGzipPos = $matches[0][1];
|
||||
$this->assertLessThan(
|
||||
$echoPos,
|
||||
$noGzipPos,
|
||||
'apache_setenv(no-gzip, 1) 는 echo 이전에 실행되어야 한다.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* install-process.php 의 `if ($installationMode === 'polling') { ... }` 본문 추출.
|
||||
*/
|
||||
private function extractPollingBranch(): string
|
||||
{
|
||||
$start = strpos($this->source, "if (\$installationMode === 'polling')");
|
||||
$this->assertNotFalse($start, "폴링 분기 if 문을 찾을 수 없습니다.");
|
||||
|
||||
// 매칭되는 닫는 중괄호 찾기
|
||||
$braceStart = strpos($this->source, '{', $start);
|
||||
$this->assertNotFalse($braceStart);
|
||||
|
||||
$depth = 0;
|
||||
$len = strlen($this->source);
|
||||
for ($i = $braceStart; $i < $len; $i++) {
|
||||
$ch = $this->source[$i];
|
||||
if ($ch === '{') {
|
||||
$depth++;
|
||||
} elseif ($ch === '}') {
|
||||
$depth--;
|
||||
if ($depth === 0) {
|
||||
return substr($this->source, $braceStart, $i - $braceStart + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->fail('폴링 분기의 닫는 중괄호를 찾을 수 없습니다.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Installer;
|
||||
|
||||
use PHPUnit\Framework\Attributes\PreserveGlobalState;
|
||||
use PHPUnit\Framework\Attributes\RunClassInSeparateProcess;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* 인스톨러 — 번들 언어팩 스캔 단위 테스트.
|
||||
*
|
||||
* `public/install/api/scan-extensions.php` 의 `scanLanguagePacks()` 함수를
|
||||
* 라이브러리 모드(SCAN_EXTENSIONS_LIBRARY) 로 require 하여 직접 호출.
|
||||
* Laravel 부팅 없이 BASE_PATH 만 격리된 디렉토리로 정의해 매니페스트 스캔
|
||||
* 결과를 검증한다.
|
||||
*
|
||||
* BASE_PATH 는 PHP 상수이므로 클래스 라이프사이클 단위로 단 한 번 정의 (setUpBeforeClass).
|
||||
* 각 테스트는 setUp 에서 BASE_PATH 하위의 lang-packs/_bundled 를 비워 초기화한다.
|
||||
*
|
||||
* 검증 항목:
|
||||
* - language-pack.json 매니페스트가 응답 항목으로 노출됨
|
||||
* - scope/target_identifier/locale 필드가 보존됨
|
||||
* - hidden=true 매니페스트는 제외됨
|
||||
* - 동일 디렉토리에 다수 패키지(코어 + 확장 + 동일 확장의 다중 locale)가 모두 노출됨
|
||||
*/
|
||||
#[RunClassInSeparateProcess]
|
||||
#[PreserveGlobalState(false)]
|
||||
class ScanLanguagePacksTest extends TestCase
|
||||
{
|
||||
private static string $sharedBase = '';
|
||||
|
||||
private static string $skipReason = '';
|
||||
|
||||
public static function setUpBeforeClass(): void
|
||||
{
|
||||
parent::setUpBeforeClass();
|
||||
|
||||
// 안전 가드: BASE_PATH 가 시스템 temp 디렉토리 하위가 아니면 (= 다른 테스트가 프로젝트 루트로 먼저 박은 경우)
|
||||
// setUp/tearDown 의 enumerate-delete 가 실제 lang-packs/_bundled 를 파괴할 수 있으므로 skip.
|
||||
$tempPrefix = realpath(sys_get_temp_dir()) ?: sys_get_temp_dir();
|
||||
if (defined('BASE_PATH')) {
|
||||
$resolved = realpath((string) BASE_PATH) ?: (string) BASE_PATH;
|
||||
if (strpos($resolved, $tempPrefix) !== 0) {
|
||||
self::$skipReason = 'BASE_PATH ('.$resolved.') 가 시스템 temp 하위가 아님 — '.
|
||||
'다른 Installer 테스트의 BASE_PATH 정의가 선행됨. 격리 실행 필요: '.
|
||||
'php vendor/bin/phpunit --filter=ScanLanguagePacksTest';
|
||||
|
||||
return;
|
||||
}
|
||||
self::$sharedBase = (string) BASE_PATH;
|
||||
} else {
|
||||
self::$sharedBase = sys_get_temp_dir().'/g7-installer-scanlp-test-'.bin2hex(random_bytes(4));
|
||||
define('BASE_PATH', self::$sharedBase);
|
||||
}
|
||||
|
||||
$bundleDir = self::$sharedBase.'/lang-packs/_bundled';
|
||||
if (! is_dir($bundleDir)) {
|
||||
mkdir($bundleDir, 0755, true);
|
||||
}
|
||||
|
||||
if (! defined('SCAN_EXTENSIONS_LIBRARY')) {
|
||||
define('SCAN_EXTENSIONS_LIBRARY', true);
|
||||
}
|
||||
|
||||
require_once dirname(__DIR__, 3).'/public/install/api/scan-extensions.php';
|
||||
}
|
||||
|
||||
public static function tearDownAfterClass(): void
|
||||
{
|
||||
// skipReason 이 설정되어 있으면 sharedBase 가 미초기화 — destructive cleanup 회피
|
||||
if (self::$skipReason === '' && self::$sharedBase !== '') {
|
||||
$bundleDir = self::$sharedBase.'/lang-packs/_bundled';
|
||||
if (is_dir($bundleDir)) {
|
||||
foreach (scandir($bundleDir) as $e) {
|
||||
if ($e === '.' || $e === '..') {
|
||||
continue;
|
||||
}
|
||||
self::removeRecursiveStatic($bundleDir.DIRECTORY_SEPARATOR.$e);
|
||||
}
|
||||
}
|
||||
}
|
||||
parent::tearDownAfterClass();
|
||||
}
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
if (self::$skipReason !== '') {
|
||||
$this->markTestSkipped(self::$skipReason);
|
||||
}
|
||||
|
||||
// 각 테스트 시작 시 lang-packs/_bundled 디렉토리 초기화
|
||||
$bundle = self::$sharedBase.'/lang-packs/_bundled';
|
||||
if (is_dir($bundle)) {
|
||||
foreach (scandir($bundle) as $e) {
|
||||
if ($e === '.' || $e === '..') {
|
||||
continue;
|
||||
}
|
||||
self::removeRecursiveStatic($bundle.DIRECTORY_SEPARATOR.$e);
|
||||
}
|
||||
} else {
|
||||
mkdir($bundle, 0755, true);
|
||||
}
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function scan_returns_empty_when_directory_empty(): void
|
||||
{
|
||||
$result = scanLanguagePacks();
|
||||
$this->assertSame([], $result);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function scan_includes_core_and_extension_packs(): void
|
||||
{
|
||||
$this->writeManifest('g7-core-ja', [
|
||||
'identifier' => 'g7-core-ja',
|
||||
'scope' => 'core',
|
||||
'target_identifier' => null,
|
||||
'locale' => 'ja',
|
||||
'locale_native_name' => '日本語',
|
||||
'name' => ['ko' => 'G7 Core Japanese', 'en' => 'G7 Core Japanese'],
|
||||
'version' => '1.0.0',
|
||||
]);
|
||||
|
||||
$this->writeManifest('g7-module-board-ja', [
|
||||
'identifier' => 'g7-module-board-ja',
|
||||
'scope' => 'module',
|
||||
'target_identifier' => 'sirsoft-board',
|
||||
'locale' => 'ja',
|
||||
'locale_native_name' => '日本語',
|
||||
'name' => 'Board JP',
|
||||
'version' => '1.0.0',
|
||||
]);
|
||||
|
||||
$result = scanLanguagePacks();
|
||||
|
||||
$ids = array_column($result, 'identifier');
|
||||
sort($ids);
|
||||
$this->assertSame(['g7-core-ja', 'g7-module-board-ja'], $ids);
|
||||
|
||||
$core = $this->findById($result, 'g7-core-ja');
|
||||
$this->assertSame('core', $core['scope']);
|
||||
$this->assertNull($core['target_identifier']);
|
||||
$this->assertSame('ja', $core['locale']);
|
||||
$this->assertSame('日本語', $core['locale_native_name']);
|
||||
|
||||
$module = $this->findById($result, 'g7-module-board-ja');
|
||||
$this->assertSame('module', $module['scope']);
|
||||
$this->assertSame('sirsoft-board', $module['target_identifier']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function scan_excludes_hidden_manifests(): void
|
||||
{
|
||||
$this->writeManifest('g7-sample-hidden-ja', [
|
||||
'identifier' => 'g7-sample-hidden-ja',
|
||||
'scope' => 'core',
|
||||
'locale' => 'ja',
|
||||
'name' => 'Hidden Sample',
|
||||
'version' => '1.0.0',
|
||||
'hidden' => true,
|
||||
]);
|
||||
|
||||
$this->writeManifest('g7-core-ja', [
|
||||
'identifier' => 'g7-core-ja',
|
||||
'scope' => 'core',
|
||||
'locale' => 'ja',
|
||||
'name' => 'G7 Core Japanese',
|
||||
'version' => '1.0.0',
|
||||
]);
|
||||
|
||||
$result = scanLanguagePacks();
|
||||
$ids = array_column($result, 'identifier');
|
||||
|
||||
$this->assertContains('g7-core-ja', $ids);
|
||||
$this->assertNotContains('g7-sample-hidden-ja', $ids);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function scan_supports_multiple_locales_for_same_extension(): void
|
||||
{
|
||||
$this->writeManifest('g7-module-board-ja', [
|
||||
'identifier' => 'g7-module-board-ja',
|
||||
'scope' => 'module',
|
||||
'target_identifier' => 'sirsoft-board',
|
||||
'locale' => 'ja',
|
||||
'name' => 'Board JP',
|
||||
'version' => '1.0.0',
|
||||
]);
|
||||
|
||||
$this->writeManifest('g7-module-board-zh-CN', [
|
||||
'identifier' => 'g7-module-board-zh-CN',
|
||||
'scope' => 'module',
|
||||
'target_identifier' => 'sirsoft-board',
|
||||
'locale' => 'zh-CN',
|
||||
'name' => 'Board CN',
|
||||
'version' => '1.0.0',
|
||||
]);
|
||||
|
||||
$result = scanLanguagePacks();
|
||||
$this->assertCount(2, $result);
|
||||
|
||||
$locales = array_column($result, 'locale');
|
||||
sort($locales);
|
||||
$this->assertSame(['ja', 'zh-CN'], $locales);
|
||||
|
||||
foreach ($result as $row) {
|
||||
$this->assertSame('sirsoft-board', $row['target_identifier']);
|
||||
}
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function scan_excludes_packs_targeting_hidden_host_extensions(): void
|
||||
{
|
||||
// hidden 처리된 모듈 매니페스트 작성 (학습용 샘플 시뮬레이션)
|
||||
$modulesDir = self::$sharedBase.'/modules/_bundled/sample-hidden-module';
|
||||
if (! is_dir($modulesDir)) {
|
||||
mkdir($modulesDir, 0755, true);
|
||||
}
|
||||
file_put_contents($modulesDir.'/module.json', json_encode([
|
||||
'identifier' => 'sample-hidden-module',
|
||||
'name' => ['ko' => '샘플 모듈', 'en' => 'Sample Module'],
|
||||
'version' => '1.0.0',
|
||||
'hidden' => true,
|
||||
], JSON_UNESCAPED_UNICODE));
|
||||
|
||||
// 일반 모듈 매니페스트
|
||||
$normalDir = self::$sharedBase.'/modules/_bundled/sirsoft-board';
|
||||
if (! is_dir($normalDir)) {
|
||||
mkdir($normalDir, 0755, true);
|
||||
}
|
||||
file_put_contents($normalDir.'/module.json', json_encode([
|
||||
'identifier' => 'sirsoft-board',
|
||||
'name' => ['ko' => '게시판', 'en' => 'Board'],
|
||||
'version' => '1.0.0',
|
||||
], JSON_UNESCAPED_UNICODE));
|
||||
|
||||
// hidden 모듈 종속 언어팩
|
||||
$this->writeManifest('g7-module-sample-hidden-module-ja', [
|
||||
'identifier' => 'g7-module-sample-hidden-module-ja',
|
||||
'scope' => 'module',
|
||||
'target_identifier' => 'sample-hidden-module',
|
||||
'locale' => 'ja',
|
||||
'name' => 'Sample Hidden JP',
|
||||
'version' => '1.0.0',
|
||||
]);
|
||||
|
||||
// 정상 모듈 종속 언어팩
|
||||
$this->writeManifest('g7-module-sirsoft-board-ja', [
|
||||
'identifier' => 'g7-module-sirsoft-board-ja',
|
||||
'scope' => 'module',
|
||||
'target_identifier' => 'sirsoft-board',
|
||||
'locale' => 'ja',
|
||||
'name' => 'Board JP',
|
||||
'version' => '1.0.0',
|
||||
]);
|
||||
|
||||
$result = scanLanguagePacks();
|
||||
$ids = array_column($result, 'identifier');
|
||||
|
||||
$this->assertContains('g7-module-sirsoft-board-ja', $ids);
|
||||
$this->assertNotContains('g7-module-sample-hidden-module-ja', $ids, 'hidden 호스트 확장 종속 언어팩은 cascade 제외되어야 함');
|
||||
|
||||
// fixture 정리
|
||||
@unlink($modulesDir.'/module.json');
|
||||
@rmdir($modulesDir);
|
||||
@unlink($normalDir.'/module.json');
|
||||
@rmdir($normalDir);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function scan_skips_directory_without_manifest(): void
|
||||
{
|
||||
mkdir(self::$sharedBase.'/lang-packs/_bundled/g7-orphan-ja', 0755, true);
|
||||
|
||||
$this->writeManifest('g7-core-ja', [
|
||||
'identifier' => 'g7-core-ja',
|
||||
'scope' => 'core',
|
||||
'locale' => 'ja',
|
||||
'name' => 'G7 Core Japanese',
|
||||
'version' => '1.0.0',
|
||||
]);
|
||||
|
||||
$result = scanLanguagePacks();
|
||||
$this->assertCount(1, $result);
|
||||
$this->assertSame('g7-core-ja', $result[0]['identifier']);
|
||||
}
|
||||
|
||||
private function writeManifest(string $directory, array $data): void
|
||||
{
|
||||
$dir = self::$sharedBase.'/lang-packs/_bundled/'.$directory;
|
||||
if (! is_dir($dir)) {
|
||||
mkdir($dir, 0755, true);
|
||||
}
|
||||
file_put_contents($dir.'/language-pack.json', json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
|
||||
}
|
||||
|
||||
private function findById(array $rows, string $id): array
|
||||
{
|
||||
foreach ($rows as $row) {
|
||||
if ($row['identifier'] === $id) {
|
||||
return $row;
|
||||
}
|
||||
}
|
||||
$this->fail("Identifier {$id} not found in scan result");
|
||||
}
|
||||
|
||||
private static function removeRecursiveStatic(string $path): void
|
||||
{
|
||||
if (! file_exists($path) && ! is_link($path)) {
|
||||
return;
|
||||
}
|
||||
if (is_file($path) || is_link($path)) {
|
||||
@unlink($path);
|
||||
|
||||
return;
|
||||
}
|
||||
$entries = scandir($path);
|
||||
foreach ($entries as $entry) {
|
||||
if ($entry === '.' || $entry === '..') {
|
||||
continue;
|
||||
}
|
||||
self::removeRecursiveStatic($path.DIRECTORY_SEPARATOR.$entry);
|
||||
}
|
||||
@rmdir($path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Installer;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* 워커 동시 실행 방지 lock/heartbeat 가드 회귀 테스트
|
||||
*
|
||||
* 시나리오 B (이슈 #319 race condition 본질 차단):
|
||||
* - 환경 (예: mod_fcgid + FcgidOutputBufferSize 미설정) 에서 SSE 가 client 까지
|
||||
* 도달 못해 사용자가 폴링으로 풀백. 그 사이 SSE 워커는 백그라운드 진행.
|
||||
* - 새 폴링 워커가 진입하면 두 워커가 동일 인스톨러 state + DB 를 동시 조작.
|
||||
* - 본 가드: state.active_worker_id + state.last_heartbeat 로 동시 실행 차단.
|
||||
*
|
||||
* 검증 대상 헬퍼:
|
||||
* - acquireWorkerLock(int $staleSeconds): ['acquired'=>bool, 'worker_id'=>string|null, 'reason'=>string]
|
||||
* - refreshWorkerHeartbeat(string $workerId): bool — 자기 worker_id 일 때만 true
|
||||
* - releaseWorkerLock(string $workerId): void
|
||||
*
|
||||
* 본 테스트는 헬퍼 자체의 결정론적 동작만 검증. 실제 두 PHP 프로세스 동시 실행은
|
||||
* 매뉴얼 시나리오 검증 영역.
|
||||
*/
|
||||
class WorkerLockGuardTest extends TestCase
|
||||
{
|
||||
private string $tempBase;
|
||||
private string $stateFile;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->tempBase = sys_get_temp_dir() . '/g7-worker-lock-test-' . bin2hex(random_bytes(4));
|
||||
mkdir($this->tempBase . '/storage', 0755, true);
|
||||
|
||||
if (! defined('BASE_PATH')) {
|
||||
define('BASE_PATH', $this->tempBase);
|
||||
}
|
||||
|
||||
$this->stateFile = BASE_PATH . '/storage/installer-state.json';
|
||||
@file_put_contents($this->stateFile, json_encode(['installation_status' => 'pending']));
|
||||
|
||||
require_once dirname(__DIR__, 3) . '/public/install/includes/config.php';
|
||||
require_once dirname(__DIR__, 3) . '/public/install/includes/installer-state.php';
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
// $this->stateFile 은 setUp 시점의 BASE_PATH 로 이미 결정되어 있으므로
|
||||
// 그 경로를 그대로 정리. 이전 코드는 BASE_PATH 가 self::tempBase 와 다를 때
|
||||
// (다른 테스트가 먼저 바인딩한 경우) 정리를 skip 하여 PO 작업 디렉토리에
|
||||
// 잔여물을 남겼다.
|
||||
@unlink($this->stateFile);
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_acquire_succeeds_when_no_active_worker(): void
|
||||
{
|
||||
$result = acquireWorkerLock(15);
|
||||
|
||||
$this->assertTrue($result['acquired']);
|
||||
$this->assertNotEmpty($result['worker_id']);
|
||||
$this->assertSame('available', $result['reason']);
|
||||
}
|
||||
|
||||
public function test_acquire_persists_worker_id_and_heartbeat_in_state(): void
|
||||
{
|
||||
$result = acquireWorkerLock(15);
|
||||
|
||||
$state = json_decode(file_get_contents($this->stateFile), true);
|
||||
$this->assertSame($result['worker_id'], $state['active_worker_id']);
|
||||
$this->assertIsInt($state['last_heartbeat']);
|
||||
$this->assertGreaterThanOrEqual(time() - 1, $state['last_heartbeat']);
|
||||
}
|
||||
|
||||
public function test_acquire_fails_when_active_worker_within_stale_window(): void
|
||||
{
|
||||
$first = acquireWorkerLock(15);
|
||||
$this->assertTrue($first['acquired']);
|
||||
|
||||
// 두 번째 워커 진입 시도 — 활동 중이라 거부되어야 함
|
||||
$second = acquireWorkerLock(15);
|
||||
|
||||
$this->assertFalse($second['acquired']);
|
||||
$this->assertNull($second['worker_id']);
|
||||
$this->assertSame('busy', $second['reason']);
|
||||
|
||||
// state 의 worker_id 는 첫 번째 그대로
|
||||
$state = json_decode(file_get_contents($this->stateFile), true);
|
||||
$this->assertSame($first['worker_id'], $state['active_worker_id']);
|
||||
}
|
||||
|
||||
public function test_acquire_takes_over_when_heartbeat_stale(): void
|
||||
{
|
||||
$first = acquireWorkerLock(15);
|
||||
|
||||
// heartbeat 를 stale 시점으로 강제 변경
|
||||
$state = json_decode(file_get_contents($this->stateFile), true);
|
||||
$state['last_heartbeat'] = time() - 60;
|
||||
file_put_contents($this->stateFile, json_encode($state));
|
||||
|
||||
$second = acquireWorkerLock(15);
|
||||
|
||||
$this->assertTrue($second['acquired']);
|
||||
$this->assertNotSame($first['worker_id'], $second['worker_id']);
|
||||
$this->assertSame('takeover_stale', $second['reason']);
|
||||
|
||||
$newState = json_decode(file_get_contents($this->stateFile), true);
|
||||
$this->assertSame($second['worker_id'], $newState['active_worker_id']);
|
||||
}
|
||||
|
||||
public function test_refresh_heartbeat_returns_true_for_owner(): void
|
||||
{
|
||||
$first = acquireWorkerLock(15);
|
||||
|
||||
// 의도적 1초 지연 (heartbeat 갱신 detection)
|
||||
sleep(1);
|
||||
|
||||
$ok = refreshWorkerHeartbeat($first['worker_id']);
|
||||
$this->assertTrue($ok);
|
||||
|
||||
$state = json_decode(file_get_contents($this->stateFile), true);
|
||||
$this->assertGreaterThanOrEqual(time() - 1, $state['last_heartbeat']);
|
||||
}
|
||||
|
||||
public function test_refresh_heartbeat_returns_false_for_non_owner(): void
|
||||
{
|
||||
$first = acquireWorkerLock(15);
|
||||
|
||||
// 다른 worker_id 가 takeover 한 상황 시뮬레이션
|
||||
$state = json_decode(file_get_contents($this->stateFile), true);
|
||||
$state['active_worker_id'] = 'someone-else';
|
||||
file_put_contents($this->stateFile, json_encode($state));
|
||||
|
||||
$ok = refreshWorkerHeartbeat($first['worker_id']);
|
||||
$this->assertFalse($ok);
|
||||
}
|
||||
|
||||
public function test_release_clears_worker_id_and_heartbeat(): void
|
||||
{
|
||||
$first = acquireWorkerLock(15);
|
||||
|
||||
releaseWorkerLock($first['worker_id']);
|
||||
|
||||
$state = json_decode(file_get_contents($this->stateFile), true);
|
||||
$this->assertArrayNotHasKey('active_worker_id', $state);
|
||||
$this->assertArrayNotHasKey('last_heartbeat', $state);
|
||||
}
|
||||
|
||||
public function test_release_no_op_when_worker_id_does_not_match(): void
|
||||
{
|
||||
$first = acquireWorkerLock(15);
|
||||
|
||||
// 다른 worker 가 takeover
|
||||
$state = json_decode(file_get_contents($this->stateFile), true);
|
||||
$newWorkerId = 'taker-' . bin2hex(random_bytes(4));
|
||||
$state['active_worker_id'] = $newWorkerId;
|
||||
file_put_contents($this->stateFile, json_encode($state));
|
||||
|
||||
// 원본 worker 가 release 시도 — 자기 worker_id 가 아니므로 무시
|
||||
releaseWorkerLock($first['worker_id']);
|
||||
|
||||
$stateAfter = json_decode(file_get_contents($this->stateFile), true);
|
||||
$this->assertSame($newWorkerId, $stateAfter['active_worker_id']);
|
||||
}
|
||||
|
||||
public function test_acquire_after_release_succeeds(): void
|
||||
{
|
||||
$first = acquireWorkerLock(15);
|
||||
releaseWorkerLock($first['worker_id']);
|
||||
|
||||
$second = acquireWorkerLock(15);
|
||||
|
||||
$this->assertTrue($second['acquired']);
|
||||
$this->assertSame('available', $second['reason']);
|
||||
$this->assertNotSame($first['worker_id'], $second['worker_id']);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 인스톨러 단위 테스트용 lang() 글로벌 스텁
|
||||
*
|
||||
* public/install/includes/functions.php 의 lang() 헬퍼 대체.
|
||||
* 메시지 키를 그대로 반환해 단위 테스트에서 검증 가능한 형태로 노출.
|
||||
*/
|
||||
if (! function_exists('lang')) {
|
||||
function lang(string $key, array $params = []): string
|
||||
{
|
||||
unset($params);
|
||||
return $key;
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,9 @@
|
||||
|
||||
namespace Tests\Unit\Jobs;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Jobs\GenerateSitemapJob;
|
||||
use App\Seo\SitemapGenerator;
|
||||
use App\Seo\SitemapManager;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
@@ -14,7 +12,8 @@ use Tests\TestCase;
|
||||
/**
|
||||
* GenerateSitemapJob 유닛 테스트
|
||||
*
|
||||
* Sitemap 생성 잡의 큐 속성, 캐시 저장, 비활성화 분기, 실패 처리를 검증합니다.
|
||||
* 잡의 큐 속성과 SitemapManager 위임 동작을 검증합니다.
|
||||
* 실제 생성/캐시/last_updated_at 로직은 SitemapManager 단위 테스트에서 검증합니다.
|
||||
*/
|
||||
class GenerateSitemapJobTest extends TestCase
|
||||
{
|
||||
@@ -46,89 +45,78 @@ class GenerateSitemapJobTest extends TestCase
|
||||
}
|
||||
|
||||
/**
|
||||
* handle() 호출 시 Sitemap을 생성하고 캐시에 저장하는지 확인합니다.
|
||||
* handle() 호출 시 SitemapManager::regenerate 에 위임하는지 확인합니다.
|
||||
*/
|
||||
public function test_handle_generates_and_caches_sitemap(): void
|
||||
public function test_handle_delegates_to_sitemap_manager(): void
|
||||
{
|
||||
Config::set('g7_settings.core.seo.sitemap_enabled', true);
|
||||
Config::set('g7_settings.core.seo.sitemap_cache_ttl', 86400);
|
||||
|
||||
$xml = '<?xml version="1.0"?><urlset></urlset>';
|
||||
|
||||
$generator = Mockery::mock(SitemapGenerator::class);
|
||||
$generator->shouldReceive('generate')
|
||||
$manager = Mockery::mock(SitemapManager::class);
|
||||
$manager->shouldReceive('regenerate')
|
||||
->once()
|
||||
->andReturn($xml);
|
||||
|
||||
$cache = Mockery::mock(CacheInterface::class);
|
||||
$cache->shouldReceive('put')
|
||||
->once()
|
||||
->with('seo.sitemap', $xml, 86400);
|
||||
->andReturn([
|
||||
'success' => true,
|
||||
'status' => 'updated',
|
||||
'data' => [
|
||||
'last_updated_at' => '2026-04-29T10:00:00+00:00',
|
||||
'size_bytes' => 1234,
|
||||
'ttl' => 86400,
|
||||
],
|
||||
]);
|
||||
|
||||
Log::shouldReceive('info')
|
||||
->once()
|
||||
->with('[SEO] Sitemap generated and cached', Mockery::on(function ($context) use ($xml) {
|
||||
return $context['size'] === strlen($xml) && $context['ttl'] === 86400;
|
||||
->with('[SEO] Sitemap generated and cached', Mockery::on(function ($context) {
|
||||
return $context['size'] === 1234 && $context['ttl'] === 86400;
|
||||
}));
|
||||
|
||||
$job = new GenerateSitemapJob();
|
||||
$job->handle($generator, $cache);
|
||||
$job->handle($manager);
|
||||
|
||||
$this->addToAssertionCount(Mockery::getContainer()->mockery_getExpectationCount());
|
||||
}
|
||||
|
||||
/**
|
||||
* sitemap_enabled=false일 때 생성을 건너뛰는지 확인합니다.
|
||||
* disabled 상태이면 생성을 건너뛰고 예외를 던지지 않는지 확인합니다.
|
||||
*/
|
||||
public function test_handle_skips_when_sitemap_disabled(): void
|
||||
public function test_handle_skips_when_disabled(): void
|
||||
{
|
||||
Config::set('g7_settings.core.seo.sitemap_enabled', false);
|
||||
|
||||
$generator = Mockery::mock(SitemapGenerator::class);
|
||||
$generator->shouldNotReceive('generate');
|
||||
$cache = Mockery::mock(CacheInterface::class);
|
||||
$manager = Mockery::mock(SitemapManager::class);
|
||||
$manager->shouldReceive('regenerate')
|
||||
->once()
|
||||
->andReturn([
|
||||
'success' => false,
|
||||
'status' => 'disabled',
|
||||
'message' => 'Sitemap 생성이 비활성화되어 있습니다.',
|
||||
]);
|
||||
|
||||
Log::shouldReceive('info')
|
||||
->once()
|
||||
->with('[SEO] Sitemap generation skipped (disabled)');
|
||||
|
||||
$job = new GenerateSitemapJob();
|
||||
$job->handle($generator, $cache);
|
||||
$job->handle($manager);
|
||||
|
||||
$this->addToAssertionCount(Mockery::getContainer()->mockery_getExpectationCount());
|
||||
}
|
||||
|
||||
/**
|
||||
* 설정된 커스텀 TTL이 cache->put에 전달되는지 확인합니다.
|
||||
* 실패 응답 시 RuntimeException 을 던져 큐가 재시도하도록 합니다.
|
||||
*/
|
||||
public function test_handle_uses_configured_cache_ttl(): void
|
||||
public function test_handle_throws_on_failure(): void
|
||||
{
|
||||
Config::set('g7_settings.core.seo.sitemap_enabled', true);
|
||||
Config::set('g7_settings.core.cache.seo_sitemap_ttl', 3600);
|
||||
Config::set('g7_settings.core.seo.sitemap_cache_ttl', 3600);
|
||||
|
||||
$xml = '<urlset/>';
|
||||
|
||||
$generator = Mockery::mock(SitemapGenerator::class);
|
||||
$generator->shouldReceive('generate')
|
||||
$manager = Mockery::mock(SitemapManager::class);
|
||||
$manager->shouldReceive('regenerate')
|
||||
->once()
|
||||
->andReturn($xml);
|
||||
->andReturn([
|
||||
'success' => false,
|
||||
'status' => 'failed',
|
||||
'message' => 'contributor crashed',
|
||||
]);
|
||||
|
||||
$cache = Mockery::mock(CacheInterface::class);
|
||||
$cache->shouldReceive('put')
|
||||
->once()
|
||||
->with('seo.sitemap', $xml, 3600);
|
||||
|
||||
Log::shouldReceive('info')
|
||||
->once()
|
||||
->with('[SEO] Sitemap generated and cached', Mockery::on(function ($context) {
|
||||
return $context['ttl'] === 3600;
|
||||
}));
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$this->expectExceptionMessage('contributor crashed');
|
||||
|
||||
$job = new GenerateSitemapJob();
|
||||
$job->handle($generator, $cache);
|
||||
|
||||
$this->addToAssertionCount(Mockery::getContainer()->mockery_getExpectationCount());
|
||||
$job->handle($manager);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Listeners;
|
||||
|
||||
use App\Listeners\CoreActivityLogListener;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 회귀: 매니저(Module/Plugin/TemplateManager)의 after_deactivate 훅 발화 시그니처와
|
||||
* Listener 핸들러 메서드 시그니처가 일치해야 한다.
|
||||
*
|
||||
* 이슈 #302 자동 비활성화 경로(부팅 시 validateAndDeactivateIncompatible*) 가
|
||||
* 트리거될 때 다음 TypeError 가 발생하던 회귀 차단:
|
||||
*
|
||||
* handleTemplateAfterDeactivate(): Argument #1 ($templateInfo) must be of type
|
||||
* array, string given
|
||||
*
|
||||
* 매니저 측 호출:
|
||||
* HookManager::doAction('core.{type}s.after_deactivate', $identifier); // string 1 인자
|
||||
*
|
||||
* Listener 핸들러는 이 호출을 받아들여야 한다 (string 1 인자).
|
||||
*/
|
||||
class CoreActivityLogListenerSignatureTest extends TestCase
|
||||
{
|
||||
public function test_handle_template_after_deactivate_accepts_string_identifier(): void
|
||||
{
|
||||
$listener = $this->app->make(CoreActivityLogListener::class);
|
||||
|
||||
$reflection = new \ReflectionMethod($listener, 'handleTemplateAfterDeactivate');
|
||||
$params = $reflection->getParameters();
|
||||
|
||||
$this->assertCount(1, $params, '템플릿 after_deactivate 핸들러는 1개 인자 (string identifier) 만 받아야 한다');
|
||||
$this->assertSame('string', (string) $params[0]->getType(), '인자 타입이 string 이어야 매니저의 string 발화를 수용');
|
||||
}
|
||||
|
||||
public function test_handle_module_after_deactivate_accepts_string_identifier(): void
|
||||
{
|
||||
$listener = $this->app->make(CoreActivityLogListener::class);
|
||||
|
||||
$reflection = new \ReflectionMethod($listener, 'handleModuleAfterDeactivate');
|
||||
$params = $reflection->getParameters();
|
||||
|
||||
$this->assertCount(1, $params, '모듈 after_deactivate 핸들러는 1개 인자 (string identifier) 만 받아야 한다');
|
||||
$this->assertSame('string', (string) $params[0]->getType());
|
||||
}
|
||||
|
||||
public function test_handle_plugin_after_deactivate_accepts_string_identifier(): void
|
||||
{
|
||||
$listener = $this->app->make(CoreActivityLogListener::class);
|
||||
|
||||
$reflection = new \ReflectionMethod($listener, 'handlePluginAfterDeactivate');
|
||||
$params = $reflection->getParameters();
|
||||
|
||||
$this->assertCount(1, $params, '플러그인 after_deactivate 핸들러는 1개 인자 (string identifier) 만 받아야 한다');
|
||||
$this->assertSame('string', (string) $params[0]->getType());
|
||||
}
|
||||
|
||||
/**
|
||||
* 실제 호출 가능 여부 — TypeError 미발생 검증.
|
||||
*/
|
||||
public function test_handlers_are_callable_with_string_only(): void
|
||||
{
|
||||
$listener = $this->app->make(CoreActivityLogListener::class);
|
||||
|
||||
$listener->handleTemplateAfterDeactivate('test-template');
|
||||
$listener->handleModuleAfterDeactivate('test-module');
|
||||
$listener->handlePluginAfterDeactivate('test-plugin');
|
||||
|
||||
$this->assertTrue(true, 'string 단일 인자로 모두 호출 가능');
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,7 @@ class CoreActivityLogListenerTest extends TestCase
|
||||
// 관리자 경로 요청 설정 (resolveLogType()이 Admin 반환하도록)
|
||||
$this->app->instance('request', Request::create('/api/admin/users'));
|
||||
|
||||
$this->listener = new CoreActivityLogListener();
|
||||
$this->listener = app(CoreActivityLogListener::class);
|
||||
|
||||
// Mock Log::channel('activity') → $logChannel
|
||||
$this->logChannel = Mockery::mock(LoggerInterface::class);
|
||||
@@ -129,12 +129,12 @@ class CoreActivityLogListenerTest extends TestCase
|
||||
// getSubscribedHooks 테스트
|
||||
// ═══════════════════════════════════════════
|
||||
|
||||
public function test_getSubscribedHooks_returns_all_61_hooks(): void
|
||||
public function test_getSubscribedHooks_returns_all_hooks(): void
|
||||
{
|
||||
$hooks = CoreActivityLogListener::getSubscribedHooks();
|
||||
|
||||
// 59개 로깅(after_*) 훅 (mail_template 2개 제거됨, 스냅샷은 Service에서 캡처하여 인수로 전달)
|
||||
$this->assertCount(59, $hooks);
|
||||
// 64개 로깅(after_*) 훅 (mail_template 2개 제거됨, IDV/auth 후속 추가 분 포함, develop 머지 후 +2)
|
||||
$this->assertCount(64, $hooks);
|
||||
}
|
||||
|
||||
public function test_handle_does_nothing(): void
|
||||
@@ -1163,7 +1163,7 @@ class CoreActivityLogListenerTest extends TestCase
|
||||
&& $context['description_params']['template_name'] === 'sirsoft-basic';
|
||||
});
|
||||
|
||||
$this->listener->handleTemplateAfterDeactivate(['identifier' => 'sirsoft-basic']);
|
||||
$this->listener->handleTemplateAfterDeactivate('sirsoft-basic');
|
||||
}
|
||||
|
||||
public function test_handleTemplateAfterUninstall_logs_activity(): void
|
||||
|
||||
@@ -19,6 +19,11 @@ class DashboardModuleListenerTest extends TestCase
|
||||
*/
|
||||
public function test_listener_broadcasts_stats_on_module_change(): void
|
||||
{
|
||||
// HookManager::broadcast 는 broadcasting.default 가 null/log 이면 dispatch 스킵.
|
||||
// 테스트에서 이벤트 발행 경로를 검증하려면 활성 드라이버 + host 설정 필요.
|
||||
config(['broadcasting.default' => 'reverb']);
|
||||
config(['broadcasting.connections.reverb.options.host' => 'localhost']);
|
||||
|
||||
Event::fake([GenericBroadcastEvent::class]);
|
||||
|
||||
$mockService = Mockery::mock(DashboardService::class);
|
||||
|
||||
@@ -19,6 +19,10 @@ class DashboardStatsListenerTest extends TestCase
|
||||
*/
|
||||
public function test_listener_broadcasts_stats_update(): void
|
||||
{
|
||||
// HookManager::broadcast 는 null/log 드라이버 또는 host 미설정 시 dispatch 스킵
|
||||
config(['broadcasting.default' => 'reverb']);
|
||||
config(['broadcasting.connections.reverb.options.host' => 'localhost']);
|
||||
|
||||
Event::fake([GenericBroadcastEvent::class]);
|
||||
|
||||
$mockService = Mockery::mock(DashboardService::class);
|
||||
@@ -41,6 +45,10 @@ class DashboardStatsListenerTest extends TestCase
|
||||
*/
|
||||
public function test_listener_fetches_data_from_dashboard_service(): void
|
||||
{
|
||||
// HookManager::broadcast 는 null/log 드라이버 또는 host 미설정 시 dispatch 스킵
|
||||
config(['broadcasting.default' => 'reverb']);
|
||||
config(['broadcasting.connections.reverb.options.host' => 'localhost']);
|
||||
|
||||
Event::fake([GenericBroadcastEvent::class]);
|
||||
|
||||
$expectedData = [
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Listeners\LanguagePack;
|
||||
|
||||
use App\Enums\LanguagePackScope;
|
||||
use App\Enums\LanguagePackStatus;
|
||||
use App\Listeners\LanguagePack\MergeFrontendLanguage;
|
||||
use App\Models\LanguagePack;
|
||||
use App\Services\LanguagePack\LanguagePackRegistry;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* MergeFrontendLanguage 리스너 단위 테스트.
|
||||
*
|
||||
* `template.language.merge` 필터가 활성 언어팩의 frontend/*.json 데이터를
|
||||
* 우선순위(core ⊂ module ⊂ plugin ⊂ template) 로 병합하는지 검증.
|
||||
*/
|
||||
class MergeFrontendLanguageTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private MergeFrontendLanguage $listener;
|
||||
|
||||
private LanguagePackRegistry $registry;
|
||||
|
||||
/** @var array<int, string> 테스트에서 생성한 패키지 디렉토리 */
|
||||
private array $packDirs = [];
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->registry = $this->app->make(LanguagePackRegistry::class);
|
||||
$this->listener = $this->app->make(MergeFrontendLanguage::class);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
foreach ($this->packDirs as $dir) {
|
||||
File::deleteDirectory($dir);
|
||||
}
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 ja 언어팩 1건과 frontend/ja.json 을 함께 생성합니다.
|
||||
*
|
||||
* @param string $identifier 팩 식별자
|
||||
* @param string $scope scope
|
||||
* @param ?string $target target_identifier
|
||||
* @param array<string, mixed> $frontendData frontend/ja.json 내용
|
||||
* @return void
|
||||
*/
|
||||
private function setupJaPack(string $identifier, string $scope, ?string $target, array $frontendData): void
|
||||
{
|
||||
$packDir = base_path('lang-packs/'.$identifier);
|
||||
File::ensureDirectoryExists($packDir.'/frontend');
|
||||
File::put($packDir.'/frontend/ja.json', json_encode($frontendData));
|
||||
$this->packDirs[] = $packDir;
|
||||
|
||||
LanguagePack::query()->create([
|
||||
'identifier' => $identifier,
|
||||
'vendor' => 'g7',
|
||||
'scope' => $scope,
|
||||
'target_identifier' => $target,
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'Japanese',
|
||||
'locale_native_name' => '日本語',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => LanguagePackStatus::Active->value,
|
||||
'is_protected' => false,
|
||||
'manifest' => [],
|
||||
'source_type' => 'bundled',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_invoke_merges_japanese_frontend_into_template_data(): void
|
||||
{
|
||||
$this->setupJaPack('test-core-ja', LanguagePackScope::Core->value, null, [
|
||||
'common' => ['save' => '保存', 'cancel' => 'キャンセル'],
|
||||
]);
|
||||
$this->registry->invalidate();
|
||||
|
||||
$base = ['common' => ['save' => '저장']];
|
||||
$result = ($this->listener)($base, 'sirsoft-admin_basic', 'ja');
|
||||
|
||||
// ja 팩 값이 base 위로 병합 (later wins)
|
||||
$this->assertSame('保存', $result['common']['save']);
|
||||
$this->assertSame('キャンセル', $result['common']['cancel']);
|
||||
}
|
||||
|
||||
public function test_template_pack_overrides_module_pack_in_priority(): void
|
||||
{
|
||||
// 모듈 ja 팩: errors.404 = "見つかりません(モジュール)"
|
||||
$this->setupJaPack('test-module-ecommerce-ja', LanguagePackScope::Module->value, 'sirsoft-ecommerce', [
|
||||
'errors' => ['404' => '見つかりません(モジュール)'],
|
||||
]);
|
||||
// 템플릿 ja 팩: errors.404 = "見つかりません(テンプレート)" — 우선순위 최고
|
||||
$this->setupJaPack('test-template-admin-ja', LanguagePackScope::Template->value, 'sirsoft-admin_basic', [
|
||||
'errors' => ['404' => '見つかりません(テンプレート)'],
|
||||
]);
|
||||
$this->registry->invalidate();
|
||||
|
||||
$result = ($this->listener)([], 'sirsoft-admin_basic', 'ja');
|
||||
|
||||
// 템플릿이 모듈을 override
|
||||
$this->assertSame('見つかりません(テンプレート)', $result['errors']['404']);
|
||||
}
|
||||
|
||||
public function test_other_template_pack_is_not_merged_for_current_render(): void
|
||||
{
|
||||
// sirsoft-basic 용 템플릿 ja 팩 — 현재 렌더링 sirsoft-admin_basic 에는 적용 안 됨
|
||||
$this->setupJaPack('test-template-basic-ja', LanguagePackScope::Template->value, 'sirsoft-basic', [
|
||||
'shop' => ['title' => 'ショップ'],
|
||||
]);
|
||||
$this->registry->invalidate();
|
||||
|
||||
$result = ($this->listener)([], 'sirsoft-admin_basic', 'ja');
|
||||
|
||||
// 다른 템플릿 팩이라 병합 안 됨
|
||||
$this->assertArrayNotHasKey('shop', $result);
|
||||
}
|
||||
|
||||
public function test_skips_when_no_active_pack_for_locale(): void
|
||||
{
|
||||
// ko 만 active, ja 미활성
|
||||
$this->setupJaPack('test-core-ko-via-ja-record', LanguagePackScope::Core->value, null, [
|
||||
'common' => ['save' => '保存'],
|
||||
]);
|
||||
// locale 을 ko 로 강제 변경 (ja 검색 시 안 잡힘)
|
||||
LanguagePack::query()->where('identifier', 'test-core-ko-via-ja-record')->update(['locale' => 'ko']);
|
||||
$this->registry->invalidate();
|
||||
|
||||
$base = ['common' => ['save' => '저장']];
|
||||
$result = ($this->listener)($base, 'sirsoft-admin_basic', 'ja');
|
||||
|
||||
// ja 활성 팩 없음 → base 그대로
|
||||
$this->assertSame('저장', $result['common']['save']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Listeners\LanguagePack;
|
||||
|
||||
use App\Enums\LanguagePackScope;
|
||||
use App\Enums\LanguagePackStatus;
|
||||
use App\Listeners\LanguagePack\SyncDatabaseTranslations;
|
||||
use App\Models\IdentityMessageDefinition;
|
||||
use App\Models\IdentityMessageTemplate;
|
||||
use App\Models\LanguagePack;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* SyncDatabaseTranslations 단위 테스트.
|
||||
*
|
||||
* 활성/비활성 훅 페이로드를 받아 DB JSON 다국어 컬럼을 갱신/제거하는 핵심 로직과
|
||||
* user_overrides 보존 정책(§6.6 Case A/B/C)을 검증합니다.
|
||||
*/
|
||||
class SyncDatabaseTranslationsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private SyncDatabaseTranslations $listener;
|
||||
|
||||
private string $packRoot;
|
||||
|
||||
private string $packIdentifier = 'test-core-ja';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->listener = $this->app->make(SyncDatabaseTranslations::class);
|
||||
|
||||
$this->packRoot = base_path('lang-packs/'.$this->packIdentifier);
|
||||
File::ensureDirectoryExists($this->packRoot.'/seed');
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
File::deleteDirectory($this->packRoot);
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 코어 ja 언어팩과 permissions seed 파일을 생성합니다.
|
||||
*
|
||||
* @param array<string, mixed> $seedData permissions seed 데이터
|
||||
* @return LanguagePack 생성된 언어팩
|
||||
*/
|
||||
private function setupPackWithPermissionsSeed(array $seedData): LanguagePack
|
||||
{
|
||||
File::put($this->packRoot.'/seed/permissions.json', json_encode($seedData));
|
||||
File::put($this->packRoot.'/seed/roles.json', json_encode($seedData));
|
||||
|
||||
return LanguagePack::query()->create([
|
||||
'identifier' => $this->packIdentifier,
|
||||
'vendor' => 'test',
|
||||
'scope' => LanguagePackScope::Core->value,
|
||||
'target_identifier' => null,
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'Japanese',
|
||||
'locale_native_name' => '日本語',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => LanguagePackStatus::Active->value,
|
||||
'is_protected' => false,
|
||||
'manifest' => [],
|
||||
'source_type' => 'zip',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_case_a_adds_locale_when_absent(): void
|
||||
{
|
||||
$perm = Permission::query()->create([
|
||||
'identifier' => 'test.foo',
|
||||
'name' => ['ko' => '테스트', 'en' => 'Test'],
|
||||
'description' => ['ko' => '설명', 'en' => 'Description'],
|
||||
'extension_type' => 'core',
|
||||
'extension_identifier' => 'core',
|
||||
'order' => 1,
|
||||
]);
|
||||
|
||||
$pack = $this->setupPackWithPermissionsSeed([
|
||||
'test.foo' => ['name' => 'テスト', 'description' => '説明'],
|
||||
]);
|
||||
|
||||
$this->listener->handleActivated($pack);
|
||||
|
||||
$perm->refresh();
|
||||
$this->assertSame('テスト', $perm->name['ja']);
|
||||
$this->assertSame('설명', $perm->description['ko']);
|
||||
}
|
||||
|
||||
public function test_case_b_skips_locale_when_user_overrides_registered(): void
|
||||
{
|
||||
// Permission 은 HasUserOverrides 미사용이므로 Role 로 검증 (Role/Menu/Notification 모두 동일 정책)
|
||||
$role = Role::query()->create([
|
||||
'identifier' => 'test_role_b',
|
||||
'name' => ['ko' => '바', 'en' => 'Bar', 'ja' => '사용자수정'],
|
||||
'description' => ['ko' => 'D', 'en' => 'D'],
|
||||
'is_active' => true,
|
||||
'user_overrides' => ['name' => ['updated_at' => now()->toIso8601String()]],
|
||||
]);
|
||||
|
||||
$pack = $this->setupPackWithPermissionsSeed([
|
||||
'test_role_b' => ['name' => 'バー', 'description' => '説明'],
|
||||
]);
|
||||
|
||||
$this->listener->handleActivated($pack);
|
||||
|
||||
$role->refresh();
|
||||
// 사용자 수정 보존 — 시드 값으로 덮어쓰지 않음
|
||||
$this->assertSame('사용자수정', $role->name['ja']);
|
||||
// description 은 user_overrides 미등록이므로 시드 값 적용 가능
|
||||
$this->assertSame('説明', $role->description['ja']);
|
||||
}
|
||||
|
||||
public function test_case_c_overwrites_locale_when_no_overrides(): void
|
||||
{
|
||||
$perm = Permission::query()->create([
|
||||
'identifier' => 'test.baz',
|
||||
'name' => ['ko' => '바즈', 'en' => 'Baz', 'ja' => '구버전'],
|
||||
'description' => ['ko' => '', 'en' => ''],
|
||||
'extension_type' => 'core',
|
||||
'extension_identifier' => 'core',
|
||||
'order' => 1,
|
||||
]);
|
||||
|
||||
$pack = $this->setupPackWithPermissionsSeed([
|
||||
'test.baz' => ['name' => '신버전', 'description' => '説明'],
|
||||
]);
|
||||
|
||||
$this->listener->handleActivated($pack);
|
||||
|
||||
$perm->refresh();
|
||||
// user_overrides 미등록 → 시드 값으로 덮어쓰기
|
||||
$this->assertSame('신버전', $perm->name['ja']);
|
||||
}
|
||||
|
||||
public function test_deactivate_strips_locale(): void
|
||||
{
|
||||
$perm = Permission::query()->create([
|
||||
'identifier' => 'test.qux',
|
||||
'name' => ['ko' => '쿡스', 'en' => 'Qux', 'ja' => 'クックス'],
|
||||
'description' => ['ko' => '', 'en' => ''],
|
||||
'extension_type' => 'core',
|
||||
'extension_identifier' => 'core',
|
||||
'order' => 1,
|
||||
]);
|
||||
|
||||
$pack = $this->setupPackWithPermissionsSeed([
|
||||
'test.qux' => ['name' => 'クックス', 'description' => ''],
|
||||
]);
|
||||
|
||||
$this->listener->handleDeactivated($pack);
|
||||
|
||||
$perm->refresh();
|
||||
// 비활성화 시 ja 키 제거
|
||||
$this->assertArrayNotHasKey('ja', $perm->name);
|
||||
$this->assertArrayHasKey('ko', $perm->name);
|
||||
$this->assertArrayHasKey('en', $perm->name);
|
||||
}
|
||||
|
||||
public function test_deactivate_preserves_locale_when_user_overrides_registered(): void
|
||||
{
|
||||
$role = Role::query()->create([
|
||||
'identifier' => 'test_role_zed',
|
||||
'name' => ['ko' => '제드', 'en' => 'Zed', 'ja' => '사용자수정ja'],
|
||||
'description' => ['ko' => '', 'en' => ''],
|
||||
'is_active' => true,
|
||||
'user_overrides' => ['name' => ['updated_at' => now()->toIso8601String()]],
|
||||
]);
|
||||
|
||||
$pack = $this->setupPackWithPermissionsSeed([
|
||||
'test_role_zed' => ['name' => 'ゼド', 'description' => ''],
|
||||
]);
|
||||
|
||||
$this->listener->handleDeactivated($pack);
|
||||
|
||||
$role->refresh();
|
||||
// 사용자 보존 — 비활성화해도 ja 키 유지
|
||||
$this->assertSame('사용자수정ja', $role->name['ja']);
|
||||
}
|
||||
|
||||
public function test_activate_merges_identity_message_locale_into_definition_and_template(): void
|
||||
{
|
||||
// Definition: provider_id=g7:core.mail + scope_type=purpose + scope_value=signup → seed key `mail.purpose.signup`
|
||||
$def = IdentityMessageDefinition::query()->create([
|
||||
'provider_id' => 'g7:core.mail',
|
||||
'scope_type' => 'purpose',
|
||||
'scope_value' => 'signup',
|
||||
'name' => ['ko' => '회원가입 인증', 'en' => 'Signup Verification'],
|
||||
'description' => ['ko' => '회원가입 단계 인증', 'en' => 'Signup-stage verification'],
|
||||
'channels' => ['mail'],
|
||||
'variables' => [],
|
||||
'extension_type' => 'core',
|
||||
'extension_identifier' => 'core',
|
||||
'is_active' => true,
|
||||
'is_default' => true,
|
||||
]);
|
||||
|
||||
$tpl = IdentityMessageTemplate::query()->create([
|
||||
'definition_id' => $def->id,
|
||||
'channel' => 'mail',
|
||||
'subject' => ['ko' => '인증 코드', 'en' => 'Verification code'],
|
||||
'body' => ['ko' => '<p>안녕하세요</p>', 'en' => '<p>Hello</p>'],
|
||||
'is_active' => true,
|
||||
'is_default' => true,
|
||||
]);
|
||||
|
||||
File::put($this->packRoot.'/seed/identity_messages.json', json_encode([
|
||||
'mail.purpose.signup' => [
|
||||
'definition' => [
|
||||
'name' => '会員登録認証',
|
||||
'description' => '会員登録段階の認証',
|
||||
],
|
||||
'templates' => [
|
||||
'mail' => [
|
||||
'subject' => '認証コード',
|
||||
'body' => '<p>こんにちは</p>',
|
||||
],
|
||||
],
|
||||
],
|
||||
]));
|
||||
|
||||
$pack = LanguagePack::query()->create([
|
||||
'identifier' => $this->packIdentifier,
|
||||
'vendor' => 'test',
|
||||
'scope' => LanguagePackScope::Core->value,
|
||||
'target_identifier' => null,
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'Japanese',
|
||||
'locale_native_name' => '日本語',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => LanguagePackStatus::Active->value,
|
||||
'is_protected' => false,
|
||||
'manifest' => [],
|
||||
'source_type' => 'zip',
|
||||
]);
|
||||
|
||||
$this->listener->handleActivated($pack);
|
||||
|
||||
$def->refresh();
|
||||
$tpl->refresh();
|
||||
$this->assertSame('会員登録認証', $def->name['ja']);
|
||||
$this->assertSame('会員登録段階の認証', $def->description['ja']);
|
||||
$this->assertSame('認証コード', $tpl->subject['ja']);
|
||||
$this->assertSame('<p>こんにちは</p>', $tpl->body['ja']);
|
||||
// 기존 ko 키는 보존
|
||||
$this->assertSame('회원가입 인증', $def->name['ko']);
|
||||
}
|
||||
|
||||
public function test_deactivate_strips_identity_message_locale(): void
|
||||
{
|
||||
$def = IdentityMessageDefinition::query()->create([
|
||||
'provider_id' => 'g7:core.mail',
|
||||
'scope_type' => 'purpose',
|
||||
'scope_value' => 'signup',
|
||||
'name' => ['ko' => '회원가입 인증', 'en' => 'Signup', 'ja' => '会員登録認証'],
|
||||
'description' => ['ko' => '설명', 'en' => 'Desc'],
|
||||
'channels' => ['mail'],
|
||||
'variables' => [],
|
||||
'extension_type' => 'core',
|
||||
'extension_identifier' => 'core',
|
||||
'is_active' => true,
|
||||
'is_default' => true,
|
||||
]);
|
||||
|
||||
File::put($this->packRoot.'/seed/identity_messages.json', json_encode([]));
|
||||
$pack = LanguagePack::query()->create([
|
||||
'identifier' => $this->packIdentifier,
|
||||
'vendor' => 'test',
|
||||
'scope' => LanguagePackScope::Core->value,
|
||||
'target_identifier' => null,
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'Japanese',
|
||||
'locale_native_name' => '日本語',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => LanguagePackStatus::Inactive->value,
|
||||
'is_protected' => false,
|
||||
'manifest' => [],
|
||||
'source_type' => 'zip',
|
||||
]);
|
||||
|
||||
$this->listener->handleDeactivated($pack);
|
||||
|
||||
$def->refresh();
|
||||
$this->assertArrayNotHasKey('ja', $def->name);
|
||||
$this->assertSame('회원가입 인증', $def->name['ko']);
|
||||
}
|
||||
}
|
||||
@@ -70,7 +70,9 @@ class MenuUserOverridesListenerTest extends TestCase
|
||||
->with($menu, Mockery::on(function ($arg) {
|
||||
$overrides = $arg['user_overrides'];
|
||||
|
||||
return in_array('name', $overrides, true)
|
||||
// 다국어 JSON name 은 sub-key dot-path 단위로 기록 (7.0.0-beta.4+)
|
||||
return in_array('name.ko', $overrides, true)
|
||||
&& in_array('name.en', $overrides, true)
|
||||
&& in_array('icon', $overrides, true)
|
||||
&& in_array('order', $overrides, true)
|
||||
&& in_array('url', $overrides, true);
|
||||
@@ -199,11 +201,11 @@ class MenuUserOverridesListenerTest extends TestCase
|
||||
*/
|
||||
public function test_duplicate_override_not_added(): void
|
||||
{
|
||||
// name, icon이 이미 user_overrides에 있는 경우
|
||||
// name.ko, name.en, icon 이 이미 user_overrides 에 있는 경우 (sub-key dot-path 형식)
|
||||
$menu = new Menu();
|
||||
$menu->name = ['ko' => '대시보드', 'en' => 'Dashboard'];
|
||||
$menu->icon = 'fa-home';
|
||||
$menu->forceFill(['user_overrides' => ['name', 'icon']]);
|
||||
$menu->forceFill(['user_overrides' => ['name.ko', 'name.en', 'icon']]);
|
||||
|
||||
$data = [
|
||||
'name' => ['ko' => '홈', 'en' => 'Home'],
|
||||
|
||||
@@ -61,8 +61,11 @@ class RoleUserOverridesListenerTest extends TestCase
|
||||
$this->roleRepository->shouldReceive('update')
|
||||
->once()
|
||||
->with($role, Mockery::on(function ($arg) {
|
||||
return in_array('name', $arg['user_overrides'], true)
|
||||
&& ! in_array('description', $arg['user_overrides'], true);
|
||||
// 다국어 JSON name/description 은 sub-key dot-path 단위 (7.0.0-beta.4+)
|
||||
return in_array('name.ko', $arg['user_overrides'], true)
|
||||
&& in_array('name.en', $arg['user_overrides'], true)
|
||||
&& ! in_array('description.ko', $arg['user_overrides'], true)
|
||||
&& ! in_array('description.en', $arg['user_overrides'], true);
|
||||
}))
|
||||
->andReturn(true);
|
||||
|
||||
@@ -70,7 +73,7 @@ class RoleUserOverridesListenerTest extends TestCase
|
||||
}
|
||||
|
||||
/**
|
||||
* description 변경 시 user_overrides에 "description" 기록
|
||||
* description 변경 시 user_overrides에 sub-key dot-path 기록
|
||||
*/
|
||||
public function test_description_change_records_user_override(): void
|
||||
{
|
||||
@@ -84,8 +87,9 @@ class RoleUserOverridesListenerTest extends TestCase
|
||||
$this->roleRepository->shouldReceive('update')
|
||||
->once()
|
||||
->with($role, Mockery::on(function ($arg) {
|
||||
return in_array('description', $arg['user_overrides'], true)
|
||||
&& ! in_array('name', $arg['user_overrides'], true);
|
||||
return in_array('description.ko', $arg['user_overrides'], true)
|
||||
&& in_array('description.en', $arg['user_overrides'], true)
|
||||
&& ! in_array('name.ko', $arg['user_overrides'], true);
|
||||
}))
|
||||
->andReturn(true);
|
||||
|
||||
@@ -154,15 +158,15 @@ class RoleUserOverridesListenerTest extends TestCase
|
||||
*/
|
||||
public function test_duplicate_override_not_added(): void
|
||||
{
|
||||
// name이 이미 user_overrides에 있는 경우
|
||||
// name.ko/name.en 가 이미 user_overrides 에 있는 경우 (sub-key dot-path 형식)
|
||||
$role = new Role();
|
||||
$role->name = ['ko' => '관리자', 'en' => 'Admin'];
|
||||
$role->description = ['ko' => '설명', 'en' => 'Description'];
|
||||
$role->forceFill(['user_overrides' => ['name']]);
|
||||
$role->forceFill(['user_overrides' => ['name.ko', 'name.en']]);
|
||||
|
||||
$data = ['name' => ['ko' => '최고관리자', 'en' => 'Super Admin']];
|
||||
|
||||
// name이 이미 있으므로 update 호출 안 됨
|
||||
// 모든 변경 sub-key 가 이미 있으므로 update 호출 안 됨
|
||||
$this->roleRepository->shouldNotReceive('update');
|
||||
|
||||
$this->listener->handleBeforeUpdate($role, $data);
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Models;
|
||||
|
||||
use App\Enums\ActivityLogType;
|
||||
use App\Models\ActivityLog;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\App;
|
||||
use Illuminate\Support\Facades\Lang;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* ActivityLog::getActionLabelAttribute() 5단계 fallback 검증
|
||||
*
|
||||
* 모듈 lang 전체키 → 모듈 lang 마지막세그먼트 → 코어 lang 전체키
|
||||
* → 코어 lang 마지막세그먼트 → raw fallback 의 우선순위가 의도대로 동작하는지 회귀 차단.
|
||||
*/
|
||||
class ActivityLogActionLabelTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
App::setLocale('ko');
|
||||
}
|
||||
|
||||
/**
|
||||
* 1단계: loggable_type 으로부터 모듈 lang 의 전체 키 우선 매칭
|
||||
*/
|
||||
public function test_module_lang_full_key_takes_precedence_over_core_lang(): void
|
||||
{
|
||||
Lang::addNamespace('sirsoft-ecommerce', __DIR__);
|
||||
Lang::addLines([
|
||||
'activity_log.action.mileage.earn' => '마일리지 적립 (모듈)',
|
||||
], 'ko', 'sirsoft-ecommerce');
|
||||
Lang::addLines([
|
||||
'activity_log.action.mileage.earn' => '마일리지 적립 (코어)',
|
||||
], 'ko');
|
||||
|
||||
$log = ActivityLog::create([
|
||||
'log_type' => ActivityLogType::User,
|
||||
'action' => 'mileage.earn',
|
||||
'loggable_type' => 'Modules\\Sirsoft\\Ecommerce\\Models\\Order',
|
||||
'loggable_id' => 1,
|
||||
]);
|
||||
|
||||
$this->assertSame('마일리지 적립 (모듈)', $log->action_label);
|
||||
}
|
||||
|
||||
/**
|
||||
* 2단계: 모듈 lang 의 마지막 세그먼트 매칭 (전체키 미정의)
|
||||
*/
|
||||
public function test_falls_back_to_module_last_segment_when_full_key_missing(): void
|
||||
{
|
||||
Lang::addNamespace('sirsoft-ecommerce', __DIR__);
|
||||
Lang::addLines([
|
||||
'activity_log.action.confirm' => '구매 확정 (모듈)',
|
||||
], 'ko', 'sirsoft-ecommerce');
|
||||
|
||||
$log = ActivityLog::create([
|
||||
'log_type' => ActivityLogType::User,
|
||||
'action' => 'order.confirm',
|
||||
'loggable_type' => 'Modules\\Sirsoft\\Ecommerce\\Models\\Order',
|
||||
'loggable_id' => 1,
|
||||
]);
|
||||
|
||||
$this->assertSame('구매 확정 (모듈)', $log->action_label);
|
||||
}
|
||||
|
||||
/**
|
||||
* 3단계: 코어 lang 의 전체 키 매칭 (모듈 lang 정의 없음)
|
||||
*/
|
||||
public function test_falls_back_to_core_full_key_when_module_lang_missing(): void
|
||||
{
|
||||
Lang::addLines([
|
||||
'activity_log.action.user.create' => '사용자 생성 전체키',
|
||||
], 'ko');
|
||||
|
||||
$log = ActivityLog::create([
|
||||
'log_type' => ActivityLogType::Admin,
|
||||
'action' => 'user.create',
|
||||
'loggable_type' => 'App\\Models\\User',
|
||||
'loggable_id' => 1,
|
||||
]);
|
||||
|
||||
$this->assertSame('사용자 생성 전체키', $log->action_label);
|
||||
}
|
||||
|
||||
/**
|
||||
* 4단계: 코어 lang 의 마지막 세그먼트 매칭
|
||||
*/
|
||||
public function test_falls_back_to_core_last_segment(): void
|
||||
{
|
||||
$log = ActivityLog::create([
|
||||
'log_type' => ActivityLogType::Admin,
|
||||
'action' => 'user.create',
|
||||
'loggable_type' => 'App\\Models\\User',
|
||||
'loggable_id' => 1,
|
||||
]);
|
||||
|
||||
// 코어 lang/ko/activity_log.php 의 'create' => '생성'
|
||||
$this->assertSame('생성', $log->action_label);
|
||||
}
|
||||
|
||||
/**
|
||||
* 5단계: raw action 문자열 fallback (어디에도 정의 없음)
|
||||
*/
|
||||
public function test_returns_raw_action_when_no_lang_match(): void
|
||||
{
|
||||
$log = ActivityLog::create([
|
||||
'log_type' => ActivityLogType::System,
|
||||
'action' => 'unknown.bizarre_segment_xyz',
|
||||
]);
|
||||
|
||||
$this->assertSame('unknown.bizarre_segment_xyz', $log->action_label);
|
||||
}
|
||||
|
||||
/**
|
||||
* loggable_type 미지정 + properties.extension_origin 으로 origin 추론
|
||||
*/
|
||||
public function test_resolves_origin_from_properties_extension_origin_when_loggable_missing(): void
|
||||
{
|
||||
Lang::addNamespace('sirsoft-ecommerce', __DIR__);
|
||||
Lang::addLines([
|
||||
'activity_log.action.mileage.expire' => '마일리지 소멸 (모듈)',
|
||||
], 'ko', 'sirsoft-ecommerce');
|
||||
|
||||
$log = ActivityLog::create([
|
||||
'log_type' => ActivityLogType::System,
|
||||
'action' => 'mileage.expire',
|
||||
'loggable_type' => null,
|
||||
'loggable_id' => null,
|
||||
'properties' => ['extension_origin' => 'sirsoft-ecommerce'],
|
||||
]);
|
||||
|
||||
$this->assertSame('마일리지 소멸 (모듈)', $log->action_label);
|
||||
}
|
||||
|
||||
/**
|
||||
* 코어 origin 라벨이 모듈 변경에도 회귀 없이 동작 (하위 호환)
|
||||
*/
|
||||
public function test_core_origin_action_label_unchanged_after_introduction(): void
|
||||
{
|
||||
$log = ActivityLog::create([
|
||||
'log_type' => ActivityLogType::Admin,
|
||||
'action' => 'auth.login',
|
||||
'loggable_type' => 'App\\Models\\User',
|
||||
'loggable_id' => 1,
|
||||
]);
|
||||
|
||||
$this->assertSame('로그인', $log->action_label);
|
||||
}
|
||||
}
|
||||
@@ -82,8 +82,7 @@ class BoardModelTest extends TestCase
|
||||
'max_file_count' => 5,
|
||||
'allowed_extensions' => ['jpg', 'png', 'pdf'],
|
||||
'comment_order' => 'ASC',
|
||||
'board_manager_id' => null,
|
||||
'notify_author_on_comment' => false,
|
||||
'notify_author' => false,
|
||||
'notify_admin_on_post' => false,
|
||||
'blocked_keywords' => ['금지어1', '금지어2'],
|
||||
];
|
||||
@@ -182,6 +181,8 @@ class BoardModelTest extends TestCase
|
||||
|
||||
/**
|
||||
* boolean 필드가 정상적으로 캐스팅되는지 테스트
|
||||
*
|
||||
* 참고: `notify_author_on_comment` 은 `notify_author` 로 필드 리네임됨 (모듈 리팩토링)
|
||||
*/
|
||||
public function test_boolean_fields_are_cast_correctly(): void
|
||||
{
|
||||
@@ -194,7 +195,7 @@ class BoardModelTest extends TestCase
|
||||
'use_reply' => true,
|
||||
'use_report' => false,
|
||||
'use_file_upload' => true,
|
||||
'notify_author_on_comment' => false,
|
||||
'notify_author' => false,
|
||||
'notify_admin_on_post' => true,
|
||||
]);
|
||||
|
||||
@@ -205,29 +206,13 @@ class BoardModelTest extends TestCase
|
||||
$this->assertTrue($board->use_reply);
|
||||
$this->assertFalse($board->use_report);
|
||||
$this->assertTrue($board->use_file_upload);
|
||||
$this->assertFalse($board->notify_author_on_comment);
|
||||
$this->assertFalse($board->notify_author);
|
||||
$this->assertTrue($board->notify_admin_on_post);
|
||||
}
|
||||
|
||||
/**
|
||||
* boardManager 관계 테스트
|
||||
*/
|
||||
public function test_belongs_to_board_manager(): void
|
||||
{
|
||||
// Arrange
|
||||
$user = User::factory()->create();
|
||||
|
||||
// Act
|
||||
$board = $this->createBoard([
|
||||
'name' => ['ko' => '게시판'],
|
||||
'slug' => 'test-board',
|
||||
'board_manager_id' => $user->id,
|
||||
]);
|
||||
|
||||
// Assert
|
||||
$this->assertInstanceOf(User::class, $board->boardManager);
|
||||
$this->assertEquals($user->id, $board->boardManager->id);
|
||||
}
|
||||
// 참고: `board_manager_id` 컬럼 및 `boardManager()` 관계는
|
||||
// 모듈 리팩토링으로 제거됨 (게시판 매니저는 Role/Permission 기반으로 이행).
|
||||
// 따라서 `test_belongs_to_board_manager` 는 삭제됨.
|
||||
|
||||
/**
|
||||
* creator 관계 테스트
|
||||
@@ -360,20 +345,27 @@ class BoardModelTest extends TestCase
|
||||
}
|
||||
|
||||
/**
|
||||
* guarded 속성 테스트 (created_by, updated_by)
|
||||
* created_by / updated_by 가 fillable 로 설정되어 명시 할당 시 저장된다.
|
||||
*
|
||||
* Board model 은 created_by/updated_by 를 $fillable 에 포함해
|
||||
* 서비스 계층에서 명시적으로 제공할 수 있도록 설계됨.
|
||||
* (auto-fill trait 은 부재 — 서비스에서 Auth::id() 등 책임 주입)
|
||||
*/
|
||||
public function test_created_by_and_updated_by_are_guarded(): void
|
||||
public function test_created_by_and_updated_by_are_fillable(): void
|
||||
{
|
||||
// Arrange: FK 제약 통과를 위해 실제 User 생성
|
||||
$creator = \App\Models\User::factory()->create();
|
||||
|
||||
// Act
|
||||
$board = $this->createBoard([
|
||||
'name' => ['ko' => '게시판'],
|
||||
'slug' => 'test-board',
|
||||
'created_by' => 999, // guarded이므로 무시되어야 함
|
||||
'updated_by' => 999, // guarded이므로 무시되어야 함
|
||||
'created_by' => $creator->id,
|
||||
'updated_by' => $creator->id,
|
||||
]);
|
||||
|
||||
// Assert
|
||||
$this->assertNull($board->created_by);
|
||||
$this->assertNull($board->updated_by);
|
||||
$this->assertSame($creator->id, $board->created_by);
|
||||
$this->assertSame($creator->id, $board->updated_by);
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,8 @@ class HasUserOverridesMassUpdateTest extends TestCase
|
||||
|
||||
$this->assertSame(['ko' => '사용자 수정'], $reloaded->name);
|
||||
$this->assertIsArray($reloaded->user_overrides);
|
||||
$this->assertContains('name', $reloaded->user_overrides, 'mass update 시에도 trackable 필드가 user_overrides 에 자동 기록');
|
||||
// 7.0.0-beta.4+ 다국어 컬럼은 sub-key dot-path 단위 기록
|
||||
$this->assertContains('name.ko', $reloaded->user_overrides, 'mass update 시에도 다국어 sub-key 가 user_overrides 에 자동 기록');
|
||||
}
|
||||
|
||||
public function test_mass_update_accumulates_overrides_across_multiple_edits(): void
|
||||
@@ -69,7 +70,7 @@ class HasUserOverridesMassUpdateTest extends TestCase
|
||||
|
||||
$reloaded = NotificationDefinition::find($definition->id);
|
||||
|
||||
$this->assertContains('name', $reloaded->user_overrides);
|
||||
$this->assertContains('name.ko', $reloaded->user_overrides);
|
||||
$this->assertContains('is_active', $reloaded->user_overrides, '여러 번의 mass update 가 누적 기록');
|
||||
}
|
||||
|
||||
@@ -101,8 +102,8 @@ class HasUserOverridesMassUpdateTest extends TestCase
|
||||
$reloadedA = NotificationDefinition::find($a->id);
|
||||
$reloadedB = NotificationDefinition::find($b->id);
|
||||
|
||||
$this->assertContains('name', $reloadedA->user_overrides ?? []);
|
||||
$this->assertContains('name', $reloadedB->user_overrides ?? []);
|
||||
$this->assertContains('name.ko', $reloadedA->user_overrides ?? []);
|
||||
$this->assertContains('name.ko', $reloadedB->user_overrides ?? []);
|
||||
}
|
||||
|
||||
public function test_seeder_context_bypasses_tracking_on_mass_update(): void
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Models\Concerns;
|
||||
|
||||
use App\Models\Menu;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* HasUserOverrides Trait 의 다국어 JSON 컬럼 sub-key dot-path 추적/보존 검증.
|
||||
*
|
||||
* 7.0.0-beta.4 신규 정책:
|
||||
* - $translatableTrackableFields 에 정의된 다국어 JSON 컬럼은 sub-key 단위로 추적
|
||||
* - 사용자가 ko 만 수정 → user_overrides=['name.ko']
|
||||
* - 시더 재실행 시 ko 만 보존, 신규 locale 키(en/ja) 는 자동 동기화
|
||||
* - 일반 scalar 필드 (icon, order 등) 는 컬럼 단위 추적 (기존 동작)
|
||||
*
|
||||
* Menu 모델을 reference 로 사용 — name(translatable JSON) + icon/order/url(scalar) 혼합.
|
||||
*/
|
||||
class HasUserOverridesSubKeyTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private function createMenu(array $attributes = []): Menu
|
||||
{
|
||||
return Menu::create(array_merge([
|
||||
'name' => ['ko' => '초기 메뉴', 'en' => 'Initial Menu'],
|
||||
'slug' => 'test-menu-'.uniqid(),
|
||||
'url' => '/test',
|
||||
'icon' => 'home',
|
||||
'order' => 0,
|
||||
'is_active' => true,
|
||||
], $attributes));
|
||||
}
|
||||
|
||||
/** 시나리오 1: 다국어 컬럼 ko 만 수정 → user_overrides=['name.ko'] */
|
||||
public function test_translatable_subkey_ko_only_modification_records_dot_path(): void
|
||||
{
|
||||
$menu = $this->createMenu();
|
||||
|
||||
$menu->name = ['ko' => '수정된 메뉴', 'en' => 'Initial Menu'];
|
||||
$menu->save();
|
||||
|
||||
$this->assertEquals(['name.ko'], $menu->fresh()->user_overrides);
|
||||
}
|
||||
|
||||
/** 시나리오 2: ko, en 동시 수정 → user_overrides=['name.ko', 'name.en'] */
|
||||
public function test_translatable_subkey_multiple_locales_modification(): void
|
||||
{
|
||||
$menu = $this->createMenu();
|
||||
|
||||
$menu->name = ['ko' => '수정 ko', 'en' => 'Modified EN'];
|
||||
$menu->save();
|
||||
|
||||
$this->assertEqualsCanonicalizing(
|
||||
['name.ko', 'name.en'],
|
||||
$menu->fresh()->user_overrides
|
||||
);
|
||||
}
|
||||
|
||||
/** 시나리오 3: ko 보존 + ja 신규 추가 (시더 재실행 시) — 사용자 ko 보존, ja 자동 동기화 */
|
||||
public function test_sync_from_upgrade_preserves_overridden_subkey_only(): void
|
||||
{
|
||||
$menu = $this->createMenu();
|
||||
$menu->name = ['ko' => '사용자 수정 ko', 'en' => 'Initial Menu'];
|
||||
$menu->save();
|
||||
|
||||
// 시더가 ja 포함 신규 데이터로 재실행
|
||||
$menu->syncFromUpgrade([
|
||||
'name' => ['ko' => '시더 ko', 'en' => 'Seeder EN', 'ja' => 'シーダー JA'],
|
||||
]);
|
||||
|
||||
$fresh = $menu->fresh();
|
||||
$this->assertEquals('사용자 수정 ko', $fresh->name['ko']); // ko 보존
|
||||
$this->assertEquals('Seeder EN', $fresh->name['en']); // en 갱신
|
||||
$this->assertEquals('シーダー JA', $fresh->name['ja']); // ja 자동 추가
|
||||
}
|
||||
|
||||
/** 시나리오 4: 사용자 미수정 시 시더 재실행이 전체 갱신 */
|
||||
public function test_sync_from_upgrade_full_replace_when_no_user_overrides(): void
|
||||
{
|
||||
$menu = $this->createMenu();
|
||||
|
||||
$menu->syncFromUpgrade([
|
||||
'name' => ['ko' => '시더 ko', 'en' => 'Seeder EN', 'ja' => 'シーダー JA'],
|
||||
]);
|
||||
|
||||
$fresh = $menu->fresh();
|
||||
$this->assertEquals(['ko' => '시더 ko', 'en' => 'Seeder EN', 'ja' => 'シーダー JA'], $fresh->name);
|
||||
$this->assertNull($fresh->user_overrides);
|
||||
}
|
||||
|
||||
/** 시나리오 5: legacy 컬럼명 user_overrides=['name'] → 전체 컬럼 보존 (역호환) */
|
||||
public function test_sync_from_upgrade_legacy_column_level_override_preserved(): void
|
||||
{
|
||||
$menu = $this->createMenu();
|
||||
// 마이그레이션 전 형식 시뮬레이션
|
||||
$menu->update(['user_overrides' => ['name']]);
|
||||
|
||||
$menu->syncFromUpgrade([
|
||||
'name' => ['ko' => '시더 ko', 'en' => 'Seeder EN', 'ja' => 'シーダー JA'],
|
||||
]);
|
||||
|
||||
$fresh = $menu->fresh();
|
||||
$this->assertEquals(['ko' => '초기 메뉴', 'en' => 'Initial Menu'], $fresh->name);
|
||||
}
|
||||
|
||||
/** 시나리오 6: scalar 필드 (icon) 수정 → 컬럼명 단위 기록 (기존 동작) */
|
||||
public function test_scalar_trackable_field_records_column_name(): void
|
||||
{
|
||||
$menu = $this->createMenu();
|
||||
|
||||
$menu->icon = 'changed-icon';
|
||||
$menu->save();
|
||||
|
||||
$this->assertEquals(['icon'], $menu->fresh()->user_overrides);
|
||||
}
|
||||
|
||||
/** 시나리오 7: scalar + translatable 동시 수정 → 두 형식 혼재 */
|
||||
public function test_mixed_scalar_and_translatable_modification(): void
|
||||
{
|
||||
$menu = $this->createMenu();
|
||||
|
||||
$menu->icon = 'new-icon';
|
||||
$menu->name = ['ko' => '수정 ko', 'en' => 'Initial Menu'];
|
||||
$menu->save();
|
||||
|
||||
$this->assertEqualsCanonicalizing(
|
||||
['icon', 'name.ko'],
|
||||
$menu->fresh()->user_overrides
|
||||
);
|
||||
}
|
||||
|
||||
/** 시나리오 8: scalar 필드는 syncFromUpgrade 시 user_overrides 등록 시 갱신 SKIP (기존 동작 회귀 없음) */
|
||||
public function test_sync_from_upgrade_preserves_scalar_overridden_field(): void
|
||||
{
|
||||
$menu = $this->createMenu();
|
||||
$menu->icon = 'user-icon';
|
||||
$menu->save();
|
||||
|
||||
$menu->syncFromUpgrade([
|
||||
'icon' => 'seeder-icon',
|
||||
'order' => 99,
|
||||
]);
|
||||
|
||||
$fresh = $menu->fresh();
|
||||
$this->assertEquals('user-icon', $fresh->icon); // 보존
|
||||
$this->assertEquals(99, $fresh->order); // 갱신
|
||||
}
|
||||
|
||||
/** 시나리오 9: 시더가 일부 locale 만 제공 + 사용자 보존 locale 누락 시 사용자 값 유지 */
|
||||
public function test_sync_from_upgrade_keeps_user_locale_when_seeder_omits_it(): void
|
||||
{
|
||||
$menu = $this->createMenu();
|
||||
$menu->name = ['ko' => '사용자 ko', 'en' => 'Initial Menu'];
|
||||
$menu->save();
|
||||
|
||||
// 시더가 ja 만 제공 (ko 누락)
|
||||
$menu->syncFromUpgrade([
|
||||
'name' => ['ja' => 'シーダー JA'],
|
||||
]);
|
||||
|
||||
$fresh = $menu->fresh();
|
||||
$this->assertEquals('사용자 ko', $fresh->name['ko']);
|
||||
$this->assertEquals('シーダー JA', $fresh->name['ja']);
|
||||
}
|
||||
|
||||
/** 시나리오 10: mass update 경로에서도 sub-key dot-path 자동 추적 */
|
||||
public function test_mass_update_records_subkey_overrides(): void
|
||||
{
|
||||
$menu = $this->createMenu();
|
||||
|
||||
Menu::where('id', $menu->id)->update([
|
||||
'name' => ['ko' => '대량 수정 ko', 'en' => 'Initial Menu'],
|
||||
]);
|
||||
|
||||
$this->assertEquals(['name.ko'], $menu->fresh()->user_overrides);
|
||||
}
|
||||
|
||||
/** 시나리오 11: 동일 sub-key 반복 수정 시 user_overrides 중복 없음 */
|
||||
public function test_repeated_subkey_modification_no_duplicate(): void
|
||||
{
|
||||
$menu = $this->createMenu();
|
||||
|
||||
$menu->name = ['ko' => '첫 수정', 'en' => 'Initial Menu'];
|
||||
$menu->save();
|
||||
$menu->name = ['ko' => '두 번째 수정', 'en' => 'Initial Menu'];
|
||||
$menu->save();
|
||||
|
||||
$this->assertEquals(['name.ko'], $menu->fresh()->user_overrides);
|
||||
}
|
||||
|
||||
/** 시나리오 12: 다른 locale 추가 수정 시 누적 */
|
||||
public function test_subsequent_locale_modification_accumulates(): void
|
||||
{
|
||||
$menu = $this->createMenu();
|
||||
|
||||
$menu->name = ['ko' => '수정 ko', 'en' => 'Initial Menu'];
|
||||
$menu->save();
|
||||
|
||||
$menu->name = ['ko' => '수정 ko', 'en' => 'Modified EN'];
|
||||
$menu->save();
|
||||
|
||||
$this->assertEqualsCanonicalizing(
|
||||
['name.ko', 'name.en'],
|
||||
$menu->fresh()->user_overrides
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Models;
|
||||
|
||||
use App\Models\IdentityMessageDefinition;
|
||||
use App\Models\IdentityMessageTemplate;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* IdentityMessageTemplate 모델 단위 테스트.
|
||||
*
|
||||
* 다국어 fallback, replaceVariables, user_overrides 보존을 격리 검증.
|
||||
*/
|
||||
class IdentityMessageTemplateTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private IdentityMessageDefinition $definition;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->definition = IdentityMessageDefinition::create([
|
||||
'provider_id' => 'g7:core.mail',
|
||||
'scope_type' => IdentityMessageDefinition::SCOPE_PURPOSE,
|
||||
'scope_value' => 'signup',
|
||||
'name' => ['ko' => '회원가입 인증', 'en' => 'Signup Verification'],
|
||||
'channels' => ['mail'],
|
||||
'extension_type' => 'core',
|
||||
'extension_identifier' => 'core',
|
||||
'is_active' => true,
|
||||
'is_default' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_localized_subject_returns_current_locale(): void
|
||||
{
|
||||
$template = $this->makeTemplate([
|
||||
'subject' => ['ko' => '한글 제목', 'en' => 'English Subject'],
|
||||
'body' => ['ko' => '한글 본문', 'en' => 'English body'],
|
||||
]);
|
||||
|
||||
$this->assertSame('한글 제목', $template->getLocalizedSubject('ko'));
|
||||
$this->assertSame('English Subject', $template->getLocalizedSubject('en'));
|
||||
}
|
||||
|
||||
public function test_localized_subject_falls_back_to_ko_then_en(): void
|
||||
{
|
||||
$template = $this->makeTemplate([
|
||||
'subject' => ['ko' => '한글만'],
|
||||
'body' => ['ko' => '본문'],
|
||||
]);
|
||||
|
||||
$this->assertSame('한글만', $template->getLocalizedSubject('en'));
|
||||
$this->assertSame('한글만', $template->getLocalizedSubject('ja'));
|
||||
}
|
||||
|
||||
public function test_replace_variables_substitutes_placeholders(): void
|
||||
{
|
||||
$template = $this->makeTemplate([
|
||||
'subject' => ['ko' => '[{app_name}] 인증 코드', 'en' => '[{app_name}] Code'],
|
||||
'body' => ['ko' => '코드: {code} (만료 {expire_minutes}분)', 'en' => 'Code: {code} ({expire_minutes}m)'],
|
||||
]);
|
||||
|
||||
$rendered = $template->replaceVariables(
|
||||
['app_name' => '테스트사이트', 'code' => '987654', 'expire_minutes' => 10],
|
||||
'ko'
|
||||
);
|
||||
|
||||
$this->assertSame('[테스트사이트] 인증 코드', $rendered['subject']);
|
||||
$this->assertSame('코드: 987654 (만료 10분)', $rendered['body']);
|
||||
$this->assertStringNotContainsString('{code}', $rendered['body']);
|
||||
}
|
||||
|
||||
public function test_replace_variables_skips_null_values_safely(): void
|
||||
{
|
||||
$template = $this->makeTemplate([
|
||||
'subject' => ['ko' => '코드: {code}', 'en' => 'Code: {code}'],
|
||||
'body' => ['ko' => '링크: {action_url}', 'en' => 'Link: {action_url}'],
|
||||
]);
|
||||
|
||||
// text_code 흐름이라 action_url=null. 본문에 {action_url} 잔여 허용 (운영자가 본문 수정 시 의도 가시화).
|
||||
$rendered = $template->replaceVariables(
|
||||
['code' => '111222', 'action_url' => null],
|
||||
'ko'
|
||||
);
|
||||
|
||||
$this->assertSame('코드: 111222', $rendered['subject']);
|
||||
$this->assertStringContainsString('{action_url}', $rendered['body'], 'null 값은 치환에서 제외되어 잔여 토큰이 유지되어야 합니다.');
|
||||
}
|
||||
|
||||
public function test_user_overrides_records_field_change_outside_seeder(): void
|
||||
{
|
||||
$template = $this->makeTemplate([
|
||||
'subject' => ['ko' => '원본', 'en' => 'Original'],
|
||||
'body' => ['ko' => '본문', 'en' => 'Body'],
|
||||
]);
|
||||
|
||||
$template->update(['subject' => ['ko' => '변경됨', 'en' => 'Changed']]);
|
||||
$template->refresh();
|
||||
|
||||
$this->assertContains('subject', $template->user_overrides ?? []);
|
||||
}
|
||||
|
||||
public function test_user_overrides_skips_recording_in_seeder_context(): void
|
||||
{
|
||||
app()->instance('user_overrides.seeding', true);
|
||||
|
||||
try {
|
||||
$template = $this->makeTemplate([
|
||||
'subject' => ['ko' => '원본', 'en' => 'Original'],
|
||||
'body' => ['ko' => '본문', 'en' => 'Body'],
|
||||
]);
|
||||
|
||||
$template->update(['subject' => ['ko' => '시드재실행', 'en' => 'Reseed']]);
|
||||
$template->refresh();
|
||||
|
||||
$this->assertEmpty(
|
||||
$template->user_overrides ?? [],
|
||||
'시더 컨텍스트에서는 user_overrides 가 기록되지 않아야 합니다.'
|
||||
);
|
||||
} finally {
|
||||
app()->forgetInstance('user_overrides.seeding');
|
||||
}
|
||||
}
|
||||
|
||||
public function test_active_scope_filters_inactive_templates(): void
|
||||
{
|
||||
$this->makeTemplate(['subject' => ['ko' => 'A'], 'body' => ['ko' => 'a'], 'is_active' => true]);
|
||||
|
||||
IdentityMessageTemplate::create([
|
||||
'definition_id' => $this->definition->id,
|
||||
'channel' => 'sms',
|
||||
'subject' => ['ko' => 'B'],
|
||||
'body' => ['ko' => 'b'],
|
||||
'is_active' => false,
|
||||
'is_default' => true,
|
||||
]);
|
||||
|
||||
$this->assertSame(1, IdentityMessageTemplate::active()->count());
|
||||
$this->assertSame(1, IdentityMessageTemplate::active()->byChannel('mail')->count());
|
||||
$this->assertSame(0, IdentityMessageTemplate::active()->byChannel('sms')->count());
|
||||
}
|
||||
|
||||
/**
|
||||
* 헬퍼 — 기본 템플릿 생성.
|
||||
*/
|
||||
private function makeTemplate(array $overrides = []): IdentityMessageTemplate
|
||||
{
|
||||
return IdentityMessageTemplate::create(array_merge([
|
||||
'definition_id' => $this->definition->id,
|
||||
'channel' => 'mail',
|
||||
'subject' => ['ko' => '제목', 'en' => 'Subject'],
|
||||
'body' => ['ko' => '본문', 'en' => 'Body'],
|
||||
'is_active' => true,
|
||||
'is_default' => true,
|
||||
], $overrides));
|
||||
}
|
||||
}
|
||||
@@ -41,9 +41,18 @@ class ProductLabelAssignmentTest extends TestCase
|
||||
$this->markTestSkipped('sirsoft-ecommerce 모듈이 설치되어 있지 않습니다.');
|
||||
}
|
||||
|
||||
// 모듈 마이그레이션 실행
|
||||
// 모듈 마이그레이션 실행 — 활성 디렉토리 우선, 부재 시 _bundled 로 폴백
|
||||
$activeMigrationPath = base_path('modules/sirsoft-ecommerce/database/migrations');
|
||||
$bundledMigrationPath = base_path('modules/_bundled/sirsoft-ecommerce/database/migrations');
|
||||
|
||||
$migrationPath = is_dir($activeMigrationPath) ? $activeMigrationPath : $bundledMigrationPath;
|
||||
|
||||
if (! is_dir($migrationPath)) {
|
||||
$this->markTestSkipped('sirsoft-ecommerce 마이그레이션 디렉토리를 찾을 수 없습니다.');
|
||||
}
|
||||
|
||||
$this->artisan('migrate', [
|
||||
'--path' => 'modules/sirsoft-ecommerce/database/migrations',
|
||||
'--path' => $migrationPath,
|
||||
'--realpath' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -80,10 +80,13 @@ class GenericNotificationTest extends TestCase
|
||||
|
||||
/**
|
||||
* via()가 notification_definitions 테이블에서 채널을 조회하는지 확인
|
||||
*
|
||||
* engine-v1.x+ 이후 via() 는 (a) 확장 채널 활성 여부 (b) readiness (c) 활성 템플릿 존재 여부
|
||||
* 를 모두 검증하므로, 채널별 NotificationTemplate 가 있어야 최종 채널에 포함됨.
|
||||
*/
|
||||
public function test_via_reads_channels_from_definition(): void
|
||||
{
|
||||
NotificationDefinition::create([
|
||||
$definition = NotificationDefinition::create([
|
||||
'type' => 'test_notification',
|
||||
'hook_prefix' => 'core.test',
|
||||
'extension_type' => 'core',
|
||||
@@ -96,6 +99,18 @@ class GenericNotificationTest extends TestCase
|
||||
'is_default' => true,
|
||||
]);
|
||||
|
||||
// 각 채널별 활성 템플릿 등록 (없으면 via() 가 filter out)
|
||||
foreach (['mail', 'database'] as $channel) {
|
||||
NotificationTemplate::create([
|
||||
'definition_id' => $definition->id,
|
||||
'channel' => $channel,
|
||||
'locale' => 'ko',
|
||||
'subject' => '테스트 제목',
|
||||
'body' => '테스트 본문',
|
||||
'is_active' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
// 캐시를 무효화하여 최신 데이터 반영
|
||||
app(NotificationDefinitionService::class)->invalidateCache('test_notification');
|
||||
|
||||
@@ -109,15 +124,19 @@ class GenericNotificationTest extends TestCase
|
||||
|
||||
/**
|
||||
* 정의가 없을 때 via()가 기본 ['mail'] 채널을 반환하는지 확인
|
||||
*
|
||||
* 현재 구현은 mail 채널에도 활성 템플릿 존재를 요구하므로, 정의 없으면 템플릿도 없어
|
||||
* via() 는 빈 배열을 반환한다. (채널 skip 은 notification_logs 에 기록됨)
|
||||
*/
|
||||
public function test_via_returns_mail_default_when_no_definition(): void
|
||||
public function test_via_returns_empty_when_no_definition_or_template(): void
|
||||
{
|
||||
$notification = new GenericNotification('nonexistent_type', 'core.auth');
|
||||
$user = new User(['email' => 'test@example.com']);
|
||||
|
||||
$channels = $notification->via($user);
|
||||
|
||||
$this->assertEquals(['mail'], $channels);
|
||||
// 활성 템플릿 없으면 모든 채널이 skip 됨 (회귀 방지 — 이전엔 ['mail'] 기본 반환)
|
||||
$this->assertEquals([], $channels);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Providers;
|
||||
|
||||
use App\Providers\InstallerRuntimeServiceProvider;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* InstallerRuntimeServiceProvider 단위 테스트
|
||||
*
|
||||
* 설치 진행 중 storage/installer/runtime.php 의 동적 설정이
|
||||
* Laravel config 에 정상 주입되는지, 부재 시 부팅에 영향이 없는지 검증.
|
||||
*
|
||||
* @see https://github.com/gnuboard/g7/issues/23
|
||||
*/
|
||||
class InstallerRuntimeServiceProviderTest extends TestCase
|
||||
{
|
||||
private string $runtimePath;
|
||||
|
||||
private ?string $originalEnv = null;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->runtimePath = base_path('storage/installer/runtime.php');
|
||||
|
||||
// 테스트 시작 시 runtime.php 정리 (이전 테스트의 잔재 제거)
|
||||
if (is_file($this->runtimePath)) {
|
||||
@unlink($this->runtimePath);
|
||||
}
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
// 테스트 후 정리 — 운영 환경 영향 방지
|
||||
if (is_file($this->runtimePath)) {
|
||||
@unlink($this->runtimePath);
|
||||
}
|
||||
|
||||
$dir = dirname($this->runtimePath);
|
||||
if (is_dir($dir) && count(scandir($dir)) === 2) {
|
||||
@rmdir($dir);
|
||||
}
|
||||
|
||||
if ($this->originalEnv !== null) {
|
||||
$this->app['env'] = $this->originalEnv;
|
||||
$this->originalEnv = null;
|
||||
}
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 인스톨러 runtime 파일의 주입을 검증하기 위해 일시적으로 production 환경으로 전환.
|
||||
*
|
||||
* register() 가 testing 환경을 감지하면 즉시 return 하므로,
|
||||
* 주입 동작 자체를 검증하는 테스트는 비-테스팅 환경 컨텍스트에서 실행.
|
||||
*/
|
||||
private function withProductionEnv(): void
|
||||
{
|
||||
$this->originalEnv = $this->app['env'] ?? null;
|
||||
$this->app['env'] = 'production';
|
||||
}
|
||||
|
||||
public function test_provider_skips_silently_when_runtime_file_absent(): void
|
||||
{
|
||||
$this->withProductionEnv();
|
||||
$this->assertFileDoesNotExist($this->runtimePath);
|
||||
|
||||
// 기존 config 값 보존 — Provider 가 덮어쓰지 않음
|
||||
$originalHost = Config::get('database.connections.mysql.write.host');
|
||||
$originalKey = Config::get('app.key');
|
||||
|
||||
$provider = new InstallerRuntimeServiceProvider($this->app);
|
||||
$provider->register();
|
||||
|
||||
$this->assertSame($originalHost, Config::get('database.connections.mysql.write.host'));
|
||||
$this->assertSame($originalKey, Config::get('app.key'));
|
||||
}
|
||||
|
||||
public function test_provider_skips_in_testing_env_even_when_runtime_present(): void
|
||||
{
|
||||
// 회귀 가드: storage/installer/runtime.php 가 프로덕션 install 로 생성되어 있어도
|
||||
// testing 환경에서는 .env.testing 의 DB 자격증명이 SSoT 로 보존되어야 한다.
|
||||
// (회귀 사고: runtime 의 g7_2 가 .env.testing 의 g7_2_testing 을 덮어써
|
||||
// RefreshDatabase 가 프로덕션 DB 를 대상으로 실행되던 결함)
|
||||
$this->writeRuntime([
|
||||
'db' => [
|
||||
'write' => [
|
||||
'host' => 'should-be-ignored',
|
||||
'port' => '3306',
|
||||
'database' => 'should-be-ignored-db',
|
||||
'username' => 'should-be-ignored-user',
|
||||
'password' => 'should-be-ignored-pass',
|
||||
],
|
||||
'prefix' => 'ignored_',
|
||||
],
|
||||
'app' => ['key' => 'base64:'.base64_encode(random_bytes(32))],
|
||||
]);
|
||||
|
||||
$originalDb = Config::get('database.connections.mysql.write.database');
|
||||
$originalKey = Config::get('app.key');
|
||||
|
||||
$this->assertSame('testing', $this->app->environment());
|
||||
|
||||
$provider = new InstallerRuntimeServiceProvider($this->app);
|
||||
$provider->register();
|
||||
|
||||
// testing env 에서는 runtime 의 값이 무시되어 기존 .env.testing 값 유지
|
||||
$this->assertSame($originalDb, Config::get('database.connections.mysql.write.database'));
|
||||
$this->assertSame($originalKey, Config::get('app.key'));
|
||||
}
|
||||
|
||||
public function test_provider_injects_db_credentials_when_runtime_file_present(): void
|
||||
{
|
||||
$this->withProductionEnv();
|
||||
$this->writeRuntime([
|
||||
'db' => [
|
||||
'write' => [
|
||||
'host' => 'test-db-host',
|
||||
'port' => '13306',
|
||||
'database' => 'test_db',
|
||||
'username' => 'test_user',
|
||||
'password' => 'test_pass',
|
||||
],
|
||||
'prefix' => 'tt_',
|
||||
],
|
||||
]);
|
||||
|
||||
$provider = new InstallerRuntimeServiceProvider($this->app);
|
||||
$provider->register();
|
||||
|
||||
$this->assertSame(['test-db-host'], Config::get('database.connections.mysql.write.host'));
|
||||
$this->assertSame('13306', Config::get('database.connections.mysql.write.port'));
|
||||
$this->assertSame('test_db', Config::get('database.connections.mysql.write.database'));
|
||||
$this->assertSame('test_user', Config::get('database.connections.mysql.write.username'));
|
||||
$this->assertSame('test_pass', Config::get('database.connections.mysql.write.password'));
|
||||
$this->assertSame('tt_', Config::get('database.connections.mysql.prefix'));
|
||||
|
||||
// read 미지정 시 write 값으로 동기화
|
||||
$this->assertSame(['test-db-host'], Config::get('database.connections.mysql.read.host'));
|
||||
}
|
||||
|
||||
public function test_provider_injects_app_key(): void
|
||||
{
|
||||
$this->withProductionEnv();
|
||||
$key = 'base64:' . base64_encode(random_bytes(32));
|
||||
|
||||
$this->writeRuntime([
|
||||
'app' => ['key' => $key],
|
||||
]);
|
||||
|
||||
$provider = new InstallerRuntimeServiceProvider($this->app);
|
||||
$provider->register();
|
||||
|
||||
$this->assertSame($key, Config::get('app.key'));
|
||||
}
|
||||
|
||||
public function test_provider_handles_separate_read_db_config(): void
|
||||
{
|
||||
$this->withProductionEnv();
|
||||
$this->writeRuntime([
|
||||
'db' => [
|
||||
'write' => [
|
||||
'host' => 'write-host',
|
||||
'port' => '3306',
|
||||
'database' => 'g7',
|
||||
'username' => 'root',
|
||||
'password' => '',
|
||||
],
|
||||
'read' => [
|
||||
'host' => 'read-host',
|
||||
'port' => '3307',
|
||||
'database' => 'g7_replica',
|
||||
'username' => 'reader',
|
||||
'password' => 'rp',
|
||||
],
|
||||
'prefix' => '',
|
||||
],
|
||||
]);
|
||||
|
||||
$provider = new InstallerRuntimeServiceProvider($this->app);
|
||||
$provider->register();
|
||||
|
||||
$this->assertSame(['read-host'], Config::get('database.connections.mysql.read.host'));
|
||||
$this->assertSame('3307', Config::get('database.connections.mysql.read.port'));
|
||||
$this->assertSame('reader', Config::get('database.connections.mysql.read.username'));
|
||||
$this->assertSame(['write-host'], Config::get('database.connections.mysql.write.host'));
|
||||
}
|
||||
|
||||
public function test_provider_silently_skips_invalid_runtime_format(): void
|
||||
{
|
||||
$this->withProductionEnv();
|
||||
// 잘못된 형식 — 배열이 아닌 스칼라
|
||||
@mkdir(dirname($this->runtimePath), 0755, true);
|
||||
file_put_contents($this->runtimePath, "<?php\nreturn 'not-an-array';\n");
|
||||
|
||||
$originalHost = Config::get('database.connections.mysql.write.host');
|
||||
|
||||
$provider = new InstallerRuntimeServiceProvider($this->app);
|
||||
$provider->register();
|
||||
|
||||
$this->assertSame($originalHost, Config::get('database.connections.mysql.write.host'));
|
||||
}
|
||||
|
||||
public function test_provider_skips_app_key_when_empty(): void
|
||||
{
|
||||
$this->withProductionEnv();
|
||||
$this->writeRuntime([
|
||||
'app' => ['key' => ''],
|
||||
]);
|
||||
|
||||
$originalKey = Config::get('app.key');
|
||||
|
||||
$provider = new InstallerRuntimeServiceProvider($this->app);
|
||||
$provider->register();
|
||||
|
||||
// 빈 문자열은 무시 — 기존 .env 값 보존
|
||||
$this->assertSame($originalKey, Config::get('app.key'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
private function writeRuntime(array $data): void
|
||||
{
|
||||
$dir = dirname($this->runtimePath);
|
||||
if (! is_dir($dir)) {
|
||||
mkdir($dir, 0755, true);
|
||||
}
|
||||
|
||||
$php = "<?php\n\nreturn " . var_export($data, true) . ";\n";
|
||||
file_put_contents($this->runtimePath, $php);
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,12 @@ class StoreEcommerceSettingsRequestCustomValidationTest extends TestCase
|
||||
|
||||
// 한국어 로케일 설정
|
||||
App::setLocale('ko');
|
||||
|
||||
// sirsoft-ecommerce 모듈 번역은 단위 테스트 환경에서 자동 로드되지 않으므로 수동 등록
|
||||
app('translator')->addLines([
|
||||
'validation.custom.language_currency.currencies.name_required' => '통화명은 최소 하나의 언어로 입력해야 합니다.',
|
||||
'validation.custom.language_currency.currencies.duplicate_code' => '중복된 통화 코드: :code',
|
||||
], 'ko', 'sirsoft-ecommerce');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -91,19 +91,20 @@ class BaseApiResourceMetaTest extends TestCase
|
||||
|
||||
/**
|
||||
* ownerField가 정의되고 요청 사용자가 소유자이면 is_owner = true.
|
||||
*
|
||||
* 실제 사용처는 Eloquent Model 래핑 (`$this->resource->{$field}` 은 객체 프로퍼티 접근)
|
||||
* 이므로 테스트도 stdClass / Model 인스턴스를 사용해야 한다 (배열로 주입 시 에러).
|
||||
*/
|
||||
public function test_resource_meta_returns_is_owner_true_when_user_is_owner(): void
|
||||
{
|
||||
$resource = new class(['id' => 1, 'user_id' => null]) extends BaseApiResource {
|
||||
$data = (object) ['id' => 1, 'user_id' => $this->adminUser->id];
|
||||
$resource = new class($data) extends BaseApiResource {
|
||||
protected function ownerField(): ?string
|
||||
{
|
||||
return 'user_id';
|
||||
}
|
||||
};
|
||||
|
||||
// user_id를 adminUser의 id로 설정
|
||||
$resource->resource['user_id'] = $this->adminUser->id;
|
||||
|
||||
$request = Request::create('/test');
|
||||
$request->setUserResolver(fn () => $this->adminUser);
|
||||
|
||||
@@ -118,7 +119,8 @@ class BaseApiResourceMetaTest extends TestCase
|
||||
*/
|
||||
public function test_resource_meta_returns_is_owner_false_when_user_is_not_owner(): void
|
||||
{
|
||||
$resource = new class(['id' => 1, 'user_id' => 999]) extends BaseApiResource {
|
||||
$data = (object) ['id' => 1, 'user_id' => 999];
|
||||
$resource = new class($data) extends BaseApiResource {
|
||||
protected function ownerField(): ?string
|
||||
{
|
||||
return 'user_id';
|
||||
@@ -139,7 +141,8 @@ class BaseApiResourceMetaTest extends TestCase
|
||||
*/
|
||||
public function test_resource_meta_returns_is_owner_false_for_guest(): void
|
||||
{
|
||||
$resource = new class(['id' => 1, 'user_id' => 1]) extends BaseApiResource {
|
||||
$data = (object) ['id' => 1, 'user_id' => 1];
|
||||
$resource = new class($data) extends BaseApiResource {
|
||||
protected function ownerField(): ?string
|
||||
{
|
||||
return 'user_id';
|
||||
@@ -218,8 +221,8 @@ class BaseApiResourceMetaTest extends TestCase
|
||||
*/
|
||||
public function test_resource_meta_returns_both_is_owner_and_abilities(): void
|
||||
{
|
||||
$userId = $this->adminUser->id;
|
||||
$resource = new class(['id' => 1, 'user_id' => $userId]) extends BaseApiResource {
|
||||
$data = (object) ['id' => 1, 'user_id' => $this->adminUser->id];
|
||||
$resource = new class($data) extends BaseApiResource {
|
||||
protected function ownerField(): ?string
|
||||
{
|
||||
return 'user_id';
|
||||
@@ -233,8 +236,6 @@ class BaseApiResourceMetaTest extends TestCase
|
||||
];
|
||||
}
|
||||
};
|
||||
// 명시적으로 user_id 재설정 (anonymous class에서 캡처 안 될 수 있으므로)
|
||||
$resource->resource['user_id'] = $this->adminUser->id;
|
||||
|
||||
$request = Request::create('/test');
|
||||
$request->setUserResolver(fn () => $this->adminUser);
|
||||
|
||||
@@ -93,6 +93,10 @@ class PerItemAbilitiesTest extends TestCase
|
||||
|
||||
/**
|
||||
* self 스코프에서 본인 행은 abilities가 true를 반환한다.
|
||||
*
|
||||
* UserResource 는 슈퍼관리자 계정만 can_delete 를 강제 false 로 설정한다.
|
||||
* 일반 관리자 계정의 삭제 가능 여부는 G7 역할/퍼미션/스코프 시스템이 평가하므로,
|
||||
* managerUser(is_super=false, self 스코프 보유) 는 본인 행에 대해 can_delete=true.
|
||||
*/
|
||||
public function test_self_scope_allows_own_row(): void
|
||||
{
|
||||
@@ -235,16 +239,16 @@ class PerItemAbilitiesTest extends TestCase
|
||||
$collection = new UserCollection($users);
|
||||
$result = $collection->withStatistics([]);
|
||||
|
||||
// 컬렉션 데이터에서 각 사용자의 abilities 확인
|
||||
$dataById = collect($result['data'])->keyBy('id');
|
||||
// UserResource 의 공개 식별자는 uuid (id 는 toArray 에 포함되지 않음)
|
||||
$dataByUuid = collect($result['data'])->keyBy('uuid');
|
||||
|
||||
// 본인(managerUser) — can_update: true
|
||||
$ownRow = $dataById[$this->managerUser->id];
|
||||
$ownRow = $dataByUuid[$this->managerUser->uuid];
|
||||
$this->assertTrue($ownRow['is_owner']);
|
||||
$this->assertTrue($ownRow['abilities']['can_update']);
|
||||
|
||||
// 타인(otherUser) — can_update: false (self 스코프)
|
||||
$otherRow = $dataById[$this->otherUser->id];
|
||||
$otherRow = $dataByUuid[$this->otherUser->uuid];
|
||||
$this->assertFalse($otherRow['is_owner']);
|
||||
$this->assertFalse($otherRow['abilities']['can_update']);
|
||||
}
|
||||
|
||||
@@ -2,10 +2,15 @@
|
||||
|
||||
namespace Tests\Unit\Rules;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Rules\ExcludeCurrentUser;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* ExcludeCurrentUser Rule 은 Auth::user()?->uuid 를 기준으로 검증한다.
|
||||
* 이전 Auth::id() 정수 비교 방식에서 UUID 비교로 변경됨 (리팩토링 반영).
|
||||
*/
|
||||
class ExcludeCurrentUserTest extends TestCase
|
||||
{
|
||||
private ExcludeCurrentUser $rule;
|
||||
@@ -17,18 +22,18 @@ class ExcludeCurrentUserTest extends TestCase
|
||||
}
|
||||
|
||||
/**
|
||||
* 로그인한 사용자가 ID 목록에 포함된 경우 검증 실패
|
||||
* 로그인한 사용자의 uuid 가 ID 목록에 포함된 경우 검증 실패
|
||||
*/
|
||||
public function test_fails_when_current_user_is_in_ids(): void
|
||||
{
|
||||
// DB 없이 테스트 - Auth::id()만 모킹
|
||||
$userId = 123;
|
||||
Auth::shouldReceive('id')->andReturn($userId);
|
||||
$currentUuid = 'user-uuid-current';
|
||||
$user = (new User)->forceFill(['uuid' => $currentUuid]);
|
||||
Auth::shouldReceive('user')->andReturn($user);
|
||||
|
||||
$failCalled = false;
|
||||
$failMessage = '';
|
||||
|
||||
$this->rule->validate('ids', [$userId, 2, 3], function ($message) use (&$failCalled, &$failMessage) {
|
||||
$this->rule->validate('ids', [$currentUuid, 'other-1', 'other-2'], function ($message) use (&$failCalled, &$failMessage) {
|
||||
$failCalled = true;
|
||||
$failMessage = $message;
|
||||
});
|
||||
@@ -38,15 +43,16 @@ class ExcludeCurrentUserTest extends TestCase
|
||||
}
|
||||
|
||||
/**
|
||||
* 로그인한 사용자가 ID 목록에 포함되지 않은 경우 검증 성공
|
||||
* 로그인한 사용자의 uuid 가 ID 목록에 포함되지 않은 경우 검증 성공
|
||||
*/
|
||||
public function test_passes_when_current_user_is_not_in_ids(): void
|
||||
{
|
||||
Auth::shouldReceive('id')->andReturn(999);
|
||||
$user = (new User)->forceFill(['uuid' => 'current-uuid']);
|
||||
Auth::shouldReceive('user')->andReturn($user);
|
||||
|
||||
$failCalled = false;
|
||||
|
||||
$this->rule->validate('ids', [1, 2, 3], function () use (&$failCalled) {
|
||||
$this->rule->validate('ids', ['uuid-1', 'uuid-2', 'uuid-3'], function () use (&$failCalled) {
|
||||
$failCalled = true;
|
||||
});
|
||||
|
||||
@@ -58,11 +64,11 @@ class ExcludeCurrentUserTest extends TestCase
|
||||
*/
|
||||
public function test_passes_when_user_is_not_authenticated(): void
|
||||
{
|
||||
Auth::shouldReceive('id')->andReturn(null);
|
||||
Auth::shouldReceive('user')->andReturn(null);
|
||||
|
||||
$failCalled = false;
|
||||
|
||||
$this->rule->validate('ids', [1, 2, 3], function () use (&$failCalled) {
|
||||
$this->rule->validate('ids', ['uuid-1', 'uuid-2'], function () use (&$failCalled) {
|
||||
$failCalled = true;
|
||||
});
|
||||
|
||||
@@ -74,7 +80,8 @@ class ExcludeCurrentUserTest extends TestCase
|
||||
*/
|
||||
public function test_passes_when_value_is_not_array(): void
|
||||
{
|
||||
Auth::shouldReceive('id')->andReturn(1);
|
||||
$user = (new User)->forceFill(['uuid' => 'current-uuid']);
|
||||
Auth::shouldReceive('user')->andReturn($user);
|
||||
|
||||
$failCalled = false;
|
||||
|
||||
@@ -90,7 +97,8 @@ class ExcludeCurrentUserTest extends TestCase
|
||||
*/
|
||||
public function test_passes_when_array_is_empty(): void
|
||||
{
|
||||
Auth::shouldReceive('id')->andReturn(1);
|
||||
$user = (new User)->forceFill(['uuid' => 'current-uuid']);
|
||||
Auth::shouldReceive('user')->andReturn($user);
|
||||
|
||||
$failCalled = false;
|
||||
|
||||
@@ -102,16 +110,18 @@ class ExcludeCurrentUserTest extends TestCase
|
||||
}
|
||||
|
||||
/**
|
||||
* 문자열 ID와 정수 ID의 느슨한 비교 테스트
|
||||
* UUID 는 strict 비교이므로 정확히 일치해야 실패.
|
||||
* (이전 테스트는 loose 비교 (1 == '1') 였으나 UUID 는 문자열 정합성 필수)
|
||||
*/
|
||||
public function test_fails_with_loose_comparison(): void
|
||||
public function test_fails_with_exact_uuid_match(): void
|
||||
{
|
||||
Auth::shouldReceive('id')->andReturn(1);
|
||||
$uuid = 'exact-uuid-match';
|
||||
$user = (new User)->forceFill(['uuid' => $uuid]);
|
||||
Auth::shouldReceive('user')->andReturn($user);
|
||||
|
||||
$failCalled = false;
|
||||
|
||||
// 문자열 '1'도 정수 1과 동일하게 처리
|
||||
$this->rule->validate('ids', ['1', 2, 3], function () use (&$failCalled) {
|
||||
$this->rule->validate('ids', [$uuid, 'other'], function () use (&$failCalled) {
|
||||
$failCalled = true;
|
||||
});
|
||||
|
||||
|
||||
+199
-135
@@ -2,7 +2,9 @@
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Seo\BotDetector;
|
||||
use App\Seo\BotDetectorCustomProvider;
|
||||
use Illuminate\Http\Request;
|
||||
use Tests\TestCase;
|
||||
|
||||
@@ -11,7 +13,7 @@ class BotDetectorTest extends TestCase
|
||||
private BotDetector $detector;
|
||||
|
||||
/**
|
||||
* 테스트 초기화 - BotDetector 인스턴스 및 기본 설정을 준비합니다.
|
||||
* 테스트 초기화 - jaybizzle 라이브러리 활성화 + G7 보강 패턴 검증을 위한 기본 상태.
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
@@ -19,27 +21,25 @@ class BotDetectorTest extends TestCase
|
||||
|
||||
$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',
|
||||
]);
|
||||
config()->set('g7_settings.core.seo.bot_detection_library_enabled', true);
|
||||
config()->set('g7_settings.core.seo.bot_user_agents', []);
|
||||
}
|
||||
|
||||
/**
|
||||
* 주어진 User-Agent 문자열로 Request를 생성합니다.
|
||||
* 테스트 종료 시 동적 등록한 훅 리스너를 정리합니다.
|
||||
*/
|
||||
protected function tearDown(): void
|
||||
{
|
||||
HookManager::clearFilter('core.seo.resolve_is_bot');
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 주어진 User-Agent / 쿼리로 Request 를 생성합니다.
|
||||
*
|
||||
* @param string $userAgent User-Agent 문자열
|
||||
* @param array $query 쿼리 파라미터
|
||||
* @param array<string, mixed> $query 쿼리 파라미터
|
||||
* @return Request 생성된 요청 객체
|
||||
*/
|
||||
private function createRequest(string $userAgent = '', array $query = []): Request
|
||||
@@ -52,139 +52,203 @@ class BotDetectorTest extends TestCase
|
||||
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)');
|
||||
// ─── 체인 1~3 단계 ────────────────────────────────────────────────────
|
||||
|
||||
$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
|
||||
public function test_bot_detection_disabled_returns_false_for_all(): 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));
|
||||
$this->assertFalse($this->detector->isBot(
|
||||
$this->createRequest('Mozilla/5.0 (compatible; Googlebot/2.1)')
|
||||
));
|
||||
$this->assertFalse($this->detector->isBot(
|
||||
$this->createRequest('Chrome/120.0', ['_escaped_fragment_' => ''])
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* 커스텀 봇 패턴이 추가되면 해당 패턴도 매칭합니다.
|
||||
*/
|
||||
public function test_custom_bot_pattern_matches(): void
|
||||
public function test_escaped_fragment_query_returns_true(): void
|
||||
{
|
||||
config()->set('g7_settings.core.seo.bot_user_agents', [
|
||||
'Googlebot',
|
||||
'MyCustomCrawler',
|
||||
]);
|
||||
|
||||
$request = $this->createRequest('MyCustomCrawler/1.0');
|
||||
$request = $this->createRequest('Mozilla/5.0 Chrome/120.0', ['_escaped_fragment_' => '']);
|
||||
|
||||
$this->assertTrue($this->detector->isBot($request));
|
||||
}
|
||||
|
||||
/**
|
||||
* bot_user_agents가 빈 배열이면 모든 요청이 봇이 아닙니다.
|
||||
*/
|
||||
public function test_empty_bot_patterns_returns_false_for_all(): void
|
||||
public function test_empty_user_agent_returns_false(): void
|
||||
{
|
||||
$this->assertFalse($this->detector->isBot($this->createRequest('')));
|
||||
}
|
||||
|
||||
// ─── 체인 4단계: 훅 슬롯 ──────────────────────────────────────────────
|
||||
|
||||
public function test_hook_returning_true_short_circuits_to_bot(): void
|
||||
{
|
||||
HookManager::addFilter('core.seo.resolve_is_bot', fn ($prev, $ctx) => true);
|
||||
|
||||
// 일반 Chrome 인데도 훅이 true 면 봇으로 결정.
|
||||
$this->assertTrue($this->detector->isBot(
|
||||
$this->createRequest('Mozilla/5.0 (Windows NT 10.0) Chrome/120.0')
|
||||
));
|
||||
}
|
||||
|
||||
public function test_hook_returning_false_short_circuits_to_not_bot(): void
|
||||
{
|
||||
HookManager::addFilter('core.seo.resolve_is_bot', fn ($prev, $ctx) => false);
|
||||
|
||||
// jaybizzle 가 알아서 잡을 GPTBot 도 훅이 false 면 봇 아님.
|
||||
$this->assertFalse($this->detector->isBot(
|
||||
$this->createRequest('Mozilla/5.0 (compatible; GPTBot/1.2)')
|
||||
));
|
||||
}
|
||||
|
||||
public function test_hook_returning_null_falls_through_to_library(): void
|
||||
{
|
||||
HookManager::addFilter('core.seo.resolve_is_bot', fn ($prev, $ctx) => null);
|
||||
|
||||
$this->assertTrue($this->detector->isBot(
|
||||
$this->createRequest('Mozilla/5.0 (compatible; GPTBot/1.2)')
|
||||
));
|
||||
}
|
||||
|
||||
// ─── 체인 5단계: jaybizzle 라이브러리 경로 ───────────────────────────
|
||||
|
||||
/**
|
||||
* jaybizzle 1.3.9 가 자체 픽스처로 잡는 대표 봇들 — 라이브러리 통합이
|
||||
* 실제로 동작하는지 한 케이스만 회귀 보장.
|
||||
*/
|
||||
public function test_library_detects_gptbot(): void
|
||||
{
|
||||
$this->assertTrue($this->detector->isBot(
|
||||
$this->createRequest('Mozilla/5.0 (compatible; GPTBot/1.2; +https://openai.com/gptbot)')
|
||||
));
|
||||
}
|
||||
|
||||
public function test_library_detects_facebookexternalhit(): void
|
||||
{
|
||||
$this->assertTrue($this->detector->isBot(
|
||||
$this->createRequest('facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)')
|
||||
));
|
||||
}
|
||||
|
||||
public function test_library_does_not_match_normal_chrome(): void
|
||||
{
|
||||
$this->assertFalse($this->detector->isBot(
|
||||
$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')
|
||||
));
|
||||
}
|
||||
|
||||
// ─── G7 보강 패턴 (jaybizzle 미커버) ─────────────────────────────────
|
||||
|
||||
public function test_custom_provider_detects_kakaotalk_scrap(): void
|
||||
{
|
||||
$this->assertTrue($this->detector->isBot(
|
||||
$this->createRequest('facebookexternalhit/1.1;kakaotalk-scrap/1.0;+https://devtalk.kakao.com/t/scrap/33984')
|
||||
));
|
||||
}
|
||||
|
||||
public function test_custom_provider_detects_meta_external_agent(): void
|
||||
{
|
||||
$this->assertTrue($this->detector->isBot(
|
||||
$this->createRequest('meta-externalagent/1.1 (+https://developers.facebook.com/docs/sharing/webmasters/crawler)')
|
||||
));
|
||||
}
|
||||
|
||||
public function test_custom_provider_detects_chatgpt_user(): void
|
||||
{
|
||||
$this->assertTrue($this->detector->isBot(
|
||||
$this->createRequest('Mozilla/5.0 ChatGPT-User/1.0')
|
||||
));
|
||||
}
|
||||
|
||||
// ─── 사용자 커스텀 패턴 (라이브러리에 주입) ──────────────────────────
|
||||
|
||||
public function test_user_custom_pattern_matches_via_library(): void
|
||||
{
|
||||
config()->set('g7_settings.core.seo.bot_user_agents', ['MyOrgCrawler']);
|
||||
|
||||
$this->assertTrue($this->detector->isBot(
|
||||
$this->createRequest('MyOrgCrawler/2.0')
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀: 운영자 커스텀 패턴이 jaybizzle Exclusions 와 충돌하지 않아야 함.
|
||||
*
|
||||
* 라이브러리는 isCrawler() 첫 단계에서 일반 브라우저 식별자(Firefox/X.Y, Chrome/X.Y,
|
||||
* Safari/X.Y, Mozilla/X.Y) 를 UA 에서 strip 한다. 운영자가 "Firefox" 패턴을 추가해도
|
||||
* strip 후 매칭 시도하면 false 가 되어 라이브러리 + 사용자 패턴이 함께 작동하지 않음.
|
||||
*
|
||||
* 본 회귀 가드: 운영자가 "Firefox" 등 브라우저 식별자를 봇 패턴으로 추가하면,
|
||||
* 라이브러리 활성 상태에서도 raw UA 에 직접 매칭하여 감지되어야 함.
|
||||
*/
|
||||
public function test_user_custom_pattern_matches_browser_identifier_excluded_by_library(): void
|
||||
{
|
||||
config()->set('g7_settings.core.seo.bot_user_agents', ['Firefox']);
|
||||
|
||||
$this->assertTrue($this->detector->isBot(
|
||||
$this->createRequest('Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0')
|
||||
));
|
||||
}
|
||||
|
||||
public function test_user_custom_pattern_treats_regex_meta_as_literal(): void
|
||||
{
|
||||
config()->set('g7_settings.core.seo.bot_user_agents', ['foo.bar+baz']);
|
||||
|
||||
$this->assertTrue($this->detector->isBot(
|
||||
$this->createRequest('foo.bar+baz client')
|
||||
));
|
||||
// '.', '+' 가 정규식 메타로 해석되었다면 'fooXbarYbaz' 도 매치되었을 것.
|
||||
$this->assertFalse($this->detector->isBot(
|
||||
$this->createRequest('fooXbarYbaz client')
|
||||
));
|
||||
}
|
||||
|
||||
// ─── 체인 6단계: 라이브러리 비활성 (레거시 stripos 경로) ───────────
|
||||
|
||||
public function test_library_disabled_falls_back_to_custom_only(): void
|
||||
{
|
||||
config()->set('g7_settings.core.seo.bot_detection_library_enabled', false);
|
||||
config()->set('g7_settings.core.seo.bot_user_agents', ['LegacyBot']);
|
||||
|
||||
$this->assertTrue($this->detector->isBot(
|
||||
$this->createRequest('LegacyBot/1.0')
|
||||
));
|
||||
// 라이브러리 비활성 이므로 GPTBot 도 잡지 못함 (커스텀 목록에 없으므로).
|
||||
$this->assertFalse($this->detector->isBot(
|
||||
$this->createRequest('Mozilla/5.0 (compatible; GPTBot/1.2)')
|
||||
));
|
||||
}
|
||||
|
||||
public function test_library_disabled_with_empty_custom_returns_false(): void
|
||||
{
|
||||
config()->set('g7_settings.core.seo.bot_detection_library_enabled', false);
|
||||
config()->set('g7_settings.core.seo.bot_user_agents', []);
|
||||
|
||||
$googlebot = $this->createRequest('Googlebot/2.1');
|
||||
$this->assertFalse($this->detector->isBot($googlebot));
|
||||
$this->assertFalse($this->detector->isBot(
|
||||
$this->createRequest('Mozilla/5.0 (compatible; Googlebot/2.1)')
|
||||
));
|
||||
}
|
||||
|
||||
$chrome = $this->createRequest('Mozilla/5.0 Chrome/120.0.0.0');
|
||||
$this->assertFalse($this->detector->isBot($chrome));
|
||||
public function test_legacy_path_is_case_insensitive(): void
|
||||
{
|
||||
config()->set('g7_settings.core.seo.bot_detection_library_enabled', false);
|
||||
config()->set('g7_settings.core.seo.bot_user_agents', ['Googlebot']);
|
||||
|
||||
$this->assertTrue($this->detector->isBot(
|
||||
$this->createRequest('mozilla/5.0 (compatible; googleBot/2.1)')
|
||||
));
|
||||
}
|
||||
|
||||
// ─── 직접 커스텀 프로바이더 단위 테스트 ──────────────────────────────
|
||||
|
||||
public function test_custom_provider_isolated_unit(): void
|
||||
{
|
||||
$provider = new BotDetectorCustomProvider(['MyBot']);
|
||||
|
||||
$this->assertTrue($provider->isCrawler('kakaotalk-scrap/1.0'));
|
||||
$this->assertTrue($provider->isCrawler('Meta-ExternalAgent/1.1'));
|
||||
$this->assertTrue($provider->isCrawler('ChatGPT-User/1.0'));
|
||||
$this->assertTrue($provider->isCrawler('MyBot v1'));
|
||||
$this->assertTrue($provider->isCrawler('Mozilla/5.0 (compatible; GPTBot/1.2)'));
|
||||
$this->assertFalse($provider->isCrawler('Mozilla/5.0 Chrome/120.0'));
|
||||
}
|
||||
}
|
||||
@@ -458,13 +458,21 @@ class SeoMetaResolverTest extends TestCase
|
||||
}
|
||||
|
||||
/**
|
||||
* OG 설정이 비어 있으면 ogTags는 빈 문자열입니다.
|
||||
* OG 설정이 비어있어도 코어 설정 기반 기본 og:type/og:site_name 등이 항상 출력됩니다.
|
||||
*
|
||||
* (이전 회귀: og 미선언 시 빈 문자열 반환 — Slack/Facebook 미리보기 무시)
|
||||
* 신규 동작: og:type=website 기본값 + 코어 설정의 site_name fallback 으로 최소 보장.
|
||||
*/
|
||||
public function test_empty_og_config_returns_empty_og_tags(): void
|
||||
public function test_empty_og_config_emits_default_type_and_site_name(): void
|
||||
{
|
||||
$result = $this->resolver->resolve([], [], null, null, []);
|
||||
|
||||
$this->assertSame('', $result['ogTags']);
|
||||
// og 배열은 항상 채워짐
|
||||
$this->assertSame('website', $result['og']['type']);
|
||||
$this->assertSame('그누보드7 쇼핑몰', $result['og']['site_name']);
|
||||
// ogTags HTML 도 최소 og:type 은 포함
|
||||
$this->assertStringContainsString('og:type" content="website"', $result['ogTags']);
|
||||
$this->assertStringContainsString('og:site_name" content="그누보드7 쇼핑몰"', $result['ogTags']);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -875,8 +883,8 @@ class SeoMetaResolverTest extends TestCase
|
||||
|
||||
$result = $this->resolver->resolve($seoConfig, [], 'sirsoft-ecommerce', null, []);
|
||||
|
||||
// nonexistent 경로 → 빈 문자열 → ' 상품'
|
||||
$this->assertSame(' 상품', $result['title']);
|
||||
// nonexistent 경로 → 빈 문자열 → '상품' (선두 공백 자동 trim — substituteVars cleanup)
|
||||
$this->assertSame('상품', $result['title']);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1232,4 +1240,402 @@ class SeoMetaResolverTest extends TestCase
|
||||
// _seo도 없고 moduleIdentifier도 null → Tier 2 스킵 → 빈 문자열
|
||||
$this->assertEquals('', $result['title']);
|
||||
}
|
||||
|
||||
/**
|
||||
* resolve()는 og 데이터를 배열로 반환합니다 (HTML 렌더 지연 패턴).
|
||||
*/
|
||||
public function test_resolve_returns_og_data_as_array(): void
|
||||
{
|
||||
$seoConfig = [
|
||||
'og' => [
|
||||
'type' => 'product',
|
||||
'title' => '{{product.data.name}}',
|
||||
'image' => 'https://example.com/p.jpg',
|
||||
],
|
||||
];
|
||||
$context = ['product' => ['data' => ['name' => '에어맥스']]];
|
||||
|
||||
$result = $this->resolver->resolve($seoConfig, $context, 'sirsoft-ecommerce', null, []);
|
||||
|
||||
$this->assertIsArray($result['og']);
|
||||
$this->assertSame('product', $result['og']['type']);
|
||||
$this->assertSame('에어맥스', $result['og']['title']);
|
||||
$this->assertSame('https://example.com/p.jpg', $result['og']['image']);
|
||||
}
|
||||
|
||||
/**
|
||||
* og:image:width / og:image:height 가 코어 설정 fallback 으로 채워집니다.
|
||||
*/
|
||||
public function test_og_image_dimensions_fallback_to_core_settings(): void
|
||||
{
|
||||
Config::set('g7_settings.core.seo.og_image_default_width', 1200);
|
||||
Config::set('g7_settings.core.seo.og_image_default_height', 630);
|
||||
|
||||
$seoConfig = [
|
||||
'og' => [
|
||||
'type' => 'product',
|
||||
'title' => 'p',
|
||||
'image' => 'https://example.com/p.jpg',
|
||||
],
|
||||
];
|
||||
|
||||
$result = $this->resolver->resolve($seoConfig, [], null, null, []);
|
||||
|
||||
$this->assertSame(1200, $result['og']['image_width']);
|
||||
$this->assertSame(630, $result['og']['image_height']);
|
||||
$this->assertStringContainsString('og:image:width" content="1200"', $result['ogTags']);
|
||||
$this->assertStringContainsString('og:image:height" content="630"', $result['ogTags']);
|
||||
}
|
||||
|
||||
/**
|
||||
* og:site_name 은 코어 설정 fallback (general.site_name) 을 사용합니다.
|
||||
*/
|
||||
public function test_og_site_name_fallback_to_core_general_site_name(): void
|
||||
{
|
||||
Config::set('g7_settings.core.seo.og_default_site_name', '');
|
||||
Config::set('g7_settings.core.general.site_name', 'GNUBOARD.NET');
|
||||
|
||||
$seoConfig = [
|
||||
'og' => [
|
||||
'type' => 'website',
|
||||
'title' => 'Home',
|
||||
],
|
||||
];
|
||||
|
||||
$result = $this->resolver->resolve($seoConfig, [], null, null, []);
|
||||
|
||||
$this->assertSame('GNUBOARD.NET', $result['og']['site_name']);
|
||||
$this->assertStringContainsString('og:site_name" content="GNUBOARD.NET"', $result['ogTags']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Twitter 카드 데이터가 OG 데이터를 fallback 으로 사용합니다.
|
||||
*/
|
||||
public function test_twitter_data_falls_back_to_og(): void
|
||||
{
|
||||
Config::set('g7_settings.core.seo.twitter_default_card', 'summary_large_image');
|
||||
|
||||
$seoConfig = [
|
||||
'og' => [
|
||||
'type' => 'product',
|
||||
'title' => '에어맥스',
|
||||
'description' => '나이키 에어맥스',
|
||||
'image' => 'https://example.com/p.jpg',
|
||||
],
|
||||
];
|
||||
|
||||
$result = $this->resolver->resolve($seoConfig, [], null, null, []);
|
||||
|
||||
$this->assertSame('summary_large_image', $result['twitter']['card']);
|
||||
$this->assertSame('에어맥스', $result['twitter']['title']);
|
||||
$this->assertSame('https://example.com/p.jpg', $result['twitter']['image']);
|
||||
$this->assertStringContainsString('twitter:card" content="summary_large_image"', $result['twitterTags']);
|
||||
$this->assertStringContainsString('twitter:image" content="https://example.com/p.jpg"', $result['twitterTags']);
|
||||
}
|
||||
|
||||
/**
|
||||
* og.extra 배열의 자유 메타태그가 출력에 포함됩니다.
|
||||
*/
|
||||
public function test_og_extra_meta_tags_rendered(): void
|
||||
{
|
||||
$seoConfig = [
|
||||
'og' => [
|
||||
'type' => 'product',
|
||||
'title' => 'p',
|
||||
'extra' => [
|
||||
['property' => 'product:price:amount', 'content' => '50000'],
|
||||
['property' => 'product:price:currency', 'content' => 'KRW'],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$result = $this->resolver->resolve($seoConfig, [], null, null, []);
|
||||
|
||||
$this->assertStringContainsString('product:price:amount" content="50000"', $result['ogTags']);
|
||||
$this->assertStringContainsString('product:price:currency" content="KRW"', $result['ogTags']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀: 모듈 템플릿 "{commerce_name} - {product_name}" 에서
|
||||
* commerce_name 이 빈 값일 때 선두 "- " 가 남는 회귀를 방지합니다.
|
||||
*
|
||||
* issue#300: og:title="- 무선 마우스 #99" 슬랙/페이스북 미리보기 제목 깨짐
|
||||
*/
|
||||
public function test_module_template_title_no_leading_dash_when_var_empty(): void
|
||||
{
|
||||
Config::set('g7_settings.modules.sirsoft-ecommerce.seo.meta_product_title', '{commerce_name} - {product_name}');
|
||||
Config::set('g7_settings.modules.sirsoft-ecommerce.seo.seo_product', true);
|
||||
Config::set('g7_settings.modules.sirsoft-ecommerce.basic_info.shop_name', '');
|
||||
|
||||
$seoConfig = [
|
||||
'page_type' => 'product',
|
||||
'vars' => [
|
||||
'product_name' => "{{product.data.name ?? ''}}",
|
||||
'commerce_name' => '$module_settings:basic_info.shop_name',
|
||||
],
|
||||
];
|
||||
$context = ['product' => ['data' => ['name' => '무선 마우스 #99']]];
|
||||
|
||||
$result = $this->resolver->resolve($seoConfig, $context, 'sirsoft-ecommerce', null, []);
|
||||
|
||||
$this->assertSame('무선 마우스 #99', $result['title'], '선두 dash 가 제거되어야 합니다');
|
||||
$this->assertStringNotContainsString('- 무선 마우스', $result['title']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀: 옵셔널 그룹 [{var} - ] 신택스 — var 채워지면 그룹 keep, 비면 통째 drop.
|
||||
*/
|
||||
public function test_module_template_title_optional_group_filled(): void
|
||||
{
|
||||
Config::set('g7_settings.modules.sirsoft-ecommerce.seo.meta_product_title', '[{commerce_name} - ]{product_name}');
|
||||
Config::set('g7_settings.modules.sirsoft-ecommerce.seo.seo_product', true);
|
||||
Config::set('g7_settings.modules.sirsoft-ecommerce.basic_info.shop_name', '나이키몰');
|
||||
|
||||
$seoConfig = [
|
||||
'page_type' => 'product',
|
||||
'vars' => [
|
||||
'product_name' => "{{product.data.name ?? ''}}",
|
||||
'commerce_name' => '$module_settings:basic_info.shop_name',
|
||||
],
|
||||
];
|
||||
$context = ['product' => ['data' => ['name' => '에어맥스']]];
|
||||
|
||||
$result = $this->resolver->resolve($seoConfig, $context, 'sirsoft-ecommerce', null, []);
|
||||
|
||||
$this->assertSame('나이키몰 - 에어맥스', $result['title']);
|
||||
}
|
||||
|
||||
public function test_module_template_title_optional_group_empty_var_dropped(): void
|
||||
{
|
||||
Config::set('g7_settings.modules.sirsoft-ecommerce.seo.meta_product_title', '[{commerce_name} - ]{product_name}');
|
||||
Config::set('g7_settings.modules.sirsoft-ecommerce.seo.seo_product', true);
|
||||
Config::set('g7_settings.modules.sirsoft-ecommerce.basic_info.shop_name', '');
|
||||
|
||||
$seoConfig = [
|
||||
'page_type' => 'product',
|
||||
'vars' => [
|
||||
'product_name' => "{{product.data.name ?? ''}}",
|
||||
'commerce_name' => '$module_settings:basic_info.shop_name',
|
||||
],
|
||||
];
|
||||
$context = ['product' => ['data' => ['name' => '에어맥스']]];
|
||||
|
||||
$result = $this->resolver->resolve($seoConfig, $context, 'sirsoft-ecommerce', null, []);
|
||||
|
||||
$this->assertSame('에어맥스', $result['title']);
|
||||
}
|
||||
|
||||
/**
|
||||
* resolveStructuredDataArray 는 배열 형태로 반환하여 hook 변경이 가능합니다.
|
||||
*/
|
||||
public function test_structured_data_returns_array_for_hook_modification(): void
|
||||
{
|
||||
$seoConfig = [
|
||||
'structured_data' => [
|
||||
'@type' => 'Product',
|
||||
'name' => '{{product.data.name}}',
|
||||
],
|
||||
];
|
||||
$context = ['product' => ['data' => ['name' => '에어맥스']]];
|
||||
|
||||
$array = $this->resolver->resolveStructuredDataArray($seoConfig, $context);
|
||||
|
||||
$this->assertIsArray($array);
|
||||
$this->assertSame('Product', $array['@type']);
|
||||
$this->assertSame('에어맥스', $array['name']);
|
||||
|
||||
// hook 이 array 를 수정 후 다시 JSON 렌더 가능한지
|
||||
$array['offers'] = ['@type' => 'Offer', 'price' => '50000'];
|
||||
$json = $this->resolver->renderStructuredJson($array);
|
||||
$this->assertNotNull($json);
|
||||
$this->assertStringContainsString('"offers"', $json);
|
||||
$this->assertStringContainsString('@context', $json);
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀: 코어 설정 site_name 이 다국어 JSON 배열로 저장된 경우에도
|
||||
* resolveOgData 가 'Array to string conversion' throw 없이 정상 동작.
|
||||
*
|
||||
* 운영자가 일반 설정 site_name 을 MultilingualInput 으로 저장하면
|
||||
* config 값이 ["ko" => "...", "en" => "..."] 배열이 됨.
|
||||
* 이전 회귀: SeoRenderer 가 봇 요청에서 항상 Array to string ErrorException → SPA fallback.
|
||||
*/
|
||||
public function test_resolve_handles_multilingual_array_in_core_settings(): void
|
||||
{
|
||||
// site_name 이 다국어 JSON 배열 (운영자가 MultilingualInput 사용 시)
|
||||
Config::set('g7_settings.core.general.site_name', [
|
||||
'ko' => '한글몰',
|
||||
'en' => 'EnglishMall',
|
||||
]);
|
||||
Config::set('g7_settings.core.seo.og_default_site_name', '');
|
||||
app()->setLocale('ko');
|
||||
|
||||
$seoConfig = [
|
||||
'og' => [
|
||||
'type' => 'product',
|
||||
'title' => 'Product',
|
||||
],
|
||||
];
|
||||
|
||||
// throw 없이 정상 반환되어야 함
|
||||
$result = $this->resolver->resolve($seoConfig, [], null, null, []);
|
||||
|
||||
$this->assertIsArray($result['og']);
|
||||
$this->assertSame('한글몰', $result['og']['site_name']);
|
||||
$this->assertStringContainsString('og:site_name" content="한글몰"', $result['ogTags']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀: 데이터소스 컬럼(meta_title/meta_description/meta_keywords) 이 다국어 JSON array 인 경우에도 throw 없이 동작.
|
||||
*
|
||||
* Product/Post 의 DB 컬럼이 multilingual JSON ({"ko":..., "en":...}) 으로 저장된 환경에서
|
||||
* getResourceMetaField / getPageSeoMetaField / resolveKeywords 의 `(string) $value` 가
|
||||
* "Array to string conversion" → SPA fallback 회귀 차단.
|
||||
*/
|
||||
public function test_resolve_handles_multilingual_array_in_resource_meta_columns(): void
|
||||
{
|
||||
app()->setLocale('ko');
|
||||
|
||||
$context = [
|
||||
'product' => [
|
||||
'data' => [
|
||||
'name' => '에어맥스',
|
||||
'meta_title' => ['ko' => '에어맥스 한정판', 'en' => 'AirMax Limited'],
|
||||
'meta_description' => ['ko' => '나이키 에어맥스 한정판 상품', 'en' => 'Limited edition'],
|
||||
'meta_keywords' => ['ko' => '운동화,에어맥스,한정판', 'en' => 'sneakers,airmax'],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
// throw 없이 정상 반환
|
||||
$result = $this->resolver->resolve([], $context, null, null, []);
|
||||
|
||||
$this->assertSame('에어맥스 한정판', $result['title']);
|
||||
$this->assertSame('나이키 에어맥스 한정판 상품', $result['description']);
|
||||
$this->assertSame('운동화,에어맥스,한정판', $result['keywords']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀: 페이지 seo_meta 객체 안에 다국어 JSON array 가 있어도 throw 없이 동작.
|
||||
*/
|
||||
public function test_resolve_handles_multilingual_array_in_page_seo_meta(): void
|
||||
{
|
||||
app()->setLocale('ko');
|
||||
|
||||
$context = [
|
||||
'page' => [
|
||||
'data' => [
|
||||
'seo_meta' => [
|
||||
'title' => ['ko' => '회사 소개', 'en' => 'About'],
|
||||
'description' => ['ko' => '저희 회사를 소개합니다', 'en' => 'About us'],
|
||||
'keywords' => ['ko' => '회사,소개', 'en' => 'about,company'],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$result = $this->resolver->resolve([], $context, null, null, []);
|
||||
|
||||
$this->assertSame('회사 소개', $result['title']);
|
||||
$this->assertSame('저희 회사를 소개합니다', $result['description']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀: substituteVars 가 다국어 JSON 배열을 변수 값으로 받은 경우에도 throw 없이 동작.
|
||||
*
|
||||
* 운영자가 var 의 source(예: $module_settings:basic_info.shop_name) 가 다국어 array 를
|
||||
* 반환하는 환경에서, 기존 substituteVars 의 `(string) $resolvedVars[$matches[1]]` 가
|
||||
* "Array to string conversion" → SeoMiddleware catch → SPA fallback 회귀를 차단.
|
||||
*
|
||||
* (이 회귀는 #300 작업의 substituteVars 강화에서 도입됨 — 이전 str_replace 기반은
|
||||
* array 받아도 fatal 안 났음.)
|
||||
*/
|
||||
public function test_substitute_vars_handles_multilingual_array_value_without_throw(): void
|
||||
{
|
||||
Config::set('g7_settings.modules.sirsoft-ecommerce.seo.meta_product_title', '{commerce_name} - {product_name}');
|
||||
Config::set('g7_settings.modules.sirsoft-ecommerce.seo.seo_product', true);
|
||||
// resolveVars 결과에 다국어 array 가 들어가는 경로: 표현식이 직접 array 반환
|
||||
// (예: 다국어 객체 리터럴 또는 evaluator 가 반환한 값)
|
||||
app()->setLocale('ko');
|
||||
|
||||
$seoConfig = [
|
||||
'page_type' => 'product',
|
||||
'vars' => [
|
||||
// 표현식이 다국어 객체를 직접 반환 — substituteVars 까지 array 전달
|
||||
'product_name' => "{{product.data.name}}",
|
||||
'commerce_name' => '$module_settings:basic_info.shop_name',
|
||||
],
|
||||
];
|
||||
|
||||
// product.data.name 자체를 다국어 array 로
|
||||
Config::set('g7_settings.modules.sirsoft-ecommerce.basic_info.shop_name', [
|
||||
'ko' => '한글몰', 'en' => 'EnglishMall',
|
||||
]);
|
||||
$context = ['product' => ['data' => ['name' => ['ko' => '에어맥스', 'en' => 'AirMax']]]];
|
||||
|
||||
// throw 없이 정상 반환 (현재 로케일 ko)
|
||||
$result = $this->resolver->resolve($seoConfig, $context, 'sirsoft-ecommerce', null, []);
|
||||
|
||||
$this->assertSame('한글몰 - 에어맥스', $result['title']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀: 모듈 설정값이 다국어 JSON 배열인 경우에도 vars 해석이 throw 없이 정상 동작.
|
||||
*
|
||||
* meta.seo.vars 에서 `$module_settings:key` 접두사로 모듈 설정을 참조하는데,
|
||||
* 운영자가 commerce_name(쇼핑몰 이름) 등을 MultilingualInput 으로 저장하면 array 가 됨.
|
||||
*
|
||||
* 이전 회귀: SeoMetaResolver.resolveVarExpression 의 `(string) g7_module_settings(...)`
|
||||
* 가 array → "Array to string conversion" → render() throw → SPA fallback.
|
||||
*/
|
||||
public function test_resolve_vars_handles_multilingual_array_in_module_settings(): void
|
||||
{
|
||||
Config::set('g7_settings.modules.sirsoft-ecommerce.seo.meta_product_title', '{commerce_name} - {product_name}');
|
||||
Config::set('g7_settings.modules.sirsoft-ecommerce.seo.seo_product', true);
|
||||
// 다국어 JSON array 형태로 저장된 모듈 설정
|
||||
Config::set('g7_settings.modules.sirsoft-ecommerce.basic_info.shop_name', [
|
||||
'ko' => '한글몰',
|
||||
'en' => 'EnglishMall',
|
||||
]);
|
||||
app()->setLocale('ko');
|
||||
|
||||
$seoConfig = [
|
||||
'page_type' => 'product',
|
||||
'vars' => [
|
||||
'product_name' => "{{product.data.name ?? ''}}",
|
||||
'commerce_name' => '$module_settings:basic_info.shop_name',
|
||||
],
|
||||
];
|
||||
$context = ['product' => ['data' => ['name' => '에어맥스']]];
|
||||
|
||||
// throw 없이 정상 반환
|
||||
$result = $this->resolver->resolve($seoConfig, $context, 'sirsoft-ecommerce', null, []);
|
||||
|
||||
$this->assertSame('한글몰 - 에어맥스', $result['title']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀: 레이아웃 og.title 이 직접 다국어 객체 리터럴 형식인 경우에도
|
||||
* resolveOgData 가 throw 없이 현재 로케일 값으로 변환.
|
||||
*/
|
||||
public function test_resolve_handles_multilingual_array_in_layout_og_field(): void
|
||||
{
|
||||
app()->setLocale('ko');
|
||||
|
||||
$seoConfig = [
|
||||
'og' => [
|
||||
'type' => 'product',
|
||||
'title' => ['ko' => '에어맥스', 'en' => 'AirMax'],
|
||||
'description' => ['ko' => '운동화', 'en' => 'Sneakers'],
|
||||
'image' => ['ko' => 'https://e.co/ko.jpg', 'en' => 'https://e.co/en.jpg'],
|
||||
],
|
||||
];
|
||||
|
||||
// throw 없이 정상 반환
|
||||
$result = $this->resolver->resolve($seoConfig, [], null, null, []);
|
||||
|
||||
$this->assertSame('에어맥스', $result['og']['title']);
|
||||
$this->assertSame('운동화', $result['og']['description']);
|
||||
$this->assertSame('https://e.co/ko.jpg', $result['og']['image']);
|
||||
}
|
||||
}
|
||||
@@ -78,6 +78,20 @@ class SeoRendererTest extends TestCase
|
||||
->andReturn([])
|
||||
->byDefault();
|
||||
|
||||
// 기본 metaResolver mock — resolveLocalizedValue 는 다국어 처리 흉내 (array → 첫 키 값)
|
||||
$this->metaResolver->shouldReceive('resolveLocalizedValue')
|
||||
->andReturnUsing(function ($value) {
|
||||
if (is_string($value)) {
|
||||
return $value;
|
||||
}
|
||||
if (is_array($value)) {
|
||||
$locale = app()->getLocale();
|
||||
return (string) ($value[$locale] ?? reset($value) ?? '');
|
||||
}
|
||||
return (string) ($value ?? '');
|
||||
})
|
||||
->byDefault();
|
||||
|
||||
// 기본 SeoConfigMerger mock (병합된 config 반환)
|
||||
$this->seoConfigMerger->shouldReceive('getMergedConfig')
|
||||
->andReturn([])
|
||||
@@ -943,13 +957,22 @@ class SeoRendererTest extends TestCase
|
||||
string $description = '',
|
||||
string $ogTags = '',
|
||||
string $jsonLd = '',
|
||||
array $og = [],
|
||||
array $twitter = [],
|
||||
?array $structuredData = null,
|
||||
string $twitterTags = '',
|
||||
): array {
|
||||
return [
|
||||
'title' => $title,
|
||||
'titleSuffix' => '',
|
||||
'description' => $description,
|
||||
'keywords' => '',
|
||||
'og' => $og,
|
||||
'twitter' => $twitter,
|
||||
'structured_data' => $structuredData,
|
||||
'extraMetaTags' => [],
|
||||
'ogTags' => $ogTags,
|
||||
'twitterTags' => $twitterTags,
|
||||
'jsonLd' => $jsonLd,
|
||||
'googleAnalyticsId' => '',
|
||||
'googleVerification' => '',
|
||||
@@ -3611,4 +3634,119 @@ class SeoRendererTest extends TestCase
|
||||
$this->assertNotNull($capturedContext);
|
||||
$this->assertArrayNotHasKey('_seo', $capturedContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀: filter_og_data 청취자가 og 배열을 수정하면 SeoRenderer 가
|
||||
* renderOgHtml 을 다시 호출하여 최종 ogTags 에 반영됨.
|
||||
*
|
||||
* 검증 포인트: hook 적용 → 변경 감지 → 재렌더 호출 흐름.
|
||||
* (실제 HTML 출력은 SeoMetaResolverTest 가 단위 레벨로 커버)
|
||||
*/
|
||||
public function test_filter_og_data_hook_triggers_rerender_via_metaresolver(): void
|
||||
{
|
||||
$request = Request::create('/products/99');
|
||||
|
||||
$this->setupRouteResolver('/products/99', [
|
||||
'templateIdentifier' => 'sirsoft-user_basic',
|
||||
'layoutName' => 'shop/show',
|
||||
'routeParams' => ['id' => '99'],
|
||||
'moduleIdentifier' => null,
|
||||
'routeMeta' => [],
|
||||
]);
|
||||
$this->layoutService->shouldReceive('getLayout')->once()->andReturn(
|
||||
$this->buildMergedLayout(seoEnabled: true, pageType: 'product')
|
||||
);
|
||||
$this->dataSourceResolver->shouldReceive('resolve')->andReturn([]);
|
||||
|
||||
// resolve() 가 og 배열 포함 결과 반환
|
||||
$initialOg = [
|
||||
'type' => 'product',
|
||||
'title' => 'p',
|
||||
'image' => 'https://e.co/p.jpg',
|
||||
'image_width' => 800,
|
||||
'site_name' => 'TestShop',
|
||||
];
|
||||
$this->metaResolver->shouldReceive('resolve')->once()->andReturn(
|
||||
$this->buildMetaResult(
|
||||
title: 'p',
|
||||
ogTags: '<initial>',
|
||||
og: $initialOg,
|
||||
)
|
||||
);
|
||||
|
||||
// 청취자: image_width 1200 으로 변경
|
||||
HookManager::addFilter('core.seo.filter_og_data', function (array $og) {
|
||||
$og['image_width'] = 1200;
|
||||
return $og;
|
||||
});
|
||||
|
||||
// hook 변경 후 SeoRenderer 가 renderOgHtml 을 다시 호출해야 함
|
||||
$this->metaResolver->shouldReceive('renderOgHtml')
|
||||
->once()
|
||||
->with(Mockery::on(fn ($og) => ($og['image_width'] ?? null) === 1200))
|
||||
->andReturn('<post-hook-og>');
|
||||
|
||||
$this->htmlMapper->shouldReceive('render')->andReturn('');
|
||||
$viewMock = Mockery::mock(\Illuminate\View\View::class);
|
||||
$viewMock->shouldReceive('render')->andReturn('<html></html>');
|
||||
View::shouldReceive('make')
|
||||
->with('seo', Mockery::on(fn ($d) => str_contains($d['ogTags'], '<post-hook-og>')))
|
||||
->once()
|
||||
->andReturn($viewMock);
|
||||
|
||||
$result = $this->renderer->render($request);
|
||||
$this->assertNotNull($result);
|
||||
|
||||
HookManager::resetAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀: filter_structured_data 청취자가 JSON-LD 배열을 수정하면 재렌더.
|
||||
*/
|
||||
public function test_filter_structured_data_hook_triggers_rerender_via_metaresolver(): void
|
||||
{
|
||||
$request = Request::create('/posts/42');
|
||||
|
||||
$this->setupRouteResolver('/posts/42', [
|
||||
'templateIdentifier' => 'sirsoft-user_basic',
|
||||
'layoutName' => 'board/show',
|
||||
'routeParams' => ['id' => '42'],
|
||||
'moduleIdentifier' => null,
|
||||
'routeMeta' => [],
|
||||
]);
|
||||
$this->layoutService->shouldReceive('getLayout')->once()->andReturn(
|
||||
$this->buildMergedLayout(seoEnabled: true, pageType: 'post')
|
||||
);
|
||||
$this->dataSourceResolver->shouldReceive('resolve')->andReturn([]);
|
||||
|
||||
$initialSchema = ['@type' => 'Article', 'headline' => 'h'];
|
||||
$this->metaResolver->shouldReceive('resolve')->once()->andReturn(
|
||||
$this->buildMetaResult(
|
||||
title: 'h',
|
||||
jsonLd: '{"@type":"Article"}',
|
||||
structuredData: $initialSchema,
|
||||
)
|
||||
);
|
||||
|
||||
// 청취자: review 배열 주입
|
||||
HookManager::addFilter('core.seo.filter_structured_data', function (?array $sd) {
|
||||
if ($sd === null) return $sd;
|
||||
$sd['review'] = [['@type' => 'Review', 'reviewBody' => 'Great!']];
|
||||
return $sd;
|
||||
});
|
||||
|
||||
$this->metaResolver->shouldReceive('renderStructuredJson')
|
||||
->once()
|
||||
->with(Mockery::on(fn ($sd) => isset($sd['review']) && count($sd['review']) === 1))
|
||||
->andReturn('{"@type":"Article","review":[...]}');
|
||||
|
||||
$this->htmlMapper->shouldReceive('render')->andReturn('');
|
||||
$viewMock = Mockery::mock(\Illuminate\View\View::class);
|
||||
$viewMock->shouldReceive('render')->andReturn('<html></html>');
|
||||
View::shouldReceive('make')->once()->andReturn($viewMock);
|
||||
|
||||
$this->renderer->render($request);
|
||||
|
||||
HookManager::resetAll();
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use App\Seo\Contracts\SitemapContributorInterface;
|
||||
use App\Seo\SitemapGenerator;
|
||||
use App\Seo\TemplateRouteResolver;
|
||||
use App\Services\TemplateService;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
@@ -35,6 +36,11 @@ class SitemapGeneratorTest extends TestCase
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
// 단일 언어 테스트의 기본 가정: 이후 다국어 테스트에서 명시적으로 override.
|
||||
// 활성 언어팩에 따라 변동되는 환경 설정 의존을 제거합니다.
|
||||
Config::set('app.locale', 'ko');
|
||||
Config::set('app.supported_locales', ['ko']);
|
||||
|
||||
$this->routeResolver = Mockery::mock(TemplateRouteResolver::class);
|
||||
$this->templateService = Mockery::mock(TemplateService::class);
|
||||
|
||||
|
||||
@@ -2,21 +2,19 @@
|
||||
|
||||
namespace Tests\Unit\Services;
|
||||
|
||||
use App\ActivityLog\ActivityLogManager;
|
||||
use App\Enums\ActivityLogType;
|
||||
use App\Extension\HookManager;
|
||||
use App\Listeners\ActivityLogListener;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Models\User;
|
||||
use App\Services\ActivityLogService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* ActivityLogService 테스트
|
||||
*
|
||||
* ActivityLogService의 훅 발행 및 조회 기능을 검증합니다.
|
||||
* ActivityLogService 는 조회/삭제 기능만 제공합니다.
|
||||
* 기록은 Log::channel('activity') → ActivityLogHandler 경로로 이행되었으므로
|
||||
* 기록 경로 테스트는 별도 파일(ActivityLogHandlerTest, CoreActivityLogListenerTest)에서 커버합니다.
|
||||
*/
|
||||
class ActivityLogServiceTest extends TestCase
|
||||
{
|
||||
@@ -30,380 +28,160 @@ class ActivityLogServiceTest extends TestCase
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
// 테스트 격리를 위한 고유 프리픽스
|
||||
$this->testPrefix = 'test_' . uniqid() . '_';
|
||||
|
||||
// HookManager 및 Laravel Event 초기화 (중복 등록 방지)
|
||||
HookManager::resetAll();
|
||||
Event::forget('hook.core.activity.log');
|
||||
Event::forget('hook.core.activity.admin');
|
||||
Event::forget('hook.core.activity.user');
|
||||
Event::forget('hook.core.activity.system');
|
||||
|
||||
// 설정 초기화
|
||||
config(['activity_log.enabled' => true]);
|
||||
config(['activity_log.driver' => 'database']);
|
||||
|
||||
// ActivityLogManager 인스턴스 초기화
|
||||
$this->app->forgetInstance(ActivityLogManager::class);
|
||||
|
||||
// 리스너 등록 - static 배열에만 등록 (addAction은 Event::listen도 호출하여 중복 실행됨)
|
||||
$listener = app(ActivityLogListener::class);
|
||||
$this->registerHookWithoutEvent('core.activity.log', [$listener, 'processLog']);
|
||||
$this->registerHookWithoutEvent('core.activity.admin', [$listener, 'handleAdmin']);
|
||||
$this->registerHookWithoutEvent('core.activity.user', [$listener, 'handleUser']);
|
||||
$this->registerHookWithoutEvent('core.activity.system', [$listener, 'handleSystem']);
|
||||
|
||||
$this->activityLogService = app(ActivityLogService::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* HookManager의 static 배열에만 훅을 등록합니다.
|
||||
* addAction은 Event::listen도 호출하여 중복 실행되므로, static 배열에만 등록합니다.
|
||||
*/
|
||||
private function registerHookWithoutEvent(string $hookName, callable $callback, int $priority = 10): void
|
||||
{
|
||||
$reflection = new \ReflectionClass(HookManager::class);
|
||||
$property = $reflection->getProperty('hooks');
|
||||
|
||||
$hooks = $property->getValue();
|
||||
if (! isset($hooks[$hookName])) {
|
||||
$hooks[$hookName] = [];
|
||||
}
|
||||
if (! isset($hooks[$hookName][$priority])) {
|
||||
$hooks[$hookName][$priority] = [];
|
||||
}
|
||||
$hooks[$hookName][$priority][] = $callback;
|
||||
$property->setValue(null, $hooks);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// log() - 기본 로그 기록 테스트 (훅 기반)
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* 기본 로그 기록이 훅을 통해 데이터베이스에 저장되는지 확인
|
||||
*/
|
||||
public function test_log_creates_activity_log_via_hook(): void
|
||||
{
|
||||
$action = $this->testPrefix . 'action';
|
||||
|
||||
$this->activityLogService->log(
|
||||
ActivityLogType::Admin,
|
||||
$action,
|
||||
'Test action description'
|
||||
);
|
||||
|
||||
$this->assertDatabaseHas('activity_logs', [
|
||||
'log_type' => ActivityLogType::Admin->value,
|
||||
'action' => $action,
|
||||
'description' => 'Test action description',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 로그에 대상 모델이 연결되는지 확인
|
||||
*/
|
||||
public function test_log_with_loggable_model(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$action = $this->testPrefix . 'user.update';
|
||||
|
||||
$this->activityLogService->log(
|
||||
ActivityLogType::Admin,
|
||||
$action,
|
||||
'User updated',
|
||||
$user
|
||||
);
|
||||
|
||||
$log = ActivityLog::where('action', $action)->first();
|
||||
$this->assertNotNull($log);
|
||||
$this->assertEquals($user->getMorphClass(), $log->loggable_type);
|
||||
$this->assertEquals($user->id, $log->loggable_id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 로그에 추가 속성이 저장되는지 확인
|
||||
*/
|
||||
public function test_log_with_properties(): void
|
||||
{
|
||||
$properties = ['old_name' => 'John', 'new_name' => 'Jane'];
|
||||
$action = $this->testPrefix . 'user.update.props';
|
||||
|
||||
$this->activityLogService->log(
|
||||
ActivityLogType::Admin,
|
||||
$action,
|
||||
'User name updated',
|
||||
null,
|
||||
$properties
|
||||
);
|
||||
|
||||
$log = ActivityLog::where('action', $action)->first();
|
||||
$this->assertNotNull($log);
|
||||
$this->assertEquals($properties, $log->properties);
|
||||
}
|
||||
|
||||
/**
|
||||
* 인증된 사용자가 로그에 기록되는지 확인
|
||||
*/
|
||||
public function test_log_records_authenticated_user(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$this->actingAs($user);
|
||||
$action = $this->testPrefix . 'auth.action';
|
||||
|
||||
$this->activityLogService->log(
|
||||
ActivityLogType::Admin,
|
||||
$action,
|
||||
'Test action'
|
||||
);
|
||||
|
||||
$log = ActivityLog::where('action', $action)->first();
|
||||
$this->assertNotNull($log);
|
||||
$this->assertEquals($user->id, $log->user_id);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// logAdmin() / logUser() / logSystem() - 헬퍼 메서드 테스트
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* logAdmin이 관리자 유형으로 로그를 생성하는지 확인
|
||||
*/
|
||||
public function test_log_admin_creates_admin_type_log(): void
|
||||
{
|
||||
$action = $this->testPrefix . 'admin.action';
|
||||
$this->activityLogService->logAdmin($action, 'Admin action');
|
||||
|
||||
$log = ActivityLog::where('action', $action)->first();
|
||||
$this->assertNotNull($log);
|
||||
$this->assertEquals(ActivityLogType::Admin, $log->log_type);
|
||||
}
|
||||
|
||||
/**
|
||||
* logUser가 사용자 유형으로 로그를 생성하는지 확인
|
||||
*/
|
||||
public function test_log_user_creates_user_type_log(): void
|
||||
{
|
||||
$action = $this->testPrefix . 'user.action';
|
||||
$this->activityLogService->logUser($action, 'User action');
|
||||
|
||||
$log = ActivityLog::where('action', $action)->first();
|
||||
$this->assertNotNull($log);
|
||||
$this->assertEquals(ActivityLogType::User, $log->log_type);
|
||||
}
|
||||
|
||||
/**
|
||||
* logSystem이 시스템 유형으로 로그를 생성하는지 확인
|
||||
*/
|
||||
public function test_log_system_creates_system_type_log(): void
|
||||
{
|
||||
$action = $this->testPrefix . 'system.action';
|
||||
$this->activityLogService->logSystem($action, 'System action');
|
||||
|
||||
$log = ActivityLog::where('action', $action)->first();
|
||||
$this->assertNotNull($log);
|
||||
$this->assertEquals(ActivityLogType::System, $log->log_type);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// getLogsForModel() - 모델별 로그 조회 테스트
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* 특정 모델의 로그만 조회되는지 확인
|
||||
* 특정 모델의 로그만 반환하는지 확인
|
||||
*/
|
||||
public function test_get_logs_for_model_returns_only_model_logs(): void
|
||||
{
|
||||
$user1 = User::factory()->create();
|
||||
$user2 = User::factory()->create();
|
||||
$actionPrefix = $this->testPrefix . 'model_';
|
||||
|
||||
// user1에 대한 로그 2개 생성
|
||||
$this->activityLogService->logAdmin($actionPrefix . 'view1', 'Viewed user 1', $user1);
|
||||
$this->activityLogService->logAdmin($actionPrefix . 'update1', 'Updated user 1', $user1);
|
||||
$actionPrefix = $this->testPrefix . 'model.';
|
||||
|
||||
// user2에 대한 로그 1개 생성
|
||||
$this->activityLogService->logAdmin($actionPrefix . 'view2', 'Viewed user 2', $user2);
|
||||
$this->createLog($actionPrefix . 'view1', $user1);
|
||||
$this->createLog($actionPrefix . 'update1', $user1);
|
||||
$this->createLog($actionPrefix . 'view2', $user2);
|
||||
|
||||
$user1Logs = $this->activityLogService->getLogsForModel($user1);
|
||||
|
||||
// 이 테스트에서 생성한 로그만 필터링
|
||||
$filteredLogs = collect($user1Logs->items())->filter(fn ($log) => str_starts_with($log->action, $actionPrefix));
|
||||
|
||||
$this->assertCount(2, $filteredLogs);
|
||||
foreach ($filteredLogs as $log) {
|
||||
$this->assertEquals(2, $user1Logs->total());
|
||||
foreach ($user1Logs->items() as $log) {
|
||||
$this->assertEquals(User::class, $log->loggable_type);
|
||||
$this->assertEquals($user1->id, $log->loggable_id);
|
||||
}
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// getList() - 전체 로그 조회 테스트
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* 로그 목록 조회가 페이지네이션을 반환하는지 확인
|
||||
* 전체 로그 목록을 페이지네이션으로 반환하는지 확인
|
||||
*/
|
||||
public function test_get_list_returns_paginated_logs(): void
|
||||
{
|
||||
$actionPrefix = $this->testPrefix . 'paginate_';
|
||||
$actionPrefix = $this->testPrefix . 'paginate.';
|
||||
|
||||
// 로그 5개 생성
|
||||
for ($i = 0; $i < 5; $i++) {
|
||||
$this->activityLogService->logAdmin($actionPrefix . $i, "Action {$i}");
|
||||
for ($i = 1; $i <= 5; $i++) {
|
||||
$this->createLog($actionPrefix . $i);
|
||||
}
|
||||
|
||||
// 전체 로그 중 이 테스트에서 생성한 것만 확인
|
||||
$allLogs = ActivityLog::where('action', 'like', $actionPrefix . '%')->get();
|
||||
$this->assertCount(5, $allLogs);
|
||||
$logs = $this->activityLogService->getList(['per_page' => 10]);
|
||||
|
||||
$this->assertEquals(5, $logs->total());
|
||||
}
|
||||
|
||||
/**
|
||||
* 로그 유형 필터가 동작하는지 확인
|
||||
* log_type 필터가 동작하는지 확인
|
||||
*/
|
||||
public function test_get_list_filters_by_log_type(): void
|
||||
{
|
||||
$actionPrefix = $this->testPrefix . 'type_';
|
||||
$actionPrefix = $this->testPrefix . 'type.';
|
||||
|
||||
$this->activityLogService->logAdmin($actionPrefix . 'admin', 'Admin action');
|
||||
$this->activityLogService->logUser($actionPrefix . 'user', 'User action');
|
||||
$this->activityLogService->logSystem($actionPrefix . 'system', 'System action');
|
||||
$this->createLog($actionPrefix . 'admin', null, ActivityLogType::Admin);
|
||||
$this->createLog($actionPrefix . 'user', null, ActivityLogType::User);
|
||||
$this->createLog($actionPrefix . 'system', null, ActivityLogType::System);
|
||||
|
||||
$adminLogs = $this->activityLogService->getList(['log_type' => ActivityLogType::Admin]);
|
||||
$adminLogs = $this->activityLogService->getList([
|
||||
'log_type' => ActivityLogType::Admin,
|
||||
'action' => $actionPrefix . 'admin',
|
||||
]);
|
||||
|
||||
// 이 테스트에서 생성한 admin 로그만 필터링
|
||||
$filteredLogs = collect($adminLogs->items())->filter(fn ($log) => str_starts_with($log->action, $actionPrefix));
|
||||
|
||||
$this->assertCount(1, $filteredLogs);
|
||||
$this->assertEquals(ActivityLogType::Admin, $filteredLogs->first()->log_type);
|
||||
$this->assertEquals(1, $adminLogs->total());
|
||||
foreach ($adminLogs->items() as $log) {
|
||||
$this->assertEquals(ActivityLogType::Admin->value, $log->log_type->value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 액션 필터가 동작하는지 확인
|
||||
* action 필터가 동작하는지 확인
|
||||
*/
|
||||
public function test_get_list_filters_by_action(): void
|
||||
{
|
||||
$action = $this->testPrefix . 'filter.update';
|
||||
|
||||
$this->activityLogService->logAdmin($this->testPrefix . 'filter.create', 'User created');
|
||||
$this->activityLogService->logAdmin($action, 'User updated');
|
||||
$this->activityLogService->logAdmin($this->testPrefix . 'filter.delete', 'User deleted');
|
||||
$this->createLog($this->testPrefix . 'filter.create');
|
||||
$this->createLog($action);
|
||||
$this->createLog($this->testPrefix . 'filter.delete');
|
||||
|
||||
$logs = $this->activityLogService->getList(['action' => $action]);
|
||||
|
||||
$this->assertCount(1, $logs);
|
||||
$this->assertEquals($action, $logs->first()->action);
|
||||
$this->assertEquals(1, $logs->total());
|
||||
$this->assertEquals($action, $logs->items()[0]->action);
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자 필터가 동작하는지 확인
|
||||
* user_id 필터가 동작하는지 확인
|
||||
*/
|
||||
public function test_get_list_filters_by_user_id(): void
|
||||
{
|
||||
$user1 = User::factory()->create();
|
||||
$user2 = User::factory()->create();
|
||||
$action1 = $this->testPrefix . 'user1_action';
|
||||
$action2 = $this->testPrefix . 'user2_action';
|
||||
|
||||
$this->actingAs($user1);
|
||||
$this->activityLogService->logAdmin($action1, 'Action by user 1');
|
||||
$action1 = $this->testPrefix . 'user1.action';
|
||||
$action2 = $this->testPrefix . 'user2.action';
|
||||
|
||||
$this->actingAs($user2);
|
||||
$this->activityLogService->logAdmin($action2, 'Action by user 2');
|
||||
$this->createLog($action1, null, ActivityLogType::Admin, $user1);
|
||||
$this->createLog($action2, null, ActivityLogType::Admin, $user2);
|
||||
|
||||
$user1Logs = $this->activityLogService->getList(['user_id' => $user1->id, 'action' => $action1]);
|
||||
|
||||
$this->assertCount(1, $user1Logs);
|
||||
$this->assertEquals($user1->id, $user1Logs->first()->user_id);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Model Accessors - 모델 속성 테스트
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* log_type_label 접근자가 동작하는지 확인
|
||||
*/
|
||||
public function test_log_type_label_accessor(): void
|
||||
{
|
||||
$action = $this->testPrefix . 'label.action';
|
||||
$this->activityLogService->logAdmin($action, 'Test');
|
||||
|
||||
$log = ActivityLog::where('action', $action)->first();
|
||||
$this->assertNotNull($log);
|
||||
$this->assertNotEmpty($log->log_type_label);
|
||||
}
|
||||
|
||||
/**
|
||||
* actor_name 접근자가 사용자 이름을 반환하는지 확인
|
||||
*/
|
||||
public function test_actor_name_accessor_with_user(): void
|
||||
{
|
||||
$user = User::factory()->create(['name' => 'Test User']);
|
||||
$this->actingAs($user);
|
||||
$action = $this->testPrefix . 'actor.action';
|
||||
|
||||
$this->activityLogService->logAdmin($action, 'Test');
|
||||
|
||||
$log = ActivityLog::where('action', $action)->first();
|
||||
$this->assertNotNull($log);
|
||||
$this->assertEquals('Test User', $log->actor_name);
|
||||
}
|
||||
|
||||
/**
|
||||
* actor_name 접근자가 사용자 없을 때 시스템을 반환하는지 확인
|
||||
*/
|
||||
public function test_actor_name_accessor_without_user(): void
|
||||
{
|
||||
$action = $this->testPrefix . 'system.actor';
|
||||
$this->activityLogService->logSystem($action, 'Test');
|
||||
|
||||
$log = ActivityLog::where('action', $action)->first();
|
||||
$this->assertNotNull($log);
|
||||
$this->assertNotEmpty($log->actor_name);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// 훅 통합 테스트
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* 훅이 비활성화되면 로그가 저장되지 않는지 확인
|
||||
*/
|
||||
public function test_log_not_saved_when_disabled(): void
|
||||
{
|
||||
config(['activity_log.enabled' => false]);
|
||||
$action = $this->testPrefix . 'disabled.action';
|
||||
|
||||
$this->activityLogService->logAdmin($action, 'Test');
|
||||
|
||||
$this->assertDatabaseMissing('activity_logs', [
|
||||
'action' => $action,
|
||||
$user1Logs = $this->activityLogService->getList([
|
||||
'user_id' => $user1->id,
|
||||
'action' => $action1,
|
||||
]);
|
||||
|
||||
$this->assertEquals(1, $user1Logs->total());
|
||||
$this->assertEquals($user1->id, $user1Logs->items()[0]->user_id);
|
||||
}
|
||||
|
||||
/**
|
||||
* null 드라이버 사용 시 로그가 저장되지 않는지 확인
|
||||
* 단일 로그 삭제가 동작하는지 확인
|
||||
*/
|
||||
public function test_log_not_saved_with_null_driver(): void
|
||||
public function test_delete_removes_log(): void
|
||||
{
|
||||
// null 드라이버 설정
|
||||
config(['activity_log.driver' => 'null']);
|
||||
$action = $this->testPrefix . 'delete.single';
|
||||
$log = $this->createLog($action);
|
||||
|
||||
// HookManager 및 Event, 매니저 초기화
|
||||
HookManager::resetAll();
|
||||
Event::forget('hook.core.activity.admin');
|
||||
$this->app->forgetInstance(ActivityLogManager::class);
|
||||
$result = $this->activityLogService->delete($log->id);
|
||||
|
||||
// null 드라이버로 리스너 다시 등록 (static 배열에만)
|
||||
$listener = app(ActivityLogListener::class);
|
||||
$this->registerHookWithoutEvent('core.activity.admin', [$listener, 'handleAdmin']);
|
||||
$this->assertTrue($result);
|
||||
$this->assertDatabaseMissing('activity_logs', ['id' => $log->id]);
|
||||
}
|
||||
|
||||
$action = $this->testPrefix . 'null_driver.action';
|
||||
$this->activityLogService->logAdmin($action, 'Test');
|
||||
/**
|
||||
* 여러 로그 일괄 삭제가 동작하는지 확인
|
||||
*/
|
||||
public function test_delete_many_removes_multiple_logs(): void
|
||||
{
|
||||
$actionPrefix = $this->testPrefix . 'delete.bulk.';
|
||||
|
||||
$this->assertDatabaseMissing('activity_logs', [
|
||||
$log1 = $this->createLog($actionPrefix . '1');
|
||||
$log2 = $this->createLog($actionPrefix . '2');
|
||||
$log3 = $this->createLog($actionPrefix . '3');
|
||||
|
||||
$count = $this->activityLogService->deleteMany([$log1->id, $log2->id, $log3->id]);
|
||||
|
||||
$this->assertEquals(3, $count);
|
||||
$this->assertDatabaseMissing('activity_logs', ['id' => $log1->id]);
|
||||
$this->assertDatabaseMissing('activity_logs', ['id' => $log2->id]);
|
||||
$this->assertDatabaseMissing('activity_logs', ['id' => $log3->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* ActivityLog 를 직접 생성합니다 (Monolog 경로 우회 — getList/delete 테스트 전용)
|
||||
*/
|
||||
private function createLog(
|
||||
string $action,
|
||||
?User $loggable = null,
|
||||
ActivityLogType $type = ActivityLogType::Admin,
|
||||
?User $user = null,
|
||||
): ActivityLog {
|
||||
return ActivityLog::create([
|
||||
'log_type' => $type->value,
|
||||
'action' => $action,
|
||||
'description' => "Test log for {$action}",
|
||||
'user_id' => $user?->id,
|
||||
'loggable_type' => $loggable ? $loggable->getMorphClass() : null,
|
||||
'loggable_id' => $loggable?->id,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services;
|
||||
|
||||
use App\Services\CoreUpdateService;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* CoreUpdateService 권한 정확 복원 회귀 테스트.
|
||||
*
|
||||
* sudo 코어 업데이트 후 storage/app 사용자 데이터 권한이 깨지는 회귀 차단:
|
||||
*
|
||||
* - snapshotOwnershipDetailed: 좁힌 영역의 항목별 owner/group/perms 재귀 스냅샷
|
||||
* - restoreOwnership: detailed snapshot 기반 항목별 정확 복원
|
||||
* - storage/app/{modules,plugins,attachments,...} 는 detailed/snapshot 둘 다 비대상
|
||||
* → snapshot 후 변형된 상태가 그대로 유지되어야 함 (사용자 데이터 비대상 보장)
|
||||
*
|
||||
* 본 테스트는 권한 비트(perms) 변경 검증에 집중. owner 변경은 root 가 아닌 일반 user
|
||||
* 환경에서 다른 user 로 chown 호출 자체가 실패하므로 best-effort 로 검증.
|
||||
*/
|
||||
class CoreUpdateServicePermissionPreservationTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* @var array<int, string>
|
||||
*/
|
||||
private array $tempDirs = [];
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
foreach ($this->tempDirs as $dir) {
|
||||
if (File::isDirectory($dir)) {
|
||||
@chmod($dir, 0775);
|
||||
$this->relaxTreePermissions($dir);
|
||||
File::deleteDirectory($dir);
|
||||
}
|
||||
}
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tear-down 직전 트리의 모든 항목에 0775/0664 부여 — tearDown 의 deleteDirectory 가
|
||||
* 깨진 perms (예: 0700) 환경에서 traversal 실패하지 않도록 안전화.
|
||||
*/
|
||||
private function relaxTreePermissions(string $root): void
|
||||
{
|
||||
if (! is_dir($root)) {
|
||||
return;
|
||||
}
|
||||
$items = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator($root, \FilesystemIterator::SKIP_DOTS),
|
||||
\RecursiveIteratorIterator::SELF_FIRST
|
||||
);
|
||||
foreach ($items as $item) {
|
||||
@chmod($item->getPathname(), $item->isDir() ? 0775 : 0664);
|
||||
}
|
||||
}
|
||||
|
||||
private function createTempDir(): string
|
||||
{
|
||||
$dir = storage_path('test_perm_preservation_'.uniqid());
|
||||
File::ensureDirectoryExists($dir);
|
||||
$this->tempDirs[] = $dir;
|
||||
|
||||
return $dir;
|
||||
}
|
||||
|
||||
private function assertPosixOrSkip(): void
|
||||
{
|
||||
if (DIRECTORY_SEPARATOR !== '/' || ! function_exists('posix_getuid') || ! function_exists('chown')) {
|
||||
$this->markTestSkipped('chmod/chown 검증은 POSIX 환경 전용 (Windows 로컬 자동 스킵)');
|
||||
}
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// OS 무관 시그니처/메서드 존재 검증 (Windows 에서도 fail 가능)
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* snapshotOwnershipDetailed 메서드 존재 검증.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_snapshot_ownership_detailed_method_exists(): void
|
||||
{
|
||||
$this->assertTrue(
|
||||
method_exists(CoreUpdateService::class, 'snapshotOwnershipDetailed'),
|
||||
'CoreUpdateService::snapshotOwnershipDetailed 메서드가 정의되어야 함 (좁힌 영역의 항목별 권한 스냅샷)',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* restoreOwnership 시그니처 — detailedSnapshot 인자 지원 검증.
|
||||
*
|
||||
* 호환성 유지: 기존 ($snapshot, $onProgress) positional 호출이 그대로 작동하도록
|
||||
* detailedSnapshot 은 세 번째 인자로 default 값 빈 배열.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_restore_ownership_supports_detailed_snapshot_argument(): void
|
||||
{
|
||||
$reflection = new \ReflectionMethod(CoreUpdateService::class, 'restoreOwnership');
|
||||
$params = $reflection->getParameters();
|
||||
$names = array_map(fn ($p) => $p->getName(), $params);
|
||||
|
||||
$this->assertContains(
|
||||
'detailedSnapshot',
|
||||
$names,
|
||||
'restoreOwnership 가 detailedSnapshot 인자를 받아야 함 (항목별 정확 복원 인프라)',
|
||||
);
|
||||
|
||||
// 기존 호출 호환성: snapshot + onProgress 인자가 첫 두 자리에 유지되어야 함
|
||||
$this->assertSame('snapshot', $names[0] ?? null, '첫 인자는 snapshot');
|
||||
$this->assertSame('onProgress', $names[1] ?? null, '두 번째 인자는 onProgress (호환성 유지)');
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// POSIX 환경 전용 — 실제 권한 동작 검증
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* snapshotOwnershipDetailed — 트리 항목별 owner/group/perms/is_dir/is_link 수집.
|
||||
*
|
||||
* 정확한 시그니처 검증 + 빈 디렉토리는 항목 1개 (루트 자체) 만 포함.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_snapshot_ownership_detailed_collects_recursive_metadata(): void
|
||||
{
|
||||
$this->assertPosixOrSkip();
|
||||
|
||||
$root = $this->createTempDir();
|
||||
$logsDir = $root.'/logs';
|
||||
File::ensureDirectoryExists($logsDir);
|
||||
chmod($logsDir, 0775);
|
||||
|
||||
$logFile = $logsDir.'/test.log';
|
||||
file_put_contents($logFile, 'log content');
|
||||
chmod($logFile, 0664);
|
||||
|
||||
$service = app(CoreUpdateService::class);
|
||||
|
||||
// base_path 상대가 아닌 절대 경로 직접 지정 가능하도록 메서드 설계 검증.
|
||||
// 본 테스트에서는 절대경로 인자도 처리되는지 확인.
|
||||
$snapshot = $service->snapshotOwnershipDetailed([$root]);
|
||||
|
||||
$this->assertArrayHasKey($root, $snapshot, '루트 디렉토리 항목 포함');
|
||||
$this->assertArrayHasKey($logsDir, $snapshot, '하위 디렉토리 항목 포함');
|
||||
$this->assertArrayHasKey($logFile, $snapshot, '하위 파일 항목 포함');
|
||||
|
||||
$this->assertSame(0775, $snapshot[$logsDir]['perms'], 'perms 정확 기록');
|
||||
$this->assertSame(0664, $snapshot[$logFile]['perms'], '파일 perms 정확 기록');
|
||||
$this->assertTrue($snapshot[$logsDir]['is_dir'], 'is_dir true');
|
||||
$this->assertFalse($snapshot[$logFile]['is_dir'], 'is_dir false for file');
|
||||
$this->assertFalse($snapshot[$logFile]['is_link'], 'is_link false for regular file');
|
||||
|
||||
$this->assertIsInt($snapshot[$logsDir]['owner']);
|
||||
$this->assertIsInt($snapshot[$logsDir]['group']);
|
||||
}
|
||||
|
||||
/**
|
||||
* snapshotOwnershipDetailed — 존재하지 않는 path 는 결과에서 제외.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_snapshot_ownership_detailed_skips_missing_paths(): void
|
||||
{
|
||||
$this->assertPosixOrSkip();
|
||||
|
||||
$service = app(CoreUpdateService::class);
|
||||
$snapshot = $service->snapshotOwnershipDetailed(['/nonexistent_path_'.uniqid()]);
|
||||
|
||||
$this->assertSame([], $snapshot);
|
||||
}
|
||||
|
||||
/**
|
||||
* restoreOwnership(detailed) — 변형된 perms 가 원본으로 정확 복원.
|
||||
*
|
||||
* 시나리오: 0775 디렉토리 + 0664 파일을 snapshot → chmod 로 0700/0600 변형 → restore
|
||||
* → snapshot 기준으로 0775/0664 정확 복원 검증.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_restore_ownership_detailed_recovers_perms_to_snapshot_state(): void
|
||||
{
|
||||
$this->assertPosixOrSkip();
|
||||
|
||||
$root = $this->createTempDir();
|
||||
$childDir = $root.'/child';
|
||||
File::ensureDirectoryExists($childDir);
|
||||
chmod($childDir, 0775);
|
||||
|
||||
$childFile = $childDir.'/data.txt';
|
||||
file_put_contents($childFile, 'x');
|
||||
chmod($childFile, 0664);
|
||||
|
||||
$service = app(CoreUpdateService::class);
|
||||
$detailedSnapshot = $service->snapshotOwnershipDetailed([$root]);
|
||||
|
||||
// sudo 변형 모방 — 자식 디렉토리/파일을 0700/0600 으로 좁힘
|
||||
chmod($childDir, 0700);
|
||||
chmod($childFile, 0600);
|
||||
|
||||
// restore — detailed snapshot 으로 정확 복원
|
||||
$service->restoreOwnership(snapshot: [], onProgress: null, detailedSnapshot: $detailedSnapshot);
|
||||
|
||||
$this->assertSame(0775, fileperms($childDir) & 0777, '디렉토리 perms 원본 복원');
|
||||
$this->assertSame(0664, fileperms($childFile) & 0777, '파일 perms 원본 복원');
|
||||
}
|
||||
|
||||
/**
|
||||
* restoreOwnership(detailed) — detailed 미포함 path 는 기존 chownRecursive 동작 유지.
|
||||
*
|
||||
* 호환성 회귀 차단: 기존 호출(`restoreOwnership($snapshot, $onProgress)`)이 그대로
|
||||
* 작동하며, detailed snapshot 인자가 default(빈 배열) 일 때 기존 로직만 실행.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_restore_ownership_backward_compatible_when_detailed_empty(): void
|
||||
{
|
||||
$this->assertPosixOrSkip();
|
||||
|
||||
$service = app(CoreUpdateService::class);
|
||||
|
||||
// 빈 snapshot + 빈 detailed → no-op. 예외 없이 종료해야 함.
|
||||
$service->restoreOwnership([], null);
|
||||
$service->restoreOwnership([], null, []);
|
||||
|
||||
$this->addToAssertionCount(1); // 시그니처 호환성 자체가 검증 포인트
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// 트랙 1 — Upgrade_7_0_0_beta_4 의 normalizeStorageAppPermissionsForLegacyParent
|
||||
//
|
||||
// beta3 → beta4+ transition 한정 우회: spawn 자식 (sudo root) 이 storage/app 트리에
|
||||
// 직접 chmod 0755/0644 적용 → 부모(beta3) chown jjh + g+w 후 최종 0775/0664 →
|
||||
// PHP-FPM other 비트로 access OK (boot 트리거의 PHP-FPM 권한 제약 회피).
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* normalizeStorageAppPermissionsForLegacyParent 메서드가 Upgrade_7_0_0_beta_4 에 존재.
|
||||
*
|
||||
* 작동 불가 메커니즘 (recordPermissionSnapshotForLegacyParent + boot 트리거) 대체.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_upgrade_beta_4_has_normalize_storage_app_permissions_method(): void
|
||||
{
|
||||
require_once base_path('upgrades/Upgrade_7_0_0_beta_4.php');
|
||||
$reflection = new \ReflectionClass(\App\Upgrades\Upgrade_7_0_0_beta_4::class);
|
||||
|
||||
$this->assertTrue(
|
||||
$reflection->hasMethod('normalizeStorageAppPermissionsForLegacyParent'),
|
||||
'Upgrade_7_0_0_beta_4 에 normalizeStorageAppPermissionsForLegacyParent 메서드 정의 필요 '
|
||||
.'(spawn 자식 root 권한으로 storage/app chmod 0755/0644 적용)',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 작동 불가 메커니즘 제거 검증 — recordPermissionSnapshotForLegacyParent 부재.
|
||||
*
|
||||
* boot 트리거 (PermissionRestoreHelper) 가 PHP-FPM 권한 제약으로 작동 못 함이
|
||||
* 확인됨. 마커 작성 단계도 의미 없으므로 함께 제거.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_upgrade_beta_4_no_longer_has_record_permission_snapshot_method(): void
|
||||
{
|
||||
require_once base_path('upgrades/Upgrade_7_0_0_beta_4.php');
|
||||
$reflection = new \ReflectionClass(\App\Upgrades\Upgrade_7_0_0_beta_4::class);
|
||||
|
||||
$this->assertFalse(
|
||||
$reflection->hasMethod('recordPermissionSnapshotForLegacyParent'),
|
||||
'작동 불가 메커니즘은 제거되어야 함 (PermissionRestoreHelper boot 트리거가 PHP-FPM 권한 제약으로 silent fail)',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* PermissionRestoreHelper 클래스 자체 제거 — 작동 불가 메커니즘 cleanup.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_permission_restore_helper_class_removed(): void
|
||||
{
|
||||
$this->assertFalse(
|
||||
class_exists(\App\Extension\Helpers\PermissionRestoreHelper::class),
|
||||
'PermissionRestoreHelper 는 권한 모델상 작동 불가 — 제거되어야 함',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자 데이터 비대상 보장 — detailed snapshot 에 미포함된 영역은 손대지 않음.
|
||||
*
|
||||
* 시나리오: storage/app/modules 모방 디렉토리를 0700 PHP-FPM owner 로 시드한 뒤
|
||||
* detailed snapshot 에 미포함 상태에서 restore 호출 → 변경 0건 검증.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_restore_ownership_does_not_touch_paths_outside_detailed_snapshot(): void
|
||||
{
|
||||
$this->assertPosixOrSkip();
|
||||
|
||||
$tempRoot = $this->createTempDir();
|
||||
|
||||
// detailed 대상 영역 (예: storage/logs) — snapshot 수집
|
||||
$detailedRoot = $tempRoot.'/logs';
|
||||
File::ensureDirectoryExists($detailedRoot);
|
||||
chmod($detailedRoot, 0775);
|
||||
|
||||
// detailed 비대상 영역 (예: storage/app/modules) — 시드 owner 0700 으로 세팅
|
||||
$userDataDir = $tempRoot.'/app_modules';
|
||||
File::ensureDirectoryExists($userDataDir);
|
||||
chmod($userDataDir, 0700);
|
||||
$userDataFile = $userDataDir.'/image.jpg';
|
||||
file_put_contents($userDataFile, 'image');
|
||||
chmod($userDataFile, 0600);
|
||||
|
||||
$userDataDirOwnerBefore = fileowner($userDataDir);
|
||||
$userDataDirPermsBefore = fileperms($userDataDir) & 0777;
|
||||
$userDataFilePermsBefore = fileperms($userDataFile) & 0777;
|
||||
|
||||
$service = app(CoreUpdateService::class);
|
||||
$detailedSnapshot = $service->snapshotOwnershipDetailed([$detailedRoot]);
|
||||
|
||||
// restore — userDataDir 는 detailed 미포함이라 손대지 않아야 함
|
||||
$service->restoreOwnership(snapshot: [], onProgress: null, detailedSnapshot: $detailedSnapshot);
|
||||
|
||||
$this->assertSame($userDataDirOwnerBefore, fileowner($userDataDir), '사용자 데이터 owner 무변경');
|
||||
$this->assertSame($userDataDirPermsBefore, fileperms($userDataDir) & 0777, '사용자 데이터 디렉토리 perms 무변경');
|
||||
$this->assertSame($userDataFilePermsBefore, fileperms($userDataFile) & 0777, '사용자 데이터 파일 perms 무변경');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services;
|
||||
|
||||
use App\Services\CoreUpdateService;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* CoreUpdateService::reloadCoreConfigAndResync() 회귀 테스트.
|
||||
*
|
||||
* 부모 프로세스가 부팅 시점에 캐시한 stale config 를 우회해 디스크의 fresh
|
||||
* config/core.php 를 Config Repository 에 재주입하는 핵심 동작을 검증.
|
||||
*
|
||||
* 회귀 시나리오 (beta.3 → beta.4 트랜지션 박제 결함):
|
||||
* - CoreUpdateCommand Step 7 (applyUpdate) 가 디스크 config/core.php 를 신버전으로 교체
|
||||
* - 부모 프로세스 메모리의 Config Repository 는 부팅 당시 구버전 값 유지
|
||||
* - Step 9 가 syncCoreRolesAndPermissions / syncCoreMenus 를 직접 호출하면 stale 값으로 sync
|
||||
* - 신규 권한/메뉴가 누락 → 사용자 401/메뉴 부재 회귀
|
||||
*
|
||||
* 본 테스트는 reloadCoreConfigAndResync() 가 메모리 stale 값을 디스크 값으로 강제 갱신하는지 검증.
|
||||
* 즉 회귀 시 reloadCoreConfigAndResync() 호출 후 config('core.*') 가 디스크 값과 일치해야 함.
|
||||
*/
|
||||
class CoreUpdateServiceReloadResyncTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* stale 메모리 config 가 reloadCoreConfigAndResync() 호출 후 디스크 값으로 복원되는지 검증.
|
||||
*
|
||||
* 시나리오:
|
||||
* 1. 디스크 config/core.php 의 실제 permissions 카탈로그를 baseline 으로 캡처
|
||||
* 2. Config Repository 에 stale 값 강제 주입 (예: permissions=[])
|
||||
* 3. reloadCoreConfigAndResync() 호출 (sync/seeder 단계는 try/catch DB 의존이라 실패해도 본 검증과 무관)
|
||||
* 4. config('core.permissions') 가 다시 baseline 값으로 복원되었는지 확인
|
||||
*/
|
||||
public function test_reload_restores_stale_memory_config_from_disk(): void
|
||||
{
|
||||
// 디스크 baseline 캡처 — 테스트 실행 환경의 실제 config/core.php 값
|
||||
$diskFresh = require config_path('core.php');
|
||||
$this->assertIsArray($diskFresh, '디스크 config/core.php 는 array 반환 필수');
|
||||
$this->assertArrayHasKey('permissions', $diskFresh, 'config/core.php 에 permissions 키 존재 필수');
|
||||
|
||||
// stale 메모리 주입 — 부모 프로세스가 부팅 후 아무 이유로든 변경된 상태 시뮬레이션
|
||||
config(['core.permissions' => ['stale' => 'value']]);
|
||||
config(['core.menus' => []]);
|
||||
$this->assertSame(['stale' => 'value'], config('core.permissions'), 'stale 주입 확인');
|
||||
|
||||
// 서비스 호출 — sync/seeder 단계는 DB 미연결 환경에서 try/catch warning 으로 graceful 처리됨
|
||||
// 본 테스트는 config 재주입 동작만 검증하고, sync/seeder 가 호출되었는지는 다른 테스트가 검증
|
||||
$service = new class extends CoreUpdateService
|
||||
{
|
||||
// sync 단계 격리 — config 재주입 검증에 무관한 부수 효과 회피
|
||||
public function syncCoreRolesAndPermissions(): void {}
|
||||
|
||||
public function syncCoreMenus(): void {}
|
||||
};
|
||||
|
||||
$service->reloadCoreConfigAndResync();
|
||||
|
||||
// 디스크 값으로 복원 확인
|
||||
$this->assertSame(
|
||||
$diskFresh['permissions'],
|
||||
config('core.permissions'),
|
||||
'reloadCoreConfigAndResync() 후 config 가 디스크 값으로 복원되어야 함 (stale 메모리 값이 우선되면 회귀)'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* reloadCoreConfigAndResync() 가 코어 도메인 5종 (권한/메뉴/알림/IDV정책/IDV메시지) 을
|
||||
* 모두 호출 시도하는지 정적 검증.
|
||||
*
|
||||
* 회귀 시나리오: 향후 누군가 reloadCoreConfigAndResync 본문에서 시더 호출 일부를 제거하면
|
||||
* upgrade 흐름에서 해당 도메인이 누락되는 결함이 잠복함. 본 테스트는 본문에 5종이 모두
|
||||
* 등장하는지 확인하여 자동 차단.
|
||||
*/
|
||||
public function test_reload_invokes_all_core_domain_seeders(): void
|
||||
{
|
||||
$servicePath = base_path('app/Services/CoreUpdateService.php');
|
||||
$this->assertFileExists($servicePath);
|
||||
|
||||
$content = file_get_contents($servicePath);
|
||||
$this->assertNotFalse($content);
|
||||
|
||||
// reloadCoreConfigAndResync 본문 추출
|
||||
$start = strpos($content, 'public function reloadCoreConfigAndResync(): void');
|
||||
$this->assertNotFalse($start, 'reloadCoreConfigAndResync 메서드 정의 존재 필수');
|
||||
$end = strpos($content, "\n }\n", $start);
|
||||
$this->assertNotFalse($end, '메서드 본문 종결 위치 식별 실패');
|
||||
$body = substr($content, $start, $end - $start);
|
||||
|
||||
$this->assertStringContainsString('syncCoreRolesAndPermissions', $body, '권한/역할 sync 호출 누락');
|
||||
$this->assertStringContainsString('syncCoreMenus', $body, '메뉴 sync 호출 누락');
|
||||
$this->assertStringContainsString('NotificationDefinitionSeeder', $body, '알림 정의 시더 호출 누락');
|
||||
$this->assertStringContainsString('IdentityPolicySeeder', $body, 'IDV 정책 시더 호출 누락');
|
||||
$this->assertStringContainsString('IdentityMessageDefinitionSeeder', $body, 'IDV 메시지 정의 시더 호출 누락');
|
||||
}
|
||||
|
||||
/**
|
||||
* CoreUpdateCommand step 9 가 reloadCoreConfigAndResync 사용 (syncCore* 직접 호출 금지) 정합성을
|
||||
* audit 룰 `core-update-command-direct-sync` 가 보장하므로, 본 테스트에서는 정적 정합성을
|
||||
* 룰 재실행으로 1회 더 확인 (1차 방어).
|
||||
*/
|
||||
public function test_audit_rule_guards_against_direct_sync_call_regression(): void
|
||||
{
|
||||
$cmdPath = base_path('app/Console/Commands/Core/CoreUpdateCommand.php');
|
||||
$this->assertFileExists($cmdPath);
|
||||
|
||||
$content = file_get_contents($cmdPath);
|
||||
$this->assertNotFalse($content);
|
||||
|
||||
// 부모 프로세스에서 syncCore* 직접 호출 금지
|
||||
$this->assertDoesNotMatchRegularExpression(
|
||||
'/->\s*syncCoreRolesAndPermissions\s*\(/',
|
||||
$content,
|
||||
'CoreUpdateCommand 가 syncCoreRolesAndPermissions() 를 직접 호출하면 부모 stale config 회귀 발생 — reloadCoreConfigAndResync() 사용'
|
||||
);
|
||||
$this->assertDoesNotMatchRegularExpression(
|
||||
'/->\s*syncCoreMenus\s*\(/',
|
||||
$content,
|
||||
'CoreUpdateCommand 가 syncCoreMenus() 를 직접 호출하면 부모 stale config 회귀 발생 — reloadCoreConfigAndResync() 사용'
|
||||
);
|
||||
|
||||
// reloadCoreConfigAndResync 호출 1회 이상 존재
|
||||
$this->assertMatchesRegularExpression(
|
||||
'/->\s*reloadCoreConfigAndResync\s*\(/',
|
||||
$content,
|
||||
'CoreUpdateCommand step 9 가 reloadCoreConfigAndResync() 를 호출해야 함'
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -395,58 +395,103 @@ MD;
|
||||
|
||||
/**
|
||||
* .env 파일의 APP_VERSION 값을 올바르게 갱신하는지 검증합니다.
|
||||
*
|
||||
* 실제 프로젝트 루트의 `.env` 를 절대 건드리지 않기 위해 임시 디렉토리로
|
||||
* `app()->setBasePath()` 를 일시적으로 전환한 뒤 검증합니다. 과거 본 테스트가
|
||||
* `base_path('.env')` 를 직접 덮어쓰는 구조였고, 테스트 실행이 중단되면
|
||||
* `finally` 의 복원 로직이 손상된 fixture 를 그대로 다시 기록해 영구 고착되는
|
||||
* 자기 영속화 결함이 있어 회귀 차단을 위해 격리 기반으로 재작성됨.
|
||||
*/
|
||||
public function test_update_version_in_env(): void
|
||||
{
|
||||
// 임시 .env 파일 생성
|
||||
$tempEnvContent = "APP_NAME=G7\nAPP_VERSION=1.0.0\nAPP_ENV=testing\n";
|
||||
$envPath = base_path('.env');
|
||||
|
||||
$originalContent = File::exists($envPath) ? File::get($envPath) : null;
|
||||
File::put($envPath, $tempEnvContent);
|
||||
$this->withIsolatedBasePath(function (string $tempBase) use ($tempEnvContent): void {
|
||||
File::put($tempBase.DIRECTORY_SEPARATOR.'.env', $tempEnvContent);
|
||||
|
||||
try {
|
||||
$this->service->updateVersionInEnv('2.5.0');
|
||||
|
||||
$updatedContent = File::get($envPath);
|
||||
$updatedContent = File::get($tempBase.DIRECTORY_SEPARATOR.'.env');
|
||||
|
||||
// APP_VERSION이 갱신되었는지 확인
|
||||
// APP_VERSION 이 갱신되었는지 확인
|
||||
$this->assertStringContainsString('APP_VERSION=2.5.0', $updatedContent);
|
||||
$this->assertStringNotContainsString('APP_VERSION=1.0.0', $updatedContent);
|
||||
|
||||
// 다른 설정은 유지되는지 확인
|
||||
$this->assertStringContainsString('APP_NAME=G7', $updatedContent);
|
||||
$this->assertStringContainsString('APP_ENV=testing', $updatedContent);
|
||||
} finally {
|
||||
// 원본 .env 복원
|
||||
if ($originalContent !== null) {
|
||||
File::put($envPath, $originalContent);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* .env 파일에 APP_VERSION이 없을 때 새로 추가하는지 검증합니다.
|
||||
* .env 파일에 APP_VERSION 이 없을 때 새로 추가하는지 검증합니다.
|
||||
*/
|
||||
public function test_update_version_in_env_appends_when_missing(): void
|
||||
{
|
||||
$tempEnvContent = "APP_NAME=G7\nAPP_ENV=testing\n";
|
||||
$envPath = base_path('.env');
|
||||
|
||||
$originalContent = File::exists($envPath) ? File::get($envPath) : null;
|
||||
File::put($envPath, $tempEnvContent);
|
||||
$this->withIsolatedBasePath(function (string $tempBase) use ($tempEnvContent): void {
|
||||
File::put($tempBase.DIRECTORY_SEPARATOR.'.env', $tempEnvContent);
|
||||
|
||||
try {
|
||||
$this->service->updateVersionInEnv('1.5.0');
|
||||
|
||||
$updatedContent = File::get($envPath);
|
||||
$updatedContent = File::get($tempBase.DIRECTORY_SEPARATOR.'.env');
|
||||
|
||||
// APP_VERSION이 추가되었는지 확인
|
||||
// APP_VERSION 이 추가되었는지 확인
|
||||
$this->assertStringContainsString('APP_VERSION=1.5.0', $updatedContent);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀 테스트 — `updateVersionInEnv` 가 실 프로젝트 루트의 `.env` 를
|
||||
* 어떤 경우에도 수정하지 않는지 검증합니다.
|
||||
*
|
||||
* 본 테스트가 실행되어도 진짜 `.env` 의 mtime/내용 모두 불변이어야 합니다.
|
||||
* 과거 회귀 (테스트 fixture 가 실 `.env` 를 덮어쓰고 finally 복원 실패 시
|
||||
* 영구 고착) 의 재발을 차단합니다.
|
||||
*/
|
||||
public function test_update_version_in_env_never_touches_real_env(): void
|
||||
{
|
||||
$realEnvPath = base_path('.env');
|
||||
|
||||
$existedBefore = File::exists($realEnvPath);
|
||||
$contentBefore = $existedBefore ? File::get($realEnvPath) : null;
|
||||
$mtimeBefore = $existedBefore ? File::lastModified($realEnvPath) : null;
|
||||
|
||||
$this->test_update_version_in_env();
|
||||
$this->test_update_version_in_env_appends_when_missing();
|
||||
|
||||
$this->assertSame($existedBefore, File::exists($realEnvPath), '실 .env 존재 여부가 변경되었습니다');
|
||||
|
||||
if ($existedBefore) {
|
||||
$this->assertSame($contentBefore, File::get($realEnvPath), '실 .env 내용이 변경되었습니다');
|
||||
$this->assertSame($mtimeBefore, File::lastModified($realEnvPath), '실 .env mtime 이 변경되었습니다');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 임시 디렉토리로 application base path 를 격리한 채 콜백을 실행합니다.
|
||||
*
|
||||
* `setBasePath` 는 `path.base` 등 다수 컨테이너 바인딩을 재바인딩하지만,
|
||||
* 본 테스트가 사용하는 helper (base_path) 만 새 경로를 따라가도록 충분합니다.
|
||||
* finally 로 원본 base path 를 복원하고 임시 디렉토리는 tempDirs 에 등록되어
|
||||
* tearDown 에서 일괄 정리됩니다.
|
||||
*
|
||||
* @param \Closure(string $tempBase): void $callback
|
||||
*/
|
||||
private function withIsolatedBasePath(\Closure $callback): void
|
||||
{
|
||||
$tempBase = sys_get_temp_dir().DIRECTORY_SEPARATOR.'g7-core-update-test-'.uniqid('', true);
|
||||
File::makeDirectory($tempBase, 0755, true);
|
||||
$this->tempDirs[] = $tempBase;
|
||||
|
||||
$originalBase = $this->app->basePath();
|
||||
$this->app->setBasePath($tempBase);
|
||||
|
||||
try {
|
||||
$callback($tempBase);
|
||||
} finally {
|
||||
if ($originalContent !== null) {
|
||||
File::put($envPath, $originalContent);
|
||||
}
|
||||
$this->app->setBasePath($originalBase);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1064,4 +1109,120 @@ MD;
|
||||
// OrphanFile.php는 삭제됨
|
||||
$this->assertFalse(File::exists($tempDest.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'OrphanFile.php'));
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// applyUpdate() — 신규 최상위 디렉토리 자동 발견 폴백 (회귀: lang-packs 누락)
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* 부모 프로세스의 stale `app.update.targets` 가 신버전 신규 최상위 디렉토리를 인식하지
|
||||
* 못할 때, applyUpdate 가 source 디렉토리에서 자동 발견하여 복사하는지 검증합니다.
|
||||
*
|
||||
* 회귀 시나리오: beta.3 → beta.4 업그레이드에서 beta.3 의 targets 에 `lang-packs/_bundled`
|
||||
* 가 없어 신버전 zip 의 lang-packs 가 활성 디렉토리로 복사되지 않은 결함.
|
||||
*/
|
||||
public function test_apply_update_auto_discovers_new_top_level_directories(): void
|
||||
{
|
||||
$sourcePath = storage_path('test_apply_autodisc_src_'.uniqid());
|
||||
$this->tempDirs[] = $sourcePath;
|
||||
File::ensureDirectoryExists($sourcePath);
|
||||
|
||||
// 신버전 source 에 신규 최상위 디렉토리 + 보호 대상 디렉토리 + 파일 배치
|
||||
File::ensureDirectoryExists($sourcePath.DIRECTORY_SEPARATOR.'lang-packs'.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.'g7-core-ja');
|
||||
File::put(
|
||||
$sourcePath.DIRECTORY_SEPARATOR.'lang-packs'.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.'g7-core-ja'.DIRECTORY_SEPARATOR.'language-pack.json',
|
||||
'{"identifier":"g7-core-ja"}'
|
||||
);
|
||||
File::ensureDirectoryExists($sourcePath.DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.'app');
|
||||
File::put($sourcePath.DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'leak.txt', 'should_not_copy');
|
||||
File::put($sourcePath.DIRECTORY_SEPARATOR.'.env', 'APP_VERSION=hijacked');
|
||||
|
||||
// 격리된 base_path 시뮬레이션
|
||||
$fakeBase = storage_path('test_apply_autodisc_base_'.uniqid());
|
||||
$this->tempDirs[] = $fakeBase;
|
||||
File::ensureDirectoryExists($fakeBase);
|
||||
|
||||
$originalBasePath = base_path();
|
||||
app()->setBasePath($fakeBase);
|
||||
|
||||
// 활성 측에 보호 대상 dir 가 이미 존재하고 내용이 있는 상태 (덮어쓰면 안 됨)
|
||||
File::ensureDirectoryExists($fakeBase.DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.'app');
|
||||
File::put($fakeBase.DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'runtime.txt', 'KEEP_ME');
|
||||
File::put($fakeBase.DIRECTORY_SEPARATOR.'.env', 'APP_VERSION=local');
|
||||
|
||||
try {
|
||||
// stale targets 시뮬레이션 — beta.3 의 targets 에는 lang-packs 가 없음
|
||||
config([
|
||||
'app.update.targets' => ['app'],
|
||||
'app.update.excludes' => [],
|
||||
'app.update.protected_paths' => ['.env', 'storage', 'vendor', 'node_modules', '.git'],
|
||||
]);
|
||||
|
||||
// app 디렉토리도 source 에 있어야 targets 분기를 거침
|
||||
File::ensureDirectoryExists($sourcePath.DIRECTORY_SEPARATOR.'app');
|
||||
File::put($sourcePath.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'Marker.php', '<?php // marker');
|
||||
|
||||
$this->service->applyUpdate($sourcePath);
|
||||
|
||||
// targets 명시 항목은 기존대로 적용
|
||||
$this->assertFileExists($fakeBase.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'Marker.php');
|
||||
|
||||
// 자동 발견: lang-packs/_bundled 가 source 에서 활성으로 복사되어야 함
|
||||
$this->assertFileExists(
|
||||
$fakeBase.DIRECTORY_SEPARATOR.'lang-packs'.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.'g7-core-ja'.DIRECTORY_SEPARATOR.'language-pack.json',
|
||||
'lang-packs/_bundled 가 source 에서 자동 발견되어 복사되어야 한다'
|
||||
);
|
||||
|
||||
// PROTECTED 보호: storage/.env 는 자동 발견 폴백이 절대 덮지 않음
|
||||
$this->assertSame('KEEP_ME', File::get($fakeBase.DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'runtime.txt'));
|
||||
$this->assertSame('APP_VERSION=local', File::get($fakeBase.DIRECTORY_SEPARATOR.'.env'));
|
||||
} finally {
|
||||
app()->setBasePath($originalBasePath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 자동 발견 폴백이 protected_paths 와 user excludes 양쪽을 존중하는지 검증합니다.
|
||||
*/
|
||||
public function test_apply_update_auto_discovery_respects_protected_paths_and_excludes(): void
|
||||
{
|
||||
$sourcePath = storage_path('test_apply_protected_src_'.uniqid());
|
||||
$this->tempDirs[] = $sourcePath;
|
||||
File::ensureDirectoryExists($sourcePath);
|
||||
|
||||
File::ensureDirectoryExists($sourcePath.DIRECTORY_SEPARATOR.'unknown-new-dir');
|
||||
File::put($sourcePath.DIRECTORY_SEPARATOR.'unknown-new-dir'.DIRECTORY_SEPARATOR.'a.txt', 'x');
|
||||
File::ensureDirectoryExists($sourcePath.DIRECTORY_SEPARATOR.'.claude');
|
||||
File::put($sourcePath.DIRECTORY_SEPARATOR.'.claude'.DIRECTORY_SEPARATOR.'leak.txt', 'should_not_copy');
|
||||
File::ensureDirectoryExists($sourcePath.DIRECTORY_SEPARATOR.'excluded-by-user');
|
||||
File::put($sourcePath.DIRECTORY_SEPARATOR.'excluded-by-user'.DIRECTORY_SEPARATOR.'a.txt', 'x');
|
||||
|
||||
$fakeBase = storage_path('test_apply_protected_base_'.uniqid());
|
||||
$this->tempDirs[] = $fakeBase;
|
||||
File::ensureDirectoryExists($fakeBase);
|
||||
|
||||
$originalBasePath = base_path();
|
||||
app()->setBasePath($fakeBase);
|
||||
|
||||
try {
|
||||
config([
|
||||
'app.update.targets' => [],
|
||||
'app.update.excludes' => ['excluded-by-user'],
|
||||
'app.update.protected_paths' => ['.claude', '.env', 'storage', 'vendor', 'node_modules', '.git'],
|
||||
]);
|
||||
|
||||
$this->service->applyUpdate($sourcePath);
|
||||
|
||||
// 자동 발견 통과
|
||||
$this->assertFileExists($fakeBase.DIRECTORY_SEPARATOR.'unknown-new-dir'.DIRECTORY_SEPARATOR.'a.txt');
|
||||
|
||||
// protected_paths 차단
|
||||
$this->assertDirectoryDoesNotExist($fakeBase.DIRECTORY_SEPARATOR.'.claude');
|
||||
|
||||
// user excludes 차단
|
||||
$this->assertDirectoryDoesNotExist($fakeBase.DIRECTORY_SEPARATOR.'excluded-by-user');
|
||||
} finally {
|
||||
app()->setBasePath($originalBasePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,11 @@ namespace Tests\Unit\Services;
|
||||
|
||||
use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
use App\Contracts\Repositories\ActivityLogRepositoryInterface;
|
||||
use App\Contracts\Repositories\UserRepositoryInterface;
|
||||
use App\Services\DashboardService;
|
||||
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Mockery;
|
||||
use Tests\TestCase;
|
||||
|
||||
@@ -15,10 +17,14 @@ use Tests\TestCase;
|
||||
*/
|
||||
class DashboardServiceTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private DashboardService $service;
|
||||
|
||||
private $userRepository;
|
||||
|
||||
private $activityLogRepository;
|
||||
|
||||
private $moduleManager;
|
||||
|
||||
private $pluginManager;
|
||||
@@ -28,11 +34,13 @@ class DashboardServiceTest extends TestCase
|
||||
parent::setUp();
|
||||
|
||||
$this->userRepository = Mockery::mock(UserRepositoryInterface::class);
|
||||
$this->activityLogRepository = Mockery::mock(ActivityLogRepositoryInterface::class);
|
||||
$this->moduleManager = Mockery::mock(ModuleManagerInterface::class);
|
||||
$this->pluginManager = Mockery::mock(PluginManagerInterface::class);
|
||||
|
||||
$this->service = new DashboardService(
|
||||
$this->userRepository,
|
||||
$this->activityLogRepository,
|
||||
$this->moduleManager,
|
||||
$this->pluginManager
|
||||
);
|
||||
@@ -180,6 +188,7 @@ class DashboardServiceTest extends TestCase
|
||||
{
|
||||
$service = Mockery::mock(DashboardService::class, [
|
||||
$this->userRepository,
|
||||
$this->activityLogRepository,
|
||||
$this->moduleManager,
|
||||
$this->pluginManager,
|
||||
])->makePartial()->shouldAllowMockingProtectedMethods();
|
||||
@@ -258,8 +267,8 @@ class DashboardServiceTest extends TestCase
|
||||
|
||||
public function test_get_recent_activities_returns_array(): void
|
||||
{
|
||||
$this->userRepository->shouldReceive('getRecentUsers')
|
||||
->with(10)
|
||||
$this->activityLogRepository->shouldReceive('getRecent')
|
||||
->with('core.dashboard.activities', 5)
|
||||
->andReturn(new EloquentCollection([]));
|
||||
|
||||
$activities = $this->service->getRecentActivities();
|
||||
@@ -269,14 +278,16 @@ class DashboardServiceTest extends TestCase
|
||||
|
||||
public function test_get_recent_activities_formats_user_registration(): void
|
||||
{
|
||||
$mockUser = Mockery::mock();
|
||||
$mockUser->name = 'Test User';
|
||||
$mockUser->email = 'test@example.com';
|
||||
$mockUser->created_at = now()->subMinutes(5);
|
||||
$mockLog = Mockery::mock(\App\Models\ActivityLog::class)->makePartial();
|
||||
$mockLog->shouldReceive('getAttribute')->with('log_type')->andReturn(\App\Enums\ActivityLogType::User);
|
||||
$mockLog->shouldReceive('getAttribute')->with('action')->andReturn('register');
|
||||
$mockLog->shouldReceive('getAttribute')->with('localized_description')->andReturn('테스트 유저가 가입했습니다');
|
||||
$mockLog->shouldReceive('getAttribute')->with('actor_name')->andReturn('Test User');
|
||||
$mockLog->shouldReceive('getAttribute')->with('created_at')->andReturn(now()->subMinutes(5));
|
||||
|
||||
$this->userRepository->shouldReceive('getRecentUsers')
|
||||
->with(10)
|
||||
->andReturn(new EloquentCollection([$mockUser]));
|
||||
$this->activityLogRepository->shouldReceive('getRecent')
|
||||
->with('core.dashboard.activities', 5)
|
||||
->andReturn(new EloquentCollection([$mockLog]));
|
||||
|
||||
$activities = $this->service->getRecentActivities();
|
||||
|
||||
@@ -302,6 +313,7 @@ class DashboardServiceTest extends TestCase
|
||||
{
|
||||
$alerts = $this->service->getSystemAlerts();
|
||||
|
||||
$this->assertIsArray($alerts);
|
||||
foreach ($alerts as $alert) {
|
||||
$this->assertArrayHasKey('id', $alert);
|
||||
$this->assertArrayHasKey('title', $alert);
|
||||
@@ -318,11 +330,19 @@ class DashboardServiceTest extends TestCase
|
||||
$alerts = $this->service->getSystemAlerts();
|
||||
$validTypes = ['info', 'warning', 'success', 'error'];
|
||||
|
||||
$this->assertIsArray($alerts);
|
||||
foreach ($alerts as $alert) {
|
||||
$this->assertContains($alert['type'], $validTypes);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_get_system_alerts_returns_empty_when_no_listeners(): void
|
||||
{
|
||||
$alerts = $this->service->getSystemAlerts();
|
||||
|
||||
$this->assertIsArray($alerts);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Mockery::close();
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services\Extension;
|
||||
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Enums\LanguagePackScope;
|
||||
use App\Models\Template;
|
||||
use App\Services\Extension\ExtensionInstallPreviewBuilder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* ExtensionInstallPreviewBuilder 의 cascade 프리뷰 응답 검증.
|
||||
*
|
||||
* 회귀: 템플릿 설치 모달에서 의존 확장의 식별자/이름/required_version 이 표시되지 않는 버그
|
||||
* — TemplateService::getTemplateInfo() 는 manifest 의 raw `{modules, plugins}` shape 를
|
||||
* 반환(TemplateResource 가 raw 를 사용해서 변경 불가)하므로, builder 단계에서 Template 스코프 한정으로
|
||||
* DependencyEnricher::enrich() 를 거쳐야 enriched 평면 배열로 변환된다.
|
||||
*/
|
||||
class ExtensionInstallPreviewBuilderTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private ExtensionInstallPreviewBuilder $builder;
|
||||
|
||||
private string $testTemplatePath;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->builder = app(ExtensionInstallPreviewBuilder::class);
|
||||
$this->testTemplatePath = base_path('templates/test-preview');
|
||||
|
||||
if (File::exists($this->testTemplatePath)) {
|
||||
File::deleteDirectory($this->testTemplatePath);
|
||||
}
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
if (File::exists($this->testTemplatePath)) {
|
||||
File::deleteDirectory($this->testTemplatePath);
|
||||
}
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function createTestTemplate(array $dependencies): void
|
||||
{
|
||||
File::makeDirectory($this->testTemplatePath.'/layouts', 0755, true);
|
||||
|
||||
File::put(
|
||||
$this->testTemplatePath.'/template.json',
|
||||
json_encode([
|
||||
'identifier' => 'test-preview',
|
||||
'vendor' => 'test',
|
||||
'name' => ['ko' => '테스트 프리뷰', 'en' => 'Test Preview'],
|
||||
'version' => '1.0.0',
|
||||
'type' => 'admin',
|
||||
'description' => ['ko' => '', 'en' => ''],
|
||||
'dependencies' => $dependencies,
|
||||
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
|
||||
);
|
||||
|
||||
// builder 가 TemplateService 를 통해 매니페스트를 다시 읽도록 매니저 캐시 갱신
|
||||
app(\App\Extension\TemplateManager::class)->loadTemplates();
|
||||
}
|
||||
|
||||
public function test_template_dependencies_are_returned_as_enriched_flat_array(): void
|
||||
{
|
||||
$this->createTestTemplate([
|
||||
'modules' => ['missing-foo' => '>=1.0.0'],
|
||||
'plugins' => ['missing-bar' => '>=2.0.0'],
|
||||
]);
|
||||
|
||||
$preview = $this->builder->build(LanguagePackScope::Template, 'test-preview');
|
||||
|
||||
$this->assertIsArray($preview['dependencies']);
|
||||
$this->assertCount(2, $preview['dependencies'], '의존성은 enriched 평면 배열이어야 함 (modules+plugins 합산)');
|
||||
|
||||
$byId = [];
|
||||
foreach ($preview['dependencies'] as $dep) {
|
||||
$this->assertArrayHasKey('identifier', $dep);
|
||||
$this->assertArrayHasKey('name', $dep);
|
||||
$this->assertArrayHasKey('type', $dep);
|
||||
$this->assertArrayHasKey('required_version', $dep);
|
||||
$this->assertArrayHasKey('is_installed', $dep);
|
||||
$this->assertArrayHasKey('is_met', $dep);
|
||||
$this->assertArrayHasKey('default_selected', $dep);
|
||||
$byId[$dep['identifier']] = $dep;
|
||||
}
|
||||
|
||||
$this->assertArrayHasKey('missing-foo', $byId);
|
||||
$this->assertSame('module', $byId['missing-foo']['type']);
|
||||
$this->assertSame('>=1.0.0', $byId['missing-foo']['required_version']);
|
||||
$this->assertFalse($byId['missing-foo']['is_installed']);
|
||||
$this->assertFalse($byId['missing-foo']['is_met']);
|
||||
$this->assertTrue($byId['missing-foo']['default_selected']);
|
||||
|
||||
$this->assertArrayHasKey('missing-bar', $byId);
|
||||
$this->assertSame('plugin', $byId['missing-bar']['type']);
|
||||
$this->assertSame('>=2.0.0', $byId['missing-bar']['required_version']);
|
||||
}
|
||||
|
||||
public function test_template_with_empty_dependencies_returns_empty_array(): void
|
||||
{
|
||||
$this->createTestTemplate([
|
||||
'modules' => [],
|
||||
'plugins' => [],
|
||||
]);
|
||||
|
||||
$preview = $this->builder->build(LanguagePackScope::Template, 'test-preview');
|
||||
|
||||
$this->assertSame([], $preview['dependencies']);
|
||||
}
|
||||
}
|
||||
@@ -79,7 +79,7 @@ class GeoIpServiceTest extends TestCase
|
||||
config(['geoip.cache.enabled' => false]);
|
||||
|
||||
// 새로운 서비스 인스턴스 생성 (설정 변경 반영)
|
||||
$service = new GeoIpService;
|
||||
$service = app(GeoIpService::class);
|
||||
|
||||
// Google DNS (미국) - America/Chicago 또는 다른 미국 타임존
|
||||
$supportedTimezones = [
|
||||
@@ -112,7 +112,7 @@ class GeoIpServiceTest extends TestCase
|
||||
config(['geoip.database_path' => $dbPath]);
|
||||
config(['geoip.cache.enabled' => false]);
|
||||
|
||||
$service = new GeoIpService;
|
||||
$service = app(GeoIpService::class);
|
||||
|
||||
// 미국 IP인데 한국 타임존만 지원하는 경우
|
||||
$result = $service->getTimezoneByIp('8.8.8.8', ['Asia/Seoul', 'Asia/Tokyo']);
|
||||
@@ -134,13 +134,14 @@ class GeoIpServiceTest extends TestCase
|
||||
config(['geoip.enabled' => true]);
|
||||
config(['geoip.database_path' => $dbPath]);
|
||||
config(['geoip.cache.enabled' => true]);
|
||||
config(['geoip.cache.prefix' => 'test.geoip.timezone.']);
|
||||
config(['geoip.cache.ttl' => 3600]);
|
||||
|
||||
// 캐시 클리어
|
||||
Cache::forget('test.geoip.timezone.8.8.8.8');
|
||||
// CacheInterface 경유 — 실제 사용 키는 'geoip.timezone.'.{ip}
|
||||
$cache = app(\App\Contracts\Extension\CacheInterface::class);
|
||||
$cacheKey = 'geoip.timezone.8.8.8.8';
|
||||
$cache->forget($cacheKey);
|
||||
|
||||
$service = new GeoIpService;
|
||||
$service = app(GeoIpService::class);
|
||||
|
||||
$supportedTimezones = [
|
||||
'America/New_York',
|
||||
@@ -153,8 +154,8 @@ class GeoIpServiceTest extends TestCase
|
||||
// 첫 번째 조회 (캐시 미스)
|
||||
$result1 = $service->getTimezoneByIp('8.8.8.8', $supportedTimezones);
|
||||
|
||||
// 캐시에 저장되었는지 확인
|
||||
$cached = Cache::get('test.geoip.timezone.8.8.8.8');
|
||||
// 캐시에 저장되었는지 확인 (빈 문자열이어도 저장됨 — 실패 반복 방지 패턴)
|
||||
$cached = $cache->get($cacheKey);
|
||||
$this->assertNotNull($cached);
|
||||
|
||||
// 두 번째 조회 (캐시 히트)
|
||||
@@ -163,7 +164,7 @@ class GeoIpServiceTest extends TestCase
|
||||
$this->assertEquals($result1, $result2);
|
||||
|
||||
// 정리
|
||||
Cache::forget('test.geoip.timezone.8.8.8.8');
|
||||
$cache->forget($cacheKey);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -181,7 +182,7 @@ class GeoIpServiceTest extends TestCase
|
||||
config(['geoip.database_path' => $dbPath]);
|
||||
config(['geoip.cache.enabled' => false]);
|
||||
|
||||
$service = new GeoIpService;
|
||||
$service = app(GeoIpService::class);
|
||||
|
||||
// KT DNS (한국)
|
||||
$supportedTimezones = ['Asia/Seoul', 'Asia/Tokyo', 'UTC'];
|
||||
@@ -206,7 +207,7 @@ class GeoIpServiceTest extends TestCase
|
||||
config(['geoip.database_path' => $dbPath]);
|
||||
config(['geoip.cache.enabled' => false]);
|
||||
|
||||
$service = new GeoIpService;
|
||||
$service = app(GeoIpService::class);
|
||||
|
||||
// NTT (일본)
|
||||
$supportedTimezones = ['Asia/Seoul', 'Asia/Tokyo', 'UTC'];
|
||||
@@ -231,7 +232,7 @@ class GeoIpServiceTest extends TestCase
|
||||
config(['geoip.database_path' => $dbPath]);
|
||||
config(['geoip.cache.enabled' => false]);
|
||||
|
||||
$service = new GeoIpService;
|
||||
$service = app(GeoIpService::class);
|
||||
|
||||
// 프라이빗 IP (192.168.x.x)
|
||||
$result = $service->getTimezoneByIp('192.168.1.1', ['Asia/Seoul', 'UTC']);
|
||||
@@ -254,7 +255,7 @@ class GeoIpServiceTest extends TestCase
|
||||
config(['geoip.database_path' => $dbPath]);
|
||||
config(['geoip.cache.enabled' => false]);
|
||||
|
||||
$service = new GeoIpService;
|
||||
$service = app(GeoIpService::class);
|
||||
|
||||
$result = $service->getTimezoneByIp('127.0.0.1', ['Asia/Seoul', 'UTC']);
|
||||
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services;
|
||||
|
||||
use App\Mail\IdentityMessageMail;
|
||||
use App\Models\IdentityMessageDefinition;
|
||||
use App\Models\IdentityMessageTemplate;
|
||||
use App\Services\IdentityMessageDispatcher;
|
||||
use Database\Seeders\IdentityMessageDefinitionSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* IdentityMessageDispatcher 단위 테스트.
|
||||
*
|
||||
* resolve 성공/실패 분기, 변수 치환, IdentityMessageMail 발송, 훅 발화 검증.
|
||||
*/
|
||||
class IdentityMessageDispatcherTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private IdentityMessageDispatcher $dispatcher;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->seed(IdentityMessageDefinitionSeeder::class);
|
||||
$this->dispatcher = $this->app->make(IdentityMessageDispatcher::class);
|
||||
Mail::fake();
|
||||
}
|
||||
|
||||
public function test_dispatch_sends_mail_when_resolved(): void
|
||||
{
|
||||
$result = $this->dispatcher->dispatch(
|
||||
providerId: 'g7:core.mail',
|
||||
purpose: 'signup',
|
||||
policyKey: null,
|
||||
renderHint: 'text_code',
|
||||
channel: 'mail',
|
||||
target: 'user@example.com',
|
||||
data: ['code' => '654321', 'expire_minutes' => 15, 'app_name' => 'TestApp'],
|
||||
);
|
||||
|
||||
$this->assertTrue($result);
|
||||
Mail::assertSent(IdentityMessageMail::class, function (IdentityMessageMail $mail) {
|
||||
$envelope = $mail->envelope();
|
||||
$body = $this->extractBody($mail);
|
||||
$this->assertStringContainsString('654321', $body);
|
||||
$this->assertStringNotContainsString('{code}', $body);
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
public function test_dispatch_returns_false_when_no_definition_resolved(): void
|
||||
{
|
||||
IdentityMessageDefinition::query()->update(['is_active' => false]);
|
||||
$this->app->make(\App\Services\IdentityMessageDefinitionService::class)->invalidateAllCache();
|
||||
|
||||
$result = $this->dispatcher->dispatch(
|
||||
providerId: 'g7:core.mail',
|
||||
purpose: 'signup',
|
||||
policyKey: null,
|
||||
renderHint: 'text_code',
|
||||
channel: 'mail',
|
||||
target: 'user@example.com',
|
||||
data: ['code' => '111111'],
|
||||
);
|
||||
|
||||
$this->assertFalse($result);
|
||||
Mail::assertNothingSent();
|
||||
}
|
||||
|
||||
public function test_dispatch_uses_purpose_definition_when_available(): void
|
||||
{
|
||||
$this->dispatcher->dispatch(
|
||||
providerId: 'g7:core.mail',
|
||||
purpose: 'signup',
|
||||
policyKey: null,
|
||||
renderHint: 'text_code',
|
||||
channel: 'mail',
|
||||
target: 'signup@example.com',
|
||||
data: ['code' => '999000', 'expire_minutes' => 15, 'app_name' => 'X'],
|
||||
);
|
||||
|
||||
Mail::assertSent(IdentityMessageMail::class, function (IdentityMessageMail $mail) {
|
||||
$envelope = $mail->envelope();
|
||||
// signup purpose 시드 subject 에 'Signup' 또는 '회원가입' 포함
|
||||
$this->assertMatchesRegularExpression('/Signup|회원가입/u', $envelope->subject);
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
public function test_dispatch_falls_back_to_provider_default_when_purpose_inactive(): void
|
||||
{
|
||||
IdentityMessageDefinition::where('scope_value', 'signup')->update(['is_active' => false]);
|
||||
$this->app->make(\App\Services\IdentityMessageDefinitionService::class)->invalidateAllCache();
|
||||
|
||||
$result = $this->dispatcher->dispatch(
|
||||
providerId: 'g7:core.mail',
|
||||
purpose: 'signup',
|
||||
policyKey: null,
|
||||
renderHint: 'text_code',
|
||||
channel: 'mail',
|
||||
target: 'fallback@example.com',
|
||||
data: ['code' => '222222', 'expire_minutes' => 15, 'app_name' => 'X'],
|
||||
);
|
||||
|
||||
$this->assertTrue($result);
|
||||
Mail::assertSent(IdentityMessageMail::class);
|
||||
}
|
||||
|
||||
public function test_dispatch_skips_when_template_inactive(): void
|
||||
{
|
||||
IdentityMessageTemplate::query()->update(['is_active' => false]);
|
||||
$this->app->make(\App\Services\IdentityMessageDefinitionService::class)->invalidateAllCache();
|
||||
|
||||
$result = $this->dispatcher->dispatch(
|
||||
providerId: 'g7:core.mail',
|
||||
purpose: 'signup',
|
||||
policyKey: null,
|
||||
renderHint: 'text_code',
|
||||
channel: 'mail',
|
||||
target: 'user@example.com',
|
||||
data: ['code' => '111111'],
|
||||
);
|
||||
|
||||
$this->assertFalse($result);
|
||||
Mail::assertNothingSent();
|
||||
}
|
||||
|
||||
public function test_unsupported_channel_does_not_send_mail(): void
|
||||
{
|
||||
$result = $this->dispatcher->dispatch(
|
||||
providerId: 'g7:core.mail',
|
||||
purpose: 'signup',
|
||||
policyKey: null,
|
||||
renderHint: 'text_code',
|
||||
channel: 'sms', // mail 채널 외 — Filter 훅으로 위임, 발송 미이행
|
||||
target: '+821011112222',
|
||||
data: ['code' => '333333'],
|
||||
);
|
||||
|
||||
// sms 정의 없음 → resolve 실패 → false
|
||||
$this->assertFalse($result);
|
||||
Mail::assertNothingSent();
|
||||
}
|
||||
|
||||
private function extractBody(IdentityMessageMail $mail): string
|
||||
{
|
||||
$reflection = new \ReflectionClass($mail);
|
||||
|
||||
// 부모 DbTemplateMail 의 private $renderedBody 추출
|
||||
$parent = $reflection->getParentClass();
|
||||
$property = $parent->getProperty('renderedBody');
|
||||
$property->setAccessible(true);
|
||||
|
||||
return (string) $property->getValue($mail);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services;
|
||||
|
||||
use App\Enums\IdentityVerificationStatus;
|
||||
use App\Exceptions\IdentityVerificationRequiredException;
|
||||
use App\Models\IdentityPolicy;
|
||||
use App\Models\IdentityVerificationLog;
|
||||
use App\Models\User;
|
||||
use App\Services\IdentityPolicyService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* IdentityPolicyService 테스트.
|
||||
*
|
||||
* resolve/enforce 동작 및 grace_minutes/fail_mode 분기를 검증합니다.
|
||||
*/
|
||||
class IdentityPolicyServiceTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private IdentityPolicyService $service;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->service = $this->app->make(IdentityPolicyService::class);
|
||||
}
|
||||
|
||||
public function test_resolve_returns_policy_by_scope_target(): void
|
||||
{
|
||||
$policy = IdentityPolicy::create([
|
||||
'key' => 'test.policy.a',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.test.one',
|
||||
'purpose' => 'sensitive_action',
|
||||
'grace_minutes' => 0,
|
||||
'enabled' => true,
|
||||
'priority' => 100,
|
||||
'source_type' => 'admin',
|
||||
'source_identifier' => 'admin',
|
||||
'applies_to' => 'both',
|
||||
'fail_mode' => 'block',
|
||||
]);
|
||||
|
||||
$resolved = $this->service->resolve('route', 'api.test.one');
|
||||
|
||||
$this->assertNotNull($resolved);
|
||||
$this->assertSame($policy->key, $resolved->key);
|
||||
}
|
||||
|
||||
public function test_resolve_returns_null_when_no_match(): void
|
||||
{
|
||||
$resolved = $this->service->resolve('route', 'api.nonexistent');
|
||||
$this->assertNull($resolved);
|
||||
}
|
||||
|
||||
public function test_enforce_throws_when_no_recent_verified(): void
|
||||
{
|
||||
$policy = $this->makePolicy(['grace_minutes' => 0]);
|
||||
|
||||
$this->expectException(IdentityVerificationRequiredException::class);
|
||||
$this->service->enforce($policy, null, ['target_email' => 'x@example.com']);
|
||||
}
|
||||
|
||||
public function test_enforce_passes_when_recent_verified_exists(): void
|
||||
{
|
||||
$policy = $this->makePolicy(['grace_minutes' => 5]);
|
||||
$user = User::factory()->create();
|
||||
|
||||
IdentityVerificationLog::create([
|
||||
'id' => (string) Str::uuid(),
|
||||
'provider_id' => 'g7:core.mail',
|
||||
'purpose' => 'sensitive_action',
|
||||
'channel' => 'email',
|
||||
'user_id' => $user->id,
|
||||
'target_hash' => hash('sha256', mb_strtolower($user->email)),
|
||||
'status' => IdentityVerificationStatus::Verified->value,
|
||||
'verified_at' => now(),
|
||||
'expires_at' => now()->addMinutes(15),
|
||||
]);
|
||||
|
||||
// 예외가 발생하지 않으면 통과
|
||||
$this->service->enforce($policy, $user, []);
|
||||
$this->assertTrue(true);
|
||||
}
|
||||
|
||||
public function test_enforce_log_only_does_not_throw_but_records_log(): void
|
||||
{
|
||||
$policy = $this->makePolicy(['grace_minutes' => 0, 'fail_mode' => 'log_only']);
|
||||
|
||||
$this->service->enforce($policy, null, ['target_email' => 'x@example.com']);
|
||||
|
||||
$this->assertDatabaseHas('identity_verification_logs', [
|
||||
'status' => IdentityVerificationStatus::PolicyViolationLogged->value,
|
||||
'origin_policy_key' => $policy->key,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_enforce_skips_when_policy_disabled(): void
|
||||
{
|
||||
$policy = $this->makePolicy(['enabled' => false]);
|
||||
|
||||
// 예외 없이 통과해야 함
|
||||
$this->service->enforce($policy, null, ['target_email' => 'x@example.com']);
|
||||
$this->assertTrue(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* applies_to=self 정책은 admin 사용자(context.user_is_admin=true)에게는 enforce 하지 않습니다.
|
||||
*/
|
||||
public function test_enforce_skips_admin_user_when_applies_to_self(): void
|
||||
{
|
||||
$policy = $this->makePolicy(['grace_minutes' => 0, 'applies_to' => 'self']);
|
||||
|
||||
$this->service->enforce($policy, null, [
|
||||
'target_email' => 'x@example.com',
|
||||
'user_is_admin' => true,
|
||||
]);
|
||||
$this->assertTrue(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* applies_to=admin 정책은 일반 사용자(user_is_admin=false)에게는 enforce 하지 않습니다.
|
||||
*/
|
||||
public function test_enforce_skips_non_admin_when_applies_to_admin(): void
|
||||
{
|
||||
$policy = $this->makePolicy(['grace_minutes' => 0, 'applies_to' => 'admin']);
|
||||
|
||||
$this->service->enforce($policy, null, [
|
||||
'target_email' => 'x@example.com',
|
||||
'user_is_admin' => false,
|
||||
]);
|
||||
$this->assertTrue(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* applies_to=admin + admin context — 일반 enforce 흐름 적용 (verified 없으면 throw).
|
||||
*/
|
||||
public function test_enforce_throws_for_admin_when_applies_to_admin_and_no_verified(): void
|
||||
{
|
||||
$policy = $this->makePolicy(['grace_minutes' => 0, 'applies_to' => 'admin']);
|
||||
|
||||
$this->expectException(IdentityVerificationRequiredException::class);
|
||||
$this->service->enforce($policy, null, [
|
||||
'target_email' => 'x@example.com',
|
||||
'user_is_admin' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* applies_to=both — admin/일반 무관 enforce 흐름 적용.
|
||||
*/
|
||||
public function test_enforce_applies_to_both_targets_everyone(): void
|
||||
{
|
||||
$policy = $this->makePolicy(['grace_minutes' => 0, 'applies_to' => 'both']);
|
||||
|
||||
$this->expectException(IdentityVerificationRequiredException::class);
|
||||
$this->service->enforce($policy, null, [
|
||||
'target_email' => 'x@example.com',
|
||||
'user_is_admin' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* conditions.signup_stage 매칭 — context 가 일치할 때만 정책 선택됨.
|
||||
*/
|
||||
public function test_resolve_matches_signup_stage_condition(): void
|
||||
{
|
||||
IdentityPolicy::create([
|
||||
'key' => 'test.signup.before',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.test.signup',
|
||||
'purpose' => 'signup',
|
||||
'grace_minutes' => 0,
|
||||
'enabled' => true,
|
||||
'priority' => 110,
|
||||
'source_type' => 'admin',
|
||||
'source_identifier' => 'admin',
|
||||
'applies_to' => 'self',
|
||||
'fail_mode' => 'block',
|
||||
'conditions' => ['signup_stage' => 'before_submit'],
|
||||
]);
|
||||
|
||||
$matched = $this->service->resolve('route', 'api.test.signup', ['signup_stage' => 'before_submit']);
|
||||
$this->assertNotNull($matched);
|
||||
$this->assertSame('test.signup.before', $matched->key);
|
||||
|
||||
$miss = $this->service->resolve('route', 'api.test.signup', ['signup_stage' => 'after_create']);
|
||||
$this->assertNull($miss);
|
||||
}
|
||||
|
||||
/**
|
||||
* conditions.signup_stage 미설정 정책 — context 무관 매칭 (기존 동작).
|
||||
*/
|
||||
public function test_resolve_signup_stage_unset_matches_any_context(): void
|
||||
{
|
||||
IdentityPolicy::create([
|
||||
'key' => 'test.signup.any',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.test.signup_any',
|
||||
'purpose' => 'signup',
|
||||
'grace_minutes' => 0,
|
||||
'enabled' => true,
|
||||
'priority' => 100,
|
||||
'source_type' => 'admin',
|
||||
'source_identifier' => 'admin',
|
||||
'applies_to' => 'self',
|
||||
'fail_mode' => 'block',
|
||||
]);
|
||||
|
||||
$resolved = $this->service->resolve('route', 'api.test.signup_any', ['signup_stage' => 'any_value']);
|
||||
$this->assertNotNull($resolved);
|
||||
}
|
||||
|
||||
/**
|
||||
* filter 훅이 IdentityPolicy 외 타입(null/string)을 반환해도 원본 정책이 유지되어야 합니다 (보안).
|
||||
*/
|
||||
public function test_resolve_filter_hook_invalid_return_type_keeps_original(): void
|
||||
{
|
||||
$policy = IdentityPolicy::create([
|
||||
'key' => 'test.filter.original',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.test.filter',
|
||||
'purpose' => 'sensitive_action',
|
||||
'grace_minutes' => 0,
|
||||
'enabled' => true,
|
||||
'priority' => 100,
|
||||
'source_type' => 'admin',
|
||||
'source_identifier' => 'admin',
|
||||
'applies_to' => 'both',
|
||||
'fail_mode' => 'block',
|
||||
]);
|
||||
|
||||
\App\Extension\HookManager::addFilter(
|
||||
'core.identity.resolve_policy',
|
||||
fn ($current) => null, // 의도적 우회 시도
|
||||
10,
|
||||
);
|
||||
|
||||
try {
|
||||
$resolved = $this->service->resolve('route', 'api.test.filter');
|
||||
|
||||
$this->assertNotNull($resolved, 'filter 훅이 null 반환해도 원본 정책이 유지되어야 함');
|
||||
$this->assertSame($policy->key, $resolved->key);
|
||||
} finally {
|
||||
\App\Extension\HookManager::clearFilter('core.identity.resolve_policy');
|
||||
}
|
||||
}
|
||||
|
||||
private function makePolicy(array $overrides = []): IdentityPolicy
|
||||
{
|
||||
return IdentityPolicy::create(array_merge([
|
||||
'key' => 'test.policy.'.Str::random(4),
|
||||
'scope' => 'route',
|
||||
'target' => 'api.test.any',
|
||||
'purpose' => 'sensitive_action',
|
||||
'grace_minutes' => 0,
|
||||
'enabled' => true,
|
||||
'priority' => 100,
|
||||
'source_type' => 'admin',
|
||||
'source_identifier' => 'admin',
|
||||
'applies_to' => 'both',
|
||||
'fail_mode' => 'block',
|
||||
], $overrides));
|
||||
}
|
||||
|
||||
/**
|
||||
* resetFieldOverride('conditions') — B안 리팩토링.
|
||||
*
|
||||
* 운영자가 conditions 를 수정한 후 "↺ 기본값으로 되돌리기" 클릭 시
|
||||
* declared default 가 복원되고 user_overrides 에서 'conditions' 가 제거되어야 한다.
|
||||
*/
|
||||
public function test_reset_field_override_restores_declared_conditions(): void
|
||||
{
|
||||
// 주의: policy key 에 dot 가 포함되므로 config dot-notation 을 회피하기 위해
|
||||
// 'core.identity_policies' 블록을 통째로 설정한다 (Service::findDeclaredDefault 와 동형).
|
||||
config([
|
||||
'core.identity_policies' => [
|
||||
'test.reset.conditions' => [
|
||||
'key' => 'test.reset.conditions',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.auth.register',
|
||||
'purpose' => 'signup',
|
||||
'conditions' => ['signup_stage' => 'before_submit'],
|
||||
'grace_minutes' => 0,
|
||||
'enabled' => true,
|
||||
'priority' => 100,
|
||||
'applies_to' => 'self',
|
||||
'fail_mode' => 'block',
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$policy = IdentityPolicy::create([
|
||||
'key' => 'test.reset.conditions',
|
||||
'scope' => 'route',
|
||||
'target' => 'api.auth.register',
|
||||
'purpose' => 'signup',
|
||||
'grace_minutes' => 0,
|
||||
'enabled' => true,
|
||||
'priority' => 100,
|
||||
'source_type' => 'core',
|
||||
'source_identifier' => 'core',
|
||||
'applies_to' => 'self',
|
||||
'fail_mode' => 'block',
|
||||
'conditions' => ['signup_stage' => 'after_create'],
|
||||
'user_overrides' => ['conditions'],
|
||||
]);
|
||||
|
||||
$result = $this->service->resetFieldOverride($policy, 'conditions');
|
||||
|
||||
$this->assertTrue($result);
|
||||
|
||||
$fresh = $policy->fresh();
|
||||
$this->assertSame(['signup_stage' => 'before_submit'], $fresh->conditions);
|
||||
$this->assertNotContains('conditions', $fresh->user_overrides ?? []);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services\LanguagePack;
|
||||
|
||||
use App\Services\LanguagePack\LanguagePackManifestValidator;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 공식 일본어 번들 언어팩 12종의 manifest 무결성 검증.
|
||||
*
|
||||
* lang-packs/_bundled/g7-*-ja/language-pack.json 이 production validator 를 통과하고,
|
||||
* 패키지 디렉토리에 선언된 파일들이 실제 존재함을 검증한다.
|
||||
*
|
||||
* 번들 미배포 상태에서는 자동 스킵 (CI 안전).
|
||||
*/
|
||||
class BundledJapanesePacksTest extends TestCase
|
||||
{
|
||||
/** @var array<int, string> 공식 ja 패키지 식별자 12종 */
|
||||
private const PACKS = [
|
||||
'g7-core-ja',
|
||||
'g7-template-sirsoft-admin_basic-ja',
|
||||
'g7-template-sirsoft-basic-ja',
|
||||
'g7-template-gnuboard7-hello_admin_template-ja',
|
||||
'g7-template-gnuboard7-hello_user_template-ja',
|
||||
'g7-module-sirsoft-ecommerce-ja',
|
||||
'g7-module-sirsoft-board-ja',
|
||||
'g7-module-sirsoft-page-ja',
|
||||
'g7-module-gnuboard7-hello_module-ja',
|
||||
'g7-plugin-sirsoft-ckeditor5-ja',
|
||||
'g7-plugin-sirsoft-marketing-ja',
|
||||
'g7-plugin-sirsoft-tosspayments-ja',
|
||||
];
|
||||
|
||||
/**
|
||||
* 12개 ja 팩의 manifest 가 모두 LanguagePackManifestValidator 를 통과하는지 검증.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_all_japanese_bundled_manifests_pass_validator(): void
|
||||
{
|
||||
$validator = $this->app->make(LanguagePackManifestValidator::class);
|
||||
$checked = 0;
|
||||
|
||||
foreach (self::PACKS as $identifier) {
|
||||
$packageRoot = base_path('lang-packs/_bundled/'.$identifier);
|
||||
$manifestPath = $packageRoot.'/language-pack.json';
|
||||
if (! File::isFile($manifestPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$manifest = json_decode(File::get($manifestPath), true);
|
||||
$this->assertIsArray($manifest, "[$identifier] manifest 가 올바른 JSON 이어야 함");
|
||||
|
||||
$validator->validate($manifest, $packageRoot);
|
||||
|
||||
$this->assertSame($identifier, $manifest['identifier']);
|
||||
$this->assertSame('ja', $manifest['locale']);
|
||||
$this->assertSame('日本語', $manifest['locale_native_name']);
|
||||
$this->assertSame('g7', $manifest['namespace'], "[$identifier] namespace=g7 (모든 G7 공식 번들의 공통 prefix)");
|
||||
$this->assertNotEmpty($manifest['vendor'], "[$identifier] vendor 는 제작자 식별자 (모듈/플러그인 매니페스트와 일관)");
|
||||
$this->assertIsArray($manifest['name'], "[$identifier] name 은 다국어 객체 (모듈/플러그인과 일관)");
|
||||
|
||||
$checked++;
|
||||
}
|
||||
|
||||
if ($checked === 0) {
|
||||
$this->markTestSkipped('일본어 ja 팩이 아직 빌드되지 않음 — build-language-pack-ja.cjs 실행 후 재시도');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 12개 ja 팩 디렉토리에 backend/frontend/seed 중 최소 1개 카테고리의 파일이 존재하는지 검증.
|
||||
*
|
||||
* 매니페스트의 `contents` 필드는 모듈/플러그인/템플릿 매니페스트와의 일관성을 위해 제거됨 —
|
||||
* 파일 인벤토리는 디스크 스캔이 SSoT.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_all_japanese_bundled_contents_files_exist(): void
|
||||
{
|
||||
$checked = 0;
|
||||
|
||||
foreach (self::PACKS as $identifier) {
|
||||
$packageRoot = base_path('lang-packs/_bundled/'.$identifier);
|
||||
if (! File::isDirectory($packageRoot)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$hasFiles = false;
|
||||
foreach (['backend', 'frontend', 'seed'] as $bucket) {
|
||||
$bucketDir = $packageRoot.DIRECTORY_SEPARATOR.$bucket;
|
||||
if (File::isDirectory($bucketDir) && count(File::allFiles($bucketDir)) > 0) {
|
||||
$hasFiles = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertTrue($hasFiles, "[$identifier] backend/frontend/seed 디렉토리에 파일이 1개 이상 존재해야 함");
|
||||
|
||||
$checked++;
|
||||
}
|
||||
|
||||
if ($checked === 0) {
|
||||
$this->markTestSkipped('일본어 ja 팩이 아직 빌드되지 않음 — build-language-pack-ja.cjs 실행 후 재시도');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 12개 ja 팩의 backend PHP 파일과 frontend JSON 파일이 한국어 원본과 동일한 키 집합을 가지는지 검증.
|
||||
*
|
||||
* 키 누락은 i18n fallback 누수로 이어지므로 bottom-line 무결성 검사.
|
||||
* 본 테스트는 g7-core-ja 만 샘플 검증 (전체 검증은 비용 대비 효과 낮음).
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_g7_core_ja_backend_keys_match_korean_origin(): void
|
||||
{
|
||||
$packageRoot = base_path('lang-packs/_bundled/g7-core-ja');
|
||||
$jaDir = $packageRoot.'/backend/ja';
|
||||
if (! File::isDirectory($jaDir)) {
|
||||
$this->markTestSkipped('g7-core-ja 가 아직 빌드되지 않음');
|
||||
}
|
||||
|
||||
$koDir = base_path('lang/ko');
|
||||
$missing = [];
|
||||
foreach (File::files($jaDir) as $jaFile) {
|
||||
$name = $jaFile->getFilename();
|
||||
$koFile = $koDir.DIRECTORY_SEPARATOR.$name;
|
||||
$this->assertFileExists($koFile, "[$name] ko 원본 부재");
|
||||
|
||||
$jaArr = require $jaFile->getRealPath();
|
||||
$koArr = require $koFile;
|
||||
$jaKeys = $this->flattenKeys($jaArr);
|
||||
$koKeys = $this->flattenKeys($koArr);
|
||||
$diff = array_diff($koKeys, $jaKeys);
|
||||
if (! empty($diff)) {
|
||||
$missing[$name] = array_values($diff);
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertEmpty($missing, '키 누락: '.json_encode($missing, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
|
||||
}
|
||||
|
||||
/**
|
||||
* 중첩 배열을 점 표기 키 목록으로 평탄화.
|
||||
*
|
||||
* @param array<string, mixed> $arr
|
||||
* @param string $prefix
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function flattenKeys(array $arr, string $prefix = ''): array
|
||||
{
|
||||
$keys = [];
|
||||
foreach ($arr as $k => $v) {
|
||||
$cur = $prefix === '' ? (string) $k : $prefix.'.'.$k;
|
||||
if (is_array($v)) {
|
||||
$keys = array_merge($keys, $this->flattenKeys($v, $cur));
|
||||
} else {
|
||||
$keys[] = $cur;
|
||||
}
|
||||
}
|
||||
|
||||
return $keys;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services\LanguagePack;
|
||||
|
||||
use App\Enums\LanguagePackScope;
|
||||
use App\Enums\LanguagePackStatus;
|
||||
use App\Models\LanguagePack;
|
||||
use App\Services\LanguagePack\LanguagePackBundledRegistrar;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* LanguagePackBundledRegistrar 단위 테스트.
|
||||
*
|
||||
* 확장(모듈/플러그인/템플릿) 설치/제거 시 가상 등록 동작 + 슬롯 다중 벤더 시나리오를 검증합니다.
|
||||
*/
|
||||
class LanguagePackBundledRegistrarTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private LanguagePackBundledRegistrar $registrar;
|
||||
|
||||
private string $extensionRoot;
|
||||
|
||||
private string $relativePath = 'storage/app/test-extension/lang';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->registrar = $this->app->make(LanguagePackBundledRegistrar::class);
|
||||
|
||||
$this->extensionRoot = base_path($this->relativePath);
|
||||
File::ensureDirectoryExists($this->extensionRoot);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
File::deleteDirectory(base_path('storage/app/test-extension'));
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 lang 디렉토리에 locale 디렉토리를 생성합니다.
|
||||
*
|
||||
* @param array<int, string> $locales 생성할 locale 목록
|
||||
* @return void
|
||||
*/
|
||||
private function setupExtensionLangDirs(array $locales): void
|
||||
{
|
||||
foreach ($locales as $locale) {
|
||||
File::ensureDirectoryExists($this->extensionRoot.'/'.$locale);
|
||||
File::put(
|
||||
$this->extensionRoot.'/'.$locale.'/messages.php',
|
||||
"<?php\nreturn ['hello' => 'Hello'];\n"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_sync_registers_bundled_records_for_each_locale(): void
|
||||
{
|
||||
$this->setupExtensionLangDirs(['ko', 'en', 'ja']);
|
||||
|
||||
$this->registrar->syncFromExtension(
|
||||
'module',
|
||||
'test-module',
|
||||
'test',
|
||||
'1.0.0',
|
||||
$this->relativePath,
|
||||
);
|
||||
|
||||
$this->assertCount(3, LanguagePack::query()->where('target_identifier', 'test-module')->get());
|
||||
}
|
||||
|
||||
public function test_sync_promotes_first_to_active_and_others_installed(): void
|
||||
{
|
||||
$this->setupExtensionLangDirs(['ko', 'en']);
|
||||
|
||||
$this->registrar->syncFromExtension('module', 'test-module', 'test', '1.0.0', $this->relativePath);
|
||||
|
||||
$packs = LanguagePack::query()->where('target_identifier', 'test-module')->get();
|
||||
$activeCount = $packs->where('status', LanguagePackStatus::Active->value)->count();
|
||||
|
||||
// 각 locale 슬롯이 비어있었으므로 모두 active 로 자동 승격
|
||||
$this->assertSame(2, $activeCount);
|
||||
}
|
||||
|
||||
public function test_sync_keeps_existing_active_when_new_record_added(): void
|
||||
{
|
||||
// 외부 벤더의 ja 언어팩이 이미 active
|
||||
LanguagePack::query()->create([
|
||||
'identifier' => 'acme-module-test-module-ja',
|
||||
'vendor' => 'acme',
|
||||
'scope' => LanguagePackScope::Module->value,
|
||||
'target_identifier' => 'test-module',
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'Japanese',
|
||||
'locale_native_name' => '日本語',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => LanguagePackStatus::Active->value,
|
||||
'is_protected' => false,
|
||||
'manifest' => [],
|
||||
'source_type' => 'zip',
|
||||
]);
|
||||
|
||||
$this->setupExtensionLangDirs(['ja']);
|
||||
$this->registrar->syncFromExtension('module', 'test-module', 'test', '1.0.0', $this->relativePath);
|
||||
|
||||
// 새 가상 레코드는 installed 상태로 진입 (기존 active 유지)
|
||||
$bundled = LanguagePack::query()
|
||||
->where('target_identifier', 'test-module')
|
||||
->where('source_type', 'bundled_with_extension')
|
||||
->first();
|
||||
|
||||
$this->assertSame(LanguagePackStatus::Installed->value, $bundled->status);
|
||||
}
|
||||
|
||||
public function test_cleanup_deletes_bundled_records(): void
|
||||
{
|
||||
$this->setupExtensionLangDirs(['ja']);
|
||||
$this->registrar->syncFromExtension('module', 'test-module', 'test', '1.0.0', $this->relativePath);
|
||||
|
||||
$this->registrar->cleanupForExtension('module', 'test-module');
|
||||
|
||||
$this->assertCount(0, LanguagePack::query()
|
||||
->where('target_identifier', 'test-module')
|
||||
->where('source_type', 'bundled_with_extension')
|
||||
->get());
|
||||
}
|
||||
|
||||
public function test_cleanup_marks_external_packs_as_error(): void
|
||||
{
|
||||
$external = LanguagePack::query()->create([
|
||||
'identifier' => 'foobar-module-test-module-ja',
|
||||
'vendor' => 'foobar',
|
||||
'scope' => LanguagePackScope::Module->value,
|
||||
'target_identifier' => 'test-module',
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'Japanese',
|
||||
'locale_native_name' => '日本語',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '2.0.0',
|
||||
'status' => LanguagePackStatus::Active->value,
|
||||
'is_protected' => false,
|
||||
'manifest' => [],
|
||||
'source_type' => 'zip',
|
||||
]);
|
||||
|
||||
$this->registrar->cleanupForExtension('module', 'test-module');
|
||||
|
||||
$this->assertSame(LanguagePackStatus::Error->value, $external->fresh()->status);
|
||||
}
|
||||
|
||||
public function test_sync_skips_invalid_locale_directories(): void
|
||||
{
|
||||
File::ensureDirectoryExists($this->extensionRoot.'/UPPERCASE_INVALID');
|
||||
File::ensureDirectoryExists($this->extensionRoot.'/ko');
|
||||
|
||||
$this->registrar->syncFromExtension('module', 'test-module', 'test', '1.0.0', $this->relativePath);
|
||||
|
||||
$packs = LanguagePack::query()->where('target_identifier', 'test-module')->get();
|
||||
$this->assertSame(1, $packs->count());
|
||||
$this->assertSame('ko', $packs->first()->locale);
|
||||
}
|
||||
|
||||
public function test_sync_handles_partial_directory_pattern(): void
|
||||
{
|
||||
// {lang}/partial/{locale}/*.json 패턴 (G7 템플릿 fragment 구조)
|
||||
File::ensureDirectoryExists($this->extensionRoot.'/partial/ja');
|
||||
File::put($this->extensionRoot.'/partial/ja/admin.json', '{"hello":"こんにちは"}');
|
||||
|
||||
$this->registrar->syncFromExtension('template', 'test-template', 'test', '1.0.0', $this->relativePath);
|
||||
|
||||
$packs = LanguagePack::query()->where('target_identifier', 'test-template')->get();
|
||||
$this->assertCount(1, $packs);
|
||||
$this->assertSame('ja', $packs->first()->locale);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services\LanguagePack;
|
||||
|
||||
use App\Services\LanguagePack\LanguagePackManifestValidator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* LanguagePackManifestValidator 단위 테스트.
|
||||
*
|
||||
* 신규 매니페스트 스키마 (namespace + vendor 분리, top-level g7_version) 기준 케이스.
|
||||
*/
|
||||
class LanguagePackManifestValidatorTest extends TestCase
|
||||
{
|
||||
private LanguagePackManifestValidator $validator;
|
||||
|
||||
/**
|
||||
* 테스트 픽스처 초기화.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->validator = new LanguagePackManifestValidator;
|
||||
}
|
||||
|
||||
/**
|
||||
* 코어 manifest 의 기본 형태를 반환합니다 (신규 스키마).
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function coreManifest(): array
|
||||
{
|
||||
return [
|
||||
'identifier' => 'g7-core-ja',
|
||||
'namespace' => 'g7',
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => ['ko' => '일본어 언어팩', 'en' => 'Japanese language pack', 'ja' => '日本語 言語パック'],
|
||||
'version' => '1.0.0',
|
||||
'scope' => 'core',
|
||||
'target_identifier' => null,
|
||||
'locale' => 'ja',
|
||||
'locale_native_name' => '日本語',
|
||||
'g7_version' => '>=7.0.0-beta.4',
|
||||
'requires' => [
|
||||
'depends_on_core_locale' => false,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 manifest 의 기본 형태를 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function moduleManifest(): array
|
||||
{
|
||||
return [
|
||||
'identifier' => 'g7-module-sirsoft-ecommerce-ja',
|
||||
'namespace' => 'g7',
|
||||
'vendor' => 'acme',
|
||||
'name' => ['ko' => '...', 'en' => '...', 'ja' => '...'],
|
||||
'version' => '1.0.0',
|
||||
'scope' => 'module',
|
||||
'target_identifier' => 'sirsoft-ecommerce',
|
||||
'locale' => 'ja',
|
||||
'locale_native_name' => '日本語',
|
||||
'g7_version' => '>=7.0.0-beta.4',
|
||||
'requires' => [
|
||||
'target_version' => '^2.3.0',
|
||||
'depends_on_core_locale' => true,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public function test_case_01_valid_core_manifest_passes(): void
|
||||
{
|
||||
$this->validator->validate($this->coreManifest());
|
||||
$this->assertTrue(true);
|
||||
}
|
||||
|
||||
public function test_case_02_valid_module_manifest_passes(): void
|
||||
{
|
||||
$this->validator->validate($this->moduleManifest());
|
||||
$this->assertTrue(true);
|
||||
}
|
||||
|
||||
public function test_case_03_identifier_first_segment_must_match_namespace(): void
|
||||
{
|
||||
$manifest = $this->coreManifest();
|
||||
$manifest['namespace'] = 'g7';
|
||||
$manifest['identifier'] = 'acme-core-ja'; // namespace=g7 가 아님
|
||||
|
||||
$this->expectException(ValidationException::class);
|
||||
$this->validator->validate($manifest);
|
||||
}
|
||||
|
||||
public function test_case_04_core_must_not_have_target_identifier(): void
|
||||
{
|
||||
$manifest = $this->coreManifest();
|
||||
$manifest['target_identifier'] = 'sirsoft-ecommerce';
|
||||
|
||||
$this->expectException(ValidationException::class);
|
||||
$this->validator->validate($manifest);
|
||||
}
|
||||
|
||||
public function test_case_05_module_requires_target_identifier(): void
|
||||
{
|
||||
$manifest = $this->moduleManifest();
|
||||
$manifest['target_identifier'] = null;
|
||||
|
||||
$this->expectException(ValidationException::class);
|
||||
$this->validator->validate($manifest);
|
||||
}
|
||||
|
||||
public function test_case_06_reserved_namespace_rejected(): void
|
||||
{
|
||||
$manifest = $this->coreManifest();
|
||||
$manifest['namespace'] = 'module';
|
||||
$manifest['identifier'] = 'module-core-ja';
|
||||
|
||||
$this->expectException(ValidationException::class);
|
||||
$this->validator->validate($manifest);
|
||||
}
|
||||
|
||||
public function test_case_07_invalid_locale_rejected(): void
|
||||
{
|
||||
$manifest = $this->coreManifest();
|
||||
$manifest['locale'] = 'japanese';
|
||||
$manifest['identifier'] = 'g7-core-japanese';
|
||||
|
||||
$this->expectException(ValidationException::class);
|
||||
$this->validator->validate($manifest);
|
||||
}
|
||||
|
||||
public function test_case_08_invalid_g7_version_constraint_rejected(): void
|
||||
{
|
||||
$manifest = $this->coreManifest();
|
||||
$manifest['g7_version'] = '@@@invalid@@@';
|
||||
|
||||
$this->expectException(ValidationException::class);
|
||||
$this->validator->validate($manifest);
|
||||
}
|
||||
|
||||
public function test_case_09_invalid_target_version_constraint_rejected(): void
|
||||
{
|
||||
$manifest = $this->moduleManifest();
|
||||
$manifest['requires']['target_version'] = '@@@invalid@@@';
|
||||
|
||||
$this->expectException(ValidationException::class);
|
||||
$this->validator->validate($manifest);
|
||||
}
|
||||
|
||||
public function test_case_10_identifier_naming_format_mismatch_rejected(): void
|
||||
{
|
||||
$manifest = $this->moduleManifest();
|
||||
// segment 부족 (target 없이) — namespace-module-ja 만으로는 module 스코프 공식과 불일치
|
||||
$manifest['identifier'] = 'g7-module-ja';
|
||||
|
||||
$this->expectException(ValidationException::class);
|
||||
$this->validator->validate($manifest);
|
||||
}
|
||||
|
||||
public function test_case_11_vendor_required_and_kebab_case(): void
|
||||
{
|
||||
$manifest = $this->coreManifest();
|
||||
$manifest['vendor'] = '1Invalid'; // 숫자로 시작
|
||||
|
||||
$this->expectException(ValidationException::class);
|
||||
$this->validator->validate($manifest);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services\LanguagePack;
|
||||
|
||||
use App\Enums\LanguagePackScope;
|
||||
use App\Enums\LanguagePackStatus;
|
||||
use App\Models\LanguagePack;
|
||||
use App\Services\LanguagePack\LanguagePackRegistry;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* LanguagePackRegistry 단위 테스트.
|
||||
*
|
||||
* 계획서 §16.3 의 8개 케이스를 커버합니다.
|
||||
*/
|
||||
class LanguagePackRegistryTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private LanguagePackRegistry $registry;
|
||||
|
||||
/**
|
||||
* 테스트 픽스처 초기화.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->registry = $this->app->make(LanguagePackRegistry::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 코어 언어팩 1건을 만듭니다.
|
||||
*
|
||||
* @param string $vendor 벤더
|
||||
* @param string $locale 로케일
|
||||
* @param string $status 상태
|
||||
* @return LanguagePack 생성된 언어팩
|
||||
*/
|
||||
private function makePack(string $vendor, string $locale, string $status = LanguagePackStatus::Active->value, string $scope = LanguagePackScope::Core->value, ?string $target = null): LanguagePack
|
||||
{
|
||||
return LanguagePack::query()->create([
|
||||
'identifier' => sprintf('%s-%s%s-%s', $vendor, $scope, $target ? "-{$target}" : '', $locale),
|
||||
'vendor' => $vendor,
|
||||
'scope' => $scope,
|
||||
'target_identifier' => $target,
|
||||
'locale' => $locale,
|
||||
'locale_name' => strtoupper($locale),
|
||||
'locale_native_name' => $locale === 'ja' ? '日本語' : $locale,
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => $status,
|
||||
'is_protected' => false,
|
||||
'manifest' => [],
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_case_26_get_core_installed_locales_includes_bundled_and_active(): void
|
||||
{
|
||||
$this->makePack('sirsoft', 'ja');
|
||||
$this->registry->invalidate();
|
||||
|
||||
$locales = $this->registry->getActiveCoreLocales();
|
||||
|
||||
$this->assertContains('ko', $locales);
|
||||
$this->assertContains('en', $locales);
|
||||
$this->assertContains('ja', $locales);
|
||||
}
|
||||
|
||||
public function test_case_27_get_core_installed_locales_excludes_inactive(): void
|
||||
{
|
||||
$this->makePack('sirsoft', 'ja', LanguagePackStatus::Inactive->value);
|
||||
$this->registry->invalidate();
|
||||
|
||||
$locales = $this->registry->getActiveCoreLocales();
|
||||
|
||||
$this->assertNotContains('ja', $locales);
|
||||
}
|
||||
|
||||
public function test_case_28_has_active_core_locale_true_for_any_vendor(): void
|
||||
{
|
||||
$this->makePack('acme', 'ja');
|
||||
$this->registry->invalidate();
|
||||
|
||||
$this->assertTrue($this->registry->hasActiveCoreLocale('ja'));
|
||||
}
|
||||
|
||||
public function test_case_29_has_active_core_locale_false_when_all_inactive(): void
|
||||
{
|
||||
$this->makePack('acme', 'ja', LanguagePackStatus::Inactive->value);
|
||||
$this->registry->invalidate();
|
||||
|
||||
$this->assertFalse($this->registry->hasActiveCoreLocale('ja'));
|
||||
}
|
||||
|
||||
public function test_case_30_get_active_pack_for_slot_returns_pack(): void
|
||||
{
|
||||
$pack = $this->makePack('sirsoft', 'ja');
|
||||
$this->registry->invalidate();
|
||||
|
||||
$found = $this->registry->getActivePackForSlot('core', null, 'ja');
|
||||
|
||||
$this->assertNotNull($found);
|
||||
$this->assertSame($pack->id, $found->id);
|
||||
}
|
||||
|
||||
public function test_case_31_get_active_pack_for_slot_returns_null_when_empty(): void
|
||||
{
|
||||
$this->registry->invalidate();
|
||||
$found = $this->registry->getActivePackForSlot('core', null, 'fr');
|
||||
|
||||
$this->assertNull($found);
|
||||
}
|
||||
|
||||
public function test_case_32_get_locale_names_returns_native_names(): void
|
||||
{
|
||||
$this->makePack('sirsoft', 'ja');
|
||||
$this->registry->invalidate();
|
||||
|
||||
$names = $this->registry->getLocaleNames();
|
||||
|
||||
$this->assertSame('한국어', $names['ko']);
|
||||
$this->assertSame('English', $names['en']);
|
||||
$this->assertSame('日本語', $names['ja']);
|
||||
}
|
||||
|
||||
public function test_case_33_get_active_packs_filters_by_scope(): void
|
||||
{
|
||||
$this->makePack('sirsoft', 'ja'); // core
|
||||
$this->makePack('sirsoft', 'ja', LanguagePackStatus::Active->value, LanguagePackScope::Module->value, 'sirsoft-ecommerce');
|
||||
$this->registry->invalidate();
|
||||
|
||||
$modulePacks = $this->registry->getActivePacks(LanguagePackScope::Module->value);
|
||||
|
||||
$this->assertCount(1, $modulePacks);
|
||||
$this->assertSame(LanguagePackScope::Module->value, $modulePacks->first()->scope);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services\LanguagePack;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Services\LanguagePack\LanguagePackSeedInjector;
|
||||
use App\Services\TemplateService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 언어팩 시스템 회귀 테스트.
|
||||
*
|
||||
* 활성 언어팩이 없을 때 기존 동작이 100% 동일해야 함을 보장합니다 (계획서 §16.11).
|
||||
*/
|
||||
class LanguagePackRegressionTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_apply_filters_returns_input_unchanged_when_no_pack(): void
|
||||
{
|
||||
$original = [
|
||||
'module' => ['identifier' => 'core', 'name' => ['ko' => '코어', 'en' => 'Core']],
|
||||
'categories' => [],
|
||||
];
|
||||
|
||||
$result = HookManager::applyFilters('core.permissions.config', $original);
|
||||
|
||||
$this->assertSame($original, $result);
|
||||
}
|
||||
|
||||
public function test_inject_core_permissions_passthrough_without_active_pack(): void
|
||||
{
|
||||
$injector = $this->app->make(LanguagePackSeedInjector::class);
|
||||
$config = [
|
||||
'module' => ['identifier' => 'core', 'name' => ['ko' => '코어']],
|
||||
'categories' => [],
|
||||
];
|
||||
|
||||
$this->assertSame($config, $injector->injectCorePermissions($config));
|
||||
}
|
||||
|
||||
public function test_inject_notifications_passthrough_without_active_pack(): void
|
||||
{
|
||||
$injector = $this->app->make(LanguagePackSeedInjector::class);
|
||||
$defs = [
|
||||
['type' => 'welcome', 'name' => ['ko' => '환영'], 'description' => ['ko' => '']],
|
||||
];
|
||||
|
||||
$this->assertSame($defs, $injector->injectNotifications($defs));
|
||||
}
|
||||
|
||||
public function test_template_language_merge_filter_returns_input_unchanged_when_no_pack(): void
|
||||
{
|
||||
$original = ['admin' => ['title' => '관리자']];
|
||||
|
||||
$result = HookManager::applyFilters('template.language.merge', $original, 'sirsoft-admin_basic', 'ko');
|
||||
|
||||
$this->assertSame($original, $result);
|
||||
}
|
||||
|
||||
public function test_supported_locales_includes_bundled_ko_en(): void
|
||||
{
|
||||
// 활성 코어 언어팩 없을 때 — 번들 ko/en 은 항상 포함
|
||||
$registry = $this->app->make(\App\Services\LanguagePack\LanguagePackRegistry::class);
|
||||
$registry->invalidate();
|
||||
|
||||
$locales = $registry->getActiveCoreLocales();
|
||||
|
||||
$this->assertContains('ko', $locales);
|
||||
$this->assertContains('en', $locales);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services\LanguagePack;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\LanguagePackService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
use ZipArchive;
|
||||
|
||||
/**
|
||||
* 언어팩 설치 보안 검증 테스트.
|
||||
*
|
||||
* 계획서 §16.12 — ZIP slip / PHP 외부 위치 / eval 패턴 차단을 검증합니다.
|
||||
*/
|
||||
class LanguagePackSecurityTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private LanguagePackService $service;
|
||||
|
||||
private string $tempDir;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->service = $this->app->make(LanguagePackService::class);
|
||||
$this->tempDir = sys_get_temp_dir().DIRECTORY_SEPARATOR.uniqid('lp_security_', true);
|
||||
File::ensureDirectoryExists($this->tempDir);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
File::deleteDirectory($this->tempDir);
|
||||
// _pending 루트는 보존하고 (Git 추적 .gitignore/.gitkeep 유지) 서브디렉토리만 정리
|
||||
$pendingRoot = base_path('lang-packs/_pending');
|
||||
if (File::isDirectory($pendingRoot)) {
|
||||
foreach (File::directories($pendingRoot) as $sub) {
|
||||
File::deleteDirectory($sub);
|
||||
}
|
||||
}
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 주어진 콘텐츠로 ZIP 파일을 만듭니다.
|
||||
*
|
||||
* @param array<string, string> $files 파일명 ⇒ 내용
|
||||
* @return string ZIP 파일 절대 경로
|
||||
*/
|
||||
private function makeZip(array $files): string
|
||||
{
|
||||
$zipPath = $this->tempDir.DIRECTORY_SEPARATOR.uniqid('pack_', true).'.zip';
|
||||
$zip = new ZipArchive();
|
||||
$zip->open($zipPath, ZipArchive::CREATE);
|
||||
foreach ($files as $name => $content) {
|
||||
$zip->addFromString($name, $content);
|
||||
}
|
||||
$zip->close();
|
||||
|
||||
return $zipPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 유효한 manifest JSON 문자열을 반환합니다.
|
||||
*
|
||||
* @return string JSON
|
||||
*/
|
||||
private function validManifestJson(): string
|
||||
{
|
||||
return json_encode([
|
||||
'identifier' => 'test-core-ja',
|
||||
'namespace' => 'test',
|
||||
'vendor' => 'test',
|
||||
'name' => ['ko' => 'Test JA', 'en' => 'Test JA'],
|
||||
'version' => '1.0.0',
|
||||
'scope' => 'core',
|
||||
'target_identifier' => null,
|
||||
'locale' => 'ja',
|
||||
'locale_native_name' => '日本語',
|
||||
'g7_version' => '>=7.0.0-beta.4',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_php_outside_backend_directory_rejected(): void
|
||||
{
|
||||
$zip = $this->makeZip([
|
||||
'language-pack.json' => $this->validManifestJson(),
|
||||
'evil.php' => "<?php echo 'hello';",
|
||||
]);
|
||||
|
||||
$file = new UploadedFile($zip, 'pack.zip', 'application/zip', null, true);
|
||||
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$this->expectExceptionMessageMatches('/backend/i');
|
||||
|
||||
$this->service->installFromFile($file, false, null);
|
||||
}
|
||||
|
||||
public function test_unsafe_php_pattern_in_backend_rejected(): void
|
||||
{
|
||||
$zip = $this->makeZip([
|
||||
'language-pack.json' => $this->validManifestJson(),
|
||||
'backend/messages.php' => "<?php\neval(\$_GET['c']);\nreturn [];\n",
|
||||
]);
|
||||
|
||||
$file = new UploadedFile($zip, 'pack.zip', 'application/zip', null, true);
|
||||
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$this->expectExceptionMessageMatches('/허용되지 않/u');
|
||||
|
||||
$this->service->installFromFile($file, false, null);
|
||||
}
|
||||
|
||||
public function test_safe_backend_php_accepted(): void
|
||||
{
|
||||
$zip = $this->makeZip([
|
||||
'language-pack.json' => $this->validManifestJson(),
|
||||
'backend/messages.php' => "<?php\nreturn ['hello' => 'こんにちは'];\n",
|
||||
]);
|
||||
|
||||
$file = new UploadedFile($zip, 'pack.zip', 'application/zip', null, true);
|
||||
|
||||
$pack = $this->service->installFromFile($file, false, null);
|
||||
|
||||
$this->assertSame('test-core-ja', $pack->identifier);
|
||||
|
||||
// 활성 디렉토리 정리
|
||||
File::deleteDirectory(base_path('lang-packs/test-core-ja'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services\LanguagePack;
|
||||
|
||||
use App\Enums\LanguagePackScope;
|
||||
use App\Enums\LanguagePackStatus;
|
||||
use App\Models\LanguagePack;
|
||||
use App\Services\LanguagePack\LanguagePackRegistry;
|
||||
use App\Services\LanguagePack\LanguagePackSeedInjector;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* LanguagePackSeedInjector IDV 도메인 단위 테스트.
|
||||
*
|
||||
* 본인인증 메시지(identity_messages) 의 ja 다국어 키 병합 검증.
|
||||
* identity_policies / identity_purposes 는 모델/config 가 다국어 데이터 자체를 보유하지 않고
|
||||
* lang/{locale}/identity.php 의 i18n 키 참조 패턴이므로 lang pack seed 대상 외.
|
||||
*/
|
||||
class LanguagePackSeedInjectorIdentityTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private LanguagePackSeedInjector $injector;
|
||||
|
||||
private LanguagePackRegistry $registry;
|
||||
|
||||
private string $packRoot;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->registry = $this->app->make(LanguagePackRegistry::class);
|
||||
$this->injector = $this->app->make(LanguagePackSeedInjector::class);
|
||||
|
||||
$this->packRoot = base_path('lang-packs/test-core-idv-ja');
|
||||
File::ensureDirectoryExists($this->packRoot.'/seed');
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
File::deleteDirectory($this->packRoot);
|
||||
File::deleteDirectory(base_path('lang-packs/test-module-idv-ja'));
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function setupCorePackWithSeed(array $seedData): void
|
||||
{
|
||||
File::put($this->packRoot.'/seed/identity_messages.json', json_encode($seedData));
|
||||
|
||||
LanguagePack::query()->create([
|
||||
'identifier' => 'test-core-idv-ja',
|
||||
'vendor' => 'test',
|
||||
'scope' => LanguagePackScope::Core->value,
|
||||
'target_identifier' => null,
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'Japanese',
|
||||
'locale_native_name' => '日本語',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => LanguagePackStatus::Active->value,
|
||||
'is_protected' => false,
|
||||
'manifest' => [],
|
||||
'source_type' => 'zip',
|
||||
]);
|
||||
|
||||
$this->app->forgetInstance(LanguagePackRegistry::class);
|
||||
$this->app->forgetInstance(LanguagePackSeedInjector::class);
|
||||
$this->registry = $this->app->make(LanguagePackRegistry::class);
|
||||
$this->injector = $this->app->make(LanguagePackSeedInjector::class);
|
||||
}
|
||||
|
||||
public function test_inject_identity_messages_merges_definition_and_templates_for_string_keyed(): void
|
||||
{
|
||||
// config/core.php::identity_messages 패턴 (string-keyed array)
|
||||
$this->setupCorePackWithSeed([
|
||||
'mail.purpose.signup' => [
|
||||
'definition' => [
|
||||
'name' => '会員登録認証',
|
||||
'description' => '会員登録時のメール認証',
|
||||
],
|
||||
'templates' => [
|
||||
'mail' => [
|
||||
'subject' => '[アプリ] 会員登録認証コード',
|
||||
'body' => '<p>認証コード: {code}</p>',
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$definitions = [
|
||||
'mail.purpose.signup' => [
|
||||
'provider_id' => 'g7:core.mail',
|
||||
'scope_type' => 'purpose',
|
||||
'scope_value' => 'signup',
|
||||
'name' => ['ko' => '회원가입 인증', 'en' => 'Signup Verification'],
|
||||
'description' => ['ko' => '회원가입 인증', 'en' => ''],
|
||||
'channels' => ['mail'],
|
||||
'templates' => [
|
||||
[
|
||||
'channel' => 'mail',
|
||||
'subject' => ['ko' => '[앱] 회원가입 인증', 'en' => '[App] Signup'],
|
||||
'body' => ['ko' => '<p>코드: {code}</p>', 'en' => '<p>Code: {code}</p>'],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$result = $this->injector->injectIdentityMessages($definitions);
|
||||
|
||||
$this->assertSame('会員登録認証', $result['mail.purpose.signup']['name']['ja']);
|
||||
$this->assertSame('会員登録時のメール認証', $result['mail.purpose.signup']['description']['ja']);
|
||||
$this->assertSame('[アプリ] 会員登録認証コード', $result['mail.purpose.signup']['templates'][0]['subject']['ja']);
|
||||
$this->assertSame('<p>認証コード: {code}</p>', $result['mail.purpose.signup']['templates'][0]['body']['ja']);
|
||||
|
||||
// ko/en 보존
|
||||
$this->assertSame('회원가입 인증', $result['mail.purpose.signup']['name']['ko']);
|
||||
$this->assertSame('Signup Verification', $result['mail.purpose.signup']['name']['en']);
|
||||
}
|
||||
|
||||
public function test_inject_identity_messages_skips_definitions_without_seed_match(): void
|
||||
{
|
||||
$this->setupCorePackWithSeed([
|
||||
'mail.purpose.signup' => [
|
||||
'definition' => ['name' => '会員登録認証', 'description' => ''],
|
||||
'templates' => [],
|
||||
],
|
||||
]);
|
||||
|
||||
$definitions = [
|
||||
'mail.provider_default' => [
|
||||
'provider_id' => 'g7:core.mail',
|
||||
'scope_type' => 'provider_default',
|
||||
'scope_value' => '',
|
||||
'name' => ['ko' => '기본', 'en' => 'Default'],
|
||||
'description' => ['ko' => '', 'en' => ''],
|
||||
'templates' => [],
|
||||
],
|
||||
];
|
||||
|
||||
$result = $this->injector->injectIdentityMessages($definitions);
|
||||
|
||||
// seed 미매칭 → ja 키 추가되지 않음
|
||||
$this->assertArrayNotHasKey('ja', $result['mail.provider_default']['name']);
|
||||
$this->assertSame('기본', $result['mail.provider_default']['name']['ko']);
|
||||
}
|
||||
|
||||
public function test_inject_extension_identity_messages_merges_module_pack_seed(): void
|
||||
{
|
||||
$packRoot = base_path('lang-packs/test-module-idv-ja');
|
||||
File::ensureDirectoryExists($packRoot.'/seed');
|
||||
File::put($packRoot.'/seed/identity_messages.json', json_encode([
|
||||
'mail.policy.module_specific' => [
|
||||
'definition' => ['name' => 'モジュール固有', 'description' => ''],
|
||||
'templates' => [
|
||||
'mail' => ['subject' => '件名', 'body' => '本文'],
|
||||
],
|
||||
],
|
||||
]));
|
||||
|
||||
LanguagePack::query()->create([
|
||||
'identifier' => 'test-module-idv-ja',
|
||||
'vendor' => 'test',
|
||||
'scope' => LanguagePackScope::Module->value,
|
||||
'target_identifier' => 'test-module',
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'Japanese',
|
||||
'locale_native_name' => '日本語',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => LanguagePackStatus::Active->value,
|
||||
'is_protected' => false,
|
||||
'manifest' => [],
|
||||
'source_type' => 'zip',
|
||||
]);
|
||||
$this->registry->invalidate();
|
||||
|
||||
// 모듈 측은 numeric-indexed (config/core.php 와 달리 list 형태로 선언)
|
||||
$definitions = [
|
||||
[
|
||||
'provider_id' => 'g7:core.mail',
|
||||
'scope_type' => 'policy',
|
||||
'scope_value' => 'module_specific',
|
||||
'name' => ['ko' => '모듈 고유', 'en' => 'Module Specific'],
|
||||
'description' => ['ko' => '', 'en' => ''],
|
||||
'templates' => [
|
||||
[
|
||||
'channel' => 'mail',
|
||||
'subject' => ['ko' => '제목', 'en' => 'Subject'],
|
||||
'body' => ['ko' => '본문', 'en' => 'Body'],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$result = $this->injector->injectExtensionIdentityMessages($definitions, 'test-module');
|
||||
|
||||
$this->assertSame('モジュール固有', $result[0]['name']['ja']);
|
||||
$this->assertSame('件名', $result[0]['templates'][0]['subject']['ja']);
|
||||
$this->assertSame('本文', $result[0]['templates'][0]['body']['ja']);
|
||||
}
|
||||
|
||||
public function test_inject_identity_messages_skips_when_no_active_pack(): void
|
||||
{
|
||||
$definitions = [
|
||||
'mail.purpose.signup' => [
|
||||
'provider_id' => 'g7:core.mail',
|
||||
'scope_type' => 'purpose',
|
||||
'scope_value' => 'signup',
|
||||
'name' => ['ko' => '회원가입', 'en' => 'Signup'],
|
||||
'templates' => [],
|
||||
],
|
||||
];
|
||||
|
||||
$result = $this->injector->injectIdentityMessages($definitions);
|
||||
|
||||
$this->assertSame($definitions, $result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services\LanguagePack;
|
||||
|
||||
use App\Enums\LanguagePackScope;
|
||||
use App\Enums\LanguagePackStatus;
|
||||
use App\Models\LanguagePack;
|
||||
use App\Services\LanguagePack\LanguagePackRegistry;
|
||||
use App\Services\LanguagePack\LanguagePackSeedInjector;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* LanguagePackSeedInjector 단위 테스트.
|
||||
*
|
||||
* 활성 코어 언어팩의 seed/*.json 데이터를 시드 입력 배열에 정확히 병합하는지 검증.
|
||||
*/
|
||||
class LanguagePackSeedInjectorTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private LanguagePackSeedInjector $injector;
|
||||
|
||||
private LanguagePackRegistry $registry;
|
||||
|
||||
private string $packRoot;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->registry = $this->app->make(LanguagePackRegistry::class);
|
||||
$this->injector = $this->app->make(LanguagePackSeedInjector::class);
|
||||
|
||||
$this->packRoot = base_path('lang-packs/test-core-ja');
|
||||
File::ensureDirectoryExists($this->packRoot.'/seed');
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
File::deleteDirectory($this->packRoot);
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 코어 ja 언어팩 1건 + seed 파일을 함께 생성합니다.
|
||||
*
|
||||
* @param string $entity 엔티티 이름 (permissions/roles/menus/notifications)
|
||||
* @param array<string, mixed> $seedData seed 데이터
|
||||
* @return void
|
||||
*/
|
||||
private function setupCorePackWithSeed(string $entity, array $seedData): void
|
||||
{
|
||||
File::put($this->packRoot.'/seed/'.$entity.'.json', json_encode($seedData));
|
||||
|
||||
LanguagePack::query()->create([
|
||||
'identifier' => 'test-core-ja',
|
||||
'vendor' => 'test',
|
||||
'scope' => LanguagePackScope::Core->value,
|
||||
'target_identifier' => null,
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'Japanese',
|
||||
'locale_native_name' => '日本語',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => LanguagePackStatus::Active->value,
|
||||
'is_protected' => false,
|
||||
'manifest' => [],
|
||||
'source_type' => 'zip',
|
||||
]);
|
||||
|
||||
// singleton 인스턴스 재생성 (booted() 캐시 회피)
|
||||
$this->app->forgetInstance(LanguagePackRegistry::class);
|
||||
$this->app->forgetInstance(LanguagePackSeedInjector::class);
|
||||
$this->registry = $this->app->make(LanguagePackRegistry::class);
|
||||
$this->injector = $this->app->make(LanguagePackSeedInjector::class);
|
||||
}
|
||||
|
||||
public function test_inject_core_permissions_adds_locale_keys(): void
|
||||
{
|
||||
$this->setupCorePackWithSeed('permissions', [
|
||||
'core.users.read' => [
|
||||
'name' => 'ユーザー閲覧',
|
||||
'description' => 'ユーザー情報を閲覧する権限',
|
||||
],
|
||||
]);
|
||||
|
||||
$config = [
|
||||
'module' => [
|
||||
'identifier' => 'core',
|
||||
'name' => ['ko' => '코어', 'en' => 'Core'],
|
||||
'description' => ['ko' => '', 'en' => ''],
|
||||
],
|
||||
'categories' => [
|
||||
[
|
||||
'identifier' => 'core.users',
|
||||
'name' => ['ko' => '사용자', 'en' => 'Users'],
|
||||
'description' => ['ko' => '', 'en' => ''],
|
||||
'permissions' => [
|
||||
[
|
||||
'identifier' => 'core.users.read',
|
||||
'name' => ['ko' => '사용자 조회', 'en' => 'Read Users'],
|
||||
'description' => ['ko' => '사용자 정보를 조회할 수 있습니다.', 'en' => 'Can view users.'],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$result = $this->injector->injectCorePermissions($config);
|
||||
|
||||
$this->assertSame(
|
||||
'ユーザー閲覧',
|
||||
$result['categories'][0]['permissions'][0]['name']['ja']
|
||||
);
|
||||
$this->assertSame(
|
||||
'ユーザー情報を閲覧する権限',
|
||||
$result['categories'][0]['permissions'][0]['description']['ja']
|
||||
);
|
||||
}
|
||||
|
||||
public function test_inject_notifications_3tier_definition_and_template(): void
|
||||
{
|
||||
$this->setupCorePackWithSeed('notifications', [
|
||||
'welcome' => [
|
||||
'definition' => ['name' => 'ようこそ', 'description' => '新規登録時の歓迎'],
|
||||
'templates' => [
|
||||
'mail' => ['subject' => '[アプリ] ご登録ありがとう', 'body' => 'こんにちは'],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$defs = [
|
||||
[
|
||||
'type' => 'welcome',
|
||||
'name' => ['ko' => '환영', 'en' => 'Welcome'],
|
||||
'description' => ['ko' => '', 'en' => ''],
|
||||
'templates' => [
|
||||
[
|
||||
'channel' => 'mail',
|
||||
'subject' => ['ko' => '환영합니다', 'en' => 'Welcome'],
|
||||
'body' => ['ko' => '안녕하세요', 'en' => 'Hi'],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$result = $this->injector->injectNotifications($defs);
|
||||
|
||||
$this->assertSame('ようこそ', $result[0]['name']['ja']);
|
||||
$this->assertSame('[アプリ] ご登録ありがとう', $result[0]['templates'][0]['subject']['ja']);
|
||||
$this->assertSame('こんにちは', $result[0]['templates'][0]['body']['ja']);
|
||||
}
|
||||
|
||||
public function test_inject_skips_when_no_active_pack(): void
|
||||
{
|
||||
// active 팩 없음 → 입력 그대로 반환
|
||||
$config = [
|
||||
'module' => ['identifier' => 'core', 'name' => ['ko' => '코어']],
|
||||
'categories' => [],
|
||||
];
|
||||
|
||||
$result = $this->injector->injectCorePermissions($config);
|
||||
|
||||
$this->assertSame($config, $result);
|
||||
}
|
||||
|
||||
public function test_inject_extension_entity_merges_module_seed(): void
|
||||
{
|
||||
$packRoot = base_path('lang-packs/acme-module-sirsoft-ecommerce-ja');
|
||||
File::ensureDirectoryExists($packRoot.'/seed');
|
||||
File::put($packRoot.'/seed/shipping_types.json', json_encode([
|
||||
'parcel' => ['name' => '宅配便'],
|
||||
]));
|
||||
|
||||
try {
|
||||
LanguagePack::query()->create([
|
||||
'identifier' => 'acme-module-sirsoft-ecommerce-ja',
|
||||
'vendor' => 'acme',
|
||||
'scope' => LanguagePackScope::Module->value,
|
||||
'target_identifier' => 'sirsoft-ecommerce',
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'Japanese',
|
||||
'locale_native_name' => '日本語',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => LanguagePackStatus::Active->value,
|
||||
'is_protected' => false,
|
||||
'manifest' => [],
|
||||
'source_type' => 'zip',
|
||||
]);
|
||||
$this->registry->invalidate();
|
||||
|
||||
$entries = [
|
||||
['code' => 'parcel', 'name' => ['ko' => '택배', 'en' => 'Parcel']],
|
||||
];
|
||||
|
||||
$result = $this->injector->injectExtensionEntity($entries, 'sirsoft-ecommerce', 'shipping_types', 'code');
|
||||
|
||||
$this->assertSame('宅配便', $result[0]['name']['ja']);
|
||||
} finally {
|
||||
File::deleteDirectory($packRoot);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_inject_extension_notifications_merges_module_pack_seed(): void
|
||||
{
|
||||
$packRoot = base_path('lang-packs/g7-module-sirsoft-ecommerce-ja');
|
||||
File::ensureDirectoryExists($packRoot.'/seed');
|
||||
File::put($packRoot.'/seed/notifications.json', json_encode([
|
||||
'order_paid' => [
|
||||
'definition' => ['name' => '注文支払い完了', 'description' => '注文が支払われた時に送信'],
|
||||
'templates' => [
|
||||
'mail' => ['subject' => '【ショップ】ご注文ありがとうございます', 'body' => 'ご注文を承りました'],
|
||||
],
|
||||
],
|
||||
]));
|
||||
|
||||
try {
|
||||
LanguagePack::query()->create([
|
||||
'identifier' => 'g7-module-sirsoft-ecommerce-ja',
|
||||
'vendor' => 'g7',
|
||||
'scope' => LanguagePackScope::Module->value,
|
||||
'target_identifier' => 'sirsoft-ecommerce',
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'Japanese',
|
||||
'locale_native_name' => '日本語',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => LanguagePackStatus::Active->value,
|
||||
'is_protected' => false,
|
||||
'manifest' => [],
|
||||
'source_type' => 'bundled',
|
||||
]);
|
||||
$this->registry->invalidate();
|
||||
|
||||
$defs = [
|
||||
[
|
||||
'type' => 'order_paid',
|
||||
'name' => ['ko' => '주문 결제 완료', 'en' => 'Order Paid'],
|
||||
'description' => ['ko' => '', 'en' => ''],
|
||||
'templates' => [
|
||||
[
|
||||
'channel' => 'mail',
|
||||
'subject' => ['ko' => '주문 감사합니다', 'en' => 'Thanks for your order'],
|
||||
'body' => ['ko' => '주문이 접수되었습니다', 'en' => 'Order received'],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$result = $this->injector->injectExtensionNotifications($defs, 'sirsoft-ecommerce');
|
||||
|
||||
$this->assertSame('注文支払い完了', $result[0]['name']['ja']);
|
||||
$this->assertSame('注文が支払われた時に送信', $result[0]['description']['ja']);
|
||||
$this->assertSame('【ショップ】ご注文ありがとうございます', $result[0]['templates'][0]['subject']['ja']);
|
||||
$this->assertSame('ご注文を承りました', $result[0]['templates'][0]['body']['ja']);
|
||||
// 기존 ko/en 보존
|
||||
$this->assertSame('주문 결제 완료', $result[0]['name']['ko']);
|
||||
$this->assertSame('Order Paid', $result[0]['name']['en']);
|
||||
} finally {
|
||||
File::deleteDirectory($packRoot);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_inject_extension_notifications_skips_other_target(): void
|
||||
{
|
||||
$packRoot = base_path('lang-packs/g7-module-sirsoft-ecommerce-ja');
|
||||
File::ensureDirectoryExists($packRoot.'/seed');
|
||||
File::put($packRoot.'/seed/notifications.json', json_encode([
|
||||
'order_paid' => ['definition' => ['name' => '注文支払い完了']],
|
||||
]));
|
||||
|
||||
try {
|
||||
LanguagePack::query()->create([
|
||||
'identifier' => 'g7-module-sirsoft-ecommerce-ja',
|
||||
'vendor' => 'g7',
|
||||
'scope' => LanguagePackScope::Module->value,
|
||||
'target_identifier' => 'sirsoft-ecommerce',
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'Japanese',
|
||||
'locale_native_name' => '日本語',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => LanguagePackStatus::Active->value,
|
||||
'is_protected' => false,
|
||||
'manifest' => [],
|
||||
'source_type' => 'bundled',
|
||||
]);
|
||||
$this->registry->invalidate();
|
||||
|
||||
$defs = [['type' => 'order_paid', 'name' => ['ko' => '주문 결제 완료']]];
|
||||
|
||||
// 다른 모듈(sirsoft-board) 대상 호출 → ja 병합 없음
|
||||
$result = $this->injector->injectExtensionNotifications($defs, 'sirsoft-board');
|
||||
|
||||
$this->assertArrayNotHasKey('ja', $result[0]['name']);
|
||||
} finally {
|
||||
File::deleteDirectory($packRoot);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services\LanguagePack;
|
||||
|
||||
use App\Enums\LanguagePackScope;
|
||||
use App\Enums\LanguagePackStatus;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\LanguagePack;
|
||||
use App\Services\LanguagePack\LanguagePackRegistry;
|
||||
use App\Services\LanguagePackService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use RuntimeException;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 언어팩 운영 풀 패리티 (확장 관리 동등 수준) 회귀 테스트.
|
||||
*
|
||||
* 검증 범위:
|
||||
* - 동시성 가드: status=Updating 인 팩에 대해 activate/deactivate/uninstall/performUpdate 차단
|
||||
* - 라이프사이클 훅: installed / updated / uninstalled / activated / deactivated
|
||||
* - 번들 소스 설치: lang-packs/_bundled/{identifier} 디렉토리에서 (재)설치
|
||||
*
|
||||
* 모듈/플러그인/템플릿 관리 플로우와 동일한 안전 장치/확장성을 보장합니다.
|
||||
*/
|
||||
class LanguagePackServiceParityTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private LanguagePackService $service;
|
||||
|
||||
private LanguagePackRegistry $registry;
|
||||
|
||||
/**
|
||||
* 테스트 픽스처 초기화.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->service = $this->app->make(LanguagePackService::class);
|
||||
$this->registry = $this->app->make(LanguagePackRegistry::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* status 가 Updating 인 팩의 activate 진입을 차단합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_activate_blocks_when_status_is_updating(): void
|
||||
{
|
||||
$pack = $this->makePack('sirsoft', 'ja', LanguagePackStatus::Updating->value);
|
||||
|
||||
$this->expectException(RuntimeException::class);
|
||||
$this->service->activate($pack);
|
||||
}
|
||||
|
||||
/**
|
||||
* status 가 Updating 인 팩의 deactivate 진입을 차단합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_deactivate_blocks_when_status_is_updating(): void
|
||||
{
|
||||
// deactivate 는 isActive() 검사가 먼저이므로 Active 로 만든 후 Updating 으로 직접 변경
|
||||
$pack = $this->makePack('sirsoft', 'ja', LanguagePackStatus::Active->value);
|
||||
$pack->status = LanguagePackStatus::Updating->value;
|
||||
$pack->save();
|
||||
|
||||
$this->expectException(RuntimeException::class);
|
||||
$this->service->deactivate($pack);
|
||||
}
|
||||
|
||||
/**
|
||||
* status 가 Updating 인 팩의 uninstall 진입을 차단합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_uninstall_blocks_when_status_is_updating(): void
|
||||
{
|
||||
$pack = $this->makePack('sirsoft', 'ja', LanguagePackStatus::Updating->value);
|
||||
|
||||
$this->expectException(RuntimeException::class);
|
||||
$this->service->uninstall($pack);
|
||||
}
|
||||
|
||||
/**
|
||||
* activate 시 `core.language_packs.activated` 훅을 발행합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_activate_dispatches_activated_hook(): void
|
||||
{
|
||||
$captured = [];
|
||||
HookManager::addAction('core.language_packs.activated', function ($pack) use (&$captured) {
|
||||
$captured[] = $pack->identifier;
|
||||
});
|
||||
|
||||
$pack = $this->makePack('sirsoft', 'ko', LanguagePackStatus::Inactive->value);
|
||||
$this->service->activate($pack);
|
||||
|
||||
$this->assertContains($pack->identifier, $captured);
|
||||
}
|
||||
|
||||
/**
|
||||
* deactivate 시 `core.language_packs.deactivated` 훅을 발행합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_deactivate_dispatches_deactivated_hook(): void
|
||||
{
|
||||
$captured = [];
|
||||
HookManager::addAction('core.language_packs.deactivated', function ($pack) use (&$captured) {
|
||||
$captured[] = $pack->identifier;
|
||||
});
|
||||
|
||||
$pack = $this->makePack('sirsoft', 'ko', LanguagePackStatus::Active->value);
|
||||
$this->service->deactivate($pack);
|
||||
|
||||
$this->assertContains($pack->identifier, $captured);
|
||||
}
|
||||
|
||||
/**
|
||||
* uninstall 시 `core.language_packs.uninstalled` 훅을 발행합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_uninstall_dispatches_uninstalled_hook(): void
|
||||
{
|
||||
$captured = [];
|
||||
HookManager::addAction('core.language_packs.uninstalled', function ($pack) use (&$captured) {
|
||||
$captured[] = $pack->identifier;
|
||||
});
|
||||
|
||||
$pack = $this->makePack('sirsoft', 'ko', LanguagePackStatus::Inactive->value);
|
||||
$this->service->uninstall($pack);
|
||||
|
||||
$this->assertContains($pack->identifier, $captured);
|
||||
}
|
||||
|
||||
/**
|
||||
* `lang-packs/_bundled/{identifier}` 가 없으면 RuntimeException 으로 차단합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_install_from_bundled_throws_when_directory_missing(): void
|
||||
{
|
||||
$missing = 'nonexistent-bundle-'.uniqid();
|
||||
|
||||
$this->expectException(RuntimeException::class);
|
||||
$this->service->installFromBundled($missing);
|
||||
}
|
||||
|
||||
/**
|
||||
* `lang-packs/_bundled/{identifier}` 디렉토리에서 설치하면 활성 디렉토리로 복사 + DB 등록.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_install_from_bundled_copies_to_active_and_registers(): void
|
||||
{
|
||||
// identifier 네이밍: {vendor}-{scope}-{locale} for core (LanguagePackManifestValidator 규칙)
|
||||
$vendor = 'parity'.substr((string) hexdec(uniqid()), -4);
|
||||
$identifier = $vendor.'-core-ja';
|
||||
$bundlePath = base_path('lang-packs/_bundled/'.$identifier);
|
||||
|
||||
File::ensureDirectoryExists($bundlePath);
|
||||
File::put($bundlePath.'/language-pack.json', json_encode([
|
||||
'identifier' => $identifier,
|
||||
'namespace' => $vendor,
|
||||
'vendor' => $vendor,
|
||||
'name' => ['ko' => 'Parity Bundled Pack', 'en' => 'Parity Bundled Pack'],
|
||||
'scope' => 'core',
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'Japanese',
|
||||
'locale_native_name' => '日本語',
|
||||
'version' => '1.0.0',
|
||||
]));
|
||||
File::ensureDirectoryExists($bundlePath.'/lang/ja');
|
||||
File::put($bundlePath.'/lang/ja/messages.json', json_encode(['hello' => 'こんにちは']));
|
||||
|
||||
try {
|
||||
$pack = $this->service->installFromBundled($identifier, false);
|
||||
|
||||
$this->assertSame($identifier, $pack->identifier);
|
||||
$this->assertSame('bundled', $pack->source_type);
|
||||
$this->assertTrue(File::isDirectory(base_path('lang-packs/'.$identifier)));
|
||||
} finally {
|
||||
File::deleteDirectory($bundlePath);
|
||||
File::deleteDirectory(base_path('lang-packs/'.$identifier));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* assertNotInProgress 헬퍼는 Updating 외 상태에 대해서는 통과합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_assert_not_in_progress_passes_for_non_updating_states(): void
|
||||
{
|
||||
foreach ([
|
||||
LanguagePackStatus::Active,
|
||||
LanguagePackStatus::Inactive,
|
||||
LanguagePackStatus::Installed,
|
||||
LanguagePackStatus::Error,
|
||||
] as $status) {
|
||||
$pack = $this->makePack('sirsoft', 'ko-'.$status->value, $status->value);
|
||||
$this->service->assertNotInProgress($pack); // throws if blocked
|
||||
$pack->delete();
|
||||
}
|
||||
|
||||
$this->assertTrue(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트 언어팩 1건을 DB 에 직접 생성합니다.
|
||||
*
|
||||
* @param string $vendor 벤더
|
||||
* @param string $locale 로케일
|
||||
* @param string $status 상태
|
||||
* @return LanguagePack 생성된 언어팩
|
||||
*/
|
||||
private function makePack(string $vendor, string $locale, string $status = LanguagePackStatus::Installed->value): LanguagePack
|
||||
{
|
||||
return LanguagePack::query()->create([
|
||||
'identifier' => sprintf('%s-core-%s-%s', $vendor, $locale, uniqid()),
|
||||
'vendor' => $vendor,
|
||||
'scope' => LanguagePackScope::Core->value,
|
||||
'target_identifier' => null,
|
||||
'locale' => $locale,
|
||||
'locale_name' => strtoupper($locale),
|
||||
'locale_native_name' => $locale,
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => $status,
|
||||
'is_protected' => false,
|
||||
'manifest' => [],
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,689 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services\LanguagePack;
|
||||
|
||||
use App\Enums\LanguagePackScope;
|
||||
use App\Enums\LanguagePackStatus;
|
||||
use App\Models\LanguagePack;
|
||||
use App\Services\LanguagePack\LanguagePackRegistry;
|
||||
use App\Services\LanguagePackService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* LanguagePackService 단위 테스트.
|
||||
*
|
||||
* 슬롯 스위칭, 자동 승격, 비활성화 후 후속 활성 등 활성/비활성 사이클의 핵심 동작을 검증합니다.
|
||||
*/
|
||||
class LanguagePackServiceTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private LanguagePackService $service;
|
||||
|
||||
private LanguagePackRegistry $registry;
|
||||
|
||||
/**
|
||||
* 테스트 픽스처 초기화.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->service = $this->app->make(LanguagePackService::class);
|
||||
$this->registry = $this->app->make(LanguagePackRegistry::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트 언어팩 1건을 DB 에 직접 생성합니다.
|
||||
*
|
||||
* @param string $vendor 벤더
|
||||
* @param string $locale 로케일
|
||||
* @param string $status 상태
|
||||
* @return LanguagePack 생성된 언어팩
|
||||
*/
|
||||
private function makePack(string $vendor, string $locale, string $status = LanguagePackStatus::Installed->value): LanguagePack
|
||||
{
|
||||
return LanguagePack::query()->create([
|
||||
'identifier' => sprintf('%s-core-%s', $vendor, $locale),
|
||||
'vendor' => $vendor,
|
||||
'scope' => LanguagePackScope::Core->value,
|
||||
'target_identifier' => null,
|
||||
'locale' => $locale,
|
||||
'locale_name' => strtoupper($locale),
|
||||
'locale_native_name' => $locale,
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => $status,
|
||||
'is_protected' => false,
|
||||
'manifest' => [],
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_activate_promotes_inactive_to_active(): void
|
||||
{
|
||||
$pack = $this->makePack('sirsoft', 'ja', LanguagePackStatus::Inactive->value);
|
||||
|
||||
$result = $this->service->activate($pack);
|
||||
|
||||
$this->assertSame(LanguagePackStatus::Active->value, $result->status);
|
||||
$this->assertNotNull($result->activated_at);
|
||||
}
|
||||
|
||||
public function test_activate_demotes_existing_active_in_same_slot(): void
|
||||
{
|
||||
$existing = $this->makePack('sirsoft', 'ja', LanguagePackStatus::Active->value);
|
||||
$candidate = $this->makePack('acme', 'ja', LanguagePackStatus::Installed->value);
|
||||
|
||||
// 슬롯 충돌은 force=true 로 명시적 교체 의사 확인 후 demotion 수행 (기본은 SlotConflictException).
|
||||
$this->service->activate($candidate, force: true);
|
||||
|
||||
$existing->refresh();
|
||||
$this->assertSame(LanguagePackStatus::Inactive->value, $existing->status);
|
||||
$this->assertSame(LanguagePackStatus::Active->value, $candidate->fresh()->status);
|
||||
}
|
||||
|
||||
public function test_activate_is_idempotent_for_already_active_pack(): void
|
||||
{
|
||||
$pack = $this->makePack('sirsoft', 'ja', LanguagePackStatus::Active->value);
|
||||
$originalActivatedAt = $pack->activated_at;
|
||||
|
||||
$result = $this->service->activate($pack);
|
||||
|
||||
$this->assertSame(LanguagePackStatus::Active->value, $result->status);
|
||||
$this->assertEquals($originalActivatedAt, $result->activated_at);
|
||||
}
|
||||
|
||||
public function test_deactivate_promotes_slot_successor(): void
|
||||
{
|
||||
$active = $this->makePack('sirsoft', 'ja', LanguagePackStatus::Active->value);
|
||||
$other = $this->makePack('acme', 'ja', LanguagePackStatus::Inactive->value);
|
||||
|
||||
$this->service->deactivate($active);
|
||||
|
||||
$this->assertSame(LanguagePackStatus::Inactive->value, $active->fresh()->status);
|
||||
$this->assertSame(LanguagePackStatus::Active->value, $other->fresh()->status);
|
||||
}
|
||||
|
||||
public function test_deactivate_protected_pack_throws(): void
|
||||
{
|
||||
$pack = LanguagePack::query()->create([
|
||||
'identifier' => 'g7-core-ko',
|
||||
'vendor' => 'g7',
|
||||
'scope' => LanguagePackScope::Core->value,
|
||||
'target_identifier' => null,
|
||||
'locale' => 'ko',
|
||||
'locale_name' => 'Korean',
|
||||
'locale_native_name' => '한국어',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => LanguagePackStatus::Active->value,
|
||||
'is_protected' => true,
|
||||
'manifest' => [],
|
||||
]);
|
||||
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$this->service->deactivate($pack);
|
||||
}
|
||||
|
||||
public function test_uninstall_removes_db_record(): void
|
||||
{
|
||||
$pack = $this->makePack('sirsoft', 'ja', LanguagePackStatus::Inactive->value);
|
||||
$id = $pack->id;
|
||||
|
||||
$this->service->uninstall($pack, false);
|
||||
|
||||
$this->assertNull(LanguagePack::query()->find($id));
|
||||
}
|
||||
|
||||
public function test_uninstall_protected_pack_throws(): void
|
||||
{
|
||||
$pack = LanguagePack::query()->create([
|
||||
'identifier' => 'g7-core-en',
|
||||
'vendor' => 'g7',
|
||||
'scope' => LanguagePackScope::Core->value,
|
||||
'target_identifier' => null,
|
||||
'locale' => 'en',
|
||||
'locale_name' => 'English',
|
||||
'locale_native_name' => 'English',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => LanguagePackStatus::Active->value,
|
||||
'is_protected' => true,
|
||||
'manifest' => [],
|
||||
]);
|
||||
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$this->service->uninstall($pack, false);
|
||||
}
|
||||
|
||||
public function test_list_returns_paginator(): void
|
||||
{
|
||||
$this->makePack('sirsoft', 'ja', LanguagePackStatus::Active->value);
|
||||
$this->makePack('acme', 'ja', LanguagePackStatus::Inactive->value);
|
||||
$this->makePack('sirsoft', 'fr', LanguagePackStatus::Active->value);
|
||||
|
||||
// installed 상태로만 필터해 미설치 번들 가상 레코드를 제외하고 DB 만 검증.
|
||||
$paginator = $this->service->list(['locale' => 'ja', 'status' => LanguagePackStatus::Installed->value], 20);
|
||||
$this->assertSame(0, $paginator->total(), 'Installed 상태 일치 0건');
|
||||
|
||||
// 활성/비활성 + locale=ja 로 DB 의 2건이 정확히 잡히는지(번들 가상은 status filter 가 차단).
|
||||
$activeOnly = $this->service->list(['locale' => 'ja', 'status' => LanguagePackStatus::Active->value], 20);
|
||||
$this->assertSame(1, $activeOnly->total());
|
||||
|
||||
$inactiveOnly = $this->service->list(['locale' => 'ja', 'status' => LanguagePackStatus::Inactive->value], 20);
|
||||
$this->assertSame(1, $inactiveOnly->total());
|
||||
}
|
||||
|
||||
public function test_find_returns_pack_or_null(): void
|
||||
{
|
||||
$pack = $this->makePack('sirsoft', 'ja', LanguagePackStatus::Active->value);
|
||||
|
||||
$this->assertNotNull($this->service->find($pack->id));
|
||||
$this->assertNull($this->service->find(999999));
|
||||
}
|
||||
|
||||
public function test_resolve_install_blocked_reason_returns_null_for_core(): void
|
||||
{
|
||||
$reason = $this->service->resolveInstallBlockedReason([
|
||||
'scope' => LanguagePackScope::Core->value,
|
||||
'locale' => 'ja',
|
||||
]);
|
||||
|
||||
$this->assertNull($reason);
|
||||
}
|
||||
|
||||
public function test_resolve_install_blocked_reason_core_locale_missing(): void
|
||||
{
|
||||
$reason = $this->service->resolveInstallBlockedReason([
|
||||
'scope' => LanguagePackScope::Module->value,
|
||||
'target_identifier' => 'gnuboard7-hello_module',
|
||||
'locale' => 'ja',
|
||||
]);
|
||||
|
||||
$this->assertSame('core_locale_missing', $reason);
|
||||
}
|
||||
|
||||
public function test_resolve_install_blocked_reason_target_not_installed(): void
|
||||
{
|
||||
// 코어 ja 활성화 → 코어 의존성 통과시키고 target 검증으로 진입.
|
||||
$this->makePack('sirsoft', 'ja', LanguagePackStatus::Active->value);
|
||||
$this->registry->invalidate();
|
||||
|
||||
$reason = $this->service->resolveInstallBlockedReason([
|
||||
'scope' => LanguagePackScope::Module->value,
|
||||
'target_identifier' => 'no-such-module',
|
||||
'locale' => 'ja',
|
||||
]);
|
||||
|
||||
$this->assertSame('target_not_installed', $reason);
|
||||
}
|
||||
|
||||
public function test_resolve_install_blocked_reason_target_inactive(): void
|
||||
{
|
||||
$this->makePack('sirsoft', 'ja', LanguagePackStatus::Active->value);
|
||||
$this->registry->invalidate();
|
||||
|
||||
\Illuminate\Support\Facades\DB::table('modules')->insert([
|
||||
'identifier' => 'gnuboard7-hello_module',
|
||||
'name' => 'Hello',
|
||||
'vendor' => 'gnuboard7',
|
||||
'version' => '1.0.0',
|
||||
'status' => 'inactive',
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
$reason = $this->service->resolveInstallBlockedReason([
|
||||
'scope' => LanguagePackScope::Module->value,
|
||||
'target_identifier' => 'gnuboard7-hello_module',
|
||||
'locale' => 'ja',
|
||||
]);
|
||||
|
||||
$this->assertSame('target_inactive', $reason);
|
||||
}
|
||||
|
||||
public function test_resolve_install_blocked_reason_target_version_too_old(): void
|
||||
{
|
||||
$this->makePack('sirsoft', 'ja', LanguagePackStatus::Active->value);
|
||||
$this->registry->invalidate();
|
||||
|
||||
\Illuminate\Support\Facades\DB::table('modules')->insert([
|
||||
'identifier' => 'gnuboard7-hello_module',
|
||||
'name' => 'Hello',
|
||||
'vendor' => 'gnuboard7',
|
||||
'version' => '1.0.0',
|
||||
'status' => 'active',
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
$reason = $this->service->resolveInstallBlockedReason([
|
||||
'scope' => LanguagePackScope::Module->value,
|
||||
'target_identifier' => 'gnuboard7-hello_module',
|
||||
'locale' => 'ja',
|
||||
'requires' => ['target_version' => '^2.0.0'],
|
||||
]);
|
||||
|
||||
$this->assertSame('target_version_too_old', $reason);
|
||||
}
|
||||
|
||||
public function test_resolve_install_blocked_reason_returns_null_when_all_satisfied(): void
|
||||
{
|
||||
$this->makePack('sirsoft', 'ja', LanguagePackStatus::Active->value);
|
||||
$this->registry->invalidate();
|
||||
|
||||
\Illuminate\Support\Facades\DB::table('modules')->insert([
|
||||
'identifier' => 'gnuboard7-hello_module',
|
||||
'name' => 'Hello',
|
||||
'vendor' => 'gnuboard7',
|
||||
'version' => '1.5.0',
|
||||
'status' => 'active',
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
$reason = $this->service->resolveInstallBlockedReason([
|
||||
'scope' => LanguagePackScope::Module->value,
|
||||
'target_identifier' => 'gnuboard7-hello_module',
|
||||
'locale' => 'ja',
|
||||
'requires' => ['target_version' => '^1.0.0'],
|
||||
]);
|
||||
|
||||
$this->assertNull($reason);
|
||||
}
|
||||
|
||||
public function test_check_updates_skips_non_github_packs(): void
|
||||
{
|
||||
$this->makePack('sirsoft', 'ja', LanguagePackStatus::Active->value);
|
||||
|
||||
$result = $this->service->checkUpdates();
|
||||
|
||||
$this->assertSame(['checked' => 0, 'updates' => 0, 'details' => []], $result);
|
||||
}
|
||||
|
||||
public function test_perform_update_throws_when_no_github_source(): void
|
||||
{
|
||||
$pack = $this->makePack('sirsoft', 'ja', LanguagePackStatus::Active->value);
|
||||
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$this->service->performUpdate($pack);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈/플러그인/템플릿과 일관되게, 매니페스트 `github_url` 이 SSoT 로 사용되는지 검증.
|
||||
*
|
||||
* source_type=bundled 로 설치된 팩이라도 매니페스트에 github_url 이 명시되어 있으면
|
||||
* checkUpdates() 의 점검 대상이 되어야 함 (count > 0). 실제 GitHub 호출은 발생하지만
|
||||
* 네트워크 결과와 무관하게 `checked` 가 증가하면 SSoT 해석이 정상 동작한 것.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_check_updates_includes_packs_with_manifest_github_url(): void
|
||||
{
|
||||
$pack = $this->makePack('sirsoft', 'ja', LanguagePackStatus::Active->value);
|
||||
$pack->forceFill([
|
||||
'source_type' => 'bundled',
|
||||
'source_url' => $pack->identifier,
|
||||
'manifest' => [
|
||||
'identifier' => $pack->identifier,
|
||||
'namespace' => 'g7',
|
||||
'vendor' => 'sirsoft',
|
||||
'github_url' => 'https://github.com/gnuboard/'.$pack->identifier,
|
||||
],
|
||||
])->save();
|
||||
|
||||
$result = $this->service->checkUpdates();
|
||||
|
||||
$this->assertSame(1, $result['checked'], '매니페스트 github_url 이 있으면 점검 대상에 포함되어야 한다');
|
||||
$this->assertCount(1, $result['details']);
|
||||
$this->assertSame($pack->identifier, $result['details'][0]['identifier']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 매니페스트 github_url 이 비어있고 source_url 도 GitHub 가 아니면서
|
||||
* 번들도 없으면 checkUpdates 점검 대상에서 제외되는지 확인 (회귀 가드).
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_check_updates_excludes_packs_with_blank_manifest_github_url(): void
|
||||
{
|
||||
$pack = $this->makePack('sirsoft', 'ja', LanguagePackStatus::Active->value);
|
||||
$pack->forceFill([
|
||||
'manifest' => [
|
||||
'identifier' => $pack->identifier,
|
||||
'github_url' => '',
|
||||
],
|
||||
])->save();
|
||||
|
||||
$result = $this->service->checkUpdates();
|
||||
|
||||
$this->assertSame(0, $result['checked']);
|
||||
}
|
||||
|
||||
public function test_refresh_cache_returns_status_map(): void
|
||||
{
|
||||
$result = $this->service->refreshCache();
|
||||
|
||||
$this->assertArrayHasKey('registry', $result);
|
||||
$this->assertArrayHasKey('translator', $result);
|
||||
$this->assertArrayHasKey('template', $result);
|
||||
$this->assertTrue($result['registry']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 공식 일본어 번들 언어팩(g7-core-ja) 을 bundled 소스로 설치 → 자동 활성 검증.
|
||||
*
|
||||
* 본 테스트는 빌드 산출 디렉토리(`lang-packs/_bundled/g7-core-ja/`)가 존재할 때만 의미가 있으며,
|
||||
* 빌드 미완료 시 자동 스킵하여 CI 가 깨지지 않도록 한다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_install_g7_core_ja_from_bundled_promotes_to_active(): void
|
||||
{
|
||||
$bundledPath = base_path('lang-packs/_bundled/g7-core-ja');
|
||||
if (! is_dir($bundledPath) || ! is_file($bundledPath.'/language-pack.json')) {
|
||||
$this->markTestSkipped('g7-core-ja 번들이 아직 빌드되지 않음 — build-language-pack-ja.cjs 실행 후 재시도');
|
||||
}
|
||||
|
||||
$pack = $this->service->installFromBundled('g7-core-ja', autoActivate: true);
|
||||
|
||||
$this->assertSame('g7-core-ja', $pack->identifier);
|
||||
$this->assertSame(LanguagePackScope::Core->value, $pack->scope);
|
||||
$this->assertNull($pack->target_identifier);
|
||||
$this->assertSame('ja', $pack->locale);
|
||||
$this->assertSame('1.0.0-beta.1', $pack->version);
|
||||
$this->assertSame(LanguagePackStatus::Active->value, $pack->status);
|
||||
$this->assertSame('bundled', $pack->source_type);
|
||||
// is_protected 는 모든 install 흐름에서 항상 false (보호 행은 코어/번들 확장의 lang/ 디렉토리를 가상 행으로 합성하는 경로에서만 true)
|
||||
$this->assertFalse($pack->is_protected);
|
||||
|
||||
// 산출 자산 검증 — backend/ja/*.php 가 실제로 복사되었는지
|
||||
$installedDir = base_path('lang-packs/g7-core-ja');
|
||||
$this->assertFileExists($installedDir.'/backend/ja/common.php');
|
||||
$this->assertFileExists($installedDir.'/seed/permissions.json');
|
||||
|
||||
// cleanup — 활성 디렉토리 제거 (RefreshDatabase 와 별개)
|
||||
\Illuminate\Support\Facades\File::deleteDirectory($installedDir);
|
||||
}
|
||||
|
||||
/**
|
||||
* 회귀 가드 — 재설치(installFromBundled 두 번째 호출) 시 자기 자신을
|
||||
* 슬롯 충돌로 오인하여 status 가 active → installed 로 강등되는 회귀 차단.
|
||||
*
|
||||
* 인스톨러가 retry 되거나 사용자가 동일 identifier 를 재설치할 때, 이전엔
|
||||
* `findActiveForSlot` 가 자기 자신(이미 active 인 row)을 반환 → `shouldActivate=false` →
|
||||
* 새 status='installed' 로 떨어져 의존하는 확장 언어팩이 'core_locale_missing' 으로
|
||||
* 차단되는 인스톨러 hang/실패가 발생했음.
|
||||
*
|
||||
* fix: `finalizeInstall` 가 `findActiveForSlot` 호출 시 `$existing?->id` 를 excludeId 로 전달.
|
||||
*/
|
||||
public function test_reinstall_active_pack_keeps_active_status(): void
|
||||
{
|
||||
$bundledPath = base_path('lang-packs/_bundled/g7-core-ja');
|
||||
if (! is_dir($bundledPath) || ! is_file($bundledPath.'/language-pack.json')) {
|
||||
$this->markTestSkipped('g7-core-ja 번들이 아직 빌드되지 않음 — build-language-pack-ja.cjs 실행 후 재시도');
|
||||
}
|
||||
|
||||
// 첫 install — autoActivate=true → status=active
|
||||
$first = $this->service->installFromBundled('g7-core-ja', autoActivate: true);
|
||||
$this->assertSame(LanguagePackStatus::Active->value, $first->status, '첫 install 은 자동 활성화되어야 함');
|
||||
|
||||
// 재설치 — 같은 identifier 가 update path 로 진입.
|
||||
// self-conflict fix 가 없다면 status 가 'installed' 로 강등됨 (회귀).
|
||||
// fix 후엔 자기 자신 제외하고 슬롯 검사하므로 active 유지.
|
||||
$second = $this->service->installFromBundled('g7-core-ja', autoActivate: true);
|
||||
$this->assertSame($first->id, $second->id, '같은 row 가 update 되어야 함');
|
||||
$this->assertSame(LanguagePackStatus::Active->value, $second->status,
|
||||
'재설치 시 자기 자신을 슬롯 충돌로 오인하여 active → installed 로 강등되면 안 됨 (회귀)');
|
||||
|
||||
// cleanup
|
||||
\Illuminate\Support\Facades\File::deleteDirectory(base_path('lang-packs/g7-core-ja'));
|
||||
}
|
||||
|
||||
public function test_install_blocks_downgrade_without_force(): void
|
||||
{
|
||||
$identifier = 'dgblock-core-ja';
|
||||
$bundledDir = $this->createBundledFixture($identifier, [
|
||||
'identifier' => $identifier,
|
||||
'namespace' => 'dgblock',
|
||||
'vendor' => 'dgblock',
|
||||
'name' => ['ko' => 'Downgrade Test', 'en' => 'Downgrade Test', 'ja' => 'Downgrade Test'],
|
||||
'description' => ['ko' => '테스트', 'en' => 'Test'],
|
||||
'version' => '1.0.0-beta.1',
|
||||
'scope' => LanguagePackScope::Core->value,
|
||||
'target_identifier' => null,
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'JA',
|
||||
'locale_native_name' => '日本語',
|
||||
'text_direction' => 'ltr',
|
||||
'g7_version' => '>=7.0.0-beta.4',
|
||||
]);
|
||||
|
||||
try {
|
||||
LanguagePack::query()->create([
|
||||
'identifier' => $identifier,
|
||||
'vendor' => 'dgblock',
|
||||
'scope' => LanguagePackScope::Core->value,
|
||||
'target_identifier' => null,
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'JA',
|
||||
'locale_native_name' => '日本語',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0-beta.2',
|
||||
'status' => LanguagePackStatus::Active->value,
|
||||
'is_protected' => false,
|
||||
'manifest' => [],
|
||||
'source_type' => 'bundled',
|
||||
]);
|
||||
|
||||
// force=false → 다운그레이드 차단 예외
|
||||
$this->expectException(\App\Exceptions\LanguagePackOperationException::class);
|
||||
$this->service->installFromBundled($identifier);
|
||||
} finally {
|
||||
\Illuminate\Support\Facades\File::deleteDirectory($bundledDir);
|
||||
\Illuminate\Support\Facades\File::deleteDirectory(base_path('lang-packs/'.$identifier));
|
||||
}
|
||||
}
|
||||
|
||||
public function test_install_allows_downgrade_with_force(): void
|
||||
{
|
||||
$identifier = 'dgforce-core-ja';
|
||||
$bundledDir = $this->createBundledFixture($identifier, [
|
||||
'identifier' => $identifier,
|
||||
'namespace' => 'dgforce',
|
||||
'vendor' => 'dgforce',
|
||||
'name' => ['ko' => 'Downgrade Force Test', 'en' => 'Downgrade Force Test', 'ja' => 'Downgrade Force Test'],
|
||||
'description' => ['ko' => '테스트', 'en' => 'Test'],
|
||||
'version' => '1.0.0-beta.1',
|
||||
'scope' => LanguagePackScope::Core->value,
|
||||
'target_identifier' => null,
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'JA',
|
||||
'locale_native_name' => '日本語',
|
||||
'text_direction' => 'ltr',
|
||||
'g7_version' => '>=7.0.0-beta.4',
|
||||
]);
|
||||
|
||||
try {
|
||||
LanguagePack::query()->create([
|
||||
'identifier' => $identifier,
|
||||
'vendor' => 'dgforce',
|
||||
'scope' => LanguagePackScope::Core->value,
|
||||
'target_identifier' => null,
|
||||
'locale' => 'ja',
|
||||
'locale_name' => 'JA',
|
||||
'locale_native_name' => '日本語',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0-beta.2',
|
||||
'status' => LanguagePackStatus::Active->value,
|
||||
'is_protected' => false,
|
||||
'manifest' => [],
|
||||
'source_type' => 'bundled',
|
||||
]);
|
||||
|
||||
// force=true → 다운그레이드 허용
|
||||
$pack = $this->service->installFromBundled($identifier, force: true);
|
||||
$this->assertSame('1.0.0-beta.1', $pack->version);
|
||||
} finally {
|
||||
\Illuminate\Support\Facades\File::deleteDirectory($bundledDir);
|
||||
\Illuminate\Support\Facades\File::deleteDirectory(base_path('lang-packs/'.$identifier));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 임시 번들 디렉토리를 생성합니다 (테스트 격리용).
|
||||
*
|
||||
* @param string $identifier 번들 디렉토리 식별자 (lang-packs/_bundled/{identifier})
|
||||
* @param array<string, mixed> $manifest manifest JSON 으로 직렬화할 데이터
|
||||
* @return string 생성된 디렉토리 절대 경로
|
||||
*/
|
||||
private function createBundledFixture(string $identifier, array $manifest): string
|
||||
{
|
||||
$path = base_path('lang-packs/_bundled/'.$identifier);
|
||||
\Illuminate\Support\Facades\File::ensureDirectoryExists($path);
|
||||
\Illuminate\Support\Facades\File::put(
|
||||
$path.DIRECTORY_SEPARATOR.'language-pack.json',
|
||||
json_encode($manifest, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)
|
||||
);
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
public function test_get_uninstalled_bundled_packs_returns_virtual_records(): void
|
||||
{
|
||||
$identifier = 'test-virtual-acme-zz-'.uniqid();
|
||||
$manifest = [
|
||||
'identifier' => $identifier,
|
||||
'vendor' => 'acme',
|
||||
'scope' => LanguagePackScope::Core->value,
|
||||
'target_identifier' => null,
|
||||
'locale' => 'zz',
|
||||
'locale_name' => 'Zzland',
|
||||
'locale_native_name' => 'Zzland Native',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '0.1.0',
|
||||
];
|
||||
$path = $this->createBundledFixture($identifier, $manifest);
|
||||
|
||||
try {
|
||||
$packs = $this->service->getUninstalledBundledPacks();
|
||||
$match = $packs->firstWhere('identifier', $identifier);
|
||||
|
||||
$this->assertNotNull($match, '미설치 번들이 가상 레코드로 반환되어야 함');
|
||||
$this->assertSame(LanguagePackStatus::Uninstalled->value, $match->status);
|
||||
$this->assertSame('bundled', $match->source_type);
|
||||
$this->assertSame($identifier, $match->getAttribute('bundled_identifier'));
|
||||
$this->assertFalse($match->exists, '가상 레코드는 exists=false 여야 함');
|
||||
$this->assertNull($match->id, '가상 레코드는 id 가 null 이어야 함');
|
||||
} finally {
|
||||
\Illuminate\Support\Facades\File::deleteDirectory($path);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_get_uninstalled_bundled_packs_excludes_already_installed_slot(): void
|
||||
{
|
||||
$identifier = 'test-installed-acme-zz-'.uniqid();
|
||||
$manifest = [
|
||||
'identifier' => $identifier,
|
||||
'vendor' => 'acme',
|
||||
'scope' => LanguagePackScope::Core->value,
|
||||
'target_identifier' => null,
|
||||
'locale' => 'zz',
|
||||
'locale_name' => 'Zzland',
|
||||
'locale_native_name' => 'Zzland Native',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '0.1.0',
|
||||
];
|
||||
$path = $this->createBundledFixture($identifier, $manifest);
|
||||
// 동일 슬롯(scope=core, target_identifier=null, locale=zz) 의 DB 레코드를 만든다 → 가상 레코드 미포함되어야 함.
|
||||
LanguagePack::query()->create([
|
||||
'identifier' => 'other-vendor-core-zz',
|
||||
'vendor' => 'other',
|
||||
'scope' => LanguagePackScope::Core->value,
|
||||
'target_identifier' => null,
|
||||
'locale' => 'zz',
|
||||
'locale_name' => 'Zzland',
|
||||
'locale_native_name' => 'Zzland',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '1.0.0',
|
||||
'status' => LanguagePackStatus::Active->value,
|
||||
'is_protected' => false,
|
||||
'manifest' => [],
|
||||
]);
|
||||
|
||||
try {
|
||||
$packs = $this->service->getUninstalledBundledPacks();
|
||||
$match = $packs->firstWhere('identifier', $identifier);
|
||||
$this->assertNull($match, '동일 슬롯에 DB 레코드가 있으면 가상 레코드가 반환되지 않아야 함');
|
||||
} finally {
|
||||
\Illuminate\Support\Facades\File::deleteDirectory($path);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_list_merges_db_records_and_uninstalled_bundled(): void
|
||||
{
|
||||
$this->makePack('sirsoft', 'fr', LanguagePackStatus::Active->value);
|
||||
|
||||
$identifier = 'test-merge-acme-yy-'.uniqid();
|
||||
$manifest = [
|
||||
'identifier' => $identifier,
|
||||
'vendor' => 'acme',
|
||||
'scope' => LanguagePackScope::Core->value,
|
||||
'target_identifier' => null,
|
||||
'locale' => 'yy',
|
||||
'locale_name' => 'Yyland',
|
||||
'locale_native_name' => 'Yyland',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '0.1.0',
|
||||
];
|
||||
$path = $this->createBundledFixture($identifier, $manifest);
|
||||
|
||||
try {
|
||||
$paginator = $this->service->list([], 100);
|
||||
|
||||
$items = collect($paginator->items());
|
||||
$this->assertGreaterThanOrEqual(
|
||||
2,
|
||||
$paginator->total(),
|
||||
'DB 레코드(fr) + 가상 번들(yy) 이 합쳐져야 함'
|
||||
);
|
||||
|
||||
$virtual = $items->firstWhere('identifier', $identifier);
|
||||
$this->assertNotNull($virtual);
|
||||
$this->assertSame(LanguagePackStatus::Uninstalled->value, $virtual->status);
|
||||
} finally {
|
||||
\Illuminate\Support\Facades\File::deleteDirectory($path);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_list_filters_uninstalled_status_excludes_db_records(): void
|
||||
{
|
||||
$this->makePack('sirsoft', 'fr', LanguagePackStatus::Active->value);
|
||||
|
||||
$identifier = 'test-filter-acme-xx-'.uniqid();
|
||||
$manifest = [
|
||||
'identifier' => $identifier,
|
||||
'vendor' => 'acme',
|
||||
'scope' => LanguagePackScope::Core->value,
|
||||
'target_identifier' => null,
|
||||
'locale' => 'xx',
|
||||
'locale_name' => 'Xxland',
|
||||
'locale_native_name' => 'Xxland',
|
||||
'text_direction' => 'ltr',
|
||||
'version' => '0.1.0',
|
||||
];
|
||||
$path = $this->createBundledFixture($identifier, $manifest);
|
||||
|
||||
try {
|
||||
$paginator = $this->service->list(['status' => LanguagePackStatus::Uninstalled->value], 100);
|
||||
$items = collect($paginator->items());
|
||||
|
||||
$this->assertNotNull($items->firstWhere('identifier', $identifier));
|
||||
$this->assertNull($items->firstWhere('status', LanguagePackStatus::Active->value));
|
||||
} finally {
|
||||
\Illuminate\Support\Facades\File::deleteDirectory($path);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Services\LanguagePack;
|
||||
|
||||
use App\Services\LanguagePack\LanguagePackTranslator;
|
||||
use Illuminate\Translation\FileLoader;
|
||||
use Illuminate\Filesystem\Filesystem;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* LanguagePackTranslator 단위 테스트.
|
||||
*
|
||||
* Translator decorator 의 코어 폴백 경로 동작을 검증합니다.
|
||||
*/
|
||||
class LanguagePackTranslatorTest extends TestCase
|
||||
{
|
||||
private string $tempDir;
|
||||
|
||||
private LanguagePackTranslator $translator;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->tempDir = sys_get_temp_dir().DIRECTORY_SEPARATOR.uniqid('lp_translator_', true);
|
||||
mkdir($this->tempDir, 0777, true);
|
||||
|
||||
$loader = new FileLoader(new Filesystem(), $this->tempDir);
|
||||
$this->translator = new LanguagePackTranslator($loader, 'ko');
|
||||
$this->translator->setFallback('ko');
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->deleteRecursive($this->tempDir);
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function deleteRecursive(string $dir): void
|
||||
{
|
||||
if (! is_dir($dir)) {
|
||||
return;
|
||||
}
|
||||
foreach (scandir($dir) as $item) {
|
||||
if ($item === '.' || $item === '..') {
|
||||
continue;
|
||||
}
|
||||
$path = $dir.DIRECTORY_SEPARATOR.$item;
|
||||
is_dir($path) ? $this->deleteRecursive($path) : unlink($path);
|
||||
}
|
||||
rmdir($dir);
|
||||
}
|
||||
|
||||
public function test_add_core_fallback_path_records_path(): void
|
||||
{
|
||||
$this->translator->addCoreFallbackPath('ja', '/some/path');
|
||||
|
||||
$this->assertSame(['ja' => ['/some/path']], $this->translator->getCoreFallbackPaths());
|
||||
}
|
||||
|
||||
public function test_load_merges_fallback_when_base_missing_key(): void
|
||||
{
|
||||
// 기본 lang/ko/messages.php 생성 — only 'foo' 정의
|
||||
mkdir($this->tempDir.'/ko', 0777, true);
|
||||
file_put_contents($this->tempDir.'/ko/messages.php', "<?php\nreturn ['foo' => 'baseFoo'];\n");
|
||||
|
||||
// 폴백 경로 — 'foo' 와 'bar' 정의
|
||||
$fallbackDir = $this->tempDir.'/lang-pack-ja';
|
||||
mkdir($fallbackDir, 0777, true);
|
||||
file_put_contents($fallbackDir.'/messages.php', "<?php\nreturn ['foo' => 'fallbackFoo', 'bar' => 'fallbackBar'];\n");
|
||||
|
||||
$this->translator->addCoreFallbackPath('ko', $fallbackDir);
|
||||
|
||||
// base 우선 — foo 는 base 값 유지
|
||||
$this->assertSame('baseFoo', $this->translator->get('messages.foo', [], 'ko'));
|
||||
// base 부재 키 — fallback 으로 보완
|
||||
$this->assertSame('fallbackBar', $this->translator->get('messages.bar', [], 'ko'));
|
||||
}
|
||||
|
||||
public function test_namespaced_load_does_not_apply_fallback(): void
|
||||
{
|
||||
// 폴백 경로 등록 (코어 폴백)
|
||||
$fallbackDir = $this->tempDir.'/lang-pack-ja';
|
||||
mkdir($fallbackDir, 0777, true);
|
||||
file_put_contents($fallbackDir.'/messages.php', "<?php\nreturn ['foo' => 'fallbackFoo'];\n");
|
||||
$this->translator->addCoreFallbackPath('ko', $fallbackDir);
|
||||
|
||||
// 모듈 namespace 키 조회 — 등록된 path 가 없으므로 키 자체 그대로 반환 (fallback 미적용)
|
||||
$result = $this->translator->get('somemodule::messages.foo', [], 'ko');
|
||||
$this->assertSame('somemodule::messages.foo', $result);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ namespace Tests\Unit\Services;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Enums\LayoutExtensionType;
|
||||
use App\Enums\LayoutSourceType;
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Models\LayoutExtension;
|
||||
use App\Models\Module;
|
||||
use App\Models\Template;
|
||||
@@ -48,6 +49,18 @@ class LayoutExtensionServiceVersionTest extends TestCase
|
||||
*/
|
||||
public function test_extension_without_version_constraint_always_applies(): void
|
||||
{
|
||||
// 오버라이드 대상 모듈을 Active 상태로 DB 에 등록 (isExtensionSourceActive 통과)
|
||||
Module::create([
|
||||
'identifier' => 'sirsoft-ecommerce',
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => ['ko' => '이커머스', 'en' => 'Ecommerce'],
|
||||
'version' => '1.0.0',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
ModuleManager::invalidateModuleStatusCache();
|
||||
$this->app->forgetInstance(LayoutExtensionService::class);
|
||||
$this->service = app(LayoutExtensionService::class);
|
||||
|
||||
// version_constraint가 없는 템플릿 오버라이드
|
||||
LayoutExtension::create([
|
||||
'template_id' => $this->template->id,
|
||||
@@ -493,6 +506,26 @@ class LayoutExtensionServiceVersionTest extends TestCase
|
||||
*/
|
||||
public function test_non_template_override_skips_version_check(): void
|
||||
{
|
||||
// 모듈을 Active 로 등록 (isExtensionSourceActive(Module) 통과용)
|
||||
Module::create([
|
||||
'identifier' => 'sirsoft-ecommerce',
|
||||
'vendor' => 'sirsoft',
|
||||
'name' => ['ko' => '이커머스', 'en' => 'Ecommerce'],
|
||||
'version' => '1.0.0',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
ModuleManager::invalidateModuleStatusCache();
|
||||
$this->app->forgetInstance(LayoutExtensionService::class);
|
||||
$this->service = app(LayoutExtensionService::class);
|
||||
|
||||
// ModuleManager.modules 는 부팅 시 filesystem 에서 디스커버링되지만 테스트 환경에서
|
||||
// 누락될 수 있으므로 LayoutExtensionService.activeModules 를 직접 주입.
|
||||
$reflection = new \ReflectionClass($this->service);
|
||||
$activeModulesProp = $reflection->getProperty('activeModules');
|
||||
$activeModulesProp->setValue($this->service, ['sirsoft-ecommerce']);
|
||||
$activePluginsProp = $reflection->getProperty('activePlugins');
|
||||
$activePluginsProp->setValue($this->service, []);
|
||||
|
||||
// 모듈에서 직접 등록된 확장 (템플릿 오버라이드가 아님)
|
||||
LayoutExtension::create([
|
||||
'template_id' => $this->template->id,
|
||||
@@ -547,6 +580,14 @@ class LayoutExtensionServiceVersionTest extends TestCase
|
||||
'version' => '2.0.0',
|
||||
'status' => ExtensionStatus::Active->value,
|
||||
]);
|
||||
ModuleManager::invalidateModuleStatusCache();
|
||||
$this->app->forgetInstance(LayoutExtensionService::class);
|
||||
$this->service = app(LayoutExtensionService::class);
|
||||
|
||||
// ModuleManager.modules 누락 대응: activeModules 직접 주입
|
||||
$reflection = new \ReflectionClass($this->service);
|
||||
$reflection->getProperty('activeModules')->setValue($this->service, ['sirsoft-ecommerce']);
|
||||
$reflection->getProperty('activePlugins')->setValue($this->service, []);
|
||||
|
||||
// 모듈이 등록한 원본 동적 UI
|
||||
LayoutExtension::create([
|
||||
|
||||
@@ -4,7 +4,6 @@ namespace Tests\Unit\Services;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Enums\PermissionType;
|
||||
use App\Exceptions\CannotDeleteAdminException;
|
||||
use App\Exceptions\CannotDeleteSuperAdminException;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
@@ -67,15 +66,18 @@ class UserServiceTest extends TestCase
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// deleteUser() - 관리자 삭제 방지 테스트
|
||||
// deleteUser() - 관리자 삭제: 권한/스코프 기반 위임 (하드코딩 차단 제거)
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* 관리자 권한을 가진 사용자 삭제 시 CannotDeleteAdminException 발생 확인
|
||||
* 관리자 권한을 가진 사용자(target=admin) 도 UserService::deleteUser 단독으로는 삭제 가능해야 한다.
|
||||
*
|
||||
* 회귀: "target.isAdmin() → CannotDeleteAdminException" 하드코딩이 G7 의 역할/퍼미션/스코프 시스템을
|
||||
* 우회해 슈퍼관리자도 다른 관리자를 삭제하지 못하도록 막던 결함. 권한/스코프 검증은 미들웨어
|
||||
* (PermissionMiddleware) 가 담당하고, 시스템 불변식인 슈퍼관리자 보호만 Service 가 보장한다.
|
||||
*/
|
||||
public function test_delete_admin_user_throws_cannot_delete_admin_exception(): void
|
||||
public function test_delete_admin_user_succeeds_when_actor_authorized(): void
|
||||
{
|
||||
// admin 타입 권한 생성
|
||||
$adminPermission = Permission::create([
|
||||
'identifier' => 'core.admin.test',
|
||||
'name' => ['ko' => '관리자 권한', 'en' => 'Admin Permission'],
|
||||
@@ -84,50 +86,19 @@ class UserServiceTest extends TestCase
|
||||
'type' => PermissionType::Admin,
|
||||
]);
|
||||
|
||||
// 역할 생성 및 권한 연결
|
||||
$role = Role::create([
|
||||
'identifier' => 'test-admin',
|
||||
'name' => ['ko' => '테스트 관리자', 'en' => 'Test Admin'],
|
||||
]);
|
||||
$role->permissions()->attach($adminPermission->id);
|
||||
|
||||
// 관리자 사용자 생성 (is_super=false이지만 admin 권한 보유)
|
||||
$adminUser = User::factory()->create(['is_super' => false]);
|
||||
$adminUser->roles()->attach($role->id);
|
||||
|
||||
$this->expectException(CannotDeleteAdminException::class);
|
||||
$result = $this->userService->deleteUser($adminUser);
|
||||
|
||||
$this->userService->deleteUser($adminUser);
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자 삭제 시 예외 메시지가 올바른지 확인
|
||||
*/
|
||||
public function test_cannot_delete_admin_exception_has_correct_message(): void
|
||||
{
|
||||
$adminPermission = Permission::create([
|
||||
'identifier' => 'core.admin.msg.test',
|
||||
'name' => ['ko' => '관리자 권한', 'en' => 'Admin Permission'],
|
||||
'extension_type' => ExtensionOwnerType::Core,
|
||||
'extension_identifier' => 'core',
|
||||
'type' => PermissionType::Admin,
|
||||
]);
|
||||
|
||||
$role = Role::create([
|
||||
'identifier' => 'test-admin-msg',
|
||||
'name' => ['ko' => '테스트 관리자', 'en' => 'Test Admin'],
|
||||
]);
|
||||
$role->permissions()->attach($adminPermission->id);
|
||||
|
||||
$adminUser = User::factory()->create(['is_super' => false]);
|
||||
$adminUser->roles()->attach($role->id);
|
||||
|
||||
try {
|
||||
$this->userService->deleteUser($adminUser);
|
||||
$this->fail('Expected CannotDeleteAdminException was not thrown');
|
||||
} catch (CannotDeleteAdminException $e) {
|
||||
$this->assertNotEmpty($e->getMessage());
|
||||
}
|
||||
$this->assertTrue($result);
|
||||
$this->assertDatabaseMissing('users', ['id' => $adminUser->id]);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
|
||||
Reference in new issue
Block a user