fix(core,board,ecommerce): 조건부 검증 결함 패밀리 일괄 수정 및 실패 안내 노출

여러 화면에서 조건부(FormRequest) 검증이 우회되거나 과도하게 제한되던 결함을 한 계열로 묶어 수정한다.

- 검증 규칙 확장 필터 이름 10개를 나머지 92개와 동일 규칙으로 통일
- 설명 길이를 바이트가 아닌 글자 수로 계산(한글 오검출 해소)
- 비활성 언어팩 번역 보존한 채 수정 허용
- 알림 템플릿 제목 nullable 존중, 미지원 발송 수단 저장 차단
- 일정/실행 이력 목록 조회 검증 정합
- 게시판 첨부 미사용 시 빈 확장자 통과, new_display_hours/최소 길이 0 허용, 일괄 적용 override_values 범위 검증(SSoT)
- 이커머스 클레임 사유 조회 검증, 용어 정정
- 원문 i18n 키 노출 다수 해소, 저장/삭제 실패 시 사유 화면 노출
- 아이콘 크기/다크모드 대비 회귀 수정

번들 확장(모듈3·플러그인6·템플릿2·언어팩5) 버전 new-bump 및 CHANGELOG 반영, ja 언어팩 동기.
This commit is contained in:
HeuJung committed 2026-07-23 10:54:17 +09:00
1 parent c001b30a87
commit 7f8fb6870f
288 files changed
+5339 -1049

No files matched your search

@@ -269,8 +269,10 @@ class ComputedInheritedSaveTest extends TestCase
$this->assertSame('{{ "공통" }}', $merged['computed']['pageTitle']);
$this->assertSame('{{ items.length }}', $merged['computed']['rowCount']);
// 출처 맵: 덮은 키=route / 미덮은 부모 키=base / 자식 고유=route
$this->assertSame('route', $merged['__computedSource']['isReadOnly']);
// 출처 맵 3종: 덮은 키=route-override / 미덮은 부모 키=base / 자식 고유=route
// 'route'(순수 자식)와 'route-override'(부모를 덮음)를 구분해야 ComputedForm 이
// 공통값 되돌리기 버튼을 덮은 키에만 노출할 수 있다 (LayoutService::buildComputedSourceMap).
$this->assertSame('route-override', $merged['__computedSource']['isReadOnly']);
$this->assertSame('base', $merged['__computedSource']['pageTitle']);
$this->assertSame('route', $merged['__computedSource']['rowCount']);
+11 -9
View File
@@ -3,11 +3,13 @@
namespace Tests\Feature\Api\Admin;
use App\Enums\ExtensionOwnerType;
use App\Enums\PermissionType;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use App\Services\ModuleService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Route;
use Illuminate\Validation\ValidationException;
use Mockery;
use Tests\TestCase;
@@ -52,7 +54,7 @@ class ModuleUpdateTest extends TestCase
'description' => json_encode(['ko' => $permIdentifier.' 권한', 'en' => $permIdentifier.' Permission']),
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => \App\Enums\PermissionType::Admin,
'type' => PermissionType::Admin,
]
);
$permissionIds[] = $permission->id;
@@ -229,7 +231,7 @@ class ModuleUpdateTest extends TestCase
{
$mockService = Mockery::mock(ModuleService::class);
$mockService->shouldReceive('updateModule')
->with('test-module', Mockery::any(), 'overwrite')
->with('test-module', Mockery::any(), 'overwrite', false)
->once()
->andReturn([
'success' => true,
@@ -288,7 +290,7 @@ class ModuleUpdateTest extends TestCase
{
$mockService = Mockery::mock(ModuleService::class);
$mockService->shouldReceive('updateModule')
->with('test-module', Mockery::any(), 'overwrite')
->with('test-module', Mockery::any(), 'overwrite', false)
->once()
->andReturn([
'success' => true,
@@ -332,7 +334,7 @@ class ModuleUpdateTest extends TestCase
{
$mockService = Mockery::mock(ModuleService::class);
$mockService->shouldReceive('updateModule')
->with('nonexistent-module', Mockery::any(), 'overwrite')
->with('nonexistent-module', Mockery::any(), 'overwrite', false)
->once()
->andThrow(
ValidationException::withMessages([
@@ -353,7 +355,7 @@ class ModuleUpdateTest extends TestCase
{
$mockService = Mockery::mock(ModuleService::class);
$mockService->shouldReceive('updateModule')
->with('test-module', Mockery::any(), 'overwrite')
->with('test-module', Mockery::any(), 'overwrite', false)
->once()
->andThrow(new \RuntimeException('Unexpected error'));
$this->app->instance(ModuleService::class, $mockService);
@@ -389,7 +391,7 @@ class ModuleUpdateTest extends TestCase
public function test_check_updates_route_name_exists(): void
{
$this->assertTrue(
\Illuminate\Support\Facades\Route::has('api.admin.modules.check-updates'),
Route::has('api.admin.modules.check-updates'),
'Route api.admin.modules.check-updates should exist'
);
}
@@ -400,7 +402,7 @@ class ModuleUpdateTest extends TestCase
public function test_update_route_name_exists(): void
{
$this->assertTrue(
\Illuminate\Support\Facades\Route::has('api.admin.modules.update'),
Route::has('api.admin.modules.update'),
'Route api.admin.modules.update should exist'
);
}
@@ -416,7 +418,7 @@ class ModuleUpdateTest extends TestCase
{
$mockService = Mockery::mock(ModuleService::class);
$mockService->shouldReceive('updateModule')
->with('test-module', Mockery::any(), 'keep')
->with('test-module', Mockery::any(), 'keep', false)
->once()
->andReturn([
'success' => true,
@@ -492,7 +494,7 @@ class ModuleUpdateTest extends TestCase
public function test_check_modified_layouts_route_name_exists(): void
{
$this->assertTrue(
\Illuminate\Support\Facades\Route::has('api.admin.modules.check-modified-layouts'),
Route::has('api.admin.modules.check-modified-layouts'),
'Route api.admin.modules.check-modified-layouts should exist'
);
}
@@ -0,0 +1,204 @@
<?php
namespace Tests\Feature\Api\Admin;
use App\Extension\HookManager;
use App\Http\Requests\NotificationDefinition\UpdateNotificationDefinitionRequest;
use App\Http\Requests\NotificationTemplate\UpdateNotificationTemplateRequest;
use App\Models\NotificationDefinition;
use App\Rules\AvailableNotificationChannel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Routing\Route;
use Illuminate\Support\Facades\Validator;
use Tests\TestCase;
/**
* 알림 정의/템플릿 조건부 검증 테스트
*
* - 템플릿 subject: 컬럼이 nullable 인데 검증만 required 였던 스키마 불일치 회귀
* - 정의 channels: 허용 채널이 런타임(config + 훅)에 결정되므로 하드코딩 화이트리스트 금지
*/
class NotificationConditionalValidationTest extends TestCase
{
use RefreshDatabase;
/**
* 알림 정의를 생성합니다.
*
* @param array<int, string> $channels 채널 목록
* @return NotificationDefinition 생성된 정의
*/
private function makeDefinition(array $channels = ['mail']): NotificationDefinition
{
return NotificationDefinition::create([
'type' => 'conditional_validation_test',
'hook_prefix' => 'core',
'extension_type' => 'core',
'extension_identifier' => 'core',
'name' => ['ko' => '조건부 검증 테스트'],
'channels' => $channels,
'hooks' => [],
]);
}
/**
* 정의가 라우트 파라미터로 주입된 Update 요청을 생성합니다.
*
* @param NotificationDefinition $definition 대상 정의
* @return UpdateNotificationDefinitionRequest 요청 객체
*/
private function makeDefinitionRequest(NotificationDefinition $definition): UpdateNotificationDefinitionRequest
{
$request = new UpdateNotificationDefinitionRequest;
$request->setRouteResolver(function () use ($definition) {
$route = \Mockery::mock(Route::class);
$route->shouldReceive('parameter')->with('definition', null)->andReturn($definition);
return $route;
});
return $request;
}
/**
* subject 미전송(부분 수정)이 통과해야 한다 (스키마 정합)
*/
public function test_template_subject_can_be_omitted(): void
{
$request = new UpdateNotificationTemplateRequest;
$validator = Validator::make([
'body' => ['ko' => '본문'],
], $request->rules());
$this->assertTrue(
$validator->passes(),
'subject 미전송은 통과해야 함: '.json_encode($validator->errors()->toArray(), JSON_UNESCAPED_UNICODE)
);
}
/**
* subject null 전송이 통과해야 한다 (컬럼이 nullable)
*/
public function test_template_subject_can_be_null(): void
{
$request = new UpdateNotificationTemplateRequest;
$validator = Validator::make([
'subject' => null,
'body' => ['ko' => '본문'],
], $request->rules());
$this->assertTrue(
$validator->passes(),
'subject=null 은 통과해야 함: '.json_encode($validator->errors()->toArray(), JSON_UNESCAPED_UNICODE)
);
}
/**
* subject 를 전송하면 다국어 배열 계약은 그대로 검증되어야 한다 (완화가 검증을 무력화하지 않음)
*/
public function test_template_subject_still_validated_when_present(): void
{
$request = new UpdateNotificationTemplateRequest;
$validator = Validator::make([
'subject' => 'not-an-array',
'body' => ['ko' => '본문'],
], $request->rules());
$this->assertFalse($validator->passes(), 'subject 가 배열이 아니면 실패해야 함');
$this->assertArrayHasKey('subject', $validator->errors()->toArray());
}
/**
* body 는 계속 필수여야 한다 (컬럼이 NOT NULL)
*/
public function test_template_body_remains_required(): void
{
$request = new UpdateNotificationTemplateRequest;
$validator = Validator::make(['subject' => ['ko' => '제목']], $request->rules());
$this->assertFalse($validator->passes(), 'body 미전송은 실패해야 함');
$this->assertArrayHasKey('body', $validator->errors()->toArray());
}
/**
* 사용 가능한 채널은 통과해야 한다
*/
public function test_definition_accepts_available_channel(): void
{
$definition = $this->makeDefinition();
$request = $this->makeDefinitionRequest($definition);
$validator = Validator::make(['channels' => ['mail', 'database']], $request->rules());
$this->assertTrue(
$validator->passes(),
'config 에 선언된 채널은 통과해야 함: '.json_encode($validator->errors()->toArray(), JSON_UNESCAPED_UNICODE)
);
}
/**
* 알 수 없는 채널은 차단되어야 한다 (기존에는 임의 문자열이 그대로 저장됨)
*/
public function test_definition_rejects_unknown_channel(): void
{
$definition = $this->makeDefinition();
$request = $this->makeDefinitionRequest($definition);
$validator = Validator::make(['channels' => ['carrier-pigeon']], $request->rules());
$this->assertFalse($validator->passes(), '알 수 없는 채널은 실패해야 함');
$this->assertArrayHasKey('channels.0', $validator->errors()->toArray());
}
/**
* 이미 저장된 채널은 목록 밖이어도 통과해야 한다
*
* 채널을 제공하던 플러그인이 비활성화된 뒤에도 기존 레코드 수정이 막히면 안 된다.
*/
public function test_definition_accepts_persisted_channel_even_if_unavailable(): void
{
$definition = $this->makeDefinition(['mail', 'sms']);
$request = $this->makeDefinitionRequest($definition);
$validator = Validator::make(['channels' => ['mail', 'sms']], $request->rules());
$this->assertTrue(
$validator->passes(),
'이미 저장된 채널은 통과해야 함: '.json_encode($validator->errors()->toArray(), JSON_UNESCAPED_UNICODE)
);
}
/**
* 플러그인이 훅으로 추가한 채널도 허용되어야 한다 (하드코딩 화이트리스트 금지)
*/
public function test_definition_accepts_channel_added_by_hook(): void
{
HookManager::addFilter(
'core.notification.filter_available_channels',
fn (array $channels) => array_merge($channels, [['id' => 'kakao', 'name' => 'KakaoTalk']])
);
$rule = new AvailableNotificationChannel;
$message = null;
$rule->validate('channels.0', 'kakao', function ($failMessage) use (&$message) {
$message = (string) $failMessage;
});
$this->assertNull($message, '훅으로 추가된 채널은 통과해야 함');
}
/**
* 테스트 정리
*/
protected function tearDown(): void
{
\Mockery::close();
parent::tearDown();
}
}
+11 -9
View File
@@ -3,11 +3,13 @@
namespace Tests\Feature\Api\Admin;
use App\Enums\ExtensionOwnerType;
use App\Enums\PermissionType;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use App\Services\PluginService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Route;
use Illuminate\Validation\ValidationException;
use Mockery;
use Tests\TestCase;
@@ -52,7 +54,7 @@ class PluginUpdateTest extends TestCase
'description' => json_encode(['ko' => $permIdentifier.' 권한', 'en' => $permIdentifier.' Permission']),
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => \App\Enums\PermissionType::Admin,
'type' => PermissionType::Admin,
]
);
$permissionIds[] = $permission->id;
@@ -229,7 +231,7 @@ class PluginUpdateTest extends TestCase
{
$mockService = Mockery::mock(PluginService::class);
$mockService->shouldReceive('updatePlugin')
->with('test-plugin', Mockery::any(), 'overwrite')
->with('test-plugin', Mockery::any(), 'overwrite', false)
->once()
->andReturn([
'success' => true,
@@ -288,7 +290,7 @@ class PluginUpdateTest extends TestCase
{
$mockService = Mockery::mock(PluginService::class);
$mockService->shouldReceive('updatePlugin')
->with('test-plugin', Mockery::any(), 'overwrite')
->with('test-plugin', Mockery::any(), 'overwrite', false)
->once()
->andReturn([
'success' => true,
@@ -332,7 +334,7 @@ class PluginUpdateTest extends TestCase
{
$mockService = Mockery::mock(PluginService::class);
$mockService->shouldReceive('updatePlugin')
->with('nonexistent-plugin', Mockery::any(), 'overwrite')
->with('nonexistent-plugin', Mockery::any(), 'overwrite', false)
->once()
->andThrow(
ValidationException::withMessages([
@@ -353,7 +355,7 @@ class PluginUpdateTest extends TestCase
{
$mockService = Mockery::mock(PluginService::class);
$mockService->shouldReceive('updatePlugin')
->with('test-plugin', Mockery::any(), 'overwrite')
->with('test-plugin', Mockery::any(), 'overwrite', false)
->once()
->andThrow(new \RuntimeException('Unexpected error'));
$this->app->instance(PluginService::class, $mockService);
@@ -389,7 +391,7 @@ class PluginUpdateTest extends TestCase
public function test_check_updates_route_name_exists(): void
{
$this->assertTrue(
\Illuminate\Support\Facades\Route::has('api.admin.plugins.check-updates'),
Route::has('api.admin.plugins.check-updates'),
'Route api.admin.plugins.check-updates should exist'
);
}
@@ -400,7 +402,7 @@ class PluginUpdateTest extends TestCase
public function test_update_route_name_exists(): void
{
$this->assertTrue(
\Illuminate\Support\Facades\Route::has('api.admin.plugins.update'),
Route::has('api.admin.plugins.update'),
'Route api.admin.plugins.update should exist'
);
}
@@ -413,7 +415,7 @@ class PluginUpdateTest extends TestCase
{
$mockService = Mockery::mock(PluginService::class);
$mockService->shouldReceive('updatePlugin')
->with('test-plugin', Mockery::any(), 'keep')
->with('test-plugin', Mockery::any(), 'keep', false)
->once()
->andReturn([
'success' => true,
@@ -474,7 +476,7 @@ class PluginUpdateTest extends TestCase
public function test_check_modified_layouts_route_name_exists(): void
{
$this->assertTrue(
\Illuminate\Support\Facades\Route::has('api.admin.plugins.check-modified-layouts'),
Route::has('api.admin.plugins.check-modified-layouts'),
'Route api.admin.plugins.check-modified-layouts should exist'
);
}
+11 -9
View File
@@ -3,11 +3,13 @@
namespace Tests\Feature\Api\Admin;
use App\Enums\ExtensionOwnerType;
use App\Enums\PermissionType;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use App\Services\TemplateService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Route;
use Illuminate\Validation\ValidationException;
use Mockery;
use Tests\TestCase;
@@ -52,7 +54,7 @@ class TemplateUpdateTest extends TestCase
'description' => json_encode(['ko' => $permIdentifier.' 권한', 'en' => $permIdentifier.' Permission']),
'extension_type' => ExtensionOwnerType::Core,
'extension_identifier' => 'core',
'type' => \App\Enums\PermissionType::Admin,
'type' => PermissionType::Admin,
]
);
$permissionIds[] = $permission->id;
@@ -229,7 +231,7 @@ class TemplateUpdateTest extends TestCase
{
$mockService = Mockery::mock(TemplateService::class);
$mockService->shouldReceive('performVersionUpdate')
->with('test-template', 'overwrite')
->with('test-template', 'overwrite', false)
->once()
->andReturn([
'success' => true,
@@ -296,7 +298,7 @@ class TemplateUpdateTest extends TestCase
{
$mockService = Mockery::mock(TemplateService::class);
$mockService->shouldReceive('performVersionUpdate')
->with('test-template', 'overwrite')
->with('test-template', 'overwrite', false)
->once()
->andReturn([
'success' => true,
@@ -342,7 +344,7 @@ class TemplateUpdateTest extends TestCase
{
$mockService = Mockery::mock(TemplateService::class);
$mockService->shouldReceive('performVersionUpdate')
->with('nonexistent-template', 'overwrite')
->with('nonexistent-template', 'overwrite', false)
->once()
->andThrow(
ValidationException::withMessages([
@@ -363,7 +365,7 @@ class TemplateUpdateTest extends TestCase
{
$mockService = Mockery::mock(TemplateService::class);
$mockService->shouldReceive('performVersionUpdate')
->with('test-template', 'overwrite')
->with('test-template', 'overwrite', false)
->once()
->andThrow(new \RuntimeException('Unexpected error'));
$this->app->instance(TemplateService::class, $mockService);
@@ -396,7 +398,7 @@ class TemplateUpdateTest extends TestCase
{
$mockService = Mockery::mock(TemplateService::class);
$mockService->shouldReceive('performVersionUpdate')
->with('test-template', 'keep')
->with('test-template', 'keep', false)
->once()
->andReturn([
'success' => true,
@@ -506,7 +508,7 @@ class TemplateUpdateTest extends TestCase
public function test_check_updates_route_name_exists(): void
{
$this->assertTrue(
\Illuminate\Support\Facades\Route::has('api.admin.templates.check-updates'),
Route::has('api.admin.templates.check-updates'),
'Route api.admin.templates.check-updates should exist'
);
}
@@ -517,7 +519,7 @@ class TemplateUpdateTest extends TestCase
public function test_update_route_name_exists(): void
{
$this->assertTrue(
\Illuminate\Support\Facades\Route::has('api.admin.templates.update'),
Route::has('api.admin.templates.update'),
'Route api.admin.templates.update should exist'
);
}
@@ -528,7 +530,7 @@ class TemplateUpdateTest extends TestCase
public function test_check_modified_layouts_route_name_exists(): void
{
$this->assertTrue(
\Illuminate\Support\Facades\Route::has('api.admin.templates.check-modified-layouts'),
Route::has('api.admin.templates.check-modified-layouts'),
'Route api.admin.templates.check-modified-layouts should exist'
);
}
@@ -2,6 +2,7 @@
namespace Tests\Feature\Api\Auth;
use App\Listeners\NotificationHookListener;
use App\Models\PasswordResetToken;
use App\Models\Permission;
use App\Models\Role;
@@ -22,6 +23,20 @@ class UserAuthControllerTest extends TestCase
{
use RefreshDatabase;
/**
* 테스트 환경 준비
*
* 이 클래스는 가입 환영/비밀번호 재설정 등 메일 발송을 단언하므로 mail 채널을
* 준비 완료 상태로 만든다. 기본 테스트 설정은 from_address 가 플레이스홀더라
* ChannelReadinessService 가 not-ready 로 판정해 mail 채널이 제외된다.
*/
protected function setUp(): void
{
parent::setUp();
$this->enableMailChannelReadiness();
}
/**
* 알림 시스템은 notification_definitions 시드 + 동적 훅 재등록 필요
*
@@ -31,7 +46,7 @@ class UserAuthControllerTest extends TestCase
private function seedNotificationDefinitions(): void
{
$this->artisan('db:seed', ['--class' => 'NotificationDefinitionSeeder']);
app(\App\Listeners\NotificationHookListener::class)->registerDynamicHooks();
app(NotificationHookListener::class)->registerDynamicHooks();
}
/**
@@ -854,7 +869,7 @@ class UserAuthControllerTest extends TestCase
$user = User::factory()->create();
// admin 역할 할당
$adminRole = \App\Models\Role::where('identifier', 'admin')->first();
$adminRole = Role::where('identifier', 'admin')->first();
if ($adminRole) {
$user->roles()->sync([$adminRole->id]);
}
@@ -2,11 +2,16 @@
namespace Tests\Feature\LanguagePack;
use App\Contracts\Repositories\LanguagePackRepositoryInterface;
use App\Enums\LanguagePackAbility;
use App\Enums\LanguagePackErrorCode;
use App\Enums\LanguagePackScope;
use App\Enums\LanguagePackSourceType;
use App\Enums\LanguagePackStatus;
use App\Enums\TextDirection;
use App\Models\LanguagePack;
use App\Services\LanguagePack\LanguagePackBaseLocales;
use App\Services\LanguagePack\LanguagePackBundledRegistrar;
use App\Services\LanguagePackService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
@@ -132,7 +137,7 @@ class PolicyAlignmentTest extends TestCase
public function test_install_flow_produces_unprotected_packs(): void
{
// 가상 행도 비보호 (요구사항 #3): 미설치 가상 행은 lang-packs/_bundled/ 의 ja 패키지 표현
$repo = app(\App\Contracts\Repositories\LanguagePackRepositoryInterface::class);
$repo = app(LanguagePackRepositoryInterface::class);
$manifest = [
'identifier' => 'g7-module-test-ja',
'vendor' => 'g7',
@@ -150,7 +155,7 @@ class PolicyAlignmentTest extends TestCase
*/
public function test_reactivation_stash_round_trip(): void
{
$registrar = app(\App\Services\LanguagePack\LanguagePackBundledRegistrar::class);
$registrar = app(LanguagePackBundledRegistrar::class);
// inactive 팩 생성
$pack = LanguagePack::create([
@@ -186,6 +191,10 @@ class PolicyAlignmentTest extends TestCase
*
* 환경설정 > 언어팩 관리 (필터 없음) 에서는 코어가 보여야 하지만, plugin/module/template
* 개별 화면은 그 확장에 해당되는 행만 노출되어야 함.
*
* 대상 플러그인은 실제 설치·활성 상태인 번들 플러그인이어야 한다 — 가상 보호 행은
* 설치된 확장의 lang/{ko,en} 존재를 근거로 생성되므로, 존재하지 않는 식별자로는
* 자체 built_in 행이 만들어지지 않는다.
*/
public function test_extension_filter_excludes_core_packs(): void
{
@@ -199,7 +208,7 @@ class PolicyAlignmentTest extends TestCase
$this->assertTrue($hasCoreKo, '필터 없는 화면에서 코어 ko 가 노출되어야 함');
// 플러그인 필터 → 코어 팩 제외, 그 플러그인 행만
$filtered = $svc->list(['target_identifier' => 'sirsoft-tosspayments'], 200);
$filtered = $svc->list(['target_identifier' => 'sirsoft-gdpr'], 200);
$corePacksLeaked = collect($filtered->items())->filter(
fn (LanguagePack $p) => $p->scope === LanguagePackScope::Core->value
);
@@ -208,7 +217,7 @@ class PolicyAlignmentTest extends TestCase
// 그 플러그인의 자체 built_in 은 여전히 노출
$hasOwnKo = collect($filtered->items())->contains(
fn (LanguagePack $p) => $p->scope === LanguagePackScope::Plugin->value
&& $p->target_identifier === 'sirsoft-tosspayments'
&& $p->target_identifier === 'sirsoft-gdpr'
&& $p->locale === 'ko'
);
$this->assertTrue($hasOwnKo, '플러그인 자체 built_in ko 는 노출되어야 함');
@@ -230,14 +239,14 @@ class PolicyAlignmentTest extends TestCase
*/
public function test_new_enums_are_defined_with_expected_cases(): void
{
$this->assertTrue(enum_exists(\App\Enums\LanguagePackSourceType::class));
$this->assertTrue(enum_exists(\App\Enums\LanguagePackErrorCode::class));
$this->assertTrue(enum_exists(\App\Enums\TextDirection::class));
$this->assertTrue(enum_exists(\App\Enums\LanguagePackAbility::class));
$this->assertTrue(enum_exists(LanguagePackSourceType::class));
$this->assertTrue(enum_exists(LanguagePackErrorCode::class));
$this->assertTrue(enum_exists(TextDirection::class));
$this->assertTrue(enum_exists(LanguagePackAbility::class));
$this->assertContains('built_in', \App\Enums\LanguagePackSourceType::values());
$this->assertContains('bundled_with_extension', \App\Enums\LanguagePackSourceType::values());
$this->assertTrue(\App\Enums\LanguagePackSourceType::BuiltIn->isProtectedByDefault());
$this->assertFalse(\App\Enums\LanguagePackSourceType::Bundled->isProtectedByDefault());
$this->assertContains('built_in', LanguagePackSourceType::values());
$this->assertContains('bundled_with_extension', LanguagePackSourceType::values());
$this->assertTrue(LanguagePackSourceType::BuiltIn->isProtectedByDefault());
$this->assertFalse(LanguagePackSourceType::Bundled->isProtectedByDefault());
}
}
@@ -2,11 +2,15 @@
namespace Tests\Feature\Rules;
use App\Models\Role;
use App\Rules\LocaleRequiredTranslatable;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class LocaleRequiredTranslatableTest extends TestCase
{
use RefreshDatabase;
/**
* 각 테스트 시작 전 실행
*/
@@ -38,7 +42,7 @@ class LocaleRequiredTranslatableTest extends TestCase
*/
public function test_fails_when_current_locale_empty(): void
{
$rule = new LocaleRequiredTranslatable();
$rule = new LocaleRequiredTranslatable;
$errorMessage = null;
$rule->validate('name', ['ko' => '', 'en' => 'English'], function ($message) use (&$errorMessage) {
@@ -55,7 +59,7 @@ class LocaleRequiredTranslatableTest extends TestCase
*/
public function test_fails_when_current_locale_null(): void
{
$rule = new LocaleRequiredTranslatable();
$rule = new LocaleRequiredTranslatable;
$errorMessage = null;
$rule->validate('name', ['ko' => null, 'en' => 'English'], function ($message) use (&$errorMessage) {
@@ -71,7 +75,7 @@ class LocaleRequiredTranslatableTest extends TestCase
*/
public function test_fails_when_current_locale_key_missing(): void
{
$rule = new LocaleRequiredTranslatable();
$rule = new LocaleRequiredTranslatable;
$errorMessage = null;
$rule->validate('name', ['en' => 'English'], function ($message) use (&$errorMessage) {
@@ -117,7 +121,7 @@ class LocaleRequiredTranslatableTest extends TestCase
*/
public function test_fails_when_not_array(): void
{
$rule = new LocaleRequiredTranslatable();
$rule = new LocaleRequiredTranslatable;
$errorMessage = null;
$rule->validate('name', 'string value', function ($message) use (&$errorMessage) {
@@ -129,11 +133,11 @@ class LocaleRequiredTranslatableTest extends TestCase
}
/**
* 지원되지 않는 언어 코드 테스트
* strictLocales=true 일 때 지원되지 않는 언어 코드는 실패
*/
public function test_fails_with_unsupported_language(): void
public function test_fails_with_unsupported_language_when_strict(): void
{
$rule = new LocaleRequiredTranslatable();
$rule = new LocaleRequiredTranslatable(strictLocales: true);
$errorMessage = null;
$rule->validate('name', ['ko' => '한국어', 'fr' => 'Français'], function ($message) use (&$errorMessage) {
@@ -145,12 +149,63 @@ class LocaleRequiredTranslatableTest extends TestCase
$this->assertStringContainsString('fr', $errorMessage);
}
/**
* 기본값(관대)에서는 지원 목록 밖 로케일 키가 있어도 통과해야 한다
*
* app.translatable_locales 는 활성 언어팩 기준으로 부팅마다 덮어써지는 가변 런타임 값이다.
* 언어팩을 비활성화하면 기존 레코드에 남은 그 로케일 키 때문에 수정이 차단되던 결함의 회귀.
*/
public function test_passes_with_stale_locale_key_by_default(): void
{
$rule = new LocaleRequiredTranslatable;
$errorMessage = null;
$rule->validate('name', ['ko' => '한국어', 'fr' => 'Français'], function ($message) use (&$errorMessage) {
$errorMessage = $message;
});
$this->assertNull($errorMessage, '비활성 언어팩의 로케일 키가 남아 있어도 통과해야 함');
}
/**
* 비활성 언어팩의 번역 값은 저장/조회 왕복에서 보존되어야 한다
*
* 완화 방침은 "검증에서 제외"이지 "데이터 삭제"가 아니다. 통과만 확인하면 검증 통과 후
* 저장 경로에서 값이 유실되는 경우를 놓친다 — 언어팩을 다시 켰을 때 번역이 그대로
* 복구되는지까지 확인한다. (TranslatableField 쪽 동일 단언과 짝)
*/
public function test_stale_locale_value_survives_model_round_trip(): void
{
config(['app.translatable_locales' => ['ko', 'en']]);
$name = ['ko' => '한국어', 'en' => 'English', 'ja' => '日本語'];
$rule = new LocaleRequiredTranslatable(maxLength: 255);
$errorMessage = null;
$rule->validate('name', $name, function ($message) use (&$errorMessage) {
$errorMessage = $message;
});
$this->assertNull($errorMessage, '지원 목록 밖 로케일이 있어도 검증은 통과해야 함');
$role = Role::create([
'name' => $name,
'identifier' => 'locale-required-stale-round-trip',
'is_admin' => false,
]);
$stored = json_decode($role->fresh()->getRawOriginal('name'), true);
$this->assertSame('日本語', $stored['ja'] ?? null, '비활성 로케일 번역이 저장에서 유실되면 안 됨');
$this->assertSame('한국어', $stored['ko'] ?? null);
$this->assertSame('English', $stored['en'] ?? null);
}
/**
* 문자열이 아닌 번역 값 테스트
*/
public function test_fails_when_translation_not_string(): void
{
$rule = new LocaleRequiredTranslatable();
$rule = new LocaleRequiredTranslatable;
$errorMessage = null;
$rule->validate('name', ['ko' => 123, 'en' => 'English'], function ($message) use (&$errorMessage) {
@@ -202,7 +257,7 @@ class LocaleRequiredTranslatableTest extends TestCase
{
app()->setLocale('en');
$rule = new LocaleRequiredTranslatable();
$rule = new LocaleRequiredTranslatable;
$errorMessage = null;
$rule->validate('name', ['ko' => '한국어', 'en' => ''], function ($message) use (&$errorMessage) {
@@ -254,7 +309,7 @@ class LocaleRequiredTranslatableTest extends TestCase
{
app()->setLocale('ja'); // 지원하지 않는 로케일
$rule = new LocaleRequiredTranslatable();
$rule = new LocaleRequiredTranslatable;
$errorMessage = null;
// 첫 번째 지원 언어(ko)가 필수가 됨
@@ -273,7 +328,7 @@ class LocaleRequiredTranslatableTest extends TestCase
{
app()->setLocale('en');
$rule = new LocaleRequiredTranslatable();
$rule = new LocaleRequiredTranslatable;
$errorMessage = null;
$rule->validate('name', 'not an array', function ($message) use (&$errorMessage) {
@@ -289,7 +344,7 @@ class LocaleRequiredTranslatableTest extends TestCase
*/
public function test_fails_when_current_locale_has_only_whitespace(): void
{
$rule = new LocaleRequiredTranslatable();
$rule = new LocaleRequiredTranslatable;
$errorMessage = null;
$rule->validate('name', ['ko' => ' ', 'en' => 'English'], function ($message) use (&$errorMessage) {
+206 -9
View File
@@ -2,11 +2,17 @@
namespace Tests\Feature\Rules;
use App\Models\Role;
use App\Rules\LocaleRequiredTranslatable;
use App\Rules\TranslatableField;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class TranslatableFieldTest extends TestCase
{
use RefreshDatabase;
/**
* 각 테스트 시작 전 실행
*/
@@ -38,7 +44,7 @@ class TranslatableFieldTest extends TestCase
*/
public function test_fails_when_not_array(): void
{
$rule = new TranslatableField();
$rule = new TranslatableField;
$errorMessage = null;
$rule->validate('name', 'string value', function ($message) use (&$errorMessage) {
@@ -50,11 +56,11 @@ class TranslatableFieldTest extends TestCase
}
/**
* 지원되지 않는 언어 코드 테스트
* strictLocales=true 일 때 지원되지 않는 언어 코드는 실패
*/
public function test_fails_with_unsupported_language(): void
public function test_fails_with_unsupported_language_when_strict(): void
{
$rule = new TranslatableField();
$rule = new TranslatableField(strictLocales: true);
$errorMessage = null;
// config('app.translatable_locales')가 ['ko', 'en']이라고 가정
@@ -67,12 +73,89 @@ class TranslatableFieldTest extends TestCase
$this->assertStringContainsString('fr', $errorMessage);
}
/**
* 기본값(관대)에서는 지원 목록 밖 로케일 키가 있어도 통과해야 한다
*
* app.translatable_locales 는 활성 언어팩 기준으로 부팅마다 덮어써지는 가변 런타임 값이다.
* 언어팩을 비활성화하면 기존 레코드에 남은 그 로케일 키 때문에 수정 자체가 차단되던 결함의 회귀.
*/
public function test_passes_with_stale_locale_key_by_default(): void
{
config(['app.translatable_locales' => ['ko', 'en']]);
$rule = new TranslatableField(maxLength: 500);
$this->assertNull($this->runRule($rule, [
'ko' => '한국어',
'en' => 'English',
'ja' => '日本語',
]), '비활성 언어팩의 로케일 키가 남아 있어도 통과해야 함');
}
/**
* LocaleRequiredTranslatable 도 동일하게 stale 로케일 키를 통과시켜야 한다
*/
public function test_locale_required_rule_passes_with_stale_locale_key_by_default(): void
{
config(['app.translatable_locales' => ['ko', 'en']]);
app()->setLocale('ko');
$rule = new LocaleRequiredTranslatable(maxLength: 500);
$this->assertNull($this->runRule($rule, [
'ko' => '한국어',
'en' => 'English',
'ja' => '日本語',
]), '비활성 언어팩의 로케일 키가 남아 있어도 통과해야 함');
}
/**
* 비활성 언어팩의 번역 값은 저장/조회 왕복에서 보존되어야 한다
*
* 완화 방침은 "검증에서 제외"이지 "데이터 삭제"가 아니다. 언어팩을 다시 켜면
* 번역이 그대로 복구되어야 한다.
*/
public function test_stale_locale_value_survives_model_round_trip(): void
{
config(['app.translatable_locales' => ['ko', 'en']]);
$name = ['ko' => '한국어', 'en' => 'English', 'ja' => '日本語'];
$rule = new TranslatableField(maxLength: 500);
$this->assertNull($this->runRule($rule, $name));
$role = Role::create([
'name' => $name,
'identifier' => 'stale-locale-test',
'is_admin' => false,
]);
$this->assertSame('日本語', $role->fresh()->getRawOriginal('name')
? json_decode($role->fresh()->getRawOriginal('name'), true)['ja']
: null);
}
/**
* 관대 모드에서도 지원 로케일의 길이 검증은 그대로 동작해야 한다 (완화가 검증을 무력화하지 않음)
*/
public function test_supported_locale_length_still_validated_in_lenient_mode(): void
{
config(['app.translatable_locales' => ['ko', 'en']]);
$rule = new TranslatableField(maxLength: 10);
$this->assertNotNull($this->runRule($rule, [
'ko' => str_repeat('가', 11),
'ja' => str_repeat('あ', 999),
]), '지원 로케일의 길이 초과는 계속 실패해야 함');
}
/**
* 문자열이 아닌 번역 값 테스트
*/
public function test_fails_when_translation_not_string(): void
{
$rule = new TranslatableField();
$rule = new TranslatableField;
$errorMessage = null;
$rule->validate('name', ['ko' => 123, 'en' => 'English'], function ($message) use (&$errorMessage) {
@@ -137,7 +220,7 @@ class TranslatableFieldTest extends TestCase
*/
public function test_passes_with_partial_translations(): void
{
$rule = new TranslatableField();
$rule = new TranslatableField;
$passes = true;
$rule->validate('name', ['ko' => '한국어', 'en' => ''], function () use (&$passes) {
@@ -152,7 +235,7 @@ class TranslatableFieldTest extends TestCase
*/
public function test_passes_with_null_values(): void
{
$rule = new TranslatableField();
$rule = new TranslatableField;
$passes = true;
$rule->validate('name', ['ko' => '한국어', 'en' => null], function () use (&$passes) {
@@ -173,7 +256,7 @@ class TranslatableFieldTest extends TestCase
// 영어로 변경
app()->setLocale('en');
$rule = new TranslatableField();
$rule = new TranslatableField;
$errorMessage = null;
$rule->validate('name', 'not an array', function ($message) use (&$errorMessage) {
@@ -198,7 +281,7 @@ class TranslatableFieldTest extends TestCase
// 한국어로 변경
app()->setLocale('ko');
$rule = new TranslatableField();
$rule = new TranslatableField;
$errorMessage = null;
$rule->validate('name', 'not an array', function ($message) use (&$errorMessage) {
@@ -211,4 +294,118 @@ class TranslatableFieldTest extends TestCase
// 원래 로케일로 복구
app()->setLocale($originalLocale);
}
/**
* 규칙을 실행하고 실패 메시지를 반환합니다.
*
* @param ValidationRule $rule 검증 규칙
* @param mixed $value 검증 값
* @return string|null 실패 메시지 (통과 시 null)
*/
private function runRule($rule, mixed $value): ?string
{
$message = null;
$rule->validate('name', $value, function ($failMessage) use (&$message) {
$message ??= (string) $failMessage;
});
return $message;
}
/**
* 한글 167자는 최대 500자 제한을 통과해야 합니다. (회귀)
*
* strlen() 은 UTF-8 한글 1자를 3바이트로 계산하므로 167자가 501바이트가 되어
* 잘못 거부됩니다. 길이는 문자 단위로 계산되어야 합니다.
*/
public function test_korean_text_under_max_length_passes(): void
{
$rule = new TranslatableField(maxLength: 500);
$korean = str_repeat('가', 167);
$this->assertSame(501, strlen($korean), '테스트 전제: 한글 167자는 501바이트');
$this->assertNull($this->runRule($rule, ['ko' => $korean]));
}
/**
* 한글 500자(경계값)는 통과해야 합니다.
*/
public function test_korean_text_at_max_length_boundary_passes(): void
{
$rule = new TranslatableField(maxLength: 500);
$this->assertNull($this->runRule($rule, ['ko' => str_repeat('가', 500)]));
}
/**
* 한글 501자는 최대 길이 초과로 실패해야 합니다.
*/
public function test_korean_text_over_max_length_fails(): void
{
$rule = new TranslatableField(maxLength: 500);
$message = $this->runRule($rule, ['ko' => str_repeat('가', 501)]);
$this->assertSame(
__('validation.translatable.max_length', ['lang' => 'ko', 'max' => 500]),
$message
);
}
/**
* 영문도 동일하게 문자 단위로 계산되어야 합니다.
*/
public function test_ascii_text_boundary_matches_character_count(): void
{
$rule = new TranslatableField(maxLength: 500);
$this->assertNull($this->runRule($rule, ['en' => str_repeat('a', 500)]));
$this->assertNotNull($this->runRule($rule, ['en' => str_repeat('a', 501)]));
}
/**
* 두 자매 규칙이 동일 입력에 동일한 길이 판정을 내려야 합니다. (재발 방지)
*
* 한쪽만 strlen() 으로 되돌아가는 회귀를 교차 단언으로 차단합니다.
*
* @dataProvider lengthJudgementProvider
*
* @param string $text 검증 문자열
* @param bool $shouldPass 통과 기대 여부
*/
public function test_both_translatable_rules_agree_on_length(string $text, bool $shouldPass): void
{
$translatable = new TranslatableField(maxLength: 500);
$localeRequired = new LocaleRequiredTranslatable(maxLength: 500);
$value = ['ko' => $text];
$translatableFailed = $this->runRule($translatable, $value) !== null;
$localeRequiredFailed = $this->runRule($localeRequired, $value) !== null;
$this->assertSame(
$translatableFailed,
$localeRequiredFailed,
'TranslatableField 와 LocaleRequiredTranslatable 의 길이 판정이 어긋났습니다.'
);
$this->assertSame(! $shouldPass, $translatableFailed);
}
/**
* 길이 판정 교차 검증 데이터.
*
* @return array<string, array{string, bool}> 검증 문자열과 통과 기대 여부
*/
public static function lengthJudgementProvider(): array
{
return [
'한글 167자 (501바이트)' => [str_repeat('가', 167), true],
'한글 500자 경계' => [str_repeat('가', 500), true],
'한글 501자 초과' => [str_repeat('가', 501), false],
'영문 500자 경계' => [str_repeat('a', 500), true],
'영문 501자 초과' => [str_repeat('a', 501), false],
'이모지 300자' => [str_repeat('😀', 300), true],
];
}
}
@@ -39,7 +39,8 @@ class NotificationDefinitionUserOverridesTest extends TestCase
$definition->name = ['ko' => '커스텀 회원가입 환영', 'en' => 'Custom Welcome'];
$definition->save();
$this->assertEquals(['name'], $definition->fresh()->user_overrides);
// 다국어 JSON 컬럼은 sub-key dot-path 단위로 기록된다 (HasUserOverrides @since 7.0.0-beta.4)
$this->assertEqualsCanonicalizing(['name.ko', 'name.en'], $definition->fresh()->user_overrides);
}
public function test_seeder_re_run_preserves_user_modified_name(): void
@@ -54,7 +55,7 @@ class NotificationDefinitionUserOverridesTest extends TestCase
$fresh = $definition->fresh();
$this->assertEquals(['ko' => '커스텀 회원가입 환영', 'en' => 'Custom Welcome'], $fresh->name);
$this->assertEquals(['name'], $fresh->user_overrides);
$this->assertEqualsCanonicalizing(['name.ko', 'name.en'], $fresh->user_overrides);
}
public function test_seeder_re_run_updates_non_trackable_fields(): void
+26
View File
@@ -2,6 +2,8 @@
namespace Tests;
use App\Contracts\Notifications\ChannelReadinessCheckerInterface;
use App\Contracts\Repositories\ConfigRepositoryInterface;
use App\Extension\Testing\ExtensionTestAllowlist;
use App\Listeners\Identity\EnforceIdentityPolicyListener;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
@@ -83,6 +85,30 @@ abstract class TestCase extends BaseTestCase
Storage::fake('settings');
}
/**
* mail 채널을 발송 준비 완료 상태로 만듭니다.
*
* 테스트 환경의 mail 설정은 from_address 가 플레이스홀더(noreply@example.com)라
* ChannelReadinessService::checkMail() 이 not-ready 로 판정하고, GenericNotification::via()
* 가 mail 채널을 제외합니다. 즉 메일 발송을 단언하는 테스트는 이 헬퍼로 명시적으로
* "메일이 설정된 사이트" 를 만들어야 합니다.
*
* (설정 미비 시 발송하지 않는 것은 의도된 제품 동작이므로 기본값은 그대로 둡니다)
*/
protected function enableMailChannelReadiness(): void
{
app(ConfigRepositoryInterface::class)->saveCategory('mail', [
'mailer' => 'smtp',
'host' => 'smtp.test.local',
'port' => 587,
'encryption' => 'tls',
'from_address' => 'test@g7.test',
'from_name' => 'G7 Test',
]);
app(ChannelReadinessCheckerInterface::class)->check('mail');
}
/**
* 테스트 종료 시 확장 allowlist 를 초기화합니다.
*
@@ -0,0 +1,114 @@
<?php
namespace Tests\Unit\Http\Requests;
use App\Http\Requests\Plugin\InstallPluginFromFileRequest;
use App\Http\Requests\Plugin\InstallPluginFromGithubRequest;
use App\Http\Requests\Plugin\PreviewPluginManifestRequest;
use Tests\TestCase;
/**
* 플러그인 설치 요청의 검증 안내 문구가 실제 문장으로 해석되는지 검증.
*
* `lang/{ko,en}/plugins.php` 에 `validation` 블록이 두 번 선언돼 있어, PHP 가 뒤 선언으로
* 앞 블록을 덮으면서 GitHub/ZIP 설치 관련 7키가 런타임에 존재하지 않던 회귀가 있었다.
* `__()` 는 미정의 키에 대해 **키 문자열을 그대로 반환**하므로, 설치 검증 실패 화면에
* `plugins.validation.file_must_be_zip` 같은 원문 키가 사용자에게 노출됐다.
*
* 정적 검출은 audit 룰 `lang-duplicate-array-key` 가 담당하고, 이 테스트는 소비 지점에서
* 실제 해석 결과를 확인해 같은 회귀를 이중으로 차단한다.
*/
class PluginInstallRequestMessagesTest extends TestCase
{
/**
* 메시지 배열의 모든 값이 원문 키가 아닌 해석된 문장이어야 한다.
*
* @param array<string, string> $messages FormRequest 가 반환한 메시지 배열
*/
private function assertAllMessagesResolved(array $messages, string $context): void
{
$this->assertNotEmpty($messages, "{$context}: 메시지 배열이 비어 있습니다");
foreach ($messages as $rule => $message) {
$this->assertStringNotContainsString(
'plugins.validation.',
$message,
"{$context}: '{$rule}' 안내가 해석되지 않은 원문 키입니다 — {$message}"
);
$this->assertNotSame('', trim($message), "{$context}: '{$rule}' 안내가 비어 있습니다");
}
}
/**
* GitHub 주소 설치 요청의 안내 문구가 모두 해석된다.
*/
public function test_github_install_messages_are_resolved(): void
{
$this->assertAllMessagesResolved(
(new InstallPluginFromGithubRequest)->messages(),
'InstallPluginFromGithubRequest'
);
}
/**
* ZIP 파일 업로드 설치 요청의 안내 문구가 모두 해석된다.
*/
public function test_file_install_messages_are_resolved(): void
{
$this->assertAllMessagesResolved(
(new InstallPluginFromFileRequest)->messages(),
'InstallPluginFromFileRequest'
);
}
/**
* manifest 미리보기 요청의 안내 문구가 모두 해석된다.
*/
public function test_manifest_preview_messages_are_resolved(): void
{
$this->assertAllMessagesResolved(
(new PreviewPluginManifestRequest)->messages(),
'PreviewPluginManifestRequest'
);
}
/**
* ko/en 양쪽에 7키가 모두 정의되어 있어야 한다 (한쪽만 있으면 로케일에 따라 회귀).
*
* @dataProvider localeProvider
*/
public function test_install_validation_keys_defined_in_all_base_locales(string $locale): void
{
$keys = [
'github_url_required',
'github_url_invalid',
'github_url_format',
'file_required',
'file_invalid',
'file_must_be_zip',
'file_max_size',
];
foreach ($keys as $key) {
$full = "plugins.validation.{$key}";
$this->assertNotSame(
$full,
__($full, [], $locale),
"[{$locale}] '{$full}' 가 정의되지 않아 원문 키가 그대로 반환됩니다"
);
}
}
/**
* 기준 로케일 목록.
*
* @return array<string, array{string}> 로케일 데이터셋
*/
public static function localeProvider(): array
{
return [
'ko' => ['ko'],
'en' => ['en'],
];
}
}
@@ -55,8 +55,19 @@ class DirectoryPermissionScanDepthTest extends TestCase
$_SERVER['SCRIPT_NAME'] = '/install/index.php';
}
require_once dirname(__DIR__, 3).'/public/install/includes/config.php';
require_once dirname(__DIR__, 3).'/public/install/includes/functions.php';
// BASE_PATH 를 temp 트리로 잡는 테스트라 config.php 의
// `require BASE_PATH.'/app/Support/*.php'` 가 해석되지 않는다.
// config.php 는 class_exists(.., false) 가드를 두고 있으므로 실제 프로젝트의
// 파일을 먼저 로드해 두면 그 require 를 건너뛴다.
$projectRoot = dirname(__DIR__, 3);
foreach (['PrivilegedDatabaseAccounts', 'OpcacheStatus'] as $supportClass) {
if (! class_exists('App\\Support\\'.$supportClass, false)) {
require_once $projectRoot.'/app/Support/'.$supportClass.'.php';
}
}
require_once $projectRoot.'/public/install/includes/config.php';
require_once $projectRoot.'/public/install/includes/functions.php';
}
public static function tearDownAfterClass(): void
@@ -9,6 +9,8 @@ use App\Models\NotificationDefinition;
use App\Models\NotificationTemplate;
use App\Models\Role;
use App\Models\User;
use App\Notifications\GenericNotification;
use App\Notifications\GuestNotifiable;
use App\Services\NotificationDefinitionService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Notification;
@@ -30,6 +32,9 @@ class NotificationDispatchIntegrationTest extends TestCase
protected function setUp(): void
{
parent::setUp();
// 메일 발송을 단언하므로 mail 채널을 준비 완료 상태로 만든다
// (기본 테스트 설정은 from_address 가 플레이스홀더라 readiness 가 false 다)
$this->enableMailChannelReadiness();
Notification::fake();
$this->listener = app(NotificationHookListener::class);
}
@@ -106,7 +111,7 @@ class NotificationDispatchIntegrationTest extends TestCase
$this->registerAndFire('core.test.after_trigger', $user);
Notification::assertSentTo($user, \App\Notifications\GenericNotification::class);
Notification::assertSentTo($user, GenericNotification::class);
}
// ──────────────────────────────────────────────
@@ -137,8 +142,8 @@ class NotificationDispatchIntegrationTest extends TestCase
$this->registerAndFire('core.test.after_role', null);
Notification::assertSentTo($admin1, \App\Notifications\GenericNotification::class);
Notification::assertSentTo($admin2, \App\Notifications\GenericNotification::class);
Notification::assertSentTo($admin1, GenericNotification::class);
Notification::assertSentTo($admin2, GenericNotification::class);
}
// ──────────────────────────────────────────────
@@ -163,9 +168,9 @@ class NotificationDispatchIntegrationTest extends TestCase
$this->registerAndFire('core.test.after_specific', null);
Notification::assertSentTo($user1, \App\Notifications\GenericNotification::class);
Notification::assertSentTo($user2, \App\Notifications\GenericNotification::class);
Notification::assertNotSentTo($other, \App\Notifications\GenericNotification::class);
Notification::assertSentTo($user1, GenericNotification::class);
Notification::assertSentTo($user2, GenericNotification::class);
Notification::assertNotSentTo($other, GenericNotification::class);
}
// ──────────────────────────────────────────────
@@ -200,8 +205,8 @@ class NotificationDispatchIntegrationTest extends TestCase
$this->registerAndFire('core.test.after_excl', $triggerUser);
Notification::assertSentTo($otherAdmin, \App\Notifications\GenericNotification::class);
Notification::assertNotSentTo($triggerUser, \App\Notifications\GenericNotification::class);
Notification::assertSentTo($otherAdmin, GenericNotification::class);
Notification::assertNotSentTo($triggerUser, GenericNotification::class);
}
// ──────────────────────────────────────────────
@@ -240,7 +245,7 @@ class NotificationDispatchIntegrationTest extends TestCase
$this->registerAndFire('core.test.after_multi', $user);
// 동일 사용자이므로 1건만 발송
Notification::assertSentTo($user, \App\Notifications\GenericNotification::class, function ($notification) {
Notification::assertSentTo($user, GenericNotification::class, function ($notification) {
return true;
});
Notification::assertCount(1);
@@ -267,7 +272,7 @@ class NotificationDispatchIntegrationTest extends TestCase
$this->registerAndFire('core.test.after_no_filter', null);
// 수신자는 결정되지만 data가 빈 상태로 발송
Notification::assertSentTo($admin, \App\Notifications\GenericNotification::class);
Notification::assertSentTo($admin, GenericNotification::class);
}
// ──────────────────────────────────────────────
@@ -333,7 +338,7 @@ class NotificationDispatchIntegrationTest extends TestCase
$this->registerAndFire('core.test.after_legacy', $user);
Notification::assertSentTo($user, \App\Notifications\GenericNotification::class);
Notification::assertSentTo($user, GenericNotification::class);
}
// ──────────────────────────────────────────────
@@ -343,7 +348,7 @@ class NotificationDispatchIntegrationTest extends TestCase
public function test_core_welcome_extract_data(): void
{
$user = User::factory()->create();
$listener = new CoreNotificationDataListener();
$listener = new CoreNotificationDataListener;
$result = $listener->extractData(
['notifiable' => null, 'notifiables' => null, 'data' => [], 'context' => []],
@@ -364,7 +369,7 @@ class NotificationDispatchIntegrationTest extends TestCase
public function test_core_reset_password_extract_data(): void
{
$user = User::factory()->create();
$listener = new CoreNotificationDataListener();
$listener = new CoreNotificationDataListener;
$result = $listener->extractData(
['notifiable' => null, 'notifiables' => null, 'data' => [], 'context' => []],
@@ -383,7 +388,7 @@ class NotificationDispatchIntegrationTest extends TestCase
public function test_core_password_changed_extract_data(): void
{
$user = User::factory()->create();
$listener = new CoreNotificationDataListener();
$listener = new CoreNotificationDataListener;
$result = $listener->extractData(
['notifiable' => null, 'notifiables' => null, 'data' => [], 'context' => []],
@@ -402,7 +407,7 @@ class NotificationDispatchIntegrationTest extends TestCase
public function test_core_unknown_type_returns_default(): void
{
$listener = new CoreNotificationDataListener();
$listener = new CoreNotificationDataListener;
$default = ['notifiable' => null, 'notifiables' => null, 'data' => [], 'context' => []];
$result = $listener->extractData($default, 'unknown_type', []);
@@ -431,7 +436,7 @@ class NotificationDispatchIntegrationTest extends TestCase
$this->registerAndFire('core.test.after_fallback', null);
Notification::assertSentTo($superAdmin, \App\Notifications\GenericNotification::class);
Notification::assertSentTo($superAdmin, GenericNotification::class);
}
// ──────────────────────────────────────────────
@@ -497,8 +502,8 @@ class NotificationDispatchIntegrationTest extends TestCase
// 비회원은 GuestNotifiable 수신자로 발송된다 (회원과 동일한 notify 경로).
// fake 는 같은 클래스 + getKey() 로 매칭하므로 동일 이메일 게스트로 단언한다.
Notification::assertSentTo(
new \App\Notifications\GuestNotifiable('guest@example.com'),
\App\Notifications\GenericNotification::class
new GuestNotifiable('guest@example.com'),
GenericNotification::class
);
}
@@ -4,8 +4,9 @@ namespace Tests\Unit\Notifications;
use App\Models\NotificationDefinition;
use App\Models\NotificationTemplate;
use App\Notifications\GuestNotifiable;
use App\Models\User;
use App\Notifications\GenericNotification;
use App\Notifications\GuestNotifiable;
use App\Services\NotificationChannelService;
use App\Services\NotificationTemplateService;
use Tests\TestCase;
@@ -24,6 +25,10 @@ class GenericNotificationGuestGateTest extends TestCase
{
parent::setUp();
// 메일 발송 통과를 단언하므로 mail 채널을 준비 완료 상태로 만든다
// (기본 테스트 설정은 from_address 가 플레이스홀더라 readiness 가 false 다)
$this->enableMailChannelReadiness();
$templateService = app(NotificationTemplateService::class);
foreach (['mail', 'database'] as $ch) {
$templateService->invalidateCache('guest_gate_check', $ch);
@@ -106,7 +111,7 @@ class GenericNotificationGuestGateTest extends TestCase
public function test_member_is_unaffected_by_guest_gate(): void
{
$member = \App\Models\User::factory()->make();
$member = User::factory()->make();
// 회원은 게스트 게이트 무영향 — database 채널도 정상 통과(템플릿 존재 + readiness)
$this->assertSame(['database'], $this->notification('database')->via($member));
@@ -8,6 +8,7 @@ use App\Models\Schedule;
use App\Models\ScheduleHistory;
use App\Services\ScheduleService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Pagination\LengthAwarePaginator;
use Tests\TestCase;
/**
@@ -34,6 +35,58 @@ class ScheduleServiceTest extends TestCase
parent::tearDown();
}
// ========================================================================
// getPaginatedSchedules() / getHistory() - 반환 타입 해석 검증
// ========================================================================
/**
* 스케줄이 존재할 때 목록 조회가 TypeError 없이 페이지네이터를 반환하는지 확인
*
* 회귀 배경: LengthAwarePaginator 를 import 하지 않아 반환 타입이
* App\Services\LengthAwarePaginator 로 해석되어 목록 API 가 500 을 반환했다.
*/
public function test_get_paginated_schedules_returns_paginator(): void
{
Schedule::create([
'name' => '목록 조회 테스트 스케줄',
'type' => ScheduleType::Artisan,
'command' => 'inspire',
'expression' => '* * * * *',
'is_active' => true,
]);
$result = $this->scheduleService->getPaginatedSchedules([]);
$this->assertInstanceOf(LengthAwarePaginator::class, $result);
$this->assertSame(1, $result->total());
}
/**
* 실행 이력이 존재할 때 이력 조회가 TypeError 없이 페이지네이터를 반환하는지 확인
*/
public function test_get_history_returns_paginator(): void
{
$schedule = Schedule::create([
'name' => '이력 조회 테스트 스케줄',
'type' => ScheduleType::Artisan,
'command' => 'inspire',
'expression' => '* * * * *',
'is_active' => true,
]);
ScheduleHistory::create([
'schedule_id' => $schedule->id,
'started_at' => now(),
'finished_at' => now(),
'result_status' => 'success',
]);
$result = $this->scheduleService->getHistory($schedule->id, []);
$this->assertInstanceOf(LengthAwarePaginator::class, $result);
$this->assertSame(1, $result->total());
}
// ========================================================================
// delete() - 관계 레코드 명시적 삭제 검증
// ========================================================================