검색 — 이 코어에 추가한 BOOLEAN MODE 정제기가 게시판에는 도달하지 않아 원문 키워드가 그대로 바인딩되고 있었다. + - * " < > 를 넣으면 오류 화면이 떴다. 코어 정제기 경유로 옮겼고, 같은 술어를 count 와 get 으로 두 번 실행하던 것을 페이지네이터 한 번으로 합쳤다. 구체 엔진 직접 호출도 해석기 경유로 바꿔 플러그인 검색엔진이 게시글·신고 검색에 적용된다. 상세 — 같은 글을 3회, 같은 게시판을 5회 읽고 있었다. 조회한 인스턴스를 넘겨 글 1회·게시판 1회로 줄였고, 조회수 증가를 권한 확인 뒤로 옮겨 열람 권한이 없는 요청이 조회수를 올리지 않게 했다. 목록 — 답변 트리의 무제한 조회에 상한과 순환 가드를 두고, O(n²) 병합을 한 패스로 바꿨다. 댓글도 무제한 조회에 상한을 두되 잘렸다는 사실과 전체 건수를 함께 알린다. 조용히 잘리면 "댓글이 그만큼뿐" 으로 보인다. 원댓글 단위 페이지네이션을 더해 답글이 부모와 떨어지지 않게 했다. 관리자 화면 — 총 건수가 잘린 목록에서 페이저가 "1페이지뿐" 으로 접히던 자리를 고쳤다. 저장소가 상한을 붙인 목록인데 화면이 그 값을 1 로 채우고 있어, 기록이 상한을 넘으면 2페이지에 도달할 방법이 없었다. 같은 파일에서 드러난 사전 결함도 함께 처리했다 — 반복 렌더 안의 정적 HTML id, Icon 의 박스 크기 지정, 단색 버튼의 다크 모드 대비.
350 lines
12 KiB
PHP
350 lines
12 KiB
PHP
<?php
|
|
|
|
namespace Modules\Sirsoft\Board\Tests;
|
|
|
|
use App\Contracts\Extension\HookListenerInterface;
|
|
use App\Enums\ExtensionStatus;
|
|
use App\Extension\HookListenerRegistrar;
|
|
use App\Extension\HookManager;
|
|
use App\Extension\ModuleManager;
|
|
use App\Http\Middleware\PermissionMiddleware;
|
|
use App\Models\Module;
|
|
use App\Models\Permission;
|
|
use App\Models\Role;
|
|
use App\Models\User;
|
|
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
|
use Illuminate\Support\Facades\Route;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Modules\Sirsoft\Board\Models\Board;
|
|
use Modules\Sirsoft\Board\Providers\BoardServiceProvider;
|
|
use Tests\TestCase;
|
|
|
|
/**
|
|
* Board 모듈 테스트 베이스 클래스
|
|
*
|
|
* 모든 Board 모듈 테스트는 이 클래스를 상속받아야 합니다.
|
|
* 모듈 오토로드, ServiceProvider 등록, 마이그레이션, 라우트 등록을 자동으로 처리합니다.
|
|
*
|
|
* 성능 최적화:
|
|
* - 각 테스트 메서드는 DatabaseTransactions로 트랜잭션 롤백만 수행 (빠름)
|
|
* - board_posts/board_comments/board_attachments 단일 테이블 사용 (DDL 불필요)
|
|
*/
|
|
abstract class ModuleTestCase extends TestCase
|
|
{
|
|
use DatabaseTransactions;
|
|
|
|
/**
|
|
* 모듈 루트 경로를 반환합니다.
|
|
*
|
|
* __DIR__을 기반으로 동적 해석하여 _bundled/활성 디렉토리 모두에서 동작합니다.
|
|
*
|
|
* @return string 모듈 루트 절대 경로
|
|
*/
|
|
protected function getModuleBasePath(): string
|
|
{
|
|
// __DIR__ = {module_root}/tests/ → dirname = {module_root}
|
|
return dirname(__DIR__);
|
|
}
|
|
|
|
/**
|
|
* 마이그레이션 완료 플래그 (클래스당 한 번만 실행)
|
|
*/
|
|
protected static bool $migrated = false;
|
|
|
|
/**
|
|
* 테스트용 공유 게시판 slug (클래스 내 모든 테스트가 공유)
|
|
*/
|
|
protected static string $sharedBoardSlug = '';
|
|
|
|
/**
|
|
* HookManager static state 스냅샷 — tearDown 에서 복원하여 테스트 간 훅 격리 보장.
|
|
*
|
|
* @var array{hooks: array, filters: array, dispatching: array}|null
|
|
*/
|
|
private ?array $hookSnapshot = null;
|
|
|
|
/**
|
|
* 테스트 환경 설정
|
|
*/
|
|
protected function setUp(): void
|
|
{
|
|
parent::setUp();
|
|
|
|
// 모듈 오토로드 등록 (테스트 환경)
|
|
$this->registerModuleAutoload();
|
|
|
|
// 모듈 ServiceProvider 등록 (Repository 바인딩)
|
|
$this->app->register(BoardServiceProvider::class);
|
|
|
|
// 모듈 마이그레이션 실행 (boards 테이블 등)
|
|
$this->runModuleMigrationIfNeeded();
|
|
|
|
// 모듈을 활성화 상태로 등록 (테스트 환경)
|
|
$this->registerModuleAsActive();
|
|
|
|
// ModuleManager 메모리 맵에 sirsoft-board 로드 (테스트 환경)
|
|
// CoreServiceProvider::boot()에서 loadModules()가 호출되지만,
|
|
// 테스트 컨테이너에서 ModuleManager 싱글톤이 비어있는 경우를 대비해 명시적으로 재로드
|
|
$this->app->make(ModuleManager::class)->loadModules();
|
|
|
|
// _bundled 디렉토리 모듈은 loadModules() 가 스캔하지 않아
|
|
// 모듈 인스턴스 등록 + 훅 리스너 자동 등록이 누락된다.
|
|
// 테스트 환경에서 module.php 가 선언한 getHookListeners() 의 리스너들을 수동 등록.
|
|
$this->registerBundledModuleInstance();
|
|
|
|
// 모듈 라우트를 수동으로 등록
|
|
$this->registerModuleRoutes();
|
|
|
|
// 기본 역할 생성
|
|
$this->createDefaultRoles();
|
|
|
|
// HookManager 상태 스냅샷 (tearDown 에서 복원하여 테스트 내 추가 훅만 제거)
|
|
$this->snapshotHookManager();
|
|
|
|
// PermissionMiddleware::$guestRoleCache 초기화 — 이전 테스트에서 로드된 guest role/permissions 캐시가
|
|
// DatabaseTransactions 롤백 후에도 남아있어 다음 테스트의 새 permission 설정이 반영되지 않는 문제 회피.
|
|
PermissionMiddleware::clearGuestRoleCache();
|
|
}
|
|
|
|
/**
|
|
* tearDown 에 HookManager 상태 복원.
|
|
*/
|
|
protected function tearDown(): void
|
|
{
|
|
$this->restoreHookManager();
|
|
|
|
parent::tearDown();
|
|
}
|
|
|
|
/**
|
|
* HookManager static $hooks / $filters / $dispatching 를 스냅샷.
|
|
*/
|
|
private function snapshotHookManager(): void
|
|
{
|
|
$ref = new \ReflectionClass(HookManager::class);
|
|
$this->hookSnapshot = [
|
|
'hooks' => $ref->getProperty('hooks')->getValue(),
|
|
'filters' => $ref->getProperty('filters')->getValue(),
|
|
'dispatching' => $ref->getProperty('dispatching')->getValue(),
|
|
];
|
|
}
|
|
|
|
/**
|
|
* 스냅샷 시점으로 HookManager 복원.
|
|
*/
|
|
private function restoreHookManager(): void
|
|
{
|
|
if ($this->hookSnapshot === null) {
|
|
return;
|
|
}
|
|
|
|
$ref = new \ReflectionClass(HookManager::class);
|
|
$ref->getProperty('hooks')->setValue(null, $this->hookSnapshot['hooks']);
|
|
$ref->getProperty('filters')->setValue(null, $this->hookSnapshot['filters']);
|
|
$ref->getProperty('dispatching')->setValue(null, $this->hookSnapshot['dispatching']);
|
|
|
|
$this->hookSnapshot = null;
|
|
}
|
|
|
|
/**
|
|
* 모듈 마이그레이션 실행 (필요한 경우에만)
|
|
*
|
|
* 코어 테이블이 없으면 먼저 코어 마이그레이션을 실행하고,
|
|
* 그 후 모듈 마이그레이션을 실행합니다.
|
|
* static $migrated 플래그로 프로세스당 한 번만 실행합니다.
|
|
*/
|
|
protected function runModuleMigrationIfNeeded(): void
|
|
{
|
|
if (static::$migrated) {
|
|
return;
|
|
}
|
|
|
|
// 매 PHP process 첫 setUp 시 DB 를 완전 초기화 후 코어+모듈 마이그레이션을 처음부터
|
|
// 실행한다 (board 는 DatabaseTransactions 사용 — RefreshDatabase 가 아니므로 schema
|
|
// 자동 재구축 없음). 이전 process 의 부분 schema 잔재(예: 컬럼은 추가됐지만 migration
|
|
// record 누락) 로 인한 "Duplicate column" 등 충돌을 차단한다.
|
|
$this->artisan('migrate:fresh');
|
|
|
|
// 모듈 마이그레이션 실행 (코어 테이블 생성 후)
|
|
$this->artisan('migrate', [
|
|
'--path' => $this->getModuleBasePath().'/database/migrations',
|
|
'--realpath' => true,
|
|
]);
|
|
|
|
static::$migrated = true;
|
|
}
|
|
|
|
/**
|
|
* _bundled 디렉토리 모듈 인스턴스 + 훅 리스너 수동 등록.
|
|
*
|
|
* ModuleManager::loadModules() 는 modules/ (활성) 디렉토리만 스캔하고
|
|
* _bundled 는 메타데이터만 로드 (loadBundledModules) — 인스턴스/훅 미등록.
|
|
* 테스트 환경에서는 _bundled 에서 직접 실행하므로 module.php 의
|
|
* getHookListeners() 가 선언한 리스너들을 수동으로 등록해야 실제 부트 시점과 동일한 훅 흐름이 복원된다.
|
|
*/
|
|
protected function registerBundledModuleInstance(): void
|
|
{
|
|
$moduleClass = \Modules\Sirsoft\Board\Module::class;
|
|
|
|
if (! class_exists($moduleClass)) {
|
|
require_once $this->getModuleBasePath().'/module.php';
|
|
}
|
|
|
|
$module = new $moduleClass;
|
|
|
|
/** @var ModuleManager $manager */
|
|
$manager = $this->app->make(ModuleManager::class);
|
|
|
|
// ModuleManager.modules 에 인스턴스 주입
|
|
$reflection = new \ReflectionClass($manager);
|
|
$modulesProp = $reflection->getProperty('modules');
|
|
$modulesProp->setAccessible(true);
|
|
$current = $modulesProp->getValue($manager);
|
|
if (! isset($current['sirsoft-board'])) {
|
|
$current['sirsoft-board'] = $module;
|
|
$modulesProp->setValue($manager, $current);
|
|
}
|
|
|
|
// 훅 리스너 등록 — module.php 의 getHookListeners() 반환 클래스들을 HookListenerRegistrar 로 등록
|
|
if (method_exists($module, 'getHookListeners')) {
|
|
foreach ($module->getHookListeners() as $listenerClass) {
|
|
if (! class_exists($listenerClass)) {
|
|
continue;
|
|
}
|
|
if (! in_array(HookListenerInterface::class, class_implements($listenerClass), true)) {
|
|
continue;
|
|
}
|
|
try {
|
|
HookListenerRegistrar::register($listenerClass, 'sirsoft-board');
|
|
} catch (\Throwable $e) {
|
|
// 중복 등록 등 무해한 예외는 무시 (snapshot/restore 패턴이 정리)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 모듈을 활성화 상태로 등록합니다.
|
|
*/
|
|
protected function registerModuleAsActive(): void
|
|
{
|
|
// 이미 등록되어 있으면 스킵
|
|
if (Module::where('identifier', 'sirsoft-board')->exists()) {
|
|
return;
|
|
}
|
|
|
|
Module::create([
|
|
'identifier' => 'sirsoft-board',
|
|
'vendor' => 'sirsoft',
|
|
'name' => ['ko' => '게시판', 'en' => 'Board'],
|
|
'status' => ExtensionStatus::Active->value,
|
|
'version' => '1.0.0',
|
|
'config' => [],
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 모듈 오토로드를 등록합니다.
|
|
*/
|
|
protected function registerModuleAutoload(): void
|
|
{
|
|
$moduleBasePath = $this->getModuleBasePath().'/src/';
|
|
|
|
spl_autoload_register(function ($class) use ($moduleBasePath) {
|
|
$prefix = 'Modules\\Sirsoft\\Board\\';
|
|
$len = strlen($prefix);
|
|
|
|
if (strncmp($prefix, $class, $len) !== 0) {
|
|
return;
|
|
}
|
|
|
|
$relativeClass = substr($class, $len);
|
|
$file = $moduleBasePath.str_replace('\\', '/', $relativeClass).'.php';
|
|
|
|
if (file_exists($file)) {
|
|
require $file;
|
|
}
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 모듈 라우트를 등록합니다.
|
|
*/
|
|
protected function registerModuleRoutes(): void
|
|
{
|
|
$apiRoutesFile = $this->getModuleBasePath().'/src/routes/api.php';
|
|
|
|
if (file_exists($apiRoutesFile)) {
|
|
Route::prefix('api/modules/sirsoft-board')
|
|
->name('api.modules.sirsoft-board.')
|
|
->middleware('api')
|
|
->group($apiRoutesFile);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 기본 역할들을 생성합니다.
|
|
*/
|
|
protected function createDefaultRoles(): void
|
|
{
|
|
Role::firstOrCreate(
|
|
['identifier' => 'admin'],
|
|
['name' => ['ko' => '관리자', 'en' => 'Administrator']]
|
|
);
|
|
|
|
Role::firstOrCreate(
|
|
['identifier' => 'user'],
|
|
['name' => ['ko' => '일반 사용자', 'en' => 'User']]
|
|
);
|
|
|
|
Role::firstOrCreate(
|
|
['identifier' => 'guest'],
|
|
['name' => ['ko' => '비회원', 'en' => 'Guest']]
|
|
);
|
|
|
|
}
|
|
|
|
/**
|
|
* 관리자 역할을 가진 사용자를 생성합니다.
|
|
*
|
|
* @param array $permissions 추가 권한 목록
|
|
* @return User
|
|
*/
|
|
protected function createAdminUser(array $permissions = []): User
|
|
{
|
|
$adminRole = Role::where('identifier', 'admin')->first();
|
|
$user = User::factory()->create();
|
|
$user->roles()->attach($adminRole->id);
|
|
|
|
// 추가 권한이 있으면 생성 및 할당
|
|
if (! empty($permissions)) {
|
|
foreach ($permissions as $permissionIdentifier) {
|
|
$permission = Permission::firstOrCreate(
|
|
['identifier' => $permissionIdentifier],
|
|
[
|
|
'name' => ['ko' => $permissionIdentifier, 'en' => $permissionIdentifier],
|
|
'type' => 'admin',
|
|
]
|
|
);
|
|
$adminRole->permissions()->syncWithoutDetaching([$permission->id]);
|
|
}
|
|
}
|
|
|
|
return $user;
|
|
}
|
|
|
|
/**
|
|
* 일반 사용자를 생성합니다.
|
|
*
|
|
* @return User
|
|
*/
|
|
protected function createUser(): User
|
|
{
|
|
$userRole = Role::where('identifier', 'user')->first();
|
|
$user = User::factory()->create();
|
|
$user->roles()->attach($userRole->id);
|
|
|
|
return $user;
|
|
}
|
|
}
|