v7.0.0-beta.1 release

This commit is contained in:
HeuJung committed 2026-04-01 10:30:52 +09:00
commit 6595fd0eb5
3967 files changed
+1875383

No files matched your search

@@ -0,0 +1,97 @@
<?php
namespace Tests\Unit\ActivityLog;
use App\ActivityLog\ActivityLogChannel;
use App\ActivityLog\ActivityLogHandler;
use App\ActivityLog\ActivityLogProcessor;
use Monolog\Logger;
use Tests\TestCase;
/**
* ActivityLogChannel 테스트
*
* Monolog 커스텀 채널 팩토리가 올바른 Logger 인스턴스를 생성하고
* ActivityLogProcessor와 ActivityLogHandler가 등록되는지 검증합니다.
*/
class ActivityLogChannelTest extends TestCase
{
private ActivityLogChannel $channel;
protected function setUp(): void
{
parent::setUp();
$this->channel = new ActivityLogChannel;
}
/**
* __invoke()가 Monolog Logger 인스턴스를 반환하는지 확인
*/
public function test_invoke_returns_monolog_logger(): void
{
$logger = ($this->channel)([]);
$this->assertInstanceOf(Logger::class, $logger);
}
/**
* Logger의 채널명이 'activity'인지 확인
*/
public function test_logger_has_correct_channel_name(): void
{
$logger = ($this->channel)([]);
$this->assertEquals('activity', $logger->getName());
}
/**
* Logger에 ActivityLogHandler가 등록되어 있는지 확인
*/
public function test_logger_has_activity_log_handler(): void
{
$logger = ($this->channel)([]);
$handlers = $logger->getHandlers();
$hasHandler = false;
foreach ($handlers as $handler) {
if ($handler instanceof ActivityLogHandler) {
$hasHandler = true;
break;
}
}
$this->assertTrue($hasHandler, 'Logger에 ActivityLogHandler가 등록되어 있어야 합니다.');
}
/**
* Logger에 ActivityLogProcessor가 등록되어 있는지 확인
*/
public function test_logger_has_activity_log_processor(): void
{
$logger = ($this->channel)([]);
$processors = $logger->getProcessors();
$hasProcessor = false;
foreach ($processors as $processor) {
if ($processor instanceof ActivityLogProcessor) {
$hasProcessor = true;
break;
}
}
$this->assertTrue($hasProcessor, 'Logger에 ActivityLogProcessor가 등록되어 있어야 합니다.');
}
/**
* 매 호출마다 새 Logger 인스턴스를 반환하는지 확인
*/
public function test_creates_new_logger_instance_each_call(): void
{
$logger1 = ($this->channel)([]);
$logger2 = ($this->channel)([]);
$this->assertNotSame($logger1, $logger2);
}
}
@@ -0,0 +1,228 @@
<?php
namespace Tests\Unit\ActivityLog;
use App\ActivityLog\ActivityLogHandler;
use App\Enums\ActivityLogType;
use App\Models\ActivityLog;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Monolog\Level;
use Monolog\LogRecord;
use Tests\TestCase;
/**
* ActivityLogHandler 테스트
*
* Monolog AbstractProcessingHandler를 확장한 핸들러가
* LogRecord context에서 구조화 데이터를 추출하여
* activity_logs 테이블에 올바르게 저장하는지 검증합니다.
*/
class ActivityLogHandlerTest extends TestCase
{
use RefreshDatabase;
private ActivityLogHandler $handler;
protected function setUp(): void
{
parent::setUp();
$this->handler = new ActivityLogHandler;
config(['activity_log.enabled' => true]);
}
/**
* write()가 context의 구조화 데이터로 ActivityLog 레코드를 생성하는지 확인
*/
public function test_write_creates_activity_log_record(): void
{
$user = User::factory()->create();
$record = new LogRecord(
datetime: new \DateTimeImmutable,
channel: 'activity',
level: Level::Info,
message: 'user.create',
context: [
'log_type' => ActivityLogType::Admin,
'description_key' => 'activity_log.description.user_created',
'description_params' => ['name' => $user->name],
'properties' => ['email' => $user->email],
'changes' => [
['field' => 'name', 'label_key' => 'user.name', 'old' => null, 'new' => $user->name],
],
'user_id' => $user->id,
'ip_address' => '127.0.0.1',
'user_agent' => 'PHPUnit',
],
);
// write()는 protected이므로 handle()을 통해 호출
$this->handler->handle($record);
$this->assertDatabaseCount('activity_logs', 1);
$log = ActivityLog::first();
$this->assertEquals(ActivityLogType::Admin, $log->log_type);
$this->assertEquals('user.create', $log->action);
$this->assertEquals('activity_log.description.user_created', $log->description_key);
$this->assertEquals(['name' => $user->name], $log->description_params);
$this->assertEquals(['email' => $user->email], $log->properties);
$this->assertIsArray($log->changes);
$this->assertCount(1, $log->changes);
$this->assertEquals($user->id, $log->user_id);
$this->assertEquals('127.0.0.1', $log->ip_address);
$this->assertEquals('PHPUnit', $log->user_agent);
}
/**
* loggable(Model 인스턴스)에서 morphType과 key를 올바르게 추출하는지 확인
*/
public function test_loggable_morphing_extracts_type_and_key(): void
{
$user = User::factory()->create();
$record = new LogRecord(
datetime: new \DateTimeImmutable,
channel: 'activity',
level: Level::Info,
message: 'user.update',
context: [
'log_type' => ActivityLogType::Admin,
'loggable' => $user,
'user_id' => $user->id,
'ip_address' => '127.0.0.1',
'user_agent' => 'PHPUnit',
],
);
$this->handler->handle($record);
$log = ActivityLog::first();
$this->assertEquals($user->getMorphClass(), $log->loggable_type);
$this->assertEquals($user->getKey(), $log->loggable_id);
}
/**
* config('activity_log.enabled')가 false이면 레코드를 생성하지 않는지 확인
*/
public function test_disabled_config_prevents_record_creation(): void
{
config(['activity_log.enabled' => false]);
$record = new LogRecord(
datetime: new \DateTimeImmutable,
channel: 'activity',
level: Level::Info,
message: 'user.create',
context: [
'log_type' => ActivityLogType::System,
'user_id' => null,
'ip_address' => '127.0.0.1',
'user_agent' => 'PHPUnit',
],
);
$this->handler->handle($record);
$this->assertDatabaseCount('activity_logs', 0);
}
/**
* user_agent가 500자를 초과하면 잘리는지 확인
*/
public function test_truncates_user_agent_exceeding_500_chars(): void
{
$longUserAgent = str_repeat('A', 600);
$record = new LogRecord(
datetime: new \DateTimeImmutable,
channel: 'activity',
level: Level::Info,
message: 'user.login',
context: [
'log_type' => ActivityLogType::User,
'user_id' => null,
'ip_address' => '127.0.0.1',
'user_agent' => $longUserAgent,
],
);
$this->handler->handle($record);
$log = ActivityLog::first();
$this->assertEquals(500, mb_strlen($log->user_agent));
}
/**
* context에 log_type이 없으면 기본값 System이 사용되는지 확인
*/
public function test_defaults_log_type_to_system(): void
{
$record = new LogRecord(
datetime: new \DateTimeImmutable,
channel: 'activity',
level: Level::Info,
message: 'system.cleanup',
context: [
'user_id' => null,
'ip_address' => '127.0.0.1',
'user_agent' => 'PHPUnit',
],
);
$this->handler->handle($record);
$log = ActivityLog::first();
$this->assertEquals(ActivityLogType::System, $log->log_type);
}
/**
* loggable가 Model 인스턴스가 아니면 loggable_type/loggable_id가 null인지 확인
*/
public function test_non_model_loggable_is_ignored(): void
{
$record = new LogRecord(
datetime: new \DateTimeImmutable,
channel: 'activity',
level: Level::Info,
message: 'system.test',
context: [
'log_type' => ActivityLogType::System,
'loggable' => 'not-a-model',
'user_id' => null,
'ip_address' => '127.0.0.1',
'user_agent' => 'PHPUnit',
],
);
$this->handler->handle($record);
$log = ActivityLog::first();
$this->assertNull($log->loggable_type);
$this->assertNull($log->loggable_id);
}
/**
* null user_agent가 그대로 null로 저장되는지 확인
*/
public function test_null_user_agent_remains_null(): void
{
$record = new LogRecord(
datetime: new \DateTimeImmutable,
channel: 'activity',
level: Level::Info,
message: 'system.test',
context: [
'log_type' => ActivityLogType::System,
'user_id' => null,
'ip_address' => '127.0.0.1',
],
);
$this->handler->handle($record);
$log = ActivityLog::first();
$this->assertNull($log->user_agent);
}
}
@@ -0,0 +1,161 @@
<?php
namespace Tests\Unit\ActivityLog;
use App\ActivityLog\ActivityLogProcessor;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Auth;
use Monolog\Level;
use Monolog\LogRecord;
use Tests\TestCase;
/**
* ActivityLogProcessor 테스트
*
* Monolog Processor가 요청별 공통 데이터(user_id, ip_address, user_agent)를
* 올바르게 자동 주입하는지 검증합니다.
*/
class ActivityLogProcessorTest extends TestCase
{
use RefreshDatabase;
private ActivityLogProcessor $processor;
protected function setUp(): void
{
parent::setUp();
$this->processor = new ActivityLogProcessor;
}
/**
* 인증된 사용자의 user_id가 자동 주입되는지 확인
*/
public function test_auto_injects_user_id_from_auth(): void
{
$user = User::factory()->create();
Auth::login($user);
$record = $this->createRecord();
$result = ($this->processor)($record);
$this->assertEquals($user->id, $result->context['user_id']);
}
/**
* ip_address가 자동 주입되는지 확인
*/
public function test_auto_injects_ip_address(): void
{
$record = $this->createRecord();
$result = ($this->processor)($record);
$this->assertArrayHasKey('ip_address', $result->context);
}
/**
* user_agent가 자동 주입되는지 확인
*/
public function test_auto_injects_user_agent(): void
{
$record = $this->createRecord();
$result = ($this->processor)($record);
$this->assertArrayHasKey('user_agent', $result->context);
}
/**
* 명시적으로 전달된 user_id를 덮어쓰지 않는지 확인
*/
public function test_does_not_overwrite_explicit_user_id(): void
{
$user = User::factory()->create();
Auth::login($user);
$explicitUserId = 99999;
$record = $this->createRecord(['user_id' => $explicitUserId]);
$result = ($this->processor)($record);
$this->assertEquals($explicitUserId, $result->context['user_id']);
}
/**
* 명시적으로 전달된 ip_address를 덮어쓰지 않는지 확인
*/
public function test_does_not_overwrite_explicit_ip_address(): void
{
$record = $this->createRecord(['ip_address' => '192.168.1.100']);
$result = ($this->processor)($record);
$this->assertEquals('192.168.1.100', $result->context['ip_address']);
}
/**
* 명시적으로 전달된 user_agent를 덮어쓰지 않는지 확인
*/
public function test_does_not_overwrite_explicit_user_agent(): void
{
$record = $this->createRecord(['user_agent' => 'CustomBot/1.0']);
$result = ($this->processor)($record);
$this->assertEquals('CustomBot/1.0', $result->context['user_agent']);
}
/**
* 인증된 사용자가 없으면 user_id가 null인지 확인
*/
public function test_user_id_defaults_to_null_when_no_auth(): void
{
Auth::logout();
$record = $this->createRecord();
$result = ($this->processor)($record);
$this->assertNull($result->context['user_id']);
}
/**
* Processor가 원본 레코드를 변경하지 않고 새 레코드를 반환하는지 확인
*/
public function test_returns_new_log_record_instance(): void
{
$record = $this->createRecord();
$result = ($this->processor)($record);
// LogRecord는 불변 객체 — with()로 새 인스턴스 반환
$this->assertNotSame($record, $result);
$this->assertInstanceOf(LogRecord::class, $result);
}
/**
* 기존 context 데이터가 보존되는지 확인
*/
public function test_preserves_existing_context_data(): void
{
$record = $this->createRecord([
'log_type' => 'admin',
'description_key' => 'test.key',
]);
$result = ($this->processor)($record);
$this->assertEquals('admin', $result->context['log_type']);
$this->assertEquals('test.key', $result->context['description_key']);
}
/**
* 테스트용 LogRecord를 생성합니다.
*
* @param array $context 추가 context 데이터
* @return LogRecord
*/
private function createRecord(array $context = []): LogRecord
{
return new LogRecord(
datetime: new \DateTimeImmutable,
channel: 'activity',
level: Level::Info,
message: 'test.action',
context: $context,
);
}
}
@@ -0,0 +1,255 @@
<?php
namespace Tests\Unit\ActivityLog;
use App\ActivityLog\ChangeDetector;
use Illuminate\Database\Eloquent\Model;
use Tests\TestCase;
/**
* ChangeDetector 테스트
*
* 모델의 $activityLogFields 메타데이터와 스냅샷을 비교하여
* 구조화된 변경 이력을 올바르게 생성하는지 검증합니다.
*/
class ChangeDetectorTest extends TestCase
{
/**
* 변경된 필드를 올바르게 감지하는지 확인
*/
public function test_detects_changed_fields(): void
{
$model = new ChangeDetectorTestModel;
$model->name = '변경 후';
$model->email = 'new@example.com';
$snapshot = [
'name' => '변경 전',
'email' => 'old@example.com',
];
$changes = ChangeDetector::detect($model, $snapshot);
$this->assertNotNull($changes);
$this->assertCount(2, $changes);
// name 필드 변경 확인
$nameChange = collect($changes)->firstWhere('field', 'name');
$this->assertEquals('model.name', $nameChange['label_key']);
$this->assertEquals('변경 전', $nameChange['old']);
$this->assertEquals('변경 후', $nameChange['new']);
$this->assertEquals('text', $nameChange['type']);
// email 필드 변경 확인
$emailChange = collect($changes)->firstWhere('field', 'email');
$this->assertEquals('model.email', $emailChange['label_key']);
$this->assertEquals('old@example.com', $emailChange['old']);
$this->assertEquals('new@example.com', $emailChange['new']);
}
/**
* 변경이 없으면 null을 반환하는지 확인
*/
public function test_returns_null_when_no_changes(): void
{
$model = new ChangeDetectorTestModel;
$model->name = '동일값';
$model->email = 'same@example.com';
$snapshot = [
'name' => '동일값',
'email' => 'same@example.com',
];
$changes = ChangeDetector::detect($model, $snapshot);
$this->assertNull($changes);
}
/**
* snapshot이 null이면 null을 반환하는지 확인
*/
public function test_returns_null_when_snapshot_is_null(): void
{
$model = new ChangeDetectorTestModel;
$model->name = 'test';
$changes = ChangeDetector::detect($model, null);
$this->assertNull($changes);
}
/**
* enum 타입 필드의 old_label_key와 new_label_key가 포함되는지 확인
*/
public function test_handles_enum_type_with_label_keys(): void
{
$model = new ChangeDetectorEnumTestModel;
$model->status = ChangeDetectorTestStatus::Active;
$snapshot = [
'status' => 'inactive',
];
$changes = ChangeDetector::detect($model, $snapshot);
$this->assertNotNull($changes);
$this->assertCount(1, $changes);
$statusChange = $changes[0];
$this->assertEquals('status', $statusChange['field']);
$this->assertEquals('model.status', $statusChange['label_key']);
$this->assertEquals('enum', $statusChange['type']);
$this->assertEquals('inactive', $statusChange['old']);
$this->assertEquals('active', $statusChange['new']);
$this->assertEquals('test.status.inactive', $statusChange['old_label_key']);
$this->assertEquals('test.status.active', $statusChange['new_label_key']);
}
/**
* enum 타입 필드의 old가 null이면 old_label_key도 null인지 확인
*/
public function test_enum_null_old_value_returns_null_label_key(): void
{
$model = new ChangeDetectorEnumTestModel;
$model->status = ChangeDetectorTestStatus::Active;
$snapshot = [
'status' => null,
];
$changes = ChangeDetector::detect($model, $snapshot);
$this->assertNotNull($changes);
$statusChange = $changes[0];
$this->assertNull($statusChange['old_label_key']);
$this->assertEquals('test.status.active', $statusChange['new_label_key']);
}
/**
* $activityLogFields에 없는 필드는 무시되는지 확인
*/
public function test_ignores_untracked_fields(): void
{
$model = new ChangeDetectorTestModel;
$model->name = '변경됨';
$model->email = 'same@example.com';
$model->untracked_field = '추적 안 됨';
$snapshot = [
'name' => '원본',
'email' => 'same@example.com',
'untracked_field' => '이전값',
];
$changes = ChangeDetector::detect($model, $snapshot);
$this->assertNotNull($changes);
$this->assertCount(1, $changes);
$this->assertEquals('name', $changes[0]['field']);
}
/**
* $activityLogFields가 없는 모델은 null을 반환하는지 확인
*/
public function test_returns_null_when_model_has_no_activity_log_fields(): void
{
$model = new ChangeDetectorNoFieldsModel;
$model->name = 'test';
$snapshot = ['name' => 'old'];
$changes = ChangeDetector::detect($model, $snapshot);
$this->assertNull($changes);
}
/**
* BackedEnum 객체가 스냅샷에 있을 때 값으로 변환하여 비교하는지 확인
*/
public function test_converts_backed_enum_in_snapshot_to_value(): void
{
$model = new ChangeDetectorEnumTestModel;
$model->status = ChangeDetectorTestStatus::Active;
// 스냅샷에 Enum 객체가 들어있는 경우 (toArray() 시 발생 가능)
$snapshot = [
'status' => ChangeDetectorTestStatus::Inactive,
];
$changes = ChangeDetector::detect($model, $snapshot);
$this->assertNotNull($changes);
$this->assertEquals('inactive', $changes[0]['old']);
$this->assertEquals('active', $changes[0]['new']);
}
}
// ============================================================
// 테스트용 모델 및 Enum 정의
// ============================================================
/**
* 테스트용 모델 (text 필드만)
*/
class ChangeDetectorTestModel extends Model
{
/** @var array<string, array> */
public static array $activityLogFields = [
'name' => ['label_key' => 'model.name', 'type' => 'text'],
'email' => ['label_key' => 'model.email', 'type' => 'text'],
];
protected $guarded = [];
}
/**
* 테스트용 모델 (enum 필드 포함)
*/
class ChangeDetectorEnumTestModel extends Model
{
/** @var array<string, array> */
public static array $activityLogFields = [
'status' => [
'label_key' => 'model.status',
'type' => 'enum',
'enum' => ChangeDetectorTestStatus::class,
],
];
protected $guarded = [];
protected function casts(): array
{
return [
'status' => ChangeDetectorTestStatus::class,
];
}
}
/**
* 테스트용 모델 ($activityLogFields 없음)
*/
class ChangeDetectorNoFieldsModel extends Model
{
protected $guarded = [];
}
/**
* 테스트용 Enum (labelKey() 메서드 포함)
*/
enum ChangeDetectorTestStatus: string
{
case Active = 'active';
case Inactive = 'inactive';
/**
* 다국어 라벨 키를 반환합니다.
*
* @return string
*/
public function labelKey(): string
{
return 'test.status.'.$this->value;
}
}
@@ -0,0 +1,130 @@
<?php
namespace Tests\Unit\ActivityLog\Drivers;
use App\ActivityLog\Drivers\DatabaseActivityLogDriver;
use App\Enums\ActivityLogType;
use App\Models\ActivityLog;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* DatabaseActivityLogDriver 테스트
*
* 데이터베이스 드라이버의 로그 저장 기능을 검증합니다.
*/
class DatabaseActivityLogDriverTest extends TestCase
{
use RefreshDatabase;
private DatabaseActivityLogDriver $driver;
protected function setUp(): void
{
parent::setUp();
$this->driver = new DatabaseActivityLogDriver;
}
/**
* 드라이버 이름이 'database'인지 확인
*/
public function test_driver_name_is_database(): void
{
$this->assertEquals('database', $this->driver->getName());
}
/**
* 기본 로그가 데이터베이스에 저장되는지 확인
*/
public function test_log_saves_to_database(): void
{
$log = $this->driver->log(
ActivityLogType::Admin,
'test.action',
'Test description'
);
$this->assertInstanceOf(ActivityLog::class, $log);
$this->assertDatabaseHas('activity_logs', [
'id' => $log->id,
'log_type' => ActivityLogType::Admin->value,
'action' => 'test.action',
'description' => 'Test description',
]);
}
/**
* 모든 필드가 정확히 저장되는지 확인
*/
public function test_log_saves_all_fields(): void
{
$user = User::factory()->create();
$log = $this->driver->log(
ActivityLogType::User,
'user.login',
'User logged in',
$user,
['browser' => 'Chrome'],
$user->id,
'192.168.1.1',
'Mozilla/5.0'
);
$this->assertEquals(ActivityLogType::User, $log->log_type);
$this->assertEquals('user.login', $log->action);
$this->assertEquals('User logged in', $log->description);
$this->assertEquals($user->getMorphClass(), $log->loggable_type);
$this->assertEquals($user->id, $log->loggable_id);
$this->assertEquals(['browser' => 'Chrome'], $log->properties);
$this->assertEquals($user->id, $log->user_id);
$this->assertEquals('192.168.1.1', $log->ip_address);
$this->assertEquals('Mozilla/5.0', $log->user_agent);
}
/**
* 긴 User-Agent가 500자로 잘리는지 확인
*/
public function test_long_user_agent_is_truncated(): void
{
$longUserAgent = str_repeat('a', 600);
$log = $this->driver->log(
ActivityLogType::Admin,
'test.action',
'Test',
null,
null,
null,
null,
$longUserAgent
);
$this->assertEquals(500, mb_strlen($log->user_agent));
}
/**
* null 값들이 정상적으로 처리되는지 확인
*/
public function test_nullable_fields_are_handled(): void
{
$log = $this->driver->log(
ActivityLogType::System,
'system.task',
'System task completed',
null,
null,
null,
null,
null
);
$this->assertNull($log->loggable_type);
$this->assertNull($log->loggable_id);
$this->assertNull($log->properties);
$this->assertNull($log->user_id);
$this->assertNull($log->ip_address);
$this->assertNull($log->user_agent);
}
}
@@ -0,0 +1,70 @@
<?php
namespace Tests\Unit\ActivityLog\Drivers;
use App\ActivityLog\Drivers\NullActivityLogDriver;
use App\Enums\ActivityLogType;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* NullActivityLogDriver 테스트
*
* Null 드라이버가 아무 동작도 하지 않는지 검증합니다.
*/
class NullActivityLogDriverTest extends TestCase
{
use RefreshDatabase;
private NullActivityLogDriver $driver;
protected function setUp(): void
{
parent::setUp();
$this->driver = new NullActivityLogDriver;
}
/**
* 드라이버 이름이 'null'인지 확인
*/
public function test_driver_name_is_null(): void
{
$this->assertEquals('null', $this->driver->getName());
}
/**
* log()가 null을 반환하는지 확인
*/
public function test_log_returns_null(): void
{
$result = $this->driver->log(
ActivityLogType::Admin,
'test.action',
'Test description'
);
$this->assertNull($result);
}
/**
* log()가 데이터베이스에 아무것도 저장하지 않는지 확인
*/
public function test_log_does_not_save_to_database(): void
{
$user = User::factory()->create();
$this->driver->log(
ActivityLogType::Admin,
'test.action',
'Test description',
$user,
['key' => 'value'],
$user->id,
'127.0.0.1',
'Test Agent'
);
$this->assertDatabaseCount('activity_logs', 0);
}
}
@@ -0,0 +1,203 @@
<?php
namespace Tests\Unit\ActivityLog;
use App\Enums\ActivityLogType;
use App\Models\ActivityLog;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Log;
use Tests\TestCase;
/**
* Monolog 통합 테스트
*
* Log::channel('activity')를 통한 전체 파이프라인이
* 올바르게 동작하는지 End-to-End로 검증합니다.
* ActivityLogChannel → ActivityLogProcessor → ActivityLogHandler 전체 흐름을 테스트합니다.
*/
class MonologIntegrationTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
config(['activity_log.enabled' => true]);
}
/**
* Log::channel('activity')->info()가 ActivityLog 레코드를 생성하는지 확인
*/
public function test_log_channel_creates_activity_log_record(): void
{
Log::channel('activity')->info('user.login', [
'log_type' => ActivityLogType::User,
'description_key' => 'activity_log.description.user_login',
'user_id' => null,
'ip_address' => '10.0.0.1',
'user_agent' => 'TestBrowser/1.0',
]);
$this->assertDatabaseCount('activity_logs', 1);
$log = ActivityLog::first();
$this->assertEquals('user.login', $log->action);
$this->assertEquals(ActivityLogType::User, $log->log_type);
$this->assertEquals('activity_log.description.user_login', $log->description_key);
}
/**
* ActivityLogProcessor가 인증된 사용자 정보를 자동 주입하는지 확인
*/
public function test_processor_auto_injects_authenticated_user(): void
{
$user = User::factory()->create();
$this->actingAs($user);
Log::channel('activity')->info('user.profile_update', [
'log_type' => ActivityLogType::User,
]);
$log = ActivityLog::first();
$this->assertEquals($user->id, $log->user_id);
}
/**
* ActivityLogProcessor가 IP 주소를 자동 주입하는지 확인
*/
public function test_processor_auto_injects_ip_address(): void
{
Log::channel('activity')->info('system.test', [
'log_type' => ActivityLogType::System,
]);
$log = ActivityLog::first();
// IP 주소가 자동 주입됨 (테스트 환경에서는 127.0.0.1 또는 null)
$this->assertArrayHasKey('ip_address', $log->toArray());
}
/**
* 전체 context(description_key, description_params, changes, loggable)가 올바르게 저장되는지 확인
*/
public function test_full_context_passes_through_pipeline(): void
{
$user = User::factory()->create();
$changes = [
[
'field' => 'name',
'label_key' => 'user.name',
'old' => '이전 이름',
'new' => '새 이름',
'type' => 'text',
],
];
$descriptionParams = ['user_name' => $user->name];
Log::channel('activity')->info('user.update', [
'log_type' => ActivityLogType::Admin,
'description_key' => 'activity_log.description.user_updated',
'description_params' => $descriptionParams,
'changes' => $changes,
'properties' => ['section' => 'profile'],
'loggable' => $user,
'user_id' => $user->id,
'ip_address' => '192.168.0.1',
'user_agent' => 'AdminPanel/2.0',
]);
$this->assertDatabaseCount('activity_logs', 1);
$log = ActivityLog::first();
// 기본 필드
$this->assertEquals('user.update', $log->action);
$this->assertEquals(ActivityLogType::Admin, $log->log_type);
$this->assertEquals($user->id, $log->user_id);
$this->assertEquals('192.168.0.1', $log->ip_address);
$this->assertEquals('AdminPanel/2.0', $log->user_agent);
// description_key, description_params
$this->assertEquals('activity_log.description.user_updated', $log->description_key);
$this->assertEquals($descriptionParams, $log->description_params);
// changes
$this->assertIsArray($log->changes);
$this->assertCount(1, $log->changes);
$this->assertEquals('name', $log->changes[0]['field']);
$this->assertEquals('이전 이름', $log->changes[0]['old']);
$this->assertEquals('새 이름', $log->changes[0]['new']);
// properties
$this->assertEquals(['section' => 'profile'], $log->properties);
// loggable (polymorphic)
$this->assertEquals($user->getMorphClass(), $log->loggable_type);
$this->assertEquals($user->getKey(), $log->loggable_id);
}
/**
* config disabled 시 Log::channel('activity')가 레코드를 생성하지 않는지 확인
*/
public function test_disabled_config_prevents_logging(): void
{
config(['activity_log.enabled' => false]);
Log::channel('activity')->info('user.create', [
'log_type' => ActivityLogType::Admin,
]);
$this->assertDatabaseCount('activity_logs', 0);
}
/**
* 여러 로그를 연속 기록할 수 있는지 확인
*/
public function test_multiple_logs_can_be_recorded_sequentially(): void
{
Log::channel('activity')->info('user.login', [
'log_type' => ActivityLogType::User,
'user_id' => null,
'ip_address' => '10.0.0.1',
'user_agent' => 'Browser/1.0',
]);
Log::channel('activity')->info('admin.settings_update', [
'log_type' => ActivityLogType::Admin,
'user_id' => null,
'ip_address' => '10.0.0.2',
'user_agent' => 'Browser/2.0',
]);
$this->assertDatabaseCount('activity_logs', 2);
$logs = ActivityLog::orderBy('id')->get();
$this->assertEquals('user.login', $logs[0]->action);
$this->assertEquals('admin.settings_update', $logs[1]->action);
}
/**
* 명시적으로 전달한 user_id가 Processor에 의해 덮어쓰이지 않는지 확인
*/
public function test_explicit_context_not_overwritten_by_processor(): void
{
$authUser = User::factory()->create();
$this->actingAs($authUser);
$explicitUserId = 99999;
Log::channel('activity')->info('system.impersonate', [
'log_type' => ActivityLogType::System,
'user_id' => $explicitUserId,
'ip_address' => '172.16.0.1',
'user_agent' => 'CLI/1.0',
]);
$log = ActivityLog::first();
$this->assertEquals($explicitUserId, $log->user_id);
$this->assertEquals('172.16.0.1', $log->ip_address);
$this->assertEquals('CLI/1.0', $log->user_agent);
}
}
@@ -0,0 +1,217 @@
<?php
namespace Tests\Unit\ActivityLog;
use App\ActivityLog\Traits\ResolvesActivityLogType;
use App\Enums\ActivityLogType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Mockery;
use Psr\Log\LoggerInterface;
use Tests\TestCase;
/**
* ResolvesActivityLogType 트레이트 단위 테스트
*
* resolveLogType()과 logActivity()의 동작을 검증합니다.
* 요청 경로 기반으로 log_type을 결정하는 로직을 테스트합니다.
*/
class ResolvesActivityLogTypeTest extends TestCase
{
private object $traitUser;
protected function setUp(): void
{
parent::setUp();
// 트레이트를 사용하는 익명 클래스 생성
$this->traitUser = new class
{
use ResolvesActivityLogType;
/**
* resolveLogType() 외부 호출용 래퍼
*/
public function getResolvedLogType(): ActivityLogType
{
return $this->resolveLogType();
}
/**
* logActivity() 외부 호출용 래퍼
*/
public function callLogActivity(string $action, array $context): void
{
$this->logActivity($action, $context);
}
};
}
protected function tearDown(): void
{
if ($container = Mockery::getContainer()) {
$this->addToAssertionCount($container->mockery_getExpectationCount());
}
Mockery::close();
parent::tearDown();
}
// ═══════════════════════════════════════════
// resolveLogType 테스트 — 요청 경로 기반 판별
// ═══════════════════════════════════════════
public function test_resolveLogType_returns_admin_for_admin_route(): void
{
$this->setRequestPath('api/admin/products');
$this->assertEquals(ActivityLogType::Admin, $this->traitUser->getResolvedLogType());
}
public function test_resolveLogType_returns_user_for_shop_route(): void
{
$this->setRequestPath('api/shop/cart');
$this->assertEquals(ActivityLogType::User, $this->traitUser->getResolvedLogType());
}
public function test_resolveLogType_returns_user_for_admin_on_user_route(): void
{
// 핵심 테스트: admin 역할이지만 사용자 화면 경로 → user
$this->setRequestPath('api/shop/cart');
$this->assertEquals(ActivityLogType::User, $this->traitUser->getResolvedLogType());
}
public function test_resolveLogType_returns_user_for_guest_on_user_route(): void
{
// 비회원이 사용자 화면 경로 → user (System이 아님)
$this->setRequestPath('api/shop/coupons/download');
$this->assertEquals(ActivityLogType::User, $this->traitUser->getResolvedLogType());
}
public function test_resolveLogType_returns_user_for_public_api_route(): void
{
$this->setRequestPath('api/auth/register');
$this->assertEquals(ActivityLogType::User, $this->traitUser->getResolvedLogType());
}
public function test_resolveLogType_returns_system_for_cli_without_request(): void
{
// CLI 환경: request()->path() === '/'
$this->setRequestPath('/');
$this->assertEquals(ActivityLogType::System, $this->traitUser->getResolvedLogType());
}
public function test_resolveLogType_returns_admin_for_nested_admin_route(): void
{
$this->setRequestPath('api/admin/sirsoft-ecommerce/orders/123/cancel');
$this->assertEquals(ActivityLogType::Admin, $this->traitUser->getResolvedLogType());
}
// ═══════════════════════════════════════════
// logActivity 테스트
// ═══════════════════════════════════════════
public function test_logActivity_auto_resolves_log_type_when_not_provided(): void
{
$this->setRequestPath('api/admin/products');
$logChannel = Mockery::mock(LoggerInterface::class);
Log::shouldReceive('channel')->with('activity')->andReturn($logChannel);
$logChannel->shouldReceive('info')
->once()
->withArgs(function (string $action, array $context) {
return $action === 'test.action'
&& $context['log_type'] === ActivityLogType::Admin
&& $context['description_key'] === 'test_key';
});
$this->traitUser->callLogActivity('test.action', [
'description_key' => 'test_key',
]);
}
public function test_logActivity_preserves_explicit_log_type(): void
{
// 경로는 admin이지만 명시적으로 User 타입이 전달된 경우 유지
$this->setRequestPath('api/admin/products');
$logChannel = Mockery::mock(LoggerInterface::class);
Log::shouldReceive('channel')->with('activity')->andReturn($logChannel);
$logChannel->shouldReceive('info')
->once()
->withArgs(function (string $action, array $context) {
// 명시적으로 전달한 User 타입이 유지되어야 함
return $context['log_type'] === ActivityLogType::User;
});
$this->traitUser->callLogActivity('test.action', [
'log_type' => ActivityLogType::User,
'description_key' => 'test_key',
]);
}
public function test_logActivity_catches_exception_and_logs_error(): void
{
$this->setRequestPath('/');
$logChannel = Mockery::mock(LoggerInterface::class);
Log::shouldReceive('channel')->with('activity')->andReturn($logChannel);
$logChannel->shouldReceive('info')
->once()
->andThrow(new \RuntimeException('DB connection failed'));
Log::shouldReceive('error')
->once()
->withArgs(function (string $message, array $context) {
return $message === 'Failed to record activity log'
&& $context['action'] === 'test.action'
&& $context['error'] === 'DB connection failed';
});
$this->traitUser->callLogActivity('test.action', [
'description_key' => 'test_key',
]);
}
public function test_logActivity_resolves_system_type_for_cli_context(): void
{
// CLI 환경 (request()->path() === '/')
$this->setRequestPath('/');
$logChannel = Mockery::mock(LoggerInterface::class);
Log::shouldReceive('channel')->with('activity')->andReturn($logChannel);
$logChannel->shouldReceive('info')
->once()
->withArgs(function (string $action, array $context) {
return $context['log_type'] === ActivityLogType::System;
});
$this->traitUser->callLogActivity('test.action', [
'description_key' => 'test_key',
]);
}
// ═══════════════════════════════════════════
// 헬퍼 메서드
// ═══════════════════════════════════════════
/**
* 테스트용 Request 경로를 설정합니다.
*
* @param string $path 요청 경로 (예: 'api/admin/products', '/' for CLI 시뮬레이션)
*/
private function setRequestPath(string $path): void
{
$request = Request::create($path === '/' ? '/' : '/'.$path);
$this->app->instance('request', $request);
}
}