Files
Gnuboard7/tests/Unit/Services/NotificationDefinitionServiceTest.php
HeuJung d17ea28da5 fix(core,board,ecommerce,page,kginicis): 정책값 하드코딩·계약 분리 결함 일괄 수정
관리자 환경설정이 값을 저장은 하지만 실제 동작에는 닿지 않던 결함군을 정리했다.
설정 화면(min/max)·저장 검증(FormRequest)·런타임 적용(Service) 세 계층이 각자
리터럴을 들고 있어 서로 조용히 갈라지던 것이 공통 원인이다.

경계값 SSoT 도입:
- config/core.php `settings_limits` 를 단일 출처로 두고, FormRequest 는 이 값으로
 규칙을 만들고 화면은 설정 응답의 `_meta.limits` 로 같은 값을 받아 바인딩한다.
- 게시판·이커머스도 각 모듈 config 의 limits 를 동일 구조로 노출한다.

적용되지 않던 정책을 실제로 적용:
- 비밀번호 최소 길이·특수문자 필수(신규 지정 7개 경로. 로그인은 제외 — 정책을
 올렸을 때 기존 회원이 자기 계정에 접근조차 못 하는 데드락을 막기 위함)
- 계정 잠금 시간 0 = 무한대(전용 컬럼 분리. timestamp 상한과 NULL 규약 때문에
 기존 컬럼 재사용이 불가능하다) + 관리자 수동 해제 경로
- 업로드 최대 크기·허용 확장자, 게시판 첨부 개수·댓글 깊이, 페이지 첨부 정책,
 장바구니 수량·구매 한도, 마일리지 사용 한도, 주문 부가세

파생 결함:
- 큐 Job(sync 드라이버)이 진행 중인 요청의 Request 바인딩을 덮어써, 뒤이어 실행되는
 훅 리스너가 헤더를 잃고 조용히 건너뛰었다. Job 이 원 바인딩을 복원하도록 고치고,
 전송 헤더가 필요한 리스너는 동기 실행으로 선언한다.
- 확장 업데이트 실패 시 상태만 되돌리고 상태 캐시를 비우지 않아, 그 확장의 관리자
 화면만 캐시 TTL(기본 하루) 동안 404 로 남았다. 실패 경로에도 무효화를 대칭으로
 두고, 빈 목록 자체를 캐시하지 않는다.
- 글 작성 시 첨부 파일이 Service 로 전달되지 않아 검증·권한은 통과하고 첨부만 사라졌다.
- 환경설정 저장 실패 안내가 내부 설정 키를 그대로 노출했다(105개 항목에 라벨 부여).

재발 방지:
- audit 룰 3종(레이아웃 경계 리터럴 / FormRequest 경계 불일치 / Service 재클램프)
- 테스트 실행 범위 강제 훅(check-test-scope)
- 트러블슈팅 사례 2건(큐 Job 요청 오염 / 확장 상태 캐시 고착)

공개 이슈: gnuboard/g7
2026-07-30 07:52:24 +09:00

224 lines
7.7 KiB
PHP

<?php
namespace Tests\Unit\Services;
use App\Models\NotificationDefinition;
use App\Services\NotificationDefinitionService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
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
{
// 코어 알림 정의(welcome 등)는 config/core.php 를 SSoT 로 부팅 시 DB 에 동기화되므로
// 같은 type 을 새로 만들면 중복이 된다. 이 테스트가 보려는 것은 resolve() 의 동작이라
// 코어가 선점하지 않는 전용 type 을 쓴다.
NotificationDefinition::create([
'type' => 'active_resolve_target',
'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('active_resolve_target');
$result = $this->service->resolve('active_resolve_target');
$this->assertNotNull($result);
$this->assertEquals('active_resolve_target', $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();
// 코어 알림 정의가 부팅 시 함께 동기화되므로 절대 개수로는 판정할 수 없다.
// 이 테스트의 주제는 "활성만 돌려주는가" 이므로 이 테스트가 만든 두 건으로 판정한다.
$types = $result->pluck('type');
$this->assertContains('active_one', $types);
$this->assertNotContains('inactive_one', $types);
}
/**
* 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);
}
/**
* getAllActive() 캐시 히트 시 notification_definitions DB 조회가 0건인지 확인.
*
* 서빙 API 부팅 비용 최적화 검증 (계획서 §2-1 나): 동적 훅(알림) 등록 경로
* (NotificationHookListener::registerDynamicHooks → getAllActive)는 이미
* `['notification']` 태그로 캐시되어 있으므로, 첫 요청(캐시 워밍) 이후에는
* 매 요청 DB 조회가 발생하지 않아야 한다 (37ms 캐시 미스는 첫 요청 1회 비용).
*
* @scenario cache_state=present_but_testing_env, listener_type=action_sync, regeneration_trigger=extension_update, registration_source=plugin
*
* @effects notification_getAllActive_cache_hit_issues_zero_db_query
*/
public function test_get_all_active_cache_hit_issues_zero_db_query(): void
{
NotificationDefinition::create([
'type' => 'cache_hit_probe',
'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,
]);
// 1차 호출: 캐시 워밍 (DB 조회 발생)
$this->service->invalidateAllCache();
$this->service->getAllActive();
// 2차 호출: 캐시 히트 → notification_definitions 조회 0건이어야 함
DB::enableQueryLog();
$this->service->getAllActive();
$queries = DB::getQueryLog();
DB::disableQueryLog();
$definitionQueries = array_filter(
$queries,
fn ($q) => str_contains($q['query'], 'notification_definitions')
);
$this->assertCount(
0,
$definitionQueries,
'캐시 히트 시 notification_definitions DB 조회가 발생하지 않아야 합니다 (동적 훅 등록 비용 제거)'
);
}
}