Files
Gnuboard7/tests/Feature/Api/Admin/NotificationLogControllerTest.php
T
HeuJung 2ae1972a3b perf(core): 대용량 목록 상한 총 건수·커서 계약 신설 및 요청당 반복 실행 비용 정리
공개 이슈 gnuboard/g7 이 지목한 병목은 "같은 일을 반복 실행한다" 축이다.
응답·행의 무게를 다룬 · 과 겹치지 않는다.

공통 계약 — 총 건수 상한과 페이지 이동 범위는 별개 결정이다. 묶으면 필요 없이
기능이 깎인다. 총 건수만 상한을 받고(파생 테이블 COUNT), "다음" 이동은
per_page + 1 실측으로 끝까지 열어 둔다. 계산이 불가능해지는 것은 마지막 페이지
번호 하나뿐이며 그 사실은 last_page: null 이 알린다. 최신순처럼 실제 컬럼으로
정렬하는 목록은 커서로 전환해 깊이와 무관하게 일정 속도로 이동한다. 관련도순은
계산값 정렬이라 커서 키로 쓸 수 없어 offset 을 유지한다.

계약의 입구는 표준 paginate 와 같은 폭이어야 한다. 관계·쿼리 빌더를 받지 못하면
그 좁은 만큼이 그대로 운영 500 이 되고, 실제로 관리자 알림 목록에서 그렇게 터졌다.
응답 조립도 컬렉션마다 손으로 하면 형태가 늘어나는 순간 없는 값을 부르거나 새
필드를 흘리므로, 형태 판정을 paginationMeta 한 곳에 모았다. 표준 paginate
응답은 필드 단위로 이전과 동일하다.

요청당 반복 비용 — 훅 구독마다 남기던 로그 400줄, 요청당 스무 번 넘던 설정 파일
재읽기, 이미 캐시된 목록의 DB 재조회를 없앴다. 권한 판정은 요청 스코프 메모를 두어
화면 요소마다 나가던 조회를 한 번으로 줄였고, 크로스 요청 캐시는 두지 않아 권한
변경이 종전처럼 다음 요청에 반영된다.

검색 질의는 활성 엔진이 만든다. 저장소가 구체 엔진을 지목하면 플러그인이 등록한
엔진은 호출될 기회 자체를 잃고 오류 없이 다른 방식으로 동작한다. 해석기를 두어
활성 엔진에 위임하고, 전문검색이 없는 DBMS 의 부분일치 폴백도 드라이버명 하드코딩
대신 선언형 config 로 옮겼다.

총 건수가 잘린 목록에서 순번을 역산하면 0 과 음수가 나온다. 지어내지 않고 null 을
돌려주며, 그 원칙을 last_page 와 동일하게 적용했다.
2026-08-06 11:13:51 +09:00

206 lines
6.9 KiB
PHP

<?php
namespace Tests\Feature\Api\Admin;
use App\Models\NotificationLog;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* 관리자 알림 발송 이력 API 테스트
*/
class NotificationLogControllerTest extends TestCase
{
use RefreshDatabase;
private User $admin;
private string $token;
protected function setUp(): void
{
parent::setUp();
$this->admin = $this->createAdminWithPermissions();
$this->token = $this->admin->createToken('test-token')->plainTextToken;
}
/**
* 목록 조회 성공 — abilities 포함
*/
public function test_index_returns_notification_logs_with_abilities(): void
{
NotificationLog::create([
'channel' => 'mail',
'notification_type' => 'welcome',
'recipient_identifier' => 'test@example.com',
'status' => 'sent',
]);
$response = $this->authRequest()->getJson('/api/admin/notification-logs');
$response->assertStatus(200)
->assertJsonPath('success', true)
->assertJsonStructure([
'data' => [
'data',
'pagination',
'abilities' => ['can_delete'],
],
])
->assertJsonPath('data.abilities.can_delete', true);
}
/**
* 채널 필터 적용
*/
public function test_index_filters_by_channel(): void
{
NotificationLog::create(['channel' => 'mail', 'notification_type' => 'test', 'recipient_identifier' => 'a@test.com', 'status' => 'sent']);
NotificationLog::create(['channel' => 'database', 'notification_type' => 'test', 'recipient_identifier' => '1', 'status' => 'sent']);
$response = $this->authRequest()->getJson('/api/admin/notification-logs?channel=mail');
$response->assertStatus(200)
->assertJsonPath('data.pagination.total', 1);
}
/**
* 커서 요청이 정상 응답하는지 확인 (#519 회귀)
*
* 이 목록은 커서를 주면 키셋 페이지로 응답한다. 커서 결과에는 총 건수와 마지막 페이지가
* 없는데, 컬렉션이 페이지네이션 블록을 손으로 조립하면 없는 값을 불러 그 요청만 500 이
* 된다. 응답 형태를 스스로 판정하는 표준 메타를 쓰는지 여기서 고정한다.
*/
public function test_index_accepts_cursor_request(): void
{
foreach (range(1, 5) as $i) {
NotificationLog::create([
'channel' => 'mail',
'notification_type' => 'test',
'recipient_identifier' => "c{$i}@test.com",
'status' => 'sent',
]);
}
// 커서 파라미터가 있어야 키셋 경로로 들어간다. 형식이 깨진 값은 첫 페이지로
// 되돌려 주므로(KeysetPaginator::decode), 진입에는 임의 문자열로 충분하다.
$first = $this->authRequest()
->getJson('/api/admin/notification-logs?per_page=2&cursor=first');
$first->assertStatus(200);
$this->assertCount(2, $first->json('data.data'));
$pagination = $first->json('data.pagination');
// 커서 결과는 총 건수를 세지 않는다 — 없는 값을 채워 내보내지 않아야 한다.
$this->assertArrayNotHasKey('total', $pagination);
$this->assertArrayNotHasKey('last_page', $pagination);
$this->assertArrayHasKey('next_cursor', $pagination, '커서 응답에 다음 커서가 없다');
// 받은 커서로 실제 다음 페이지까지 이동되는지 확인
$second = $this->authRequest()
->getJson('/api/admin/notification-logs?per_page=2&cursor='.urlencode($pagination['next_cursor']));
$second->assertStatus(200);
$this->assertNotEmpty($second->json('data.data'));
}
/**
* 상한형 목록이 정확도 메타를 함께 싣는지 확인 (#519 — 성능 개선 유지)
*/
public function test_index_carries_total_accuracy_meta(): void
{
NotificationLog::create(['channel' => 'mail', 'notification_type' => 'test', 'recipient_identifier' => 'm@test.com', 'status' => 'sent']);
$response = $this->authRequest()->getJson('/api/admin/notification-logs?per_page=15');
$response->assertStatus(200);
$pagination = $response->json('data.pagination');
$this->assertArrayHasKey('total_relation', $pagination, '상한 계약의 정확도 메타가 사라졌다');
$this->assertArrayHasKey('total_is_exact', $pagination);
$this->assertArrayHasKey('result_cap', $pagination);
}
/**
* 단건 삭제
*/
public function test_destroy_deletes_log(): void
{
$log = NotificationLog::create([
'channel' => 'mail',
'notification_type' => 'test',
'recipient_identifier' => 'test@example.com',
'status' => 'sent',
]);
$response = $this->authRequest()->deleteJson("/api/admin/notification-logs/{$log->id}");
$response->assertStatus(200)
->assertJsonPath('success', true);
$this->assertDatabaseMissing('notification_logs', ['id' => $log->id]);
}
/**
* 다건 삭제
*/
public function test_bulk_destroy(): void
{
$log1 = NotificationLog::create(['channel' => 'mail', 'notification_type' => 'test', 'recipient_identifier' => 'a@test.com', 'status' => 'sent']);
$log2 = NotificationLog::create(['channel' => 'mail', 'notification_type' => 'test', 'recipient_identifier' => 'b@test.com', 'status' => 'sent']);
$response = $this->authRequest()->postJson('/api/admin/notification-logs/bulk-delete', [
'ids' => [$log1->id, $log2->id],
]);
$response->assertStatus(200)
->assertJsonPath('data.deleted_count', 2);
}
/**
* 인증된 요청 헬퍼.
*
* @return static
*/
private function authRequest(): static
{
return $this->withHeaders([
'Authorization' => 'Bearer '.$this->token,
'Accept' => 'application/json',
]);
}
/**
* 관리자 생성 헬퍼.
*
* @return User
*/
private function createAdminWithPermissions(): User
{
$user = User::factory()->create();
$role = Role::create([
'name' => ['ko' => '최고관리자'],
'identifier' => 'super_admin',
'is_admin' => true,
]);
foreach (['core.notification-logs.read', 'core.notification-logs.delete'] as $identifier) {
$perm = Permission::firstOrCreate(
['identifier' => $identifier],
['name' => ['ko' => $identifier], 'type' => 'admin', 'order' => 1]
);
$role->permissions()->attach($perm->id);
}
$user->roles()->attach($role->id);
return $user;
}
}