v7.0.0-beta.2 release

This commit is contained in:
HeuJung committed 2026-04-20 20:37:49 +09:00
1 parent 6595fd0eb5
commit fa8eba7a0d
1165 files changed
+107118 -762127

No files matched your search

-243
View File
@@ -1,243 +0,0 @@
<?php
namespace Tests\Unit\Services;
use App\Services\CacheService;
use Illuminate\Support\Facades\Cache;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* CacheService 단위 테스트
*
* 빈 배열 캐싱 금지 기능을 검증합니다.
*/
class CacheServiceTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
Cache::flush();
}
protected function tearDown(): void
{
Cache::flush();
parent::tearDown();
}
/**
* 빈 배열은 캐시하지 않아야 합니다.
*/
#[Test]
public function it_does_not_cache_empty_arrays(): void
{
$callCount = 0;
$callback = function () use (&$callCount) {
$callCount++;
return [];
};
// 첫 번째 호출
$result1 = CacheService::remember('test', 'empty_array', $callback);
$this->assertEquals([], $result1);
$this->assertEquals(1, $callCount);
// 두 번째 호출 - 캐시되지 않았으므로 콜백 재실행
$result2 = CacheService::remember('test', 'empty_array', $callback);
$this->assertEquals([], $result2);
$this->assertEquals(2, $callCount);
// 캐시에 값이 없음을 확인
$this->assertNull(Cache::get(CacheService::key('test', 'empty_array')));
}
/**
* 비어있지 않은 배열은 정상적으로 캐시되어야 합니다.
*/
#[Test]
public function it_caches_non_empty_arrays(): void
{
$callCount = 0;
$callback = function () use (&$callCount) {
$callCount++;
return ['item1', 'item2'];
};
// 첫 번째 호출
$result1 = CacheService::remember('test', 'non_empty_array', $callback);
$this->assertEquals(['item1', 'item2'], $result1);
$this->assertEquals(1, $callCount);
// 두 번째 호출 - 캐시 히트
$result2 = CacheService::remember('test', 'non_empty_array', $callback);
$this->assertEquals(['item1', 'item2'], $result2);
$this->assertEquals(1, $callCount); // 콜백 재실행 안함
}
/**
* 문자열 등 배열이 아닌 값은 정상적으로 캐시되어야 합니다.
*/
#[Test]
public function it_caches_non_array_values(): void
{
$callCount = 0;
$callback = function () use (&$callCount) {
$callCount++;
return 'string_value';
};
$result1 = CacheService::remember('test', 'string', $callback);
$this->assertEquals('string_value', $result1);
$this->assertEquals(1, $callCount);
$result2 = CacheService::remember('test', 'string', $callback);
$this->assertEquals('string_value', $result2);
$this->assertEquals(1, $callCount);
}
/**
* 정수 값은 정상적으로 캐시되어야 합니다.
*/
#[Test]
public function it_caches_integer_values(): void
{
$callCount = 0;
$callback = function () use (&$callCount) {
$callCount++;
return 42;
};
$result1 = CacheService::remember('test', 'integer', $callback);
$this->assertEquals(42, $result1);
$this->assertEquals(1, $callCount);
$result2 = CacheService::remember('test', 'integer', $callback);
$this->assertEquals(42, $result2);
$this->assertEquals(1, $callCount);
}
/**
* 연관 배열도 정상적으로 캐시되어야 합니다.
*/
#[Test]
public function it_caches_associative_arrays(): void
{
$callCount = 0;
$callback = function () use (&$callCount) {
$callCount++;
return ['key' => 'value', 'count' => 10];
};
$result1 = CacheService::remember('test', 'assoc_array', $callback);
$this->assertEquals(['key' => 'value', 'count' => 10], $result1);
$this->assertEquals(1, $callCount);
$result2 = CacheService::remember('test', 'assoc_array', $callback);
$this->assertEquals(['key' => 'value', 'count' => 10], $result2);
$this->assertEquals(1, $callCount);
}
/**
* DB 테이블이 없으면 빈 배열을 반환하고 캐시하지 않아야 합니다.
*/
#[Test]
public function it_returns_empty_array_without_caching_when_table_not_exists(): void
{
$callCount = 0;
$callback = function () use (&$callCount) {
$callCount++;
return ['data'];
};
// 존재하지 않는 테이블 지정
$result = CacheService::remember(
'test',
'no_table',
$callback,
null,
'non_existent_table_xyz_123'
);
$this->assertEquals([], $result);
$this->assertEquals(0, $callCount); // 콜백 실행 안함
$this->assertNull(Cache::get(CacheService::key('test', 'no_table')));
}
/**
* 캐시 키가 올바르게 생성되어야 합니다.
*/
#[Test]
public function it_generates_correct_cache_key(): void
{
$key = CacheService::key('modules', 'active_identifiers');
$this->assertEquals('g7:modules:active_identifiers', $key);
}
/**
* forget 메서드가 캐시를 삭제해야 합니다.
*/
#[Test]
public function it_forgets_cached_values(): void
{
// 값 캐시
CacheService::remember('test', 'to_forget', fn () => ['data']);
// 캐시 확인
$this->assertNotNull(Cache::get(CacheService::key('test', 'to_forget')));
// 캐시 삭제
CacheService::forget('test', 'to_forget');
// 삭제 확인
$this->assertNull(Cache::get(CacheService::key('test', 'to_forget')));
}
/**
* forgetMany 메서드가 여러 캐시를 삭제해야 합니다.
*/
#[Test]
public function it_forgets_many_cached_values(): void
{
// 여러 값 캐시
CacheService::remember('test', 'key1', fn () => ['data1']);
CacheService::remember('test', 'key2', fn () => ['data2']);
// 캐시 확인
$this->assertNotNull(Cache::get(CacheService::key('test', 'key1')));
$this->assertNotNull(Cache::get(CacheService::key('test', 'key2')));
// 여러 캐시 삭제
CacheService::forgetMany('test', ['key1', 'key2']);
// 삭제 확인
$this->assertNull(Cache::get(CacheService::key('test', 'key1')));
$this->assertNull(Cache::get(CacheService::key('test', 'key2')));
}
/**
* refresh 메서드가 캐시를 갱신해야 합니다.
*/
#[Test]
public function it_refreshes_cached_values(): void
{
$value = 1;
// 초기 캐시
CacheService::remember('test', 'refresh', fn () => $value);
$this->assertEquals(1, Cache::get(CacheService::key('test', 'refresh')));
// 값 변경 후 refresh
$value = 2;
$result = CacheService::refresh('test', 'refresh', fn () => $value);
$this->assertEquals(2, $result);
$this->assertEquals(2, Cache::get(CacheService::key('test', 'refresh')));
}
}
@@ -0,0 +1,232 @@
<?php
namespace Tests\Unit\Services;
use App\Contracts\Repositories\ConfigRepositoryInterface;
use App\Services\ChannelReadinessService;
use Illuminate\Support\Facades\Schema;
use Mockery;
use Tests\TestCase;
/**
* ChannelReadinessService 단위 테스트
*/
class ChannelReadinessServiceTest extends TestCase
{
private ConfigRepositoryInterface $configRepo;
private ChannelReadinessService $service;
protected function setUp(): void
{
parent::setUp();
$this->configRepo = Mockery::mock(ConfigRepositoryInterface::class);
$this->service = new ChannelReadinessService($this->configRepo);
}
protected function tearDown(): void
{
Mockery::close();
parent::tearDown();
}
/**
* SMTP 설정 완료 시 mail 채널 ready
*/
public function test_mail_smtp_ready_when_configured(): void
{
$this->configRepo->shouldReceive('getCategory')
->with('mail')
->andReturn([
'mailer' => 'smtp',
'host' => 'smtp.gmail.com',
'port' => 587,
'from_address' => 'test@example.com',
'from_name' => 'Test',
]);
$result = $this->service->check('mail');
$this->assertTrue($result['ready']);
$this->assertNull($result['reason']);
}
/**
* SMTP host 미설정 시 not ready
*/
public function test_mail_smtp_not_ready_when_host_empty(): void
{
$this->configRepo->shouldReceive('getCategory')
->with('mail')
->andReturn([
'mailer' => 'smtp',
'host' => '',
'port' => 587,
'from_address' => 'test@example.com',
]);
$result = $this->service->check('mail');
$this->assertFalse($result['ready']);
$this->assertEquals('notification.readiness.mail_smtp_host_empty', $result['reason']);
}
/**
* from_address 기본값(noreply@example.com) 시 not ready
*/
public function test_mail_not_ready_when_from_address_is_default(): void
{
$this->configRepo->shouldReceive('getCategory')
->with('mail')
->andReturn([
'mailer' => 'smtp',
'host' => 'smtp.gmail.com',
'port' => 587,
'from_address' => 'noreply@example.com',
]);
$result = $this->service->check('mail');
$this->assertFalse($result['ready']);
$this->assertEquals('notification.readiness.mail_from_address_not_configured', $result['reason']);
}
/**
* Mailgun 설정 미완료 시 not ready
*/
public function test_mail_mailgun_not_ready_when_domain_empty(): void
{
$this->configRepo->shouldReceive('getCategory')
->with('mail')
->andReturn([
'mailer' => 'mailgun',
'mailgun_domain' => '',
'mailgun_secret' => 'secret',
'from_address' => 'test@example.com',
]);
$result = $this->service->check('mail');
$this->assertFalse($result['ready']);
$this->assertEquals('notification.readiness.mail_mailgun_domain_empty', $result['reason']);
}
/**
* SES 설정 미완료 시 not ready
*/
public function test_mail_ses_not_ready_when_key_empty(): void
{
$this->configRepo->shouldReceive('getCategory')
->with('mail')
->andReturn([
'mailer' => 'ses',
'ses_key' => '',
'ses_secret' => 'secret',
'from_address' => 'test@example.com',
]);
$result = $this->service->check('mail');
$this->assertFalse($result['ready']);
$this->assertEquals('notification.readiness.mail_ses_key_empty', $result['reason']);
}
/**
* log mailer는 항상 ready
*/
public function test_mail_log_mailer_always_ready(): void
{
$this->configRepo->shouldReceive('getCategory')
->with('mail')
->andReturn([
'mailer' => 'log',
'from_address' => 'test@example.com',
]);
$result = $this->service->check('mail');
$this->assertTrue($result['ready']);
}
/**
* database 채널 — notifications 테이블 존재 시 ready
*/
public function test_database_ready_when_table_exists(): void
{
Schema::shouldReceive('hasTable')
->with('notifications')
->andReturn(true);
$result = $this->service->check('database');
$this->assertTrue($result['ready']);
}
/**
* 알 수 없는 채널은 기본 ready
*/
public function test_unknown_channel_defaults_to_ready(): void
{
$result = $this->service->check('fcm');
$this->assertTrue($result['ready']);
}
/**
* isReady() 편의 메서드
*/
public function test_is_ready_returns_boolean(): void
{
$this->configRepo->shouldReceive('getCategory')
->with('mail')
->andReturn([
'mailer' => 'smtp',
'host' => '',
'port' => 587,
'from_address' => 'test@example.com',
]);
$this->assertFalse($this->service->isReady('mail'));
}
/**
* checkAll() 일괄 체크
*/
public function test_check_all_returns_all_channels(): void
{
$this->configRepo->shouldReceive('getCategory')
->with('mail')
->andReturn([
'mailer' => 'smtp',
'host' => 'smtp.gmail.com',
'port' => 587,
'from_address' => 'test@example.com',
]);
Schema::shouldReceive('hasTable')
->with('notifications')
->andReturn(true);
$results = $this->service->checkAll(['mail', 'database']);
$this->assertArrayHasKey('mail', $results);
$this->assertArrayHasKey('database', $results);
$this->assertTrue($results['mail']['ready']);
$this->assertTrue($results['database']['ready']);
}
/**
* 프로퍼티 캐시 — 동일 채널 반복 호출 시 1회만 체크
*/
public function test_result_is_cached_within_instance(): void
{
$this->configRepo->shouldReceive('getCategory')
->with('mail')
->once() // 1회만 호출되어야 함
->andReturn([
'mailer' => 'smtp',
'host' => 'smtp.gmail.com',
'port' => 587,
'from_address' => 'test@example.com',
]);
$result1 = $this->service->check('mail');
$result2 = $this->service->check('mail');
$result3 = $this->service->isReady('mail');
$this->assertTrue($result1['ready']);
$this->assertSame($result1, $result2);
$this->assertTrue($result3);
}
}
+109 -82
View File
@@ -144,69 +144,15 @@ class CoreUpdateServiceTest extends TestCase
$this->assertTrue($result['check_failed']);
}
// ========================================================================
// buildGithubHeaders() - GitHub API 헤더 생성
// ========================================================================
/**
* 토큰 없이 기본 헤더만 생성되는지 검증합니다.
*/
public function test_build_github_headers_without_token(): void
{
$method = new \ReflectionMethod(CoreUpdateService::class, 'buildGithubHeaders');
$headers = $method->invoke($this->service, '');
$this->assertCount(2, $headers);
$this->assertContains('User-Agent: G7', $headers);
$this->assertContains('Accept: application/vnd.github.v3+json', $headers);
}
/**
* 토큰이 있을 때 Authorization 헤더가 포함되는지 검증합니다.
*/
public function test_build_github_headers_with_token(): void
{
$method = new \ReflectionMethod(CoreUpdateService::class, 'buildGithubHeaders');
$headers = $method->invoke($this->service, 'ghp_test_token_123');
$this->assertCount(3, $headers);
$this->assertContains('Authorization: Bearer ghp_test_token_123', $headers);
}
// ========================================================================
// extractHttpStatusCode() - HTTP 상태 코드 추출
// ========================================================================
/**
* HTTP 응답 헤더에서 상태 코드를 올바르게 추출하는지 검증합니다.
*/
public function test_extract_http_status_code(): void
{
$method = new \ReflectionMethod(CoreUpdateService::class, 'extractHttpStatusCode');
// 일반 200 응답
$this->assertEquals(200, $method->invoke($this->service, ['HTTP/1.1 200 OK']));
// 404 응답
$this->assertEquals(404, $method->invoke($this->service, ['HTTP/1.1 404 Not Found']));
// 리다이렉트 후 최종 상태 코드
$this->assertEquals(200, $method->invoke($this->service, [
'HTTP/1.1 302 Found',
'Location: https://example.com',
'HTTP/1.1 200 OK',
]));
// 빈 헤더
$this->assertEquals(0, $method->invoke($this->service, []));
}
// ========================================================================
// getChangelog() - CHANGELOG.md 파싱
// ========================================================================
// 참고: GitHub API 헤더/상태코드/URL 해석/다운로드 로직은 `GithubHelper`로 이관되어
// `GithubHelperTest`에서 Http::fake() 기반으로 검증합니다. CoreUpdateService에 있던
// buildGithubHeaders / extractHttpStatusCode / resolveGithubArchiveUrl / downloadArchive
// 중복 구현은 제거되었습니다. (`allow_url_fopen=Off` 대응)
/**
* CHANGELOG.md 파일을 파싱하여 올바른 버전 엔트리를 반환하는지 검증합니다.
*/
@@ -529,7 +475,7 @@ MD;
// 파일 내용 검증
$content = File::get($reportPath);
$this->assertStringContainsString('G7 코어 업데이트 실패 리포트', $content);
$this->assertStringContainsString('그누보드7 코어 업데이트 실패 리포트', $content);
$this->assertStringContainsString('시작 버전: 1.0.0', $content);
$this->assertStringContainsString('대상 버전: 2.0.0', $content);
$this->assertStringContainsString('테스트 오류 메시지', $content);
@@ -908,28 +854,6 @@ MD;
$this->assertEquals('Hello World', File::get($extractDir.DIRECTORY_SEPARATOR.'test-dir'.DIRECTORY_SEPARATOR.'hello.txt'));
}
// ========================================================================
// resolveGithubArchiveUrl() — GitHub URL 해석
// ========================================================================
/**
* resolveGithubArchiveUrl이 유효하지 않은 태그에 대해 null을 반환하는지 검증합니다.
*/
public function test_resolve_github_archive_url_returns_null_for_invalid_tag(): void
{
$authHeaders = $this->invokeProtectedMethod($this->service, 'buildGithubHeaders', ['']);
$result = $this->invokeProtectedMethod($this->service, 'resolveGithubArchiveUrl', [
'nonexistent-owner',
'nonexistent-repo',
'999.999.999',
'zipball',
$authHeaders,
]);
$this->assertNull($result);
}
// ========================================================================
// validatePendingUpdate() — 패키지 검증 (G7 프로젝트 확인)
// ========================================================================
@@ -1004,6 +928,109 @@ MD;
return $reflection->invoke($object, ...$args);
}
// ========================================================================
// extractZipToPending() — 외부 ZIP 추출
// ========================================================================
/**
* 평탄 루트 G7 ZIP 을 _pending 으로 추출하고 검증을 통과하는지 확인합니다.
*/
public function test_extract_zip_to_pending_flat_layout(): void
{
if (! class_exists(\ZipArchive::class)) {
$this->markTestSkipped('ZipArchive not available');
}
$pendingBase = storage_path('test_core_zip_pending_'.uniqid());
$this->tempDirs[] = $pendingBase;
File::ensureDirectoryExists($pendingBase);
config(['app.update.pending_path' => $pendingBase]);
$zipDir = storage_path('test_core_zip_src_'.uniqid());
$this->tempDirs[] = $zipDir;
File::ensureDirectoryExists($zipDir);
$zipPath = $zipDir.DIRECTORY_SEPARATOR.'g7.zip';
$zip = new \ZipArchive;
$zip->open($zipPath, \ZipArchive::CREATE);
$zip->addFromString('composer.json', '{"name":"g7/core"}');
$zip->addFromString('app/.gitkeep', '');
$zip->addFromString('config/app.php', "<?php\nreturn ['version' => '9.9.9'];");
$zip->close();
$result = $this->service->extractZipToPending($zipPath);
$this->assertTrue(File::exists($result.DIRECTORY_SEPARATOR.'composer.json'));
$this->assertTrue(File::isDirectory($result.DIRECTORY_SEPARATOR.'app'));
}
/**
* 래퍼 디렉토리(owner-repo-hash/) 를 자동 감지하여 그 내부를 반환하는지 검증합니다.
*/
public function test_extract_zip_to_pending_unwraps_wrapper_directory(): void
{
if (! class_exists(\ZipArchive::class)) {
$this->markTestSkipped('ZipArchive not available');
}
$pendingBase = storage_path('test_core_zip_pending_wrap_'.uniqid());
$this->tempDirs[] = $pendingBase;
File::ensureDirectoryExists($pendingBase);
config(['app.update.pending_path' => $pendingBase]);
$zipDir = storage_path('test_core_zip_wrap_src_'.uniqid());
$this->tempDirs[] = $zipDir;
File::ensureDirectoryExists($zipDir);
$zipPath = $zipDir.DIRECTORY_SEPARATOR.'g7-wrap.zip';
$zip = new \ZipArchive;
$zip->open($zipPath, \ZipArchive::CREATE);
$zip->addFromString('g7-core-abc123/composer.json', '{"name":"g7/core"}');
$zip->addFromString('g7-core-abc123/app/.gitkeep', '');
$zip->addFromString('g7-core-abc123/config/app.php', "<?php\nreturn ['version' => '7.0.1'];");
$zip->close();
$result = $this->service->extractZipToPending($zipPath);
$this->assertStringEndsWith('g7-core-abc123', $result);
$this->assertTrue(File::exists($result.DIRECTORY_SEPARATOR.'composer.json'));
}
/**
* ZIP 파일이 존재하지 않을 때 RuntimeException 이 발생하는지 검증합니다.
*/
public function test_extract_zip_to_pending_throws_when_zip_missing(): void
{
$this->expectException(\RuntimeException::class);
$this->service->extractZipToPending(storage_path('nonexistent_'.uniqid().'.zip'));
}
/**
* ZIP 내용이 G7 패키지가 아닐 때 검증에서 RuntimeException 이 발생하는지 확인합니다.
*/
public function test_extract_zip_to_pending_throws_for_invalid_package(): void
{
if (! class_exists(\ZipArchive::class)) {
$this->markTestSkipped('ZipArchive not available');
}
$pendingBase = storage_path('test_core_zip_pending_invalid_'.uniqid());
$this->tempDirs[] = $pendingBase;
File::ensureDirectoryExists($pendingBase);
config(['app.update.pending_path' => $pendingBase]);
$zipDir = storage_path('test_core_zip_invalid_src_'.uniqid());
$this->tempDirs[] = $zipDir;
File::ensureDirectoryExists($zipDir);
$zipPath = $zipDir.DIRECTORY_SEPARATOR.'invalid.zip';
$zip = new \ZipArchive;
$zip->open($zipPath, \ZipArchive::CREATE);
$zip->addFromString('README.md', '# not g7');
$zip->close();
$this->expectException(\RuntimeException::class);
$this->service->extractZipToPending($zipPath);
}
/**
* applyUpdate가 소스에 없는 파일을 삭제하는지 검증합니다.
*/
@@ -0,0 +1,93 @@
<?php
namespace Tests\Unit\Services;
use App\Extension\Vendor\Exceptions\VendorInstallException;
use App\Extension\Vendor\VendorBundler;
use App\Extension\Vendor\VendorMode;
use App\Services\CoreUpdateService;
use Illuminate\Support\Facades\File;
use Tests\TestCase;
/**
* CoreUpdateService::runVendorInstallInPending() 검증.
*
* VendorResolver 경유로 Composer/Bundled 모드 분기가 올바르게 동작하는지 확인.
*/
class CoreUpdateServiceVendorModeTest extends TestCase
{
private CoreUpdateService $service;
private string $pendingDir;
protected function setUp(): void
{
parent::setUp();
$this->service = app(CoreUpdateService::class);
$this->pendingDir = storage_path('app/test-core-vendor-pending-'.uniqid());
File::ensureDirectoryExists($this->pendingDir);
}
protected function tearDown(): void
{
if (File::isDirectory($this->pendingDir)) {
File::deleteDirectory($this->pendingDir);
}
parent::tearDown();
}
/**
* 테스트용 _pending 디렉토리에 vendor-bundle.zip 생성.
*/
private function createPendingWithBundle(): void
{
File::put($this->pendingDir.'/composer.json', json_encode([
'name' => 'test/core',
'require' => ['php' => '^8.2'],
]));
$zipPath = $this->pendingDir.'/vendor-bundle.zip';
$zip = new \ZipArchive;
$zip->open($zipPath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
$zip->addFromString('vendor/autoload.php', '<?php // test autoload');
$zip->addFromString('vendor/laravel/framework/src/file.php', '<?php // test');
$zip->close();
File::put($this->pendingDir.'/vendor-bundle.json', json_encode([
'schema_version' => VendorBundler::SCHEMA_VERSION,
'zip_sha256' => hash_file('sha256', $zipPath),
'package_count' => 1,
]));
}
public function test_bundled_mode_extracts_vendor_bundle_zip(): void
{
$this->createPendingWithBundle();
$result = $this->service->runVendorInstallInPending($this->pendingDir, VendorMode::Bundled);
$this->assertSame(VendorMode::Bundled, $result->mode);
$this->assertSame('bundled', $result->strategy);
$this->assertFileExists($this->pendingDir.'/vendor/autoload.php');
}
public function test_bundled_mode_fails_when_no_bundle_present(): void
{
File::put($this->pendingDir.'/composer.json', json_encode(['name' => 'test/core']));
$this->expectException(VendorInstallException::class);
$this->service->runVendorInstallInPending($this->pendingDir, VendorMode::Bundled);
}
public function test_auto_mode_prefers_bundle_when_composer_cannot_execute(): void
{
$this->createPendingWithBundle();
// canExecuteComposer를 직접 제어할 수 없으므로 bundle 존재를 전제로
// Auto가 composer 가능하면 composer 콜백을 호출하려 시도할 것이고,
// composer 콜백은 실패할 것 — 대신 bundled로 해결되는 경로를 Bundled 명시로 시뮬레이션
$result = $this->service->runVendorInstallInPending($this->pendingDir, VendorMode::Bundled);
$this->assertSame('bundled', $result->strategy);
}
}
@@ -0,0 +1,731 @@
<?php
namespace Tests\Unit\Services;
use App\Extension\HookManager;
use App\Extension\Storage\CoreStorageDriver;
use App\Extension\Storage\ModuleStorageDriver;
use App\Extension\Storage\PluginStorageDriver;
use App\Services\DriverRegistryService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* 드라이버 확장 시스템 통합 테스트
*
* 플러그인이 필터 훅으로 새 드라이버를 등록했을 때,
* 각 카테고리별로 실제 동작이 정상 수행되는지 검증합니다.
*/
class DriverExtensionIntegrationTest extends TestCase
{
private DriverRegistryService $driverRegistry;
protected function setUp(): void
{
parent::setUp();
$this->driverRegistry = new DriverRegistryService();
// 테스트용 디렉토리 정리
Storage::disk('modules')->deleteDirectory('test-driver-module');
Storage::disk('plugins')->deleteDirectory('test-driver-plugin');
}
protected function tearDown(): void
{
Storage::disk('modules')->deleteDirectory('test-driver-module');
Storage::disk('plugins')->deleteDirectory('test-driver-plugin');
// 캐시 정리
Cache::flush();
HookManager::resetAll();
parent::tearDown();
}
// ========================================================================
// 공통: 플러그인 드라이버 등록 + 사용 가능 여부
// ========================================================================
/**
* 7개 카테고리 모두에 플러그인 드라이버를 등록하면 available 목록에 포함되는지 검증합니다.
*/
#[Test]
public function plugin_can_register_drivers_for_all_categories(): void
{
$categories = ['storage', 'cache', 'session', 'queue', 'log', 'websocket', 'mail'];
foreach ($categories as $category) {
HookManager::addFilter(
"core.settings.available_{$category}_drivers",
function (array $drivers) use ($category) {
$drivers[] = [
'id' => "test_plugin_{$category}",
'label' => ['ko' => "테스트 {$category}", 'en' => "Test {$category}"],
'provider' => 'sirsoft-test_plugin',
];
return $drivers;
}
);
}
foreach ($categories as $category) {
$available = $this->driverRegistry->getAvailableDrivers($category);
$ids = array_column($available, 'id');
$this->assertContains(
"test_plugin_{$category}",
$ids,
"{$category} 카테고리에 플러그인 드라이버가 등록되지 않았습니다."
);
}
}
/**
* 플러그인 드라이버 등록 후 apply_driver_config 액션 훅이 올바른 파라미터로 발행되는지 검증합니다.
*/
#[Test]
public function apply_driver_config_hook_fires_with_correct_params(): void
{
$firedParams = [];
HookManager::addFilter('core.settings.available_cache_drivers', function (array $drivers) {
$drivers[] = [
'id' => 'plugin_redis_cluster',
'label' => ['ko' => 'Redis 클러스터', 'en' => 'Redis Cluster'],
'provider' => 'sirsoft-redis_cluster',
];
return $drivers;
});
HookManager::addAction('core.settings.apply_driver_config', function (string $category, string $driver, array $settings) use (&$firedParams) {
$firedParams = compact('category', 'driver', 'settings');
});
// 시뮬레이션: CoreServiceProvider가 플러그인 드라이버 선택 시 훅 발행
$category = 'cache';
$selectedDriver = 'plugin_redis_cluster';
$settings = ['cache_driver' => 'plugin_redis_cluster'];
if ($this->driverRegistry->isDriverAvailable($category, $selectedDriver)) {
HookManager::doAction('core.settings.apply_driver_config', $category, $selectedDriver, $settings);
}
$this->assertEquals('cache', $firedParams['category']);
$this->assertEquals('plugin_redis_cluster', $firedParams['driver']);
$this->assertEquals(['cache_driver' => 'plugin_redis_cluster'], $firedParams['settings']);
}
// ========================================================================
// Storage 드라이버: 플러그인이 커스텀 스토리지 드라이버를 등록한 경우
// ========================================================================
/**
* 플러그인이 스토리지 드라이버를 등록하고, apply_driver_config으로 Config을 적용하면
* 코어 StorageDriver로 실제 파일 읽기/쓰기가 가능한지 검증합니다.
*/
#[Test]
public function storage_driver_plugin_core_file_read_write(): void
{
$this->registerStoragePlugin();
$this->applyPluginStorageConfig();
// 코어 StorageDriver로 파일 쓰기/읽기
$coreStorage = new CoreStorageDriver(Config::get('filesystems.default'));
$coreStorage->put('temp', 'core-test.txt', 'core-content');
$this->assertTrue($coreStorage->exists('temp', 'core-test.txt'));
$this->assertEquals('core-content', $coreStorage->get('temp', 'core-test.txt'));
// 정리
$coreStorage->delete('temp', 'core-test.txt');
}
/**
* 플러그인 스토리지 드라이버 등록 후 모듈 StorageDriver로 파일 읽기/쓰기가 가능한지 검증합니다.
*/
#[Test]
public function storage_driver_plugin_module_file_read_write(): void
{
// 모듈은 자체 disk('modules')를 사용하므로 filesystems.default 변경과 독립
$moduleStorage = new ModuleStorageDriver('test-driver-module', 'modules');
$moduleStorage->put('attachments', 'module-file.txt', 'module-content-123');
$this->assertTrue($moduleStorage->exists('attachments', 'module-file.txt'));
$this->assertEquals('module-content-123', $moduleStorage->get('attachments', 'module-file.txt'));
// 다른 카테고리도 격리 확인
$moduleStorage->put('settings', 'config.json', '{"key": "value"}');
$this->assertEquals('{"key": "value"}', $moduleStorage->get('settings', 'config.json'));
// 파일 목록 확인
$files = $moduleStorage->files('attachments');
$this->assertNotEmpty($files);
}
/**
* 플러그인 StorageDriver로 자체 파일 읽기/쓰기가 가능한지 검증합니다.
*/
#[Test]
public function storage_driver_plugin_own_file_read_write(): void
{
$pluginStorage = new PluginStorageDriver('test-driver-plugin', 'plugins');
$pluginStorage->put('data', 'analytics.json', '{"visits": 100}');
$this->assertTrue($pluginStorage->exists('data', 'analytics.json'));
$this->assertEquals('{"visits": 100}', $pluginStorage->get('data', 'analytics.json'));
// 삭제 검증
$pluginStorage->delete('data', 'analytics.json');
$this->assertFalse($pluginStorage->exists('data', 'analytics.json'));
}
/**
* 스토리지 드라이버 변경 시 모듈/플러그인 StorageDriver 경로가 격리되는지 검증합니다.
*/
#[Test]
public function storage_driver_change_does_not_affect_module_plugin_isolation(): void
{
$moduleStorage = new ModuleStorageDriver('test-driver-module', 'modules');
$pluginStorage = new PluginStorageDriver('test-driver-plugin', 'plugins');
// 동일 파일명이지만 격리된 경로
$moduleStorage->put('settings', 'shared-name.txt', 'module-data');
$pluginStorage->put('settings', 'shared-name.txt', 'plugin-data');
$this->assertEquals('module-data', $moduleStorage->get('settings', 'shared-name.txt'));
$this->assertEquals('plugin-data', $pluginStorage->get('settings', 'shared-name.txt'));
// 기본 스토리지 드라이버 변경이 모듈/플러그인에 영향 없음
Config::set('filesystems.default', 'local');
$this->assertEquals('module-data', $moduleStorage->get('settings', 'shared-name.txt'));
$this->assertEquals('plugin-data', $pluginStorage->get('settings', 'shared-name.txt'));
}
// ========================================================================
// Cache 드라이버: 플러그인이 커스텀 캐시 드라이버를 등록한 경우
// ========================================================================
/**
* 기본 캐시 드라이버(file)로 코어 캐시 읽기/쓰기가 동작하는지 검증합니다.
*/
#[Test]
public function cache_driver_core_read_write(): void
{
Cache::put('core_test_key', 'core_value', 60);
$this->assertEquals('core_value', Cache::get('core_test_key'));
Cache::forget('core_test_key');
$this->assertNull(Cache::get('core_test_key'));
}
/**
* 플러그인이 캐시 드라이버를 등록하고, 액션 훅으로 Config을 적용하면
* cache store가 전환되는지 검증합니다.
*/
#[Test]
public function cache_driver_plugin_registration_and_config_application(): void
{
HookManager::addFilter('core.settings.available_cache_drivers', function (array $drivers) {
$drivers[] = [
'id' => 'array_custom',
'label' => ['ko' => '어레이 커스텀', 'en' => 'Array Custom'],
'provider' => 'sirsoft-array_cache',
];
return $drivers;
});
// 플러그인이 액션 훅에서 Config 적용
HookManager::addAction('core.settings.apply_driver_config', function (string $category, string $driver, array $settings) {
if ($category === 'cache' && $driver === 'array_custom') {
Config::set('cache.default', 'array');
}
});
$this->assertTrue($this->driverRegistry->isDriverAvailable('cache', 'array_custom'));
// 액션 훅 발행 시뮬레이션
HookManager::doAction('core.settings.apply_driver_config', 'cache', 'array_custom', ['cache_driver' => 'array_custom']);
$this->assertEquals('array', Config::get('cache.default'));
// array 드라이버로 실제 캐시 동작 검증
Cache::store('array')->put('plugin_test', 'plugin_value', 60);
$this->assertEquals('plugin_value', Cache::store('array')->get('plugin_test'));
}
/**
* 모듈/플러그인이 자체 캐시 키 네임스페이스로 독립적으로 캐시를 사용하는지 검증합니다.
*/
#[Test]
public function cache_driver_module_plugin_isolation(): void
{
// 코어, 모듈, 플러그인이 동일 캐시 드라이버를 사용해도 키로 격리
Cache::put('core:settings:version', '1.0', 60);
Cache::put('module:sirsoft-ecommerce:products_count', 42, 60);
Cache::put('plugin:sirsoft-payment:config', '{"key": "secret"}', 60);
$this->assertEquals('1.0', Cache::get('core:settings:version'));
$this->assertEquals(42, Cache::get('module:sirsoft-ecommerce:products_count'));
$this->assertEquals('{"key": "secret"}', Cache::get('plugin:sirsoft-payment:config'));
// 코어 캐시 삭제가 모듈/플러그인에 영향 없음
Cache::forget('core:settings:version');
$this->assertNull(Cache::get('core:settings:version'));
$this->assertEquals(42, Cache::get('module:sirsoft-ecommerce:products_count'));
}
// ========================================================================
// Session 드라이버: 플러그인이 커스텀 세션 드라이버를 등록한 경우
// ========================================================================
/**
* 플러그인이 세션 드라이버를 등록하고 Config이 적용되는지 검증합니다.
*/
#[Test]
public function session_driver_plugin_registration_and_config(): void
{
HookManager::addFilter('core.settings.available_session_drivers', function (array $drivers) {
$drivers[] = [
'id' => 'custom_session',
'label' => ['ko' => '커스텀 세션', 'en' => 'Custom Session'],
'provider' => 'sirsoft-session_plugin',
];
return $drivers;
});
$this->assertTrue($this->driverRegistry->isDriverAvailable('session', 'custom_session'));
$this->assertFalse($this->driverRegistry->isCoreDriver('session', 'custom_session'));
// Config 적용 시뮬레이션
HookManager::addAction('core.settings.apply_driver_config', function (string $category, string $driver, array $settings) {
if ($category === 'session' && $driver === 'custom_session') {
Config::set('session.driver', 'array');
Config::set('session.lifetime', 180);
}
});
HookManager::doAction('core.settings.apply_driver_config', 'session', 'custom_session', []);
$this->assertEquals('array', Config::get('session.driver'));
$this->assertEquals(180, Config::get('session.lifetime'));
}
/**
* 세션 드라이버 변경 후 실제 세션 읽기/쓰기가 동작하는지 검증합니다.
*/
#[Test]
public function session_driver_actual_read_write_after_config(): void
{
// array 드라이버로 세션 테스트 (외부 의존성 없음)
Config::set('session.driver', 'array');
$session = app('session.store');
$session->put('test_key', 'session_value');
$this->assertEquals('session_value', $session->get('test_key'));
$session->forget('test_key');
$this->assertNull($session->get('test_key'));
}
// ========================================================================
// Queue 드라이버: 플러그인이 커스텀 큐 드라이버를 등록한 경우
// ========================================================================
/**
* 플러그인이 큐 드라이버를 등록하고 Config이 적용되는지 검증합니다.
*/
#[Test]
public function queue_driver_plugin_registration_and_config(): void
{
HookManager::addFilter('core.settings.available_queue_drivers', function (array $drivers) {
$drivers[] = [
'id' => 'custom_queue',
'label' => ['ko' => '커스텀 큐', 'en' => 'Custom Queue'],
'provider' => 'sirsoft-queue_plugin',
];
return $drivers;
});
$this->assertTrue($this->driverRegistry->isDriverAvailable('queue', 'custom_queue'));
// Config 적용 시뮬레이션
HookManager::addAction('core.settings.apply_driver_config', function (string $category, string $driver, array $settings) {
if ($category === 'queue' && $driver === 'custom_queue') {
Config::set('queue.default', 'sync');
}
});
HookManager::doAction('core.settings.apply_driver_config', 'queue', 'custom_queue', []);
$this->assertEquals('sync', Config::get('queue.default'));
}
/**
* sync 큐 드라이버로 Config이 올바르게 적용되는지 검증합니다.
*/
#[Test]
public function queue_driver_sync_config_applied(): void
{
Config::set('queue.default', 'sync');
$this->assertEquals('sync', Config::get('queue.default'));
// sync 드라이버 커넥션이 유효한지 확인
$connection = app('queue')->connection('sync');
$this->assertNotNull($connection);
}
// ========================================================================
// Log 드라이버: 플러그인이 커스텀 로그 드라이버를 등록한 경우
// ========================================================================
/**
* 플러그인이 로그 드라이버를 등록하고 Config이 적용되는지 검증합니다.
*/
#[Test]
public function log_driver_plugin_registration_and_config(): void
{
HookManager::addFilter('core.settings.available_log_drivers', function (array $drivers) {
$drivers[] = [
'id' => 'custom_log',
'label' => ['ko' => '커스텀 로그', 'en' => 'Custom Log'],
'provider' => 'sirsoft-log_plugin',
];
return $drivers;
});
$this->assertTrue($this->driverRegistry->isDriverAvailable('log', 'custom_log'));
// 플러그인이 커스텀 채널 등록
HookManager::addAction('core.settings.apply_driver_config', function (string $category, string $driver, array $settings) {
if ($category === 'log' && $driver === 'custom_log') {
Config::set('logging.channels.custom_log', [
'driver' => 'single',
'path' => storage_path('logs/custom_plugin.log'),
'level' => 'debug',
]);
Config::set('logging.channels.stack.channels', ['custom_log']);
}
});
HookManager::doAction('core.settings.apply_driver_config', 'log', 'custom_log', []);
$channels = Config::get('logging.channels.stack.channels');
$this->assertContains('custom_log', $channels);
$this->assertNotNull(Config::get('logging.channels.custom_log'));
}
/**
* 커스텀 로그 채널로 실제 로그 기록이 동작하는지 검증합니다.
*/
#[Test]
public function log_driver_actual_write_to_custom_channel(): void
{
$logPath = storage_path('logs/driver_test.log');
// 파일 정리
if (file_exists($logPath)) {
unlink($logPath);
}
Config::set('logging.channels.driver_test', [
'driver' => 'single',
'path' => $logPath,
'level' => 'debug',
]);
Log::channel('driver_test')->info('플러그인 드라이버 로그 테스트', ['source' => 'integration_test']);
$this->assertFileExists($logPath);
$logContent = file_get_contents($logPath);
$this->assertStringContainsString('플러그인 드라이버 로그 테스트', $logContent);
$this->assertStringContainsString('integration_test', $logContent);
// 정리
unlink($logPath);
}
// ========================================================================
// WebSocket 드라이버: 플러그인이 커스텀 웹소켓 드라이버를 등록한 경우
// ========================================================================
/**
* 플러그인이 웹소켓 드라이버를 등록하고 Config이 적용되는지 검증합니다.
*/
#[Test]
public function websocket_driver_plugin_registration_and_config(): void
{
HookManager::addFilter('core.settings.available_websocket_drivers', function (array $drivers) {
$drivers[] = [
'id' => 'custom_ws',
'label' => ['ko' => '커스텀 웹소켓', 'en' => 'Custom WebSocket'],
'provider' => 'sirsoft-ws_plugin',
];
return $drivers;
});
$this->assertTrue($this->driverRegistry->isDriverAvailable('websocket', 'custom_ws'));
// 플러그인이 웹소켓 Config 적용
HookManager::addAction('core.settings.apply_driver_config', function (string $category, string $driver, array $settings) {
if ($category === 'websocket' && $driver === 'custom_ws') {
Config::set('broadcasting.default', 'custom_ws');
Config::set('broadcasting.connections.custom_ws', [
'driver' => 'pusher',
'key' => 'custom-app-key',
'options' => [
'host' => 'ws.custom-provider.com',
'port' => 6001,
'scheme' => 'wss',
],
]);
}
});
HookManager::doAction('core.settings.apply_driver_config', 'websocket', 'custom_ws', []);
$this->assertEquals('custom_ws', Config::get('broadcasting.default'));
$this->assertEquals('ws.custom-provider.com', Config::get('broadcasting.connections.custom_ws.options.host'));
$this->assertEquals(6001, Config::get('broadcasting.connections.custom_ws.options.port'));
}
// ========================================================================
// Mail 드라이버: 플러그인이 커스텀 메일 드라이버를 등록한 경우
// ========================================================================
/**
* 플러그인이 메일 드라이버를 등록하고 Config이 적용되는지 검증합니다.
*/
#[Test]
public function mail_driver_plugin_registration_and_config(): void
{
HookManager::addFilter('core.settings.available_mail_drivers', function (array $drivers) {
$drivers[] = [
'id' => 'custom_mail_api',
'label' => ['ko' => '커스텀 메일 API', 'en' => 'Custom Mail API'],
'provider' => 'sirsoft-custom_mail',
];
return $drivers;
});
$this->assertTrue($this->driverRegistry->isDriverAvailable('mail', 'custom_mail_api'));
// 플러그인이 메일 Config 적용
HookManager::addAction('core.settings.apply_driver_config', function (string $category, string $driver, array $settings) {
if ($category === 'mail' && $driver === 'custom_mail_api') {
Config::set('mail.default', 'custom_mail_api');
Config::set('mail.mailers.custom_mail_api', [
'transport' => 'log', // 테스트에서는 log transport 사용
]);
}
});
HookManager::doAction('core.settings.apply_driver_config', 'mail', 'custom_mail_api', ['mailer' => 'custom_mail_api']);
$this->assertEquals('custom_mail_api', Config::get('mail.default'));
$this->assertEquals('log', Config::get('mail.mailers.custom_mail_api.transport'));
}
/**
* 커스텀 메일 드라이버(log transport)로 실제 메일 발송이 동작하는지 검증합니다.
*/
#[Test]
public function mail_driver_actual_send_with_log_transport(): void
{
Config::set('mail.mailers.test_mailer', [
'transport' => 'log',
]);
// log transport는 실제 발송 없이 로그에 기록
$mailer = app('mail.manager')->mailer('test_mailer');
$this->assertNotNull($mailer);
}
// ========================================================================
// 폴백 시나리오: 플러그인 드라이버 사용 불가 시 기본 드라이버로 복원
// ========================================================================
/**
* 각 카테고리에서 플러그인 드라이버가 사용 불가능하면 기본 드라이버로 폴백하는지 검증합니다.
*/
#[Test]
public function fallback_to_default_driver_for_all_categories(): void
{
$expectedDefaults = [
'storage' => ['local', 'filesystems.default'],
'cache' => ['file', 'cache.default'],
'session' => ['database', 'session.driver'],
'queue' => ['database', 'queue.default'],
'log' => ['daily', null],
'websocket' => ['', null],
'mail' => ['smtp', 'mail.default'],
];
foreach ($expectedDefaults as $category => [$defaultDriver, $configKey]) {
// 등록되지 않은 드라이버 선택 시
$unavailable = "nonexistent_{$category}_driver";
$this->assertFalse(
$this->driverRegistry->isDriverAvailable($category, $unavailable),
"'{$unavailable}'가 {$category}에서 available로 잘못 판별됩니다."
);
// 폴백 드라이버 확인
$this->assertEquals(
$defaultDriver,
$this->driverRegistry->getDefaultDriver($category),
"{$category} 카테고리의 기본 드라이버가 '{$defaultDriver}'가 아닙니다."
);
// Config 폴백 적용 검증
if ($configKey && $defaultDriver) {
Config::set($configKey, $defaultDriver);
$this->assertEquals($defaultDriver, Config::get($configKey));
}
}
}
/**
* 스토리지 폴백 후 코어/모듈/플러그인 파일 조작이 여전히 정상 동작하는지 검증합니다.
*/
#[Test]
public function storage_fallback_preserves_file_operations(): void
{
// 존재하지 않는 드라이버에서 기본값 'local'로 폴백
Config::set('filesystems.default', 'local');
$coreStorage = new CoreStorageDriver('local');
$moduleStorage = new ModuleStorageDriver('test-driver-module', 'modules');
$pluginStorage = new PluginStorageDriver('test-driver-plugin', 'plugins');
// 코어
$coreStorage->put('temp', 'fallback-core.txt', 'core-fallback');
$this->assertEquals('core-fallback', $coreStorage->get('temp', 'fallback-core.txt'));
$coreStorage->delete('temp', 'fallback-core.txt');
// 모듈
$moduleStorage->put('temp', 'fallback-module.txt', 'module-fallback');
$this->assertEquals('module-fallback', $moduleStorage->get('temp', 'fallback-module.txt'));
// 플러그인
$pluginStorage->put('temp', 'fallback-plugin.txt', 'plugin-fallback');
$this->assertEquals('plugin-fallback', $pluginStorage->get('temp', 'fallback-plugin.txt'));
}
/**
* 캐시 폴백 후 캐시 조작이 여전히 정상 동작하는지 검증합니다.
*/
#[Test]
public function cache_fallback_preserves_cache_operations(): void
{
// 기본값 'file'로 폴백
Config::set('cache.default', 'file');
Cache::put('fallback_test', 'fallback_value', 60);
$this->assertEquals('fallback_value', Cache::get('fallback_test'));
Cache::forget('fallback_test');
$this->assertNull(Cache::get('fallback_test'));
}
// ========================================================================
// 복수 플러그인 동시 등록
// ========================================================================
/**
* 여러 플러그인이 같은 카테고리에 드라이버를 등록해도 모두 목록에 포함되는지 검증합니다.
*/
#[Test]
public function multiple_plugins_can_register_drivers_in_same_category(): void
{
HookManager::addFilter('core.settings.available_cache_drivers', function (array $drivers) {
$drivers[] = [
'id' => 'plugin_a_cache',
'label' => ['ko' => 'A 캐시', 'en' => 'A Cache'],
'provider' => 'sirsoft-plugin_a',
];
return $drivers;
});
HookManager::addFilter('core.settings.available_cache_drivers', function (array $drivers) {
$drivers[] = [
'id' => 'plugin_b_cache',
'label' => ['ko' => 'B 캐시', 'en' => 'B Cache'],
'provider' => 'sirsoft-plugin_b',
];
return $drivers;
});
$cacheDrivers = $this->driverRegistry->getAvailableDrivers('cache');
$ids = array_column($cacheDrivers, 'id');
// 코어 + 플러그인 A + 플러그인 B 모두 포함
$this->assertContains('file', $ids);
$this->assertContains('redis', $ids);
$this->assertContains('plugin_a_cache', $ids);
$this->assertContains('plugin_b_cache', $ids);
}
// ========================================================================
// Helper Methods
// ========================================================================
/**
* 테스트용 스토리지 플러그인을 등록합니다.
*/
private function registerStoragePlugin(): void
{
HookManager::addFilter('core.settings.available_storage_drivers', function (array $drivers) {
$drivers[] = [
'id' => 'plugin_local_extended',
'label' => ['ko' => '확장 로컬', 'en' => 'Extended Local'],
'provider' => 'sirsoft-storage_ext',
];
return $drivers;
});
HookManager::addAction('core.settings.apply_driver_config', function (string $category, string $driver, array $settings) {
if ($category === 'storage' && $driver === 'plugin_local_extended') {
// 플러그인이 커스텀 디스크 등록 + filesystems.default 변경
Config::set('filesystems.disks.plugin_local_extended', [
'driver' => 'local',
'root' => storage_path('app/private'),
'throw' => true,
]);
Config::set('filesystems.default', 'plugin_local_extended');
}
});
}
/**
* 등록된 스토리지 플러그인의 Config을 적용합니다.
*/
private function applyPluginStorageConfig(): void
{
$category = 'storage';
$selectedDriver = 'plugin_local_extended';
if ($this->driverRegistry->isDriverAvailable($category, $selectedDriver)) {
HookManager::doAction('core.settings.apply_driver_config', $category, $selectedDriver, [
'storage_driver' => $selectedDriver,
]);
}
}
}
@@ -0,0 +1,249 @@
<?php
namespace Tests\Unit\Services;
use App\Extension\HookManager;
use App\Services\DriverRegistryService;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* DriverRegistryService 단위 테스트
*
* 코어 드라이버 레지스트리의 핵심 기능을 검증합니다:
* - 코어 드라이버 반환
* - 필터 훅 통합
* - 코어 드라이버 판별
* - 사용 가능 여부 확인
* - 기본 폴백 드라이버
*/
class DriverRegistryServiceTest extends TestCase
{
private DriverRegistryService $service;
protected function setUp(): void
{
parent::setUp();
$this->service = new DriverRegistryService();
}
protected function tearDown(): void
{
// 테스트에서 등록한 필터 훅 정리
HookManager::resetAll();
parent::tearDown();
}
/**
* 코어 드라이버가 7개 카테고리를 모두 포함하는지 검증합니다.
*/
#[Test]
public function it_returns_all_seven_categories(): void
{
$categories = $this->service->getCategories();
$this->assertCount(7, $categories);
$this->assertEquals(
['storage', 'cache', 'session', 'queue', 'log', 'websocket', 'mail'],
$categories
);
}
/**
* 각 카테고리별 코어 드라이버가 올바르게 반환되는지 검증합니다.
*/
#[Test]
public function it_returns_core_drivers_for_each_category(): void
{
$storageDrivers = $this->service->getAvailableDrivers('storage');
$driverIds = array_column($storageDrivers, 'id');
$this->assertContains('local', $driverIds);
$this->assertContains('s3', $driverIds);
}
/**
* 메일 카테고리 코어 드라이버를 검증합니다.
*/
#[Test]
public function it_returns_mail_core_drivers(): void
{
$mailDrivers = $this->service->getAvailableDrivers('mail');
$driverIds = array_column($mailDrivers, 'id');
$this->assertContains('smtp', $driverIds);
$this->assertContains('mailgun', $driverIds);
$this->assertContains('ses', $driverIds);
}
/**
* 모든 카테고리의 드라이버를 한 번에 반환하는지 검증합니다.
*/
#[Test]
public function it_returns_all_available_drivers_at_once(): void
{
$all = $this->service->getAllAvailableDrivers();
$this->assertArrayHasKey('storage', $all);
$this->assertArrayHasKey('cache', $all);
$this->assertArrayHasKey('session', $all);
$this->assertArrayHasKey('queue', $all);
$this->assertArrayHasKey('log', $all);
$this->assertArrayHasKey('websocket', $all);
$this->assertArrayHasKey('mail', $all);
$this->assertCount(7, $all);
}
/**
* 코어 드라이버 판별이 올바르게 동작하는지 검증합니다.
*/
#[Test]
public function it_identifies_core_drivers_correctly(): void
{
$this->assertTrue($this->service->isCoreDriver('storage', 'local'));
$this->assertTrue($this->service->isCoreDriver('storage', 's3'));
$this->assertTrue($this->service->isCoreDriver('mail', 'smtp'));
$this->assertFalse($this->service->isCoreDriver('storage', 'custom_storage'));
$this->assertFalse($this->service->isCoreDriver('mail', 'custom_api'));
$this->assertFalse($this->service->isCoreDriver('nonexistent', 'local'));
}
/**
* 코어 드라이버의 사용 가능 여부가 true로 반환되는지 검증합니다.
*/
#[Test]
public function it_reports_core_drivers_as_available(): void
{
$this->assertTrue($this->service->isDriverAvailable('cache', 'file'));
$this->assertTrue($this->service->isDriverAvailable('cache', 'redis'));
$this->assertTrue($this->service->isDriverAvailable('session', 'database'));
}
/**
* 등록되지 않은 드라이버가 사용 불가로 판별되는지 검증합니다.
*/
#[Test]
public function it_reports_unregistered_drivers_as_unavailable(): void
{
$this->assertFalse($this->service->isDriverAvailable('cache', 'custom_cache'));
$this->assertFalse($this->service->isDriverAvailable('mail', 'custom_api'));
}
/**
* 카테고리별 기본 폴백 드라이버가 올바르게 반환되는지 검증합니다.
*/
#[Test]
public function it_returns_correct_default_drivers(): void
{
$this->assertEquals('local', $this->service->getDefaultDriver('storage'));
$this->assertEquals('file', $this->service->getDefaultDriver('cache'));
$this->assertEquals('database', $this->service->getDefaultDriver('session'));
$this->assertEquals('database', $this->service->getDefaultDriver('queue'));
$this->assertEquals('daily', $this->service->getDefaultDriver('log'));
$this->assertEquals('', $this->service->getDefaultDriver('websocket'));
$this->assertEquals('smtp', $this->service->getDefaultDriver('mail'));
}
/**
* 존재하지 않는 카테고리의 기본 드라이버가 빈 문자열인지 검증합니다.
*/
#[Test]
public function it_returns_empty_string_for_unknown_category_default(): void
{
$this->assertEquals('', $this->service->getDefaultDriver('nonexistent'));
}
/**
* 필터 훅으로 플러그인 드라이버가 추가되는지 검증합니다.
*/
#[Test]
public function it_includes_plugin_drivers_via_filter_hook(): void
{
// 플러그인이 메일 드라이버를 추가하는 필터 훅 등록
HookManager::addFilter('core.settings.available_mail_drivers', function (array $drivers) {
$drivers[] = [
'id' => 'custom_api',
'label' => ['ko' => '커스텀 API', 'en' => 'Custom API'],
'provider' => 'sirsoft-custom_mail',
];
return $drivers;
});
$mailDrivers = $this->service->getAvailableDrivers('mail');
$driverIds = array_column($mailDrivers, 'id');
// 코어 드라이버 + 플러그인 드라이버
$this->assertContains('smtp', $driverIds);
$this->assertContains('mailgun', $driverIds);
$this->assertContains('ses', $driverIds);
$this->assertContains('custom_api', $driverIds);
}
/**
* 필터 훅으로 추가된 플러그인 드라이버가 사용 가능으로 판별되는지 검증합니다.
*/
#[Test]
public function it_reports_plugin_drivers_as_available_after_hook_registration(): void
{
$this->assertFalse($this->service->isDriverAvailable('cache', 'custom_cache'));
HookManager::addFilter('core.settings.available_cache_drivers', function (array $drivers) {
$drivers[] = [
'id' => 'custom_cache',
'label' => ['ko' => '커스텀 캐시', 'en' => 'Custom Cache'],
'provider' => 'sirsoft-custom_cache',
];
return $drivers;
});
$this->assertTrue($this->service->isDriverAvailable('cache', 'custom_cache'));
}
/**
* 드라이버 데이터에 다국어 label이 포함되는지 검증합니다.
*/
#[Test]
public function it_includes_localized_labels_in_driver_data(): void
{
$storageDrivers = $this->service->getAvailableDrivers('storage');
foreach ($storageDrivers as $driver) {
$this->assertArrayHasKey('id', $driver);
$this->assertArrayHasKey('label', $driver);
$this->assertArrayHasKey('ko', $driver['label']);
$this->assertArrayHasKey('en', $driver['label']);
}
}
/**
* 카테고리별 설정 키 정보가 올바르게 반환되는지 검증합니다.
*/
#[Test]
public function it_returns_settings_key_for_each_category(): void
{
$storageKey = $this->service->getSettingsKey('storage');
$this->assertEquals(['category' => 'drivers', 'key' => 'storage_driver'], $storageKey);
$mailKey = $this->service->getSettingsKey('mail');
$this->assertEquals(['category' => 'mail', 'key' => 'mailer'], $mailKey);
$this->assertNull($this->service->getSettingsKey('nonexistent'));
}
/**
* 카테고리별 Laravel Config 키가 올바르게 반환되는지 검증합니다.
*/
#[Test]
public function it_returns_config_key_for_each_category(): void
{
$this->assertEquals('filesystems.default', $this->service->getConfigKey('storage'));
$this->assertEquals('cache.default', $this->service->getConfigKey('cache'));
$this->assertEquals('session.driver', $this->service->getConfigKey('session'));
$this->assertEquals('queue.default', $this->service->getConfigKey('queue'));
$this->assertEquals('mail.default', $this->service->getConfigKey('mail'));
$this->assertNull($this->service->getConfigKey('nonexistent'));
}
}
@@ -0,0 +1,175 @@
<?php
namespace Tests\Unit\Services\GeoIp;
use App\Contracts\Repositories\ConfigRepositoryInterface;
use App\Services\GeoIpDatabaseService;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use Mockery;
use Tests\TestCase;
/**
* GeoIpDatabaseService 단위 테스트.
*
* HTTP 호출은 Http::fake로 모킹하고, 파일시스템 조작은 실제
* storage/framework/testing/ 하위 임시 디렉토리에서 수행합니다.
*/
class GeoIpDatabaseServiceTest extends TestCase
{
private string $testGeoipDir;
protected function setUp(): void
{
parent::setUp();
$this->testGeoipDir = storage_path('framework/testing/geoip-test-'.uniqid());
config([
'geoip.database_path' => $this->testGeoipDir.'/GeoLite2-City.mmdb',
// 테스트 시 retry 지연 최소화 (실제 운영은 config/geoip.php 기본값 사용)
'geoip.download.retry_attempts' => 1,
'geoip.download.retry_delay_ms' => 1,
]);
if (File::isDirectory($this->testGeoipDir)) {
File::deleteDirectory($this->testGeoipDir);
}
}
protected function tearDown(): void
{
if (File::isDirectory($this->testGeoipDir)) {
File::deleteDirectory($this->testGeoipDir);
}
Mockery::close();
parent::tearDown();
}
/**
* 서비스 인스턴스를 생성합니다 (ConfigRepository는 mock).
*/
private function makeService(?ConfigRepositoryInterface $configRepo = null): GeoIpDatabaseService
{
$configRepo ??= Mockery::mock(ConfigRepositoryInterface::class)
->shouldReceive('getCategory')->with('cache')->andReturn([])->byDefault()
->shouldReceive('saveCategory')->andReturn(true)->byDefault()
->getMock();
return new GeoIpDatabaseService($configRepo);
}
public function test_missing_license_key_returns_error(): void
{
config(['geoip.license_key' => '']);
$service = $this->makeService();
$result = $service->updateDatabase();
$this->assertFalse($result['success']);
$this->assertEquals('missing_license_key', $result['status']);
}
public function test_is_license_key_configured_reflects_config(): void
{
$service = $this->makeService();
config(['geoip.license_key' => '']);
$this->assertFalse($service->isLicenseKeyConfigured());
config(['geoip.license_key' => 'abcd1234']);
$this->assertTrue($service->isLicenseKeyConfigured());
}
public function test_build_download_url_masks_license_key(): void
{
config(['geoip.license_key' => 'secretKey1234567890']);
$service = $this->makeService();
$masked = $service->buildDownloadUrlForDisplay(true);
$this->assertStringContainsString('secr', $masked);
$this->assertStringNotContainsString('secretKey1234567890', $masked);
$this->assertStringContainsString('****', $masked);
}
public function test_mask_key_keeps_first_four_chars(): void
{
$service = $this->makeService();
$this->assertEquals('abcd*****', $service->maskKey('abcd12345'));
$this->assertEquals('****', $service->maskKey('abcd'));
$this->assertEquals('**', $service->maskKey('ab'));
}
public function test_update_skipped_when_recently_updated_without_force(): void
{
config(['geoip.license_key' => 'abcd1234']);
File::makeDirectory($this->testGeoipDir, 0755, true);
$mmdbPath = $this->testGeoipDir.'/GeoLite2-City.mmdb';
File::put($mmdbPath, 'dummy-mmdb-content');
$service = $this->makeService();
$result = $service->updateDatabase(false);
$this->assertTrue($result['success']);
$this->assertEquals('skipped', $result['status']);
$this->assertArrayHasKey('data', $result);
}
public function test_update_unauthorized_on_http_401(): void
{
config(['geoip.license_key' => 'invalid_key']);
Http::fake([
'download.maxmind.com/*' => Http::response('', 401),
]);
$service = $this->makeService();
$result = $service->updateDatabase(true);
$this->assertFalse($result['success']);
$this->assertEquals('unauthorized', $result['status']);
$this->assertStringContainsString('401', $result['message']);
}
public function test_update_download_failed_on_http_500(): void
{
config(['geoip.license_key' => 'validkey123']);
Http::fake([
'download.maxmind.com/*' => Http::response('', 500),
]);
$service = $this->makeService();
$result = $service->updateDatabase(true);
$this->assertFalse($result['success']);
$this->assertEquals('download_failed', $result['status']);
}
public function test_get_database_status_returns_missing_when_file_absent(): void
{
$service = $this->makeService();
$status = $service->getDatabaseStatus();
$this->assertFalse($status['exists']);
$this->assertEquals(0, $status['file_size_bytes']);
$this->assertNull($status['last_updated_at']);
}
public function test_get_database_status_returns_metadata_when_file_exists(): void
{
File::makeDirectory($this->testGeoipDir, 0755, true);
$mmdbPath = $this->testGeoipDir.'/GeoLite2-City.mmdb';
File::put($mmdbPath, str_repeat('x', 1024));
$service = $this->makeService();
$status = $service->getDatabaseStatus();
$this->assertTrue($status['exists']);
$this->assertEquals(1024, $status['file_size_bytes']);
$this->assertNotNull($status['last_updated_at']);
}
}
@@ -1988,6 +1988,105 @@ class LayoutExtensionServiceTest extends TestCase
$this->assertArrayHasKey('onAddressSelect', $injectedComponent['extensionPointProps']);
}
/**
* extension_point의 callbacks가 주입 컴포넌트에 extensionPointCallbacks로 전달되는지 테스트
*/
public function test_passes_extension_point_callbacks_to_injected_components(): void
{
LayoutExtension::create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::ExtensionPoint,
'target_name' => 'editor_slot',
'source_type' => LayoutSourceType::Plugin,
'source_identifier' => 'sirsoft-test',
'content' => [
'extension_point' => 'editor_slot',
'components' => [
[
'id' => 'editor_container',
'type' => 'basic',
'name' => 'Div',
],
],
],
'is_active' => true,
]);
$layout = [
'layout_name' => 'test_form',
'components' => [
[
'id' => 'form_editor_slot',
'type' => 'extension_point',
'name' => 'editor_slot',
'props' => [
'readOnlyFields' => ['content'],
],
'callbacks' => [
'onContentChange' => [
'handler' => 'setState',
'params' => ['target' => 'local', 'form.content' => '{{$event}}'],
],
],
],
],
'data_sources' => [],
];
$result = $this->service->applyExtensions($layout, $this->template->id);
$injectedComponent = $result['components'][0]['children'][0];
// props가 extensionPointProps로 전달되었는지 확인
$this->assertArrayHasKey('extensionPointProps', $injectedComponent);
$this->assertEquals(['content'], $injectedComponent['extensionPointProps']['readOnlyFields']);
// callbacks가 extensionPointCallbacks로 전달되었는지 확인
$this->assertArrayHasKey('extensionPointCallbacks', $injectedComponent);
$this->assertEquals('setState', $injectedComponent['extensionPointCallbacks']['onContentChange']['handler']);
$this->assertEquals('{{$event}}', $injectedComponent['extensionPointCallbacks']['onContentChange']['params']['form.content']);
}
/**
* callbacks가 없는 extension_point에서 extensionPointCallbacks가 생성되지 않는지 테스트
*/
public function test_no_callbacks_key_when_extension_point_has_no_callbacks(): void
{
LayoutExtension::create([
'template_id' => $this->template->id,
'extension_type' => LayoutExtensionType::ExtensionPoint,
'target_name' => 'simple_slot',
'source_type' => LayoutSourceType::Plugin,
'source_identifier' => 'sirsoft-test',
'content' => [
'extension_point' => 'simple_slot',
'components' => [
['id' => 'simple_component', 'type' => 'basic', 'name' => 'Div'],
],
],
'is_active' => true,
]);
$layout = [
'layout_name' => 'test_page',
'components' => [
[
'id' => 'simple_ext_slot',
'type' => 'extension_point',
'name' => 'simple_slot',
'props' => ['label' => 'test'],
],
],
'data_sources' => [],
];
$result = $this->service->applyExtensions($layout, $this->template->id);
$injectedComponent = $result['components'][0]['children'][0];
$this->assertArrayHasKey('extensionPointProps', $injectedComponent);
$this->assertArrayNotHasKey('extensionPointCallbacks', $injectedComponent);
}
/**
* components와 modals 양쪽에 동일 이름의 extension_point가 있을 때 모두 주입되는지 테스트
*/
@@ -28,10 +28,7 @@ class LayoutResolverServiceTest extends TestCase
{
parent::setUp();
$this->layoutRepository = app(LayoutRepository::class);
$this->resolverService = new LayoutResolverService(
$this->layoutRepository,
app(ModuleManager::class)
);
$this->resolverService = app(LayoutResolverService::class);
// 테스트용 템플릿 생성
$this->template = Template::create([
@@ -65,7 +65,7 @@ class LayoutServiceCachingTest extends TestCase
);
// Assert: 캐시에 저장되었는지 확인
$cacheKey = "template.{$this->template->id}.layout.dashboard";
$cacheKey = "g7:core:template.{$this->template->id}.layout.dashboard";
$this->assertTrue(Cache::has($cacheKey));
// Act: 두 번째 호출 (캐시 히트)
@@ -106,7 +106,7 @@ class LayoutServiceCachingTest extends TestCase
// 캐시 생성
$this->layoutService->loadAndMergeLayout($this->template->id, '_base');
$cacheKey = "template.{$this->template->id}.layout._base";
$cacheKey = "g7:core:template.{$this->template->id}.layout._base";
$this->assertTrue(Cache::has($cacheKey));
// Act: 캐시 무효화
@@ -173,9 +173,9 @@ class LayoutServiceCachingTest extends TestCase
$this->layoutService->loadAndMergeLayout($this->template->id, 'dashboard');
$this->layoutService->loadAndMergeLayout($this->template->id, 'dashboard_custom');
$baseCacheKey = "template.{$this->template->id}.layout._base";
$dashboardCacheKey = "template.{$this->template->id}.layout.dashboard";
$customCacheKey = "template.{$this->template->id}.layout.dashboard_custom";
$baseCacheKey = "g7:core:template.{$this->template->id}.layout._base";
$dashboardCacheKey = "g7:core:template.{$this->template->id}.layout.dashboard";
$customCacheKey = "g7:core:template.{$this->template->id}.layout.dashboard_custom";
$this->assertTrue(Cache::has($baseCacheKey));
$this->assertTrue(Cache::has($dashboardCacheKey));
@@ -241,7 +241,7 @@ class LayoutServiceCachingTest extends TestCase
// Act: 첫 호출로 캐시 생성
$result1 = $this->layoutService->loadAndMergeLayout($this->template->id, '_base');
$cacheKey = "template.{$this->template->id}.layout._base";
$cacheKey = "g7:core:template.{$this->template->id}.layout._base";
$this->assertTrue(Cache::has($cacheKey));
// 캐시 수동 삭제 (만료 시뮬레이션)
@@ -295,8 +295,8 @@ class LayoutServiceCachingTest extends TestCase
$this->layoutService->loadAndMergeLayout($this->template->id, 'dashboard');
// Assert: 부모와 자식 모두 캐싱됨
$baseCacheKey = "template.{$this->template->id}.layout._base";
$dashboardCacheKey = "template.{$this->template->id}.layout.dashboard";
$baseCacheKey = "g7:core:template.{$this->template->id}.layout._base";
$dashboardCacheKey = "g7:core:template.{$this->template->id}.layout.dashboard";
$this->assertTrue(Cache::has($baseCacheKey));
$this->assertTrue(Cache::has($dashboardCacheKey));
+116
View File
@@ -1192,4 +1192,120 @@ class LayoutServiceTest extends TestCase
// 첫 번째 DOT에서 매칭
$this->assertTrue($method->invoke($this->layoutService, 'sirsoft-sample.admin.sub'));
}
/**
* transition_overlay 병합 - 자식이 wait_for 만 명시해도 부모의 spinner 설정이 보존되어야 함
*
* 이슈 #245 — engine-v1.30.0
*/
public function test_merge_transition_overlay_shallow_merge_preserves_parent_keys(): void
{
$parent = [
'transition_overlay' => [
'enabled' => true,
'style' => 'spinner',
'target' => 'main_content',
'spinner' => ['component' => 'PageLoading'],
],
'data_sources' => [],
'components' => [],
];
$child = [
'transition_overlay' => [
'wait_for' => ['settings'],
],
'data_sources' => [],
'components' => [],
];
$result = $this->layoutService->mergeLayouts($parent, $child);
$this->assertSame(true, $result['transition_overlay']['enabled']);
$this->assertSame('spinner', $result['transition_overlay']['style']);
$this->assertSame('main_content', $result['transition_overlay']['target']);
$this->assertSame(['component' => 'PageLoading'], $result['transition_overlay']['spinner']);
$this->assertSame(['settings'], $result['transition_overlay']['wait_for']);
}
/**
* transition_overlay 병합 - 자식이 동일 키를 명시하면 자식이 우선
*/
public function test_merge_transition_overlay_child_overrides_parent_keys(): void
{
$parent = [
'transition_overlay' => [
'enabled' => true,
'style' => 'spinner',
'target' => 'main_content',
],
'data_sources' => [],
'components' => [],
];
$child = [
'transition_overlay' => [
'target' => 'tab_content',
'wait_for' => ['tab_data'],
],
'data_sources' => [],
'components' => [],
];
$result = $this->layoutService->mergeLayouts($parent, $child);
$this->assertSame('tab_content', $result['transition_overlay']['target']);
$this->assertSame('spinner', $result['transition_overlay']['style']);
$this->assertSame(['tab_data'], $result['transition_overlay']['wait_for']);
}
/**
* transition_overlay 병합 - 부모만 정의된 경우 자식 폴백
*/
public function test_merge_transition_overlay_parent_only_fallback(): void
{
$parent = [
'transition_overlay' => [
'enabled' => true,
'style' => 'spinner',
'target' => 'main_content',
],
'data_sources' => [],
'components' => [],
];
$child = [
'data_sources' => [],
'components' => [],
];
$result = $this->layoutService->mergeLayouts($parent, $child);
$this->assertSame('main_content', $result['transition_overlay']['target']);
}
/**
* transition_overlay 병합 - boolean 케이스는 shallow merge 가 의미 없으므로 자식 우선
*/
public function test_merge_transition_overlay_boolean_uses_child_priority(): void
{
$parent = [
'transition_overlay' => [
'enabled' => true,
'style' => 'spinner',
],
'data_sources' => [],
'components' => [],
];
$child = [
'transition_overlay' => false,
'data_sources' => [],
'components' => [],
];
$result = $this->layoutService->mergeLayouts($parent, $child);
$this->assertSame(false, $result['transition_overlay']);
}
}
@@ -1,367 +0,0 @@
<?php
namespace Tests\Unit\Services;
use App\Enums\ExtensionOwnerType;
use App\Enums\MailSendStatus;
use App\Models\MailSendLog;
use App\Services\MailSendLogService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* MailSendLogService 테스트
*
* 메일 발송 이력 서비스의 로깅, 조회, 통계 메서드를 검증합니다.
*/
class MailSendLogServiceTest extends TestCase
{
use RefreshDatabase;
private MailSendLogService $service;
protected function setUp(): void
{
parent::setUp();
$this->service = app(MailSendLogService::class);
}
// ========================================================================
// logSent
// ========================================================================
/**
* 발송 성공 이력을 기록합니다
*/
public function test_log_sent_creates_sent_record(): void
{
$log = $this->service->logSent(
recipientEmail: 'user@example.com',
recipientName: 'John Doe',
subject: 'Welcome',
templateType: 'welcome',
extensionType: ExtensionOwnerType::Core,
extensionIdentifier: 'core',
source: 'notification',
);
$this->assertInstanceOf(MailSendLog::class, $log);
$this->assertTrue($log->exists);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'user@example.com',
'recipient_name' => 'John Doe',
'subject' => 'Welcome',
'template_type' => 'welcome',
'extension_type' => ExtensionOwnerType::Core->value,
'extension_identifier' => 'core',
'source' => 'notification',
'status' => MailSendStatus::Sent->value,
]);
}
/**
* logSent는 기본값으로 extensionType=Core, extensionIdentifier='core', source=null을 사용
*/
public function test_log_sent_uses_default_values(): void
{
$log = $this->service->logSent(
recipientEmail: 'test@example.com',
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'test@example.com',
'recipient_name' => null,
'subject' => null,
'template_type' => null,
'extension_type' => ExtensionOwnerType::Core->value,
'extension_identifier' => 'core',
'source' => null,
'status' => MailSendStatus::Sent->value,
]);
}
/**
* logSent는 sent_at을 자동 설정
*/
public function test_log_sent_sets_sent_at(): void
{
$log = $this->service->logSent(recipientEmail: 'test@example.com');
$this->assertNotNull($log->sent_at);
}
/**
* logSent는 body를 기록합니다
*/
public function test_log_sent_records_body(): void
{
$body = '<p>Welcome to G7!</p>';
$log = $this->service->logSent(
recipientEmail: 'user@example.com',
subject: 'Welcome',
body: $body,
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'user@example.com',
'body' => $body,
]);
}
/**
* logSent는 body가 null일 수 있음
*/
public function test_log_sent_allows_null_body(): void
{
$log = $this->service->logSent(
recipientEmail: 'test@example.com',
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'test@example.com',
'body' => null,
]);
}
/**
* logSent는 발송자 정보를 기록합니다
*/
public function test_log_sent_records_sender(): void
{
$log = $this->service->logSent(
recipientEmail: 'user@example.com',
subject: 'Welcome',
senderEmail: 'admin@example.com',
senderName: 'G7 Admin',
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'user@example.com',
'sender_email' => 'admin@example.com',
'sender_name' => 'G7 Admin',
]);
}
/**
* logSent는 발송자 정보가 null일 수 있음
*/
public function test_log_sent_allows_null_sender(): void
{
$log = $this->service->logSent(
recipientEmail: 'test@example.com',
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'test@example.com',
'sender_email' => null,
'sender_name' => null,
]);
}
// ========================================================================
// logFailed
// ========================================================================
/**
* 발송 실패 이력을 기록합니다
*/
public function test_log_failed_creates_failed_record(): void
{
$log = $this->service->logFailed(
recipientEmail: 'user@example.com',
subject: 'Order Confirmation',
templateType: 'order_confirmed',
extensionType: ExtensionOwnerType::Module,
extensionIdentifier: 'sirsoft-ecommerce',
source: 'notification',
errorMessage: 'Connection timeout',
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'user@example.com',
'subject' => 'Order Confirmation',
'template_type' => 'order_confirmed',
'extension_type' => ExtensionOwnerType::Module->value,
'extension_identifier' => 'sirsoft-ecommerce',
'source' => 'notification',
'status' => MailSendStatus::Failed->value,
'error_message' => 'Connection timeout',
]);
}
/**
* logFailed는 body를 기록합니다
*/
public function test_log_failed_records_body(): void
{
$body = '<p>Order Confirmation</p>';
$log = $this->service->logFailed(
recipientEmail: 'user@example.com',
subject: 'Order',
errorMessage: 'SMTP error',
body: $body,
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'user@example.com',
'body' => $body,
'status' => MailSendStatus::Failed->value,
]);
}
/**
* logFailed는 발송자 정보를 기록합니다
*/
public function test_log_failed_records_sender(): void
{
$log = $this->service->logFailed(
recipientEmail: 'user@example.com',
errorMessage: 'SMTP error',
senderEmail: 'noreply@example.com',
senderName: 'G7 System',
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'user@example.com',
'sender_email' => 'noreply@example.com',
'sender_name' => 'G7 System',
'status' => MailSendStatus::Failed->value,
]);
}
/**
* logFailed는 error_message가 null일 수 있음
*/
public function test_log_failed_allows_null_error_message(): void
{
$log = $this->service->logFailed(
recipientEmail: 'test@example.com',
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'test@example.com',
'status' => MailSendStatus::Failed->value,
'error_message' => null,
]);
}
// ========================================================================
// logSkipped
// ========================================================================
/**
* 발송 건너뛰기 이력을 기록합니다
*/
public function test_log_skipped_creates_skipped_record(): void
{
$log = $this->service->logSkipped(
recipientEmail: 'user@example.com',
recipientName: 'User',
templateType: 'welcome',
extensionType: ExtensionOwnerType::Core,
extensionIdentifier: 'core',
source: 'notification',
errorMessage: '비활성 템플릿',
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'user@example.com',
'recipient_name' => 'User',
'subject' => null,
'template_type' => 'welcome',
'extension_type' => ExtensionOwnerType::Core->value,
'extension_identifier' => 'core',
'source' => 'notification',
'status' => MailSendStatus::Skipped->value,
'error_message' => '비활성 템플릿',
]);
}
/**
* logSkipped는 발송자 정보를 기록합니다
*/
public function test_log_skipped_records_sender(): void
{
$log = $this->service->logSkipped(
recipientEmail: 'user@example.com',
senderEmail: 'admin@example.com',
senderName: 'G7 Admin',
);
$this->assertDatabaseHas('mail_send_logs', [
'recipient_email' => 'user@example.com',
'sender_email' => 'admin@example.com',
'sender_name' => 'G7 Admin',
'status' => MailSendStatus::Skipped->value,
]);
}
/**
* logSkipped는 subject를 항상 null로 설정
*/
public function test_log_skipped_always_sets_null_subject(): void
{
$log = $this->service->logSkipped(
recipientEmail: 'test@example.com',
);
$this->assertNull($log->subject);
}
// ========================================================================
// getLogs
// ========================================================================
/**
* 발송 이력 목록 조회
*/
public function test_get_logs_returns_paginated_result(): void
{
MailSendLog::factory()->count(5)->create();
$result = $this->service->getLogs();
$this->assertCount(5, $result->items());
$this->assertEquals(5, $result->total());
}
/**
* 발송 이력 목록 필터 조회
*/
public function test_get_logs_applies_filters(): void
{
MailSendLog::factory()->forExtension(ExtensionOwnerType::Core, 'core')->count(3)->create();
MailSendLog::factory()->forExtension(ExtensionOwnerType::Module, 'sirsoft-ecommerce')->count(2)->create();
$result = $this->service->getLogs(['extension_type' => 'core']);
$this->assertCount(3, $result->items());
}
// ========================================================================
// getStatistics
// ========================================================================
/**
* 발송 통계 조회
*/
public function test_get_statistics_returns_correct_data(): void
{
MailSendLog::factory()->count(3)->create([
'status' => MailSendStatus::Sent->value,
'sent_at' => now(),
]);
MailSendLog::factory()->failed()->count(1)->create([
'sent_at' => now(),
]);
$stats = $this->service->getStatistics();
$this->assertEquals(4, $stats['total']);
$this->assertEquals(3, $stats['sent']);
$this->assertEquals(1, $stats['failed']);
$this->assertEquals(4, $stats['today']);
}
}
@@ -1,260 +0,0 @@
<?php
namespace Tests\Unit\Services;
use App\Models\MailTemplate;
use App\Models\User;
use App\Services\MailTemplateService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;
/**
* MailTemplateService 테스트
*
* 서비스의 CRUD, resolveTemplate 캐시, toggleActive, resetToDefault를 검증합니다.
*/
class MailTemplateServiceTest extends TestCase
{
use RefreshDatabase;
private MailTemplateService $service;
protected function setUp(): void
{
parent::setUp();
Cache::flush();
$this->service = app(MailTemplateService::class);
}
// ========================================================================
// getTemplatesForSettings
// ========================================================================
/**
* 전체 템플릿 목록을 반환
*/
public function test_get_templates_for_settings_returns_all(): void
{
MailTemplate::factory()->withType('welcome')->create();
MailTemplate::factory()->withType('reset_password')->create();
MailTemplate::factory()->withType('password_changed')->inactive()->create();
$result = $this->service->getTemplatesForSettings();
$this->assertCount(3, $result);
}
// ========================================================================
// updateTemplate
// ========================================================================
/**
* 템플릿 수정이 올바르게 동작
*/
public function test_update_template_saves_data(): void
{
$user = User::factory()->create();
$template = MailTemplate::factory()->withType('welcome')->create();
$updated = $this->service->updateTemplate($template, [
'subject' => ['ko' => '수정된 제목', 'en' => 'Updated Subject'],
'body' => ['ko' => '<p>수정됨</p>', 'en' => '<p>Updated</p>'],
'is_active' => true,
], $user->id);
$this->assertEquals(['ko' => '수정된 제목', 'en' => 'Updated Subject'], $updated->subject);
$this->assertFalse($updated->is_default);
$this->assertEquals($user->id, $updated->updated_by);
}
/**
* 수정 시 캐시가 무효화됨
*/
public function test_update_template_invalidates_cache(): void
{
$template = MailTemplate::factory()->withType('welcome')->create();
Cache::put('mail_template:core:welcome', $template, 3600);
$this->service->updateTemplate($template, [
'subject' => ['ko' => '새 제목'],
'body' => ['ko' => '<p>새 본문</p>'],
]);
$this->assertFalse(Cache::has('mail_template:core:welcome'));
}
// ========================================================================
// toggleActive
// ========================================================================
/**
* 활성 상태를 토글
*/
public function test_toggle_active_flips_state(): void
{
$template = MailTemplate::factory()->create(['is_active' => true]);
$toggled = $this->service->toggleActive($template);
$this->assertFalse($toggled->is_active);
}
/**
* 비활성→활성 토글
*/
public function test_toggle_active_activates_inactive(): void
{
$template = MailTemplate::factory()->inactive()->create();
$toggled = $this->service->toggleActive($template);
$this->assertTrue($toggled->is_active);
}
/**
* 토글 시 캐시가 무효화됨
*/
public function test_toggle_active_invalidates_cache(): void
{
$template = MailTemplate::factory()->withType('reset_password')->create();
Cache::put('mail_template:core:reset_password', $template, 3600);
$this->service->toggleActive($template);
$this->assertFalse(Cache::has('mail_template:core:reset_password'));
}
// ========================================================================
// resolveTemplate (캐시)
// ========================================================================
/**
* resolveTemplate이 활성 템플릿을 반환
*/
public function test_resolve_template_returns_active(): void
{
MailTemplate::factory()->withType('welcome')->create(['is_active' => true]);
$result = $this->service->resolveTemplate('welcome');
$this->assertNotNull($result);
$this->assertEquals('welcome', $result->type);
}
/**
* resolveTemplate이 비활성 템플릿에 null 반환
*/
public function test_resolve_template_returns_null_for_inactive(): void
{
MailTemplate::factory()->withType('welcome')->inactive()->create();
$result = $this->service->resolveTemplate('welcome');
$this->assertNull($result);
}
/**
* resolveTemplate이 결과를 캐싱
*/
public function test_resolve_template_caches_result(): void
{
MailTemplate::factory()->withType('welcome')->create(['is_active' => true]);
$this->service->resolveTemplate('welcome');
$this->assertTrue(Cache::has('mail_template:core:welcome'));
}
// ========================================================================
// getPreview
// ========================================================================
/**
* 미리보기가 변수를 placeholder로 치환
*/
public function test_get_preview_replaces_variables(): void
{
$data = [
'subject' => 'Hello {name}',
'body' => '<p>Welcome to {app_name}</p>',
'variables' => [
['key' => 'name'],
['key' => 'app_name'],
],
];
$result = $this->service->getPreview($data);
$this->assertEquals('Hello {name}', $result['subject']);
$this->assertEquals('<p>Welcome to {app_name}</p>', $result['body']);
}
// ========================================================================
// resetToDefault
// ========================================================================
// ========================================================================
// getTemplates (페이지네이션)
// ========================================================================
/**
* 페이지네이션된 목록을 반환
*/
public function test_get_templates_returns_paginated(): void
{
MailTemplate::factory()->count(5)->create();
$result = $this->service->getTemplates([], 2);
$this->assertEquals(5, $result->total());
$this->assertCount(2, $result->items());
$this->assertEquals(3, $result->lastPage());
}
/**
* 검색 필터가 동작
*/
public function test_get_templates_filters_by_search(): void
{
MailTemplate::factory()->withType('welcome')->create([
'subject' => ['ko' => '환영 메일', 'en' => 'Welcome'],
]);
MailTemplate::factory()->withType('reset_password')->create([
'subject' => ['ko' => '비밀번호 재설정', 'en' => 'Reset Password'],
]);
$result = $this->service->getTemplates(['search' => '환영', 'search_type' => 'subject']);
$this->assertEquals(1, $result->total());
}
// ========================================================================
// resetToDefault
// ========================================================================
/**
* 기본값으로 복원
*/
public function test_reset_to_default_restores_data(): void
{
$template = MailTemplate::factory()->withType('welcome')->create([
'subject' => ['ko' => '사용자 수정'],
'body' => ['ko' => '<p>수정됨</p>'],
'is_default' => false,
]);
$defaultData = [
'subject' => ['ko' => '원래 제목', 'en' => 'Original Subject'],
'body' => ['ko' => '<p>원래 본문</p>', 'en' => '<p>Original Body</p>'],
'variables' => [['key' => 'name', 'description' => '이름']],
];
$result = $this->service->resetToDefault($template, $defaultData);
$this->assertEquals(['ko' => '원래 제목', 'en' => 'Original Subject'], $result->subject);
$this->assertTrue($result->is_default);
$this->assertTrue($result->is_active);
}
}
@@ -0,0 +1,217 @@
<?php
namespace Tests\Unit\Services;
use App\Services\ModuleSettingsService;
use App\Services\NotificationChannelService;
use App\Services\PluginSettingsService;
use App\Services\SettingsService;
use Mockery;
use Tests\TestCase;
/**
* NotificationChannelService 단위 테스트
*
* 확장(core/module/plugin) 단위 채널 전역 활성 여부 조회를 검증합니다.
*/
class NotificationChannelServiceTest extends TestCase
{
private NotificationChannelService $service;
protected function setUp(): void
{
parent::setUp();
$this->service = new NotificationChannelService;
}
protected function tearDown(): void
{
Mockery::close();
parent::tearDown();
}
/**
* 코어 설정에서 채널이 활성화된 경우 true를 반환한다.
*/
public function test_core_channel_enabled_when_is_active_true(): void
{
$this->mockCoreSettings([
['id' => 'mail', 'is_active' => true],
['id' => 'database', 'is_active' => true],
]);
$this->assertTrue(
$this->service->isChannelEnabledForExtension('core', 'core', 'mail')
);
}
/**
* 코어 설정에서 채널이 비활성화된 경우 false를 반환한다.
*/
public function test_core_channel_disabled_when_is_active_false(): void
{
$this->mockCoreSettings([
['id' => 'mail', 'is_active' => false],
['id' => 'database', 'is_active' => true],
]);
$this->assertFalse(
$this->service->isChannelEnabledForExtension('core', 'core', 'mail')
);
$this->assertTrue(
$this->service->isChannelEnabledForExtension('core', 'core', 'database')
);
}
/**
* 설정에 엔트리가 없으면 기본 활성(true) — 하위호환 + 신규 플러그인 채널 대응.
*/
public function test_core_channel_defaults_to_enabled_when_entry_missing(): void
{
$this->mockCoreSettings([
['id' => 'mail', 'is_active' => true],
]);
// slack은 설정에 없음 → 기본 true
$this->assertTrue(
$this->service->isChannelEnabledForExtension('core', 'core', 'slack')
);
}
/**
* notifications.channels 키 자체가 없으면(빈 배열) 모든 채널 활성.
*/
public function test_core_channel_defaults_to_enabled_when_settings_empty(): void
{
$this->mockCoreSettings([]);
$this->assertTrue(
$this->service->isChannelEnabledForExtension('core', 'core', 'mail')
);
}
/**
* 모듈 경로: ModuleSettingsService를 통해 조회한다.
*/
public function test_module_channel_resolved_via_module_settings(): void
{
$moduleSettings = Mockery::mock(ModuleSettingsService::class);
$moduleSettings->shouldReceive('get')
->with('sirsoft-ecommerce', 'notifications.channels', [])
->andReturn([
['id' => 'mail', 'is_active' => false],
['id' => 'database', 'is_active' => true],
]);
$this->app->instance(ModuleSettingsService::class, $moduleSettings);
$this->assertFalse(
$this->service->isChannelEnabledForExtension('module', 'sirsoft-ecommerce', 'mail')
);
$this->assertTrue(
$this->service->isChannelEnabledForExtension('module', 'sirsoft-ecommerce', 'database')
);
}
/**
* 플러그인 경로: PluginSettingsService를 통해 조회한다.
*/
public function test_plugin_channel_resolved_via_plugin_settings(): void
{
$pluginSettings = Mockery::mock(PluginSettingsService::class);
$pluginSettings->shouldReceive('get')
->with('sirsoft-slack', 'notifications.channels', [])
->andReturn([
['id' => 'slack', 'is_active' => true],
]);
$this->app->instance(PluginSettingsService::class, $pluginSettings);
$this->assertTrue(
$this->service->isChannelEnabledForExtension('plugin', 'sirsoft-slack', 'slack')
);
}
/**
* 모듈 식별자가 비어 있으면 기본 활성 반환.
*/
public function test_module_without_identifier_returns_default_enabled(): void
{
$this->assertTrue(
$this->service->isChannelEnabledForExtension('module', null, 'mail')
);
$this->assertTrue(
$this->service->isChannelEnabledForExtension('module', '', 'mail')
);
}
/**
* 동일 조합 반복 호출 시 캐시를 사용한다 (SettingsService 1회만 호출).
*/
public function test_memoizes_channel_enabled_lookup(): void
{
$settingsService = Mockery::mock(SettingsService::class);
$settingsService->shouldReceive('getSetting')
->once() // 캐시 검증
->with('notifications.channels', [])
->andReturn([
['id' => 'mail', 'is_active' => false],
]);
$this->app->instance(SettingsService::class, $settingsService);
$this->service->isChannelEnabledForExtension('core', 'core', 'mail');
$this->service->isChannelEnabledForExtension('core', 'core', 'mail');
$this->service->isChannelEnabledForExtension('core', 'core', 'mail');
$this->assertFalse(
$this->service->isChannelEnabledForExtension('core', 'core', 'mail')
);
}
/**
* clearChannelEnabledCache() 호출 시 캐시가 초기화된다.
*/
public function test_clear_channel_enabled_cache(): void
{
$settingsService = Mockery::mock(SettingsService::class);
$settingsService->shouldReceive('getSetting')
->twice()
->with('notifications.channels', [])
->andReturn([['id' => 'mail', 'is_active' => true]]);
$this->app->instance(SettingsService::class, $settingsService);
$this->service->isChannelEnabledForExtension('core', 'core', 'mail');
$this->service->clearChannelEnabledCache();
$this->service->isChannelEnabledForExtension('core', 'core', 'mail');
// 2회 호출 검증은 Mockery가 처리
$this->assertTrue(true);
}
/**
* 설정 조회 중 예외 발생 시 기본 활성(true) 반환.
*/
public function test_returns_default_enabled_on_settings_service_exception(): void
{
$settingsService = Mockery::mock(SettingsService::class);
$settingsService->shouldReceive('getSetting')
->andThrow(new \RuntimeException('DB unavailable'));
$this->app->instance(SettingsService::class, $settingsService);
$this->assertTrue(
$this->service->isChannelEnabledForExtension('core', 'core', 'mail')
);
}
/**
* 코어 SettingsService 응답을 mocking 하는 헬퍼.
*
* @param array $channels
*/
private function mockCoreSettings(array $channels): void
{
$settingsService = Mockery::mock(SettingsService::class);
$settingsService->shouldReceive('getSetting')
->with('notifications.channels', [])
->andReturn($channels);
$this->app->instance(SettingsService::class, $settingsService);
}
}
@@ -0,0 +1,166 @@
<?php
namespace Tests\Unit\Services;
use App\Models\NotificationDefinition;
use App\Services\NotificationDefinitionService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* NotificationDefinitionService 테스트
*
* 알림 정의 조회, 캐싱, 수정 동작을 검증합니다.
*/
class NotificationDefinitionServiceTest extends TestCase
{
use RefreshDatabase;
private NotificationDefinitionService $service;
protected function setUp(): void
{
parent::setUp();
$this->service = app(NotificationDefinitionService::class);
}
/**
* resolve()가 활성 정의를 반환하는지 확인
*/
public function test_resolve_returns_active_definition(): void
{
NotificationDefinition::create([
'type' => 'welcome',
'hook_prefix' => 'core.auth',
'extension_type' => 'core',
'extension_identifier' => 'core',
'name' => ['ko' => '환영', 'en' => 'Welcome'],
'variables' => [],
'channels' => ['mail'],
'hooks' => ['core.auth.after_register'],
'is_active' => true,
'is_default' => true,
]);
$this->service->invalidateCache('welcome');
$result = $this->service->resolve('welcome');
$this->assertNotNull($result);
$this->assertEquals('welcome', $result->type);
}
/**
* resolve()가 비활성 정의를 반환하지 않는지 확인
*/
public function test_resolve_returns_null_for_inactive_definition(): void
{
NotificationDefinition::create([
'type' => 'inactive_type',
'hook_prefix' => 'core.auth',
'extension_type' => 'core',
'extension_identifier' => 'core',
'name' => ['ko' => '비활성', 'en' => 'Inactive'],
'variables' => [],
'channels' => ['mail'],
'hooks' => [],
'is_active' => false,
'is_default' => true,
]);
$this->service->invalidateCache('inactive_type');
$result = $this->service->resolve('inactive_type');
$this->assertNull($result);
}
/**
* getAllActive()가 활성 정의만 반환하는지 확인
*/
public function test_get_all_active_returns_only_active(): void
{
NotificationDefinition::create([
'type' => 'active_one',
'hook_prefix' => 'core.auth',
'extension_type' => 'core',
'extension_identifier' => 'core',
'name' => ['ko' => '활성1'],
'variables' => [],
'channels' => ['mail'],
'hooks' => [],
'is_active' => true,
'is_default' => true,
]);
NotificationDefinition::create([
'type' => 'inactive_one',
'hook_prefix' => 'core.auth',
'extension_type' => 'core',
'extension_identifier' => 'core',
'name' => ['ko' => '비활성1'],
'variables' => [],
'channels' => ['mail'],
'hooks' => [],
'is_active' => false,
'is_default' => true,
]);
$this->service->invalidateAllCache();
$result = $this->service->getAllActive();
$this->assertCount(1, $result);
$this->assertEquals('active_one', $result->first()->type);
}
/**
* toggleActive()가 활성 상태를 반전시키는지 확인
*/
public function test_toggle_active_inverts_status(): void
{
$definition = NotificationDefinition::create([
'type' => 'toggle_test',
'hook_prefix' => 'core.auth',
'extension_type' => 'core',
'extension_identifier' => 'core',
'name' => ['ko' => '토글 테스트'],
'variables' => [],
'channels' => ['mail'],
'hooks' => [],
'is_active' => true,
'is_default' => true,
]);
$result = $this->service->toggleActive($definition);
$this->assertFalse($result->is_active);
}
/**
* updateDefinition()이 채널과 훅을 수정하는지 확인
*/
public function test_update_definition_modifies_channels_and_hooks(): void
{
$definition = NotificationDefinition::create([
'type' => 'update_test',
'hook_prefix' => 'core.auth',
'extension_type' => 'core',
'extension_identifier' => 'core',
'name' => ['ko' => '수정 테스트'],
'variables' => [],
'channels' => ['mail'],
'hooks' => ['core.auth.after_register'],
'is_active' => true,
'is_default' => true,
]);
$result = $this->service->updateDefinition($definition, [
'channels' => ['mail', 'database'],
'hooks' => ['core.auth.after_register', 'core.auth.after_login'],
]);
$this->assertEquals(['mail', 'database'], $result->channels);
$this->assertEquals(['core.auth.after_register', 'core.auth.after_login'], $result->hooks);
}
}
@@ -0,0 +1,125 @@
<?php
namespace Tests\Unit\Services;
use App\Enums\NotificationLogStatus;
use App\Models\NotificationLog;
use App\Services\NotificationLogService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* NotificationLogService 테스트
*
* 알림 발송 이력 기록, 조회, 삭제 동작을 검증합니다.
*/
class NotificationLogServiceTest extends TestCase
{
use RefreshDatabase;
private NotificationLogService $service;
protected function setUp(): void
{
parent::setUp();
$this->service = app(NotificationLogService::class);
}
/**
* logSent()가 sent 상태로 로그를 기록하는지 확인
*/
public function test_log_sent_creates_sent_record(): void
{
$log = $this->service->logSent([
'channel' => 'mail',
'notification_type' => 'welcome',
'recipient_identifier' => 'test@example.com',
'recipient_name' => 'Test User',
'subject' => 'Welcome',
'source' => 'notification',
]);
$this->assertInstanceOf(NotificationLog::class, $log);
$this->assertEquals(NotificationLogStatus::Sent, $log->status);
$this->assertEquals('mail', $log->channel);
$this->assertEquals('welcome', $log->notification_type);
}
/**
* logFailed()가 failed 상태로 로그를 기록하는지 확인
*/
public function test_log_failed_creates_failed_record(): void
{
$log = $this->service->logFailed([
'channel' => 'mail',
'notification_type' => 'welcome',
'recipient_identifier' => 'test@example.com',
'error_message' => 'SMTP connection refused',
'source' => 'notification',
]);
$this->assertEquals(NotificationLogStatus::Failed, $log->status);
$this->assertEquals('SMTP connection refused', $log->error_message);
}
/**
* logSkipped()가 skipped 상태로 로그를 기록하는지 확인
*/
public function test_log_skipped_creates_skipped_record(): void
{
$log = $this->service->logSkipped([
'channel' => 'mail',
'notification_type' => 'welcome',
'recipient_identifier' => 'test@example.com',
'source' => 'notification',
]);
$this->assertEquals(NotificationLogStatus::Skipped, $log->status);
}
/**
* deleteLog()가 로그를 삭제하는지 확인
*/
public function test_delete_log(): void
{
$log = $this->service->logSent([
'channel' => 'mail',
'notification_type' => 'test',
'recipient_identifier' => 'test@example.com',
]);
$result = $this->service->deleteLog($log);
$this->assertTrue($result);
$this->assertDatabaseMissing('notification_logs', ['id' => $log->id]);
}
/**
* bulkDelete()가 다건 삭제하는지 확인
*/
public function test_bulk_delete(): void
{
$log1 = $this->service->logSent(['channel' => 'mail', 'notification_type' => 'test', 'recipient_identifier' => 'a@test.com']);
$log2 = $this->service->logSent(['channel' => 'mail', 'notification_type' => 'test', 'recipient_identifier' => 'b@test.com']);
$log3 = $this->service->logSent(['channel' => 'mail', 'notification_type' => 'test', 'recipient_identifier' => 'c@test.com']);
$count = $this->service->bulkDelete([$log1->id, $log2->id]);
$this->assertEquals(2, $count);
$this->assertDatabaseHas('notification_logs', ['id' => $log3->id]);
}
/**
* getLogs()가 채널 필터를 적용하는지 확인
*/
public function test_get_logs_filters_by_channel(): void
{
$this->service->logSent(['channel' => 'mail', 'notification_type' => 'test', 'recipient_identifier' => 'a@test.com']);
$this->service->logSent(['channel' => 'database', 'notification_type' => 'test', 'recipient_identifier' => '42']);
$this->service->logSent(['channel' => 'mail', 'notification_type' => 'test', 'recipient_identifier' => 'b@test.com']);
$result = $this->service->getLogs(['channel' => 'mail']);
$this->assertEquals(2, $result->total());
}
}
@@ -0,0 +1,284 @@
<?php
namespace Tests\Unit\Services;
use App\Models\Role;
use App\Models\User;
use App\Services\NotificationRecipientResolver;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* NotificationRecipientResolver 테스트
*
* 수신자 타입별(trigger_user, related_user, role, specific_users)
* 해석 로직과 exclude_trigger_user 필터를 검증합니다.
*/
class NotificationRecipientResolverTest extends TestCase
{
use RefreshDatabase;
private NotificationRecipientResolver $resolver;
protected function setUp(): void
{
parent::setUp();
$this->resolver = app(NotificationRecipientResolver::class);
}
// ──────────────────────────────────────────────
// trigger_user 타입
// ──────────────────────────────────────────────
public function test_trigger_user_resolves_from_context(): void
{
$user = User::factory()->create();
$result = $this->resolver->resolve(
[['type' => 'trigger_user']],
['trigger_user_id' => $user->id, 'trigger_user' => $user]
);
$this->assertCount(1, $result);
$this->assertEquals($user->id, $result->first()->id);
}
public function test_trigger_user_resolves_from_id_only(): void
{
$user = User::factory()->create();
$result = $this->resolver->resolve(
[['type' => 'trigger_user']],
['trigger_user_id' => $user->id]
);
$this->assertCount(1, $result);
$this->assertEquals($user->id, $result->first()->id);
}
public function test_trigger_user_returns_empty_without_context(): void
{
$result = $this->resolver->resolve(
[['type' => 'trigger_user']],
[]
);
$this->assertCount(0, $result);
}
// ──────────────────────────────────────────────
// related_user 타입
// ──────────────────────────────────────────────
public function test_related_user_resolves_from_context(): void
{
$author = User::factory()->create();
$result = $this->resolver->resolve(
[['type' => 'related_user', 'relation' => 'author']],
['related_users' => ['author' => $author]]
);
$this->assertCount(1, $result);
$this->assertEquals($author->id, $result->first()->id);
}
public function test_related_user_returns_empty_when_relation_missing(): void
{
$result = $this->resolver->resolve(
[['type' => 'related_user', 'relation' => 'author']],
['related_users' => []]
);
$this->assertCount(0, $result);
}
public function test_related_user_supports_collection(): void
{
$users = User::factory()->count(2)->create();
$result = $this->resolver->resolve(
[['type' => 'related_user', 'relation' => 'managers']],
['related_users' => ['managers' => $users]]
);
$this->assertCount(2, $result);
}
// ──────────────────────────────────────────────
// role 타입
// ──────────────────────────────────────────────
public function test_role_resolves_users_by_role_identifier(): void
{
$role = Role::factory()->create(['identifier' => 'test_admin']);
$admin1 = User::factory()->create();
$admin2 = User::factory()->create();
$role->users()->attach([$admin1->id, $admin2->id]);
$result = $this->resolver->resolve(
[['type' => 'role', 'value' => 'test_admin']],
[]
);
$this->assertCount(2, $result);
$this->assertTrue($result->contains('id', $admin1->id));
$this->assertTrue($result->contains('id', $admin2->id));
}
public function test_role_falls_back_to_super_admin(): void
{
Role::factory()->create(['identifier' => 'empty_role']);
$superAdmin = User::factory()->create(['is_super' => true]);
$result = $this->resolver->resolve(
[['type' => 'role', 'value' => 'empty_role']],
[]
);
$this->assertCount(1, $result);
$this->assertEquals($superAdmin->id, $result->first()->id);
}
public function test_role_nonexistent_falls_back_to_super_admin(): void
{
$superAdmin = User::factory()->create(['is_super' => true]);
$result = $this->resolver->resolve(
[['type' => 'role', 'value' => 'nonexistent_role']],
[]
);
$this->assertCount(1, $result);
$this->assertEquals($superAdmin->id, $result->first()->id);
}
// ──────────────────────────────────────────────
// specific_users 타입
// ──────────────────────────────────────────────
public function test_specific_users_resolves_by_uuid(): void
{
$user1 = User::factory()->create();
$user2 = User::factory()->create();
User::factory()->create();
$result = $this->resolver->resolve(
[['type' => 'specific_users', 'value' => [$user1->uuid, $user2->uuid]]],
[]
);
$this->assertCount(2, $result);
$this->assertTrue($result->contains('uuid', $user1->uuid));
$this->assertTrue($result->contains('uuid', $user2->uuid));
}
public function test_specific_users_returns_empty_for_empty_ids(): void
{
$result = $this->resolver->resolve(
[['type' => 'specific_users', 'value' => []]],
[]
);
$this->assertCount(0, $result);
}
// ──────────────────────────────────────────────
// exclude_trigger_user 필터
// ──────────────────────────────────────────────
public function test_exclude_trigger_user_filters_out_trigger(): void
{
$triggerUser = User::factory()->create();
$role = Role::factory()->create(['identifier' => 'admin_excl_test']);
$admin = User::factory()->create();
$role->users()->attach([$triggerUser->id, $admin->id]);
$result = $this->resolver->resolve(
[['type' => 'role', 'value' => 'admin_excl_test', 'exclude_trigger_user' => true]],
['trigger_user_id' => $triggerUser->id]
);
$this->assertCount(1, $result);
$this->assertEquals($admin->id, $result->first()->id);
$this->assertFalse($result->contains('id', $triggerUser->id));
}
public function test_no_exclude_keeps_trigger_user(): void
{
$triggerUser = User::factory()->create();
$role = Role::factory()->create(['identifier' => 'admin_no_excl']);
$role->users()->attach([$triggerUser->id]);
$result = $this->resolver->resolve(
[['type' => 'role', 'value' => 'admin_no_excl']],
['trigger_user_id' => $triggerUser->id]
);
$this->assertCount(1, $result);
$this->assertEquals($triggerUser->id, $result->first()->id);
}
// ──────────────────────────────────────────────
// 복합 규칙
// ──────────────────────────────────────────────
public function test_multiple_rules_combine_recipients(): void
{
$triggerUser = User::factory()->create();
$relatedUser = User::factory()->create();
$result = $this->resolver->resolve(
[
['type' => 'trigger_user'],
['type' => 'related_user', 'relation' => 'author'],
],
[
'trigger_user_id' => $triggerUser->id,
'trigger_user' => $triggerUser,
'related_users' => ['author' => $relatedUser],
]
);
$this->assertCount(2, $result);
$this->assertTrue($result->contains('id', $triggerUser->id));
$this->assertTrue($result->contains('id', $relatedUser->id));
}
public function test_duplicate_users_are_deduplicated(): void
{
$user = User::factory()->create();
$result = $this->resolver->resolve(
[
['type' => 'trigger_user'],
['type' => 'specific_users', 'value' => [$user->uuid]],
],
['trigger_user_id' => $user->id, 'trigger_user' => $user]
);
$this->assertCount(1, $result);
}
public function test_empty_rules_returns_empty(): void
{
$result = $this->resolver->resolve([], []);
$this->assertCount(0, $result);
}
public function test_unknown_type_is_skipped_gracefully(): void
{
$user = User::factory()->create();
$result = $this->resolver->resolve(
[
['type' => 'unknown_type'],
['type' => 'trigger_user'],
],
['trigger_user_id' => $user->id, 'trigger_user' => $user]
);
$this->assertCount(1, $result);
$this->assertEquals($user->id, $result->first()->id);
}
}
@@ -0,0 +1,150 @@
<?php
namespace Tests\Unit\Services;
use App\Models\User;
use App\Notifications\GenericNotification;
use App\Services\NotificationService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Notification;
use Tests\TestCase;
/**
* NotificationService 테스트
*
* 사이트내 알림 조회, 읽음 처리, 삭제, 정리 동작을 검증합니다.
*/
class NotificationServiceTest extends TestCase
{
use RefreshDatabase;
private NotificationService $service;
protected function setUp(): void
{
parent::setUp();
$this->service = app(NotificationService::class);
}
/**
* 사용자의 알림 목록 조회
*/
public function test_get_notifications_returns_paginated_list(): void
{
$user = User::factory()->create();
// database 채널로 알림 3개 발송
Notification::fake();
// fake 대신 실제 database 채널로 발송하여 DB에 저장
Notification::swap(new \Illuminate\Support\Testing\Fakes\NotificationFake());
// 직접 notifications 테이블에 레코드 생성
for ($i = 0; $i < 3; $i++) {
$user->notifications()->create([
'id' => \Illuminate\Support\Str::uuid(),
'type' => GenericNotification::class,
'data' => ['type' => 'test', 'subject' => "Test {$i}"],
]);
}
$result = $this->service->getNotifications($user, [], 20);
$this->assertEquals(3, $result->total());
}
/**
* 미읽음 알림 수 조회
*/
public function test_get_unread_count(): void
{
$user = User::factory()->create();
$user->notifications()->create([
'id' => \Illuminate\Support\Str::uuid(),
'type' => GenericNotification::class,
'data' => ['type' => 'test'],
]);
$user->notifications()->create([
'id' => \Illuminate\Support\Str::uuid(),
'type' => GenericNotification::class,
'data' => ['type' => 'test'],
'read_at' => now(),
]);
$count = $this->service->getUnreadCount($user);
$this->assertEquals(1, $count);
}
/**
* 알림 읽음 처리
*/
public function test_mark_as_read(): void
{
$user = User::factory()->create();
$notification = $user->notifications()->create([
'id' => \Illuminate\Support\Str::uuid(),
'type' => GenericNotification::class,
'data' => ['type' => 'test'],
]);
$result = $this->service->markAsRead($user, $notification->id);
$this->assertNotNull($result);
$this->assertNotNull($result->read_at);
}
/**
* 전체 읽음 처리
*/
public function test_mark_all_as_read(): void
{
$user = User::factory()->create();
for ($i = 0; $i < 3; $i++) {
$user->notifications()->create([
'id' => \Illuminate\Support\Str::uuid(),
'type' => GenericNotification::class,
'data' => ['type' => 'test'],
]);
}
$count = $this->service->markAllAsRead($user);
$this->assertEquals(3, $count);
$this->assertEquals(0, $this->service->getUnreadCount($user));
}
/**
* 알림 삭제
*/
public function test_delete_notification(): void
{
$user = User::factory()->create();
$notification = $user->notifications()->create([
'id' => \Illuminate\Support\Str::uuid(),
'type' => GenericNotification::class,
'data' => ['type' => 'test'],
]);
$result = $this->service->deleteNotification($user, $notification->id);
$this->assertTrue($result);
$this->assertEquals(0, $user->notifications()->count());
}
/**
* 존재하지 않는 알림 삭제 시 false 반환
*/
public function test_delete_nonexistent_notification_returns_false(): void
{
$user = User::factory()->create();
$result = $this->service->deleteNotification($user, 'nonexistent-uuid');
$this->assertFalse($result);
}
}
@@ -0,0 +1,183 @@
<?php
namespace Tests\Unit\Services;
use App\Models\NotificationDefinition;
use App\Models\NotificationTemplate;
use App\Services\NotificationTemplateService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* NotificationTemplateService 테스트
*
* 알림 템플릿 조회, 캐싱, 수정, 미리보기 동작을 검증합니다.
*/
class NotificationTemplateServiceTest extends TestCase
{
use RefreshDatabase;
private NotificationTemplateService $service;
protected function setUp(): void
{
parent::setUp();
$this->service = app(NotificationTemplateService::class);
}
/**
* resolve()가 활성 템플릿을 반환하는지 확인
*/
public function test_resolve_returns_active_template(): void
{
$definition = NotificationDefinition::create([
'type' => 'test_resolve',
'hook_prefix' => 'core.test',
'extension_type' => 'core',
'extension_identifier' => 'core',
'name' => ['ko' => '테스트'],
'variables' => [],
'channels' => ['mail'],
'hooks' => [],
'is_active' => true,
'is_default' => true,
]);
NotificationTemplate::create([
'definition_id' => $definition->id,
'channel' => 'mail',
'subject' => ['ko' => '제목', 'en' => 'Subject'],
'body' => ['ko' => '본문', 'en' => 'Body'],
'is_active' => true,
'is_default' => true,
]);
$this->service->invalidateCache('test_resolve', 'mail');
$result = $this->service->resolve('test_resolve', 'mail');
$this->assertNotNull($result);
$this->assertEquals('mail', $result->channel);
}
/**
* resolve()가 비활성 템플릿을 반환하지 않는지 확인
*/
public function test_resolve_returns_null_for_inactive_template(): void
{
$definition = NotificationDefinition::create([
'type' => 'test_inactive',
'hook_prefix' => 'core.test',
'extension_type' => 'core',
'extension_identifier' => 'core',
'name' => ['ko' => '테스트'],
'variables' => [],
'channels' => ['mail'],
'hooks' => [],
'is_active' => true,
'is_default' => true,
]);
NotificationTemplate::create([
'definition_id' => $definition->id,
'channel' => 'mail',
'subject' => ['ko' => '제목'],
'body' => ['ko' => '본문'],
'is_active' => false,
'is_default' => true,
]);
$this->service->invalidateCache('test_inactive', 'mail');
$result = $this->service->resolve('test_inactive', 'mail');
$this->assertNull($result);
}
/**
* updateTemplate()이 템플릿을 수정하는지 확인
*/
public function test_update_template(): void
{
$definition = NotificationDefinition::create([
'type' => 'test_update',
'hook_prefix' => 'core.test',
'extension_type' => 'core',
'extension_identifier' => 'core',
'name' => ['ko' => '테스트'],
'variables' => [],
'channels' => ['mail'],
'hooks' => [],
'is_active' => true,
'is_default' => true,
]);
$template = NotificationTemplate::create([
'definition_id' => $definition->id,
'channel' => 'mail',
'subject' => ['ko' => '원본 제목'],
'body' => ['ko' => '원본 본문'],
'is_active' => true,
'is_default' => true,
]);
$updated = $this->service->updateTemplate($template, [
'subject' => ['ko' => '수정된 제목'],
'body' => ['ko' => '수정된 본문'],
]);
$this->assertEquals(['ko' => '수정된 제목'], $updated->subject);
$this->assertEquals(['ko' => '수정된 본문'], $updated->body);
}
/**
* toggleActive()가 활성 상태를 반전하는지 확인
*/
public function test_toggle_active(): void
{
$definition = NotificationDefinition::create([
'type' => 'test_toggle',
'hook_prefix' => 'core.test',
'extension_type' => 'core',
'extension_identifier' => 'core',
'name' => ['ko' => '테스트'],
'variables' => [],
'channels' => ['mail'],
'hooks' => [],
'is_active' => true,
'is_default' => true,
]);
$template = NotificationTemplate::create([
'definition_id' => $definition->id,
'channel' => 'mail',
'subject' => ['ko' => '제목'],
'body' => ['ko' => '본문'],
'is_active' => true,
'is_default' => true,
]);
$result = $this->service->toggleActive($template);
$this->assertFalse($result->is_active);
}
/**
* getPreview()가 변수를 치환하는지 확인
*/
public function test_get_preview_replaces_variables(): void
{
$result = $this->service->getPreview([
'subject' => ['ko' => '{name}님 환영합니다'],
'body' => ['ko' => '<p>{app_name}입니다</p>'],
'locale' => 'ko',
'variables' => [
'name' => '홍길동',
'app_name' => 'G7',
],
]);
$this->assertEquals('홍길동님 환영합니다', $result['subject']);
$this->assertEquals('<p>G7입니다</p>', $result['body']);
}
}
@@ -24,7 +24,9 @@ class SettingsServiceAppConfigTest extends TestCase
}
/**
* getAppConfigForFrontend()가 supportedTimezones를 올바르게 반환하는지 테스트합니다.
* getAppConfigForFrontend()가 supportedTimezones를 올바른 Select 옵션 형식으로 반환하는지 테스트합니다.
*
* 전 IANA 타임존 지원 + 오프셋 라벨 형식
*/
public function test_get_app_config_returns_supported_timezones(): void
{
@@ -34,8 +36,58 @@ class SettingsServiceAppConfigTest extends TestCase
$this->assertArrayHasKey('supportedTimezones', $result);
$this->assertIsArray($result['supportedTimezones']);
$this->assertContains('Asia/Seoul', $result['supportedTimezones']);
$this->assertContains('UTC', $result['supportedTimezones']);
$this->assertNotEmpty($result['supportedTimezones']);
// 각 항목이 {value, label} 형식인지 확인
foreach ($result['supportedTimezones'] as $item) {
$this->assertIsArray($item);
$this->assertArrayHasKey('value', $item);
$this->assertArrayHasKey('label', $item);
$this->assertMatchesRegularExpression(
'/^\(UTC[+-]\d{2}:\d{2}\) .+/',
$item['label']
);
}
// Asia/Seoul, UTC가 포함되는지 확인 (value 기준)
$values = array_column($result['supportedTimezones'], 'value');
$this->assertContains('Asia/Seoul', $values);
$this->assertContains('UTC', $values);
}
/**
* supportedTimezones가 IANA 전체 목록 크기와 일치하는지 테스트합니다.
*/
public function test_supported_timezones_contains_full_iana_list(): void
{
$service = app(SettingsService::class);
$result = $service->getAppConfigForFrontend();
$this->assertCount(
count(\DateTimeZone::listIdentifiers()),
$result['supportedTimezones']
);
}
/**
* supportedTimezones가 오프셋 오름차순으로 정렬되는지 테스트합니다.
*/
public function test_supported_timezones_sorted_by_offset_ascending(): void
{
$service = app(SettingsService::class);
$result = $service->getAppConfigForFrontend();
$now = new \DateTime('now', new \DateTimeZone('UTC'));
$prevOffset = null;
foreach ($result['supportedTimezones'] as $item) {
$offset = (new \DateTimeZone($item['value']))->getOffset($now);
if ($prevOffset !== null) {
$this->assertGreaterThanOrEqual($prevOffset, $offset);
}
$prevOffset = $offset;
}
}
/**
@@ -0,0 +1,117 @@
<?php
namespace Tests\Unit\Services;
use App\Contracts\Extension\CacheInterface;
use App\Contracts\Repositories\AttachmentRepositoryInterface;
use App\Contracts\Repositories\ConfigRepositoryInterface;
use App\Services\SettingsService;
use Illuminate\Support\Facades\Artisan;
use Tests\TestCase;
/**
* SettingsService 설정 저장 시 config:clear 자동 실행 테스트
*
* 환경설정 저장 후 Laravel 설정 캐시를 자동으로 클리어하여
* config:cache 상태에서도 변경사항이 즉시 반영되는지 검증합니다.
*/
class SettingsServiceConfigClearTest extends TestCase
{
private function mockDependencies(array $configExpectations): SettingsService
{
$configRepository = $this->mock(ConfigRepositoryInterface::class)->shouldIgnoreMissing();
foreach ($configExpectations as $expectation) {
$configRepository->shouldReceive($expectation['method'])
->with(...$expectation['args'])
->andReturn($expectation['return']);
}
$this->mock(AttachmentRepositoryInterface::class)->shouldIgnoreMissing();
return app(SettingsService::class);
}
/**
* 일반 탭 설정 저장 시 config:clear가 호출되는지 테스트합니다.
*/
public function test_save_settings_calls_config_clear(): void
{
Artisan::shouldReceive('call')
->with('config:clear')
->once();
$this->mock(CacheInterface::class)
->shouldReceive('forget')
->with('settings.system')
->once()
->andReturn(true);
$service = $this->mockDependencies([
['method' => 'getCategory', 'args' => ['mail'], 'return' => []],
['method' => 'saveCategory', 'args' => ['mail', \Mockery::type('array')], 'return' => true],
]);
$result = $service->saveSettings([
'_tab' => 'mail',
'mail' => ['mailer' => 'smtp'],
]);
$this->assertTrue($result);
}
/**
* advanced 탭 설정 저장 시 config:clear가 호출되는지 테스트합니다.
*/
public function test_save_advanced_settings_calls_config_clear(): void
{
Artisan::shouldReceive('call')
->with('config:clear')
->once();
$this->mock(CacheInterface::class)
->shouldReceive('forget')
->with('settings.system')
->once()
->andReturn(true);
$service = $this->mockDependencies([
['method' => 'getCategory', 'args' => ['cache'], 'return' => []],
['method' => 'saveCategory', 'args' => ['cache', \Mockery::type('array')], 'return' => true],
]);
$result = $service->saveSettings([
'_tab' => 'advanced',
'advanced' => ['enabled' => true],
]);
$this->assertTrue($result);
}
/**
* 설정 저장 실패 시 config:clear가 호출되지 않는지 테스트합니다.
*/
public function test_save_settings_does_not_call_config_clear_on_failure(): void
{
Artisan::shouldReceive('call')
->with('config:clear')
->never();
$this->mock(CacheInterface::class)
->shouldReceive('forget')
->with('settings.system')
->never();
$service = $this->mockDependencies([
['method' => 'getCategory', 'args' => ['mail'], 'return' => []],
['method' => 'saveCategory', 'args' => ['mail', \Mockery::type('array')], 'return' => false],
]);
$result = $service->saveSettings([
'_tab' => 'mail',
'mail' => ['mailer' => 'smtp'],
]);
$this->assertFalse($result);
}
}