Files
Gnuboard7/tests/Unit/Services/PluginSettingsServiceTest.php
HeuJung 85e266d361 fix(core,extensions): 확장 쓰기 경로 공통화 · HTMLPurifier 정의 캐시 storage 이전
https://github.com/gnuboard/g7/issues/125 — 상품 상세설명을 HTML 로 저장할 때
HTMLPurifier 가 모듈 vendor 폴더 안에 정의 캐시를 만들려다 실패해 저장이 매번 500 으로
끝나던 문제를 고친다. vendor 를 읽기 전용으로 두는 표준 배포에서 그 쓰기는 예외가 아니라
PHP 경고로 나오고 Laravel 이 이를 ErrorException 으로 승격시킨다. 캐시는 설정 해시당 1회만
기록되므로 캐시가 영영 생기지 않아 재시도해도 같은 결과였다.

캐시 경로를 storage 아래로 옮기고, 그 경로마저 확보하지 못하면 캐시만 끄고 정화는 그대로
수행한다 — 캐시는 성능 장치이고 정화는 보안 장치라, 전자의 실패가 후자를 건너뛰게 만들면
안 된다. 저장은 성공하므로 운영자에게 도달하는 흔적이 로그 하나뿐이라 error 수준으로 남긴다
(출하 기본 로그 수준이 error 라 warning 은 기본 설치 상태에서 파일에 남지 않는다).

그 과정에서 갈라져 있던 두 축을 코어 한 곳으로 모은다.

- 쓰기 디렉토리 확보: 억제 생성·chmod·setgid·소유권 상속·쓰기 판정 절차가 정적 게시와
 정의 캐시 두 곳에 서로 다른 하드닝으로 복제돼 있었다(억제 mkdir·setgid·clearstatcache 가
 사본마다 한쪽씩 빠져 있었다). FilePermissionHelper 의 ensureWritableDirectory 와
 hardenDirectory 로 통합하고, 실패 사유는 out 파라미터로 올려 정책(조용한 성능 저하 대
 시끄러운 실패)은 호출부가 정하게 둔다.

- 확장 저장 경로: storage_path('app/modules/…') 손조립이 30곳에 흩어져 있어 테스트 격리
 분기를 넣으려면 사본마다 복제해야 했고, 한 곳만 빠뜨려도 그 확장의 테스트가 운영 설정
 파일을 덮어쓴다. 디스크 root 를 단일 출처로 읽는 ExtensionStoragePath 로 전환하고 테스트
 분기는 config/filesystems.php 한 줄에서 끝낸다.

함께 고친 것

- 테스트가 운영 라우트 캐시로 부팅해 확장 allowlist 가 라우트 축에서 통째로 무력화되던
 문제. 삭제가 아니라 경로를 돌린다 — 라우트 캐시는 확장 작업 전까지 재생성되지 않아,
 삭제하면 운영 사이트가 그때까지 라우트 파일 스캔 경로로 떨어진다.
- PHPUnit 프로세스가 확장 vendor 의 제3자 composer 패키지를 오토로드하지 않아 그 패키지를
 쓰는 코드 경로가 통째로 테스트 불가였던 문제. 확장 자신의 오토로더를 그대로 쓰면 활성
 디렉토리가 _bundled 를 이기고 base path 유추까지 깨지므로, 생성된 맵에서 제3자 항목만
 골라 별도 로더로 등록한다.
- 게시 폴더가 setgid 를 갖지 않아, 명령줄과 웹이 번갈아 만든 하위 폴더를 다른 쪽이 쓰지
 못하던 문제.
- 관리자 템플릿이 HTML 정화 라이브러리를 직접 지정하지 않아 전이 의존으로 딸려온 구버전이
 쓰이던 문제.

동반 산출물

- 규정 표(·AGENTS.md) 6행 + storage-driver/service-repository/testing-guide 문서
- audit 룰 2종 + coverage 6항목. 저장소가 이미 전량 전환돼 전수 실행이 공허 통과하므로
 판정식은 픽스처 36건이 잠근다
- INSTALL.md 에 설치 후 파일 권한 절 추가 (vendor 쓰기 권한 불요를 명시)
2026-08-28 15:22:22 +09:00

985 lines
31 KiB
PHP

<?php
namespace Tests\Unit\Services;
use App\Extension\PluginManager;
use App\Extension\TemplateManager;
use App\Services\LayoutService;
use App\Services\PluginSettingsService;
use App\Support\ExtensionStoragePath;
use Illuminate\Support\Facades\Crypt;
use Mockery;
use Tests\Helpers\MocksExtensions;
use Tests\TestCase;
/**
* PluginSettingsService 단위 테스트
*
* 플러그인 설정 조회, 저장, 레이아웃 조회 기능을 테스트합니다.
* 설정은 파일 기반으로 storage/app/plugins/{identifier}/settings/setting.json에 저장됩니다.
*/
class PluginSettingsServiceTest extends TestCase
{
use MocksExtensions;
private PluginSettingsService $service;
private PluginManager $pluginManager;
private TemplateManager $templateManager;
private LayoutService $layoutService;
private string $testSettingsDir;
protected function setUp(): void
{
parent::setUp();
$this->pluginManager = app(PluginManager::class);
$this->templateManager = app(TemplateManager::class);
$this->layoutService = app(LayoutService::class);
$this->service = new PluginSettingsService(
$this->pluginManager,
$this->templateManager,
$this->layoutService
);
// 테스트용 설정 디렉토리 경로
$this->testSettingsDir = dirname(ExtensionStoragePath::plugin('placeholder'));
}
// ========================================================================
// get() 메서드 테스트
// ========================================================================
/**
* 존재하지 않는 플러그인 조회 시 기본값 반환
*/
public function test_get_returns_default_when_plugin_not_found(): void
{
$result = $this->service->get('nonexistent-plugin');
$this->assertNull($result);
}
/**
* 존재하지 않는 플러그인에 기본값 지정 시 해당 기본값 반환
*/
public function test_get_returns_custom_default_when_plugin_not_found(): void
{
$defaultValue = ['key' => 'default'];
$result = $this->service->get('nonexistent-plugin', null, $defaultValue);
$this->assertEquals($defaultValue, $result);
}
/**
* 플러그인 전체 설정 조회 성공
*/
public function test_get_returns_all_settings_when_key_is_null(): void
{
// Mock plugin with config values
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => 'test-settings-plugin',
'configValues' => [
'api_key' => 'default-api-key',
'enabled' => true,
'timeout' => 30,
],
'settingsSchema' => [],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with('test-settings-plugin')
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->get('test-settings-plugin');
$this->assertIsArray($result);
$this->assertArrayHasKey('api_key', $result);
$this->assertArrayHasKey('enabled', $result);
$this->assertArrayHasKey('timeout', $result);
}
/**
* 특정 키의 설정값 조회 성공
*/
public function test_get_returns_specific_key_value(): void
{
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => 'test-key-plugin',
'configValues' => [
'api_key' => 'my-secret-key',
'timeout' => 60,
],
'settingsSchema' => [],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with('test-key-plugin')
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->get('test-key-plugin', 'timeout');
$this->assertEquals(60, $result);
}
/**
* 존재하지 않는 키 조회 시 기본값 반환
*/
public function test_get_returns_default_for_missing_key(): void
{
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => 'test-missing-key-plugin',
'configValues' => ['existing_key' => 'value'],
'settingsSchema' => [],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with('test-missing-key-plugin')
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->get('test-missing-key-plugin', 'nonexistent_key', 'default_value');
$this->assertEquals('default_value', $result);
}
/**
* 중첩된 키 값 조회 (dot notation)
*/
public function test_get_returns_nested_key_value(): void
{
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => 'test-nested-plugin',
'configValues' => [
'database' => [
'host' => 'localhost',
'port' => 3306,
],
],
'settingsSchema' => [],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with('test-nested-plugin')
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$host = $service->get('test-nested-plugin', 'database.host');
$port = $service->get('test-nested-plugin', 'database.port');
$this->assertEquals('localhost', $host);
$this->assertEquals(3306, $port);
}
// ========================================================================
// save() 메서드 테스트
// ========================================================================
/**
* 존재하지 않는 플러그인 저장 시 false 반환
*/
public function test_save_returns_false_when_plugin_not_found(): void
{
$result = $this->service->save('nonexistent-plugin', ['key' => 'value']);
$this->assertFalse($result);
}
/**
* 플러그인 설정 저장 성공
*/
public function test_save_stores_settings_successfully(): void
{
$identifier = 'test-save-plugin-'.uniqid();
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'configValues' => [],
'settingsSchema' => [],
'storage' => [
'exists' => false,
'put' => true,
],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->save($identifier, [
'api_key' => 'new-api-key',
'enabled' => true,
]);
$this->assertTrue($result);
}
/**
* 기존 설정과 병합되는지 확인
*/
public function test_save_merges_with_existing_settings(): void
{
$identifier = 'test-merge-plugin-'.uniqid();
// 기존 설정 파일 내용
$existingContent = json_encode([
'existing_key' => 'existing_value',
'to_update' => 'old_value',
]);
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'configValues' => [],
'settingsSchema' => [],
'storage' => [
'exists' => true,
'get' => $existingContent,
'put' => true,
],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->save($identifier, [
'to_update' => 'new_value',
'new_key' => 'new_value',
]);
$this->assertTrue($result);
}
// ========================================================================
// getLayout() 메서드 테스트
// ========================================================================
/**
* 플러그인 인스턴스가 없으면 null 반환
*/
public function test_get_layout_returns_null_when_plugin_instance_not_found(): void
{
$result = $this->service->getLayout('nonexistent-plugin');
$this->assertNull($result);
}
/**
* 레이아웃 파일이 없으면 null 반환
*/
public function test_get_layout_returns_null_when_layout_file_not_exists(): void
{
// Mock PluginManager to return a plugin without layout file
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => 'test-no-layout',
'settingsLayout' => '/nonexistent/path/settings.json',
]);
$mockPluginManager->shouldReceive('getPlugin')
->with('test-no-layout')
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getLayout('test-no-layout');
$this->assertNull($result);
}
/**
* 실제 Daum 우편번호 플러그인 레이아웃 조회 테스트
*/
public function test_get_layout_returns_layout_for_daum_postcode_plugin(): void
{
// Daum 우편번호 플러그인이 설치되어 있는지 확인
$pluginPath = base_path('plugins/sirsoft-daum_postcode/resources/layouts/settings.json');
if (! file_exists($pluginPath)) {
$this->markTestSkipped('Daum postcode plugin layout file not found');
}
// Mock PluginManager
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => 'sirsoft-daum_postcode',
'settingsLayout' => $pluginPath,
]);
$mockPluginManager->shouldReceive('getPlugin')
->with('sirsoft-daum_postcode')
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getLayout('sirsoft-daum_postcode');
$this->assertIsArray($result);
$this->assertArrayHasKey('version', $result);
$this->assertArrayHasKey('meta', $result);
$this->assertArrayHasKey('schema', $result);
}
/**
* 레이아웃 파일 파싱 실패 시 null 반환
*/
public function test_get_layout_returns_null_on_invalid_json(): void
{
// 임시 잘못된 JSON 파일 생성
$tempPath = sys_get_temp_dir().'/invalid_layout_'.uniqid().'.json';
file_put_contents($tempPath, 'invalid json content {{{');
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => 'test-invalid-json',
'settingsLayout' => $tempPath,
]);
$mockPluginManager->shouldReceive('getPlugin')
->with('test-invalid-json')
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getLayout('test-invalid-json');
$this->assertNull($result);
// 임시 파일 삭제
@unlink($tempPath);
}
/**
* 레이아웃이 sanitize 되는지 확인 (components, data_sources 대상)
*/
public function test_get_layout_sanitizes_layout_content(): void
{
// 임시 레이아웃 파일 생성 (components에 XSS 포함)
$tempPath = sys_get_temp_dir().'/xss_layout_'.uniqid().'.json';
$layoutContent = json_encode([
'version' => '1.0.0',
'meta' => [
'title' => 'Test Plugin Settings',
],
'schema' => [
'field1' => [
'type' => 'string',
'label' => 'API Key',
],
],
'components' => [
[
'type' => 'basic',
'name' => 'Div',
'props' => [
'onClick' => 'javascript:alert("XSS")',
],
],
],
]);
file_put_contents($tempPath, $layoutContent);
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => 'test-xss-plugin',
'settingsLayout' => $tempPath,
]);
$mockPluginManager->shouldReceive('getPlugin')
->with('test-xss-plugin')
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getLayout('test-xss-plugin');
$this->assertIsArray($result);
// 레이아웃이 정상적으로 반환되는지 확인
$this->assertArrayHasKey('version', $result);
$this->assertArrayHasKey('meta', $result);
$this->assertArrayHasKey('schema', $result);
// components의 props에서 javascript: 프로토콜이 제거되었는지 확인
$this->assertArrayHasKey('components', $result);
$this->assertStringNotContainsString('javascript:', $result['components'][0]['props']['onClick'] ?? '');
// 임시 파일 삭제
@unlink($tempPath);
}
// ========================================================================
// 암호화/복호화 테스트
// ========================================================================
/**
* 민감한 필드가 암호화되어 저장되는지 확인
*/
public function test_save_encrypts_sensitive_fields(): void
{
$identifier = 'test-encrypt-plugin-'.uniqid();
// Mock plugin with sensitive field schema
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'configValues' => [],
'settingsSchema' => [
'api_key' => [
'type' => 'string',
'sensitive' => true,
],
'public_key' => [
'type' => 'string',
'sensitive' => false,
],
],
'storage' => [
'exists' => false,
'put' => true,
],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->save($identifier, [
'api_key' => 'secret-api-key',
'public_key' => 'public-value',
]);
$this->assertTrue($result);
// 암호화 로직은 내부적으로 동작하며, put이 호출되었으므로 성공으로 간주
}
/**
* 민감한 필드가 복호화되어 조회되는지 확인
*/
public function test_get_decrypts_sensitive_fields(): void
{
$identifier = 'test-decrypt-plugin-'.uniqid();
// 암호화된 값으로 설정 파일 내용 생성
$encryptedValue = Crypt::encryptString('decrypted-secret');
$fileContent = json_encode([
'secret_key' => $encryptedValue,
'normal_key' => 'normal-value',
]);
// Mock plugin with sensitive field schema and Storage
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'configValues' => [],
'settingsSchema' => [
'secret_key' => [
'type' => 'string',
'sensitive' => true,
],
'normal_key' => [
'type' => 'string',
'sensitive' => false,
],
],
'storage' => [
'exists' => true,
'get' => $fileContent,
],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->get($identifier);
// 민감한 필드는 복호화되어 반환됨
$this->assertEquals('decrypted-secret', $result['secret_key']);
// 비민감 필드는 그대로 반환됨
$this->assertEquals('normal-value', $result['normal_key']);
}
/**
* 복호화 실패 시 원래 값 유지 (레거시 데이터 호환)
*/
public function test_get_preserves_value_on_decrypt_failure(): void
{
$identifier = 'test-legacy-plugin-'.uniqid();
// 암호화되지 않은 레거시 값으로 설정 파일 내용 생성
$fileContent = json_encode([
'old_secret' => 'plain-text-secret', // 암호화되지 않은 레거시 값
]);
// Mock plugin with sensitive field schema
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'configValues' => [],
'settingsSchema' => [
'old_secret' => [
'type' => 'string',
'sensitive' => true,
],
],
'storage' => [
'exists' => true,
'get' => $fileContent,
],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->get($identifier);
// 복호화 실패 시 원래 값 유지
$this->assertEquals('plain-text-secret', $result['old_secret']);
}
/**
* 이미 암호화된 값은 다시 암호화하지 않음
*/
public function test_save_does_not_double_encrypt(): void
{
$identifier = 'test-double-encrypt-plugin-'.uniqid();
$originalValue = 'original-secret';
$encryptedOnce = Crypt::encryptString($originalValue);
// Mock plugin with sensitive field schema
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'configValues' => [],
'settingsSchema' => [
'api_key' => [
'type' => 'string',
'sensitive' => true,
],
],
'storage' => [
'exists' => false,
'put' => true,
],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
// 이미 암호화된 값을 저장
$result = $service->save($identifier, [
'api_key' => $encryptedOnce,
]);
$this->assertTrue($result);
// 암호화 로직은 내부적으로 동작하며, put이 호출되었으므로 성공으로 간주
}
/**
* reset() 메서드가 설정 파일을 삭제하는지 확인
*/
public function test_reset_deletes_settings_file(): void
{
$identifier = 'test-reset-plugin-'.uniqid();
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'storage' => [
'exists' => true,
'delete' => true,
],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->reset($identifier);
$this->assertTrue($result);
}
/**
* clearCache() 메서드가 캐시를 초기화하는지 확인
*/
public function test_clear_cache_clears_settings_cache(): void
{
$identifier = 'test-cache-plugin';
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'configValues' => ['initial' => 'value'],
'settingsSchema' => [],
]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
// 첫 번째 조회 (캐시에 저장됨)
$service->get($identifier);
// 캐시 초기화
$service->clearCache($identifier);
// 캐시가 초기화되었으므로 다시 getPlugin이 호출되어야 함
// (이 테스트는 내부 동작을 확인하는 것이 어려우므로 예외 없이 실행되는지만 확인)
$this->assertTrue(true);
}
// ========================================================================
// getAllActiveSettings() 메서드 테스트
// ========================================================================
/**
* frontend_schema가 있는 defaults.json이 있을 때 스키마 기반 필터링
*/
public function test_get_all_active_settings_uses_frontend_schema_when_defaults_exists(): void
{
$identifier = 'test-frontend-schema-plugin';
// defaults.json 임시 파일 생성
$tempDefaultsPath = sys_get_temp_dir().'/defaults_'.uniqid().'.json';
file_put_contents($tempDefaultsPath, json_encode([
'defaults' => [
'display_mode' => 'layer',
'popup_width' => 500,
'theme_color' => '#1D4ED8',
],
'frontend_schema' => [
'display_mode' => ['expose' => true],
'popup_width' => ['expose' => true],
'theme_color' => ['expose' => false],
],
]));
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'hasSettings' => true,
'configValues' => [
'display_mode' => 'layer',
'popup_width' => 500,
'theme_color' => '#1D4ED8',
],
'settingsSchema' => [],
'settingsDefaultsPath' => $tempDefaultsPath,
]);
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPluginManager->shouldReceive('getActivePlugins')
->andReturn([$mockPlugin]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getAllActiveSettings();
$this->assertArrayHasKey($identifier, $result);
$this->assertArrayHasKey('display_mode', $result[$identifier]);
$this->assertArrayHasKey('popup_width', $result[$identifier]);
$this->assertArrayNotHasKey('theme_color', $result[$identifier]);
@unlink($tempDefaultsPath);
}
/**
* defaults.json이 없을 때 기존 동작 유지 (sensitive만 제외)
*/
public function test_get_all_active_settings_falls_back_to_exclude_sensitive_when_no_defaults(): void
{
$identifier = 'test-no-defaults-plugin';
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'hasSettings' => true,
'configValues' => [
'display_mode' => 'popup',
'api_key' => 'secret-key',
],
'settingsSchema' => [
'display_mode' => ['type' => 'string'],
'api_key' => ['type' => 'string', 'sensitive' => true],
],
'settingsDefaultsPath' => null,
]);
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPluginManager->shouldReceive('getActivePlugins')
->andReturn([$mockPlugin]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getAllActiveSettings();
$this->assertArrayHasKey($identifier, $result);
$this->assertArrayHasKey('display_mode', $result[$identifier]);
$this->assertArrayNotHasKey('api_key', $result[$identifier]);
}
/**
* hasSettings()=false인 플러그인은 결과에 미포함
*/
public function test_get_all_active_settings_skips_plugins_without_settings(): void
{
$mockPlugin = $this->createMockPlugin([
'identifier' => 'no-settings-plugin',
'hasSettings' => false,
'configValues' => [],
'settingsSchema' => [],
]);
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPluginManager->shouldReceive('getActivePlugins')
->andReturn([$mockPlugin]);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getAllActiveSettings();
$this->assertEmpty($result);
}
/**
* frontend_schema로 카테고리 구조 필터링 (카테고리 expose:false → 전체 제외)
*/
public function test_get_all_active_settings_filters_by_category_expose(): void
{
$identifier = 'test-category-expose-plugin';
// 카테고리 구조 설정을 가진 defaults.json
$tempDefaultsPath = sys_get_temp_dir().'/defaults_cat_'.uniqid().'.json';
file_put_contents($tempDefaultsPath, json_encode([
'defaults' => [
'general' => ['site_name' => 'Test'],
'secrets' => ['api_key' => 'hidden'],
],
'frontend_schema' => [
'general' => ['expose' => true],
'secrets' => ['expose' => false],
],
]));
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'hasSettings' => true,
'configValues' => [
'general' => ['site_name' => 'Test'],
'secrets' => ['api_key' => 'hidden'],
],
'settingsSchema' => [],
'settingsDefaultsPath' => $tempDefaultsPath,
]);
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPluginManager->shouldReceive('getActivePlugins')
->andReturn([$mockPlugin]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getAllActiveSettings();
$this->assertArrayHasKey($identifier, $result);
$this->assertArrayHasKey('general', $result[$identifier]);
$this->assertArrayNotHasKey('secrets', $result[$identifier]);
@unlink($tempDefaultsPath);
}
/**
* frontend_schema로 필드 레벨 필터링 (필드 expose:false → 해당 필드만 제외)
*/
public function test_get_all_active_settings_filters_by_field_expose(): void
{
$identifier = 'test-field-expose-plugin';
$tempDefaultsPath = sys_get_temp_dir().'/defaults_field_'.uniqid().'.json';
file_put_contents($tempDefaultsPath, json_encode([
'defaults' => [
'payment' => [
'currency' => 'KRW',
'secret_key' => 'sk_xxx',
'public_key' => 'pk_xxx',
],
],
'frontend_schema' => [
'payment' => [
'expose' => true,
'fields' => [
'currency' => ['expose' => true],
'secret_key' => ['expose' => false],
'public_key' => ['expose' => true],
],
],
],
]));
$mockPlugin = $this->createMockPlugin([
'identifier' => $identifier,
'hasSettings' => true,
'configValues' => [
'payment' => [
'currency' => 'KRW',
'secret_key' => 'sk_xxx',
'public_key' => 'pk_xxx',
],
],
'settingsSchema' => [],
'settingsDefaultsPath' => $tempDefaultsPath,
]);
$mockPluginManager = Mockery::mock(PluginManager::class);
$mockPluginManager->shouldReceive('getActivePlugins')
->andReturn([$mockPlugin]);
$mockPluginManager->shouldReceive('getPlugin')
->with($identifier)
->andReturn($mockPlugin);
$service = new PluginSettingsService(
$mockPluginManager,
$this->templateManager,
$this->layoutService
);
$result = $service->getAllActiveSettings();
$this->assertArrayHasKey($identifier, $result);
$this->assertArrayHasKey('payment', $result[$identifier]);
$this->assertSame('KRW', $result[$identifier]['payment']['currency']);
$this->assertSame('pk_xxx', $result[$identifier]['payment']['public_key']);
$this->assertArrayNotHasKey('secret_key', $result[$identifier]['payment']);
@unlink($tempDefaultsPath);
}
protected function tearDown(): void
{
Mockery::close();
parent::tearDown();
}
}