feat(core,board,ecommerce,page): 성능 계측 인프라 4축 확장 및 계측 대상 선언 지점 신설
계측 축이 "목록 SELECT" 하나였고 프로파일 12종이 커맨드 파일에 하드코딩돼 있어 확장이 자기 대상을 추가할 수 없었다. 확장이 설치·제거되는 설치본마다 "실제로 존재하는 대상"이 달라지므로, 대상을 소유자가 선언하고 코어가 수집하도록 뒤집었다. - 선언 지점 두 곳, 스키마 하나: 코어 config/benchmark.php, 확장 getBenchmarkProfiles (모듈/플러그인). 수집은 method_exists 기반이라 인터페이스를 직접 구현한 서드파티 확장이 깨지지 않는다. - 축 4종(목록/화면/쓰기/배치)을 실행기로 분리하고 컨테이너 태그로 주입 — 축이 늘 때 커맨드를 고치지 않는다. - 화면 축은 HTTP 커널로 내부 요청을 처리한다. 라우트만 dispatch 하면 전역 미들웨어를 건너뛰어 화면과 다른 것을 재게 된다. 인증은 프로파일이 선언한 권한만 가진 임시 계정이 기본이며 --as 로 기존 계정을 지목할 수 있다. - 화면/쓰기 축은 계측 계정 생성부터 처리까지 롤백되는 트랜잭션 안에서 실행해 운영 DB 에도 잔여 데이터를 남기지 않는다. 배치 축은 내부 커밋·락 보유 때문에 감싸지 않고 --allow-write 로만 통제한다. - 잘못된 선언은 조용히 버리지 않고 사유를 경고로 남긴다. 버려진 선언이 곧 계측 사각이 되기 때문이다. 전부 건너뛴 실행은 종료 코드 1 로 끝난다. - 리포트는 환경 정보를 함께 적어 저장소 밖(storage/app/benchmarks)에 남긴다. 측정값이 실행 머신에 종속되므로 저장소에 축적하면 비교 불가능한 수치가 섞인다. 작업 중 발견해 함께 고친 것: - 이관 프로파일 3종의 soft_delete 선언이 실제 스키마와 어긋나 있었다 (users/product_inquiries/pages 에 deleted_at 없음). - 주문 목록이 상태 미지정 시 임시 주문 상태를 NOT IN 으로 제외하는데 선언에 빠져 있었다. filters 가 등가 비교만 지원한 것이 근본 원인이라 연산자 형태를 받도록 넓히고, 미허용 연산자는 측정 전에 거부한다. - 댓글 프로파일은 지배적 술어가 상관 서브쿼리라 선언형으로 재현할 수 없어 제거했다. 맨 테이블 스캔은 어느 화면도 내지 않는 수치가 된다. g7:bench:pagination → g7:bench 로 개명(4축을 재므로). 이전 이름은 별칭으로 남겼다. 테스트 61건 통과, 라이브 18종 전건 측정.
This commit is contained in:
1 parent
be9befe023
commit
5f4a733b3b
40 files changed
+5266
-567
No files matched your search
@@ -0,0 +1,725 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Console;
|
||||
|
||||
use App\Benchmark\BenchmarkProfileRegistry;
|
||||
use App\Benchmark\DTO\BenchmarkProfile;
|
||||
use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
use App\Enums\BenchmarkAxis;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* `g7:bench` 커맨드 및 프로파일 레지스트리 Feature 테스트.
|
||||
*
|
||||
* 계측 결과는 시간 값이라 실행마다 달라지므로 **수치는 단언하지 않는다**. 단언 대상은
|
||||
* 산출 구조(표 헤더 / JSON 키), 프로파일 수집, 축별 실행 분기, 안전장치 동작이다.
|
||||
*
|
||||
* 프로파일은 코어 `config/benchmark.php` 와 확장 `getBenchmarkProfiles()` 두 지점에서
|
||||
* 수집되므로, 테스트는 config 를 런타임 치환해 "커맨드가 선언을 읽는다"는 성질 자체를
|
||||
* 검증한다 — 특정 확장 설치 여부에 의존하면 설치본마다 결과가 갈린다.
|
||||
*/
|
||||
class BenchCommandTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* 각 테스트가 자기 프로파일만 보도록 코어 선언을 치환하고 레지스트리 캐시를 비운다.
|
||||
*
|
||||
* 활성 확장의 선언도 함께 차단한다 — 차단하지 않으면 설치된 번들 확장 구성에 따라
|
||||
* 정확 집합 단언이 갈리고, 테스트가 검증하려는 성질(커맨드가 선언을 읽는다)과 무관한
|
||||
* 이유로 실패한다. 확장 선언 수집 자체는 가짜 확장을 주입하는 테스트가 담당한다.
|
||||
*
|
||||
* @param array<string, array<string, mixed>> $profiles 치환할 코어 프로파일 선언
|
||||
*/
|
||||
private function withCoreProfiles(array $profiles): void
|
||||
{
|
||||
Config::set('benchmark.profiles', $profiles);
|
||||
|
||||
// 레지스트리는 수집 결과를 인스턴스에 캐시하므로 새 인스턴스를 강제한다
|
||||
$this->bindExtensionManagers([], []);
|
||||
}
|
||||
|
||||
/**
|
||||
* 코어 config 선언이 프로파일 목록에 노출됩니다.
|
||||
*
|
||||
* @effects core_config_profiles_are_collected
|
||||
*/
|
||||
#[Test]
|
||||
public function 코어_config_선언이_프로파일_목록에_노출된다(): void
|
||||
{
|
||||
$this->withCoreProfiles([
|
||||
'bench_users' => [
|
||||
'type' => 'list',
|
||||
'label' => '테스트 회원 목록',
|
||||
'table' => 'users',
|
||||
'columns' => ['id'],
|
||||
'order' => [['id', 'desc']],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->artisan('g7:bench', ['--list-profiles' => true])
|
||||
->expectsOutputToContain('core/bench_users')
|
||||
->assertExitCode(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장이 선언한 프로파일도 같은 목록에 함께 수집됩니다.
|
||||
*
|
||||
* 확장 선언 지점(`getBenchmarkProfiles()`)이 실제로 수집 경로에 연결돼 있는지를
|
||||
* 확인합니다. 특정 번들 확장에 의존하지 않도록 가짜 모듈을 매니저에 주입합니다.
|
||||
*
|
||||
* @effects module_declared_profiles_are_collected, profile_source_kind_and_identifier_are_recorded
|
||||
*/
|
||||
#[Test]
|
||||
public function 확장_선언_프로파일이_수집된다(): void
|
||||
{
|
||||
$this->withCoreProfiles([]);
|
||||
$this->fakeModuleWithProfiles([
|
||||
'fake_list' => [
|
||||
'type' => 'list',
|
||||
'label' => '가짜 확장 목록',
|
||||
'table' => 'users',
|
||||
'columns' => ['id'],
|
||||
],
|
||||
]);
|
||||
|
||||
$profiles = app(BenchmarkProfileRegistry::class)->all();
|
||||
|
||||
$this->assertArrayHasKey('vendor-fake/fake_list', $profiles);
|
||||
$this->assertSame('module', $profiles['vendor-fake/fake_list']->sourceKind);
|
||||
$this->assertSame(BenchmarkAxis::ListQuery, $profiles['vendor-fake/fake_list']->axis);
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인이 선언한 프로파일도 함께 수집됩니다.
|
||||
*
|
||||
* @effects plugin_declared_profiles_are_collected
|
||||
*/
|
||||
#[Test]
|
||||
public function 플러그인_선언_프로파일이_수집된다(): void
|
||||
{
|
||||
$this->withCoreProfiles([]);
|
||||
$this->fakeExtensionsWithProfiles([], [
|
||||
'fake_plugin_list' => ['type' => 'list', 'table' => 'users', 'columns' => ['id']],
|
||||
]);
|
||||
|
||||
$profiles = app(BenchmarkProfileRegistry::class)->all();
|
||||
|
||||
$this->assertArrayHasKey('vendor-fake-plugin/fake_plugin_list', $profiles);
|
||||
$this->assertSame('plugin', $profiles['vendor-fake-plugin/fake_plugin_list']->sourceKind);
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 하나의 선언 실패가 전체 목록을 날리지 않습니다.
|
||||
*
|
||||
* 확장 하나가 던진 예외로 목록이 비면 계측 자체를 못 하게 되므로, 실패한 확장만 사유와
|
||||
* 함께 제외하고 나머지는 살립니다.
|
||||
*
|
||||
* @effects extension_declaration_failure_is_isolated_to_that_extension
|
||||
*/
|
||||
#[Test]
|
||||
public function 확장_선언_실패는_그_확장에만_국한된다(): void
|
||||
{
|
||||
$this->withCoreProfiles([
|
||||
'survivor' => ['type' => 'list', 'table' => 'users', 'columns' => ['id']],
|
||||
]);
|
||||
|
||||
$broken = new class
|
||||
{
|
||||
/**
|
||||
* @return string 모듈 식별자
|
||||
*/
|
||||
public function getIdentifier(): string
|
||||
{
|
||||
return 'vendor-broken';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array<string, mixed>> 선언 (항상 실패)
|
||||
*/
|
||||
public function getBenchmarkProfiles(): array
|
||||
{
|
||||
throw new \RuntimeException('declaration blew up');
|
||||
}
|
||||
};
|
||||
|
||||
$this->bindExtensionManagers([$broken], []);
|
||||
|
||||
$registry = app(BenchmarkProfileRegistry::class);
|
||||
|
||||
// 코어 선언은 살아남는다
|
||||
$this->assertArrayHasKey('core/survivor', $registry->all());
|
||||
// 실패한 확장은 사유와 함께 드러난다
|
||||
$this->assertStringContainsString('vendor-broken', implode("\n", $registry->warnings()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 잘못된 선언은 조용히 버려지지 않고 사유와 함께 경고로 드러납니다.
|
||||
*
|
||||
* @effects missing_type_declaration_is_rejected_with_reason, unknown_axis_type_is_rejected_with_allowed_values, missing_required_option_is_rejected_naming_the_option, rejected_declarations_appear_in_warnings_not_silently_dropped
|
||||
*/
|
||||
#[Test]
|
||||
public function 잘못된_선언은_사유와_함께_경고로_드러난다(): void
|
||||
{
|
||||
$this->withCoreProfiles([
|
||||
'no_type' => ['table' => 'users'],
|
||||
'unknown_axis' => ['type' => 'nonsense', 'table' => 'users'],
|
||||
'missing_required' => ['type' => 'screen'],
|
||||
'valid' => ['type' => 'list', 'table' => 'users', 'columns' => ['id']],
|
||||
]);
|
||||
|
||||
$registry = app(BenchmarkProfileRegistry::class);
|
||||
|
||||
// 정상 선언만 남는다
|
||||
$this->assertSame(['core/valid'], array_keys($registry->all()));
|
||||
|
||||
$warnings = implode("\n", $registry->warnings());
|
||||
$this->assertStringContainsString('core/no_type', $warnings);
|
||||
$this->assertStringContainsString('core/unknown_axis', $warnings);
|
||||
$this->assertStringContainsString('core/missing_required', $warnings);
|
||||
// screen 축은 route 또는 uri 중 하나가 필요하다는 사유가 드러나야 한다
|
||||
$this->assertStringContainsString('route|uri', $warnings);
|
||||
}
|
||||
|
||||
/**
|
||||
* 짧은 키가 둘 이상의 출처에서 선언되면 후보를 제시하고 실행을 거부합니다.
|
||||
*
|
||||
* 임의로 하나를 고르면 어느 확장의 대상을 잰 것인지 알 수 없게 됩니다.
|
||||
*
|
||||
* @effects ambiguous_short_key_lists_candidates_and_refuses, qualified_key_resolves_exactly, unique_short_key_resolves
|
||||
*/
|
||||
#[Test]
|
||||
public function 모호한_짧은_키는_후보를_제시하고_거부한다(): void
|
||||
{
|
||||
$this->withCoreProfiles([
|
||||
'orders' => ['type' => 'list', 'table' => 'users', 'columns' => ['id']],
|
||||
]);
|
||||
$this->fakeModuleWithProfiles([
|
||||
'orders' => ['type' => 'list', 'table' => 'users', 'columns' => ['id']],
|
||||
]);
|
||||
|
||||
$this->artisan('g7:bench', ['--profile' => ['orders']])
|
||||
->expectsOutputToContain('모호')
|
||||
->assertExitCode(1);
|
||||
|
||||
// 정규화 키로 지목하면 정상 해석된다
|
||||
$registry = app(BenchmarkProfileRegistry::class);
|
||||
$profile = $registry->find('vendor-fake/orders');
|
||||
$this->assertInstanceOf(BenchmarkProfile::class, $profile);
|
||||
$this->assertSame('vendor-fake', $profile->sourceIdentifier);
|
||||
|
||||
// 겹치지 않는 짧은 키는 그대로 해석된다 (모호할 때만 거부)
|
||||
$this->withCoreProfiles([
|
||||
'only_here' => ['type' => 'list', 'table' => 'users', 'columns' => ['id']],
|
||||
]);
|
||||
|
||||
[$unique, $error] = app(BenchmarkProfileRegistry::class)->resolve('only_here');
|
||||
$this->assertNull($error);
|
||||
$this->assertSame('core/only_here', $unique->qualifiedKey());
|
||||
}
|
||||
|
||||
/**
|
||||
* 미등록 프로파일 키는 실패로 끝납니다.
|
||||
*
|
||||
* @effects unknown_key_fails_with_list_profiles_hint
|
||||
*/
|
||||
#[Test]
|
||||
public function 미등록_프로파일_키는_실패한다(): void
|
||||
{
|
||||
$this->withCoreProfiles([]);
|
||||
|
||||
$this->artisan('g7:bench', ['--profile' => ['nope']])
|
||||
->expectsOutputToContain('등록되지 않은 프로파일')
|
||||
->assertExitCode(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 대상 지정이 없으면 무엇을 잴지 알 수 없으므로 실패합니다.
|
||||
*
|
||||
* @effects no_selection_fails_asking_for_profile_or_axis_or_all
|
||||
*/
|
||||
#[Test]
|
||||
public function 대상_미지정_실행은_실패한다(): void
|
||||
{
|
||||
$this->withCoreProfiles([
|
||||
'bench_users' => ['type' => 'list', 'table' => 'users', 'columns' => ['id']],
|
||||
]);
|
||||
|
||||
$this->artisan('g7:bench')
|
||||
->expectsOutputToContain('--profile / --axis / --all')
|
||||
->assertExitCode(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록 축은 컬럼 폭 3축 표를 산출합니다. (수치는 단언하지 않음)
|
||||
*
|
||||
* @effects list_axis_reports_all_list_and_id_only_columns
|
||||
*/
|
||||
#[Test]
|
||||
public function 목록_축은_컬럼_폭_3축_표를_산출한다(): void
|
||||
{
|
||||
$this->withCoreProfiles([
|
||||
'bench_users' => [
|
||||
'type' => 'list',
|
||||
'table' => 'users',
|
||||
'columns' => ['id', 'email'],
|
||||
'order' => [['id', 'desc']],
|
||||
'soft_delete' => true,
|
||||
],
|
||||
]);
|
||||
|
||||
$exitCode = Artisan::call('g7:bench', [
|
||||
'--profile' => ['core/bench_users'],
|
||||
'--offsets' => '0',
|
||||
'--runs' => 1,
|
||||
]);
|
||||
|
||||
$this->assertSame(0, $exitCode);
|
||||
|
||||
$output = Artisan::output();
|
||||
|
||||
// 세 축이 함께 나와야 배수(전체÷ID)의 근거가 성립한다
|
||||
$this->assertStringContainsString('전체 컬럼(ms)', $output);
|
||||
$this->assertStringContainsString('목록 컬럼(ms)', $output);
|
||||
$this->assertStringContainsString('ID만(ms)', $output);
|
||||
$this->assertStringContainsString('전체÷ID', $output);
|
||||
}
|
||||
|
||||
/**
|
||||
* 없는 테이블을 가리키는 목록 프로파일은 사유와 함께 건너뛰어집니다.
|
||||
*
|
||||
* 확장이 제거된 설치본에서 계측이 죽지 않아야 하고, 동시에 "측정했다"로 읽혀서도
|
||||
* 안 되므로 사유가 남고 종료 코드는 실패입니다.
|
||||
*
|
||||
* @effects skipped_profiles_remain_in_output_with_reason
|
||||
*/
|
||||
#[Test]
|
||||
public function 없는_테이블_프로파일은_사유와_함께_건너뛴다(): void
|
||||
{
|
||||
$this->withCoreProfiles([
|
||||
'ghost' => ['type' => 'list', 'table' => 'table_that_does_not_exist', 'columns' => ['id']],
|
||||
]);
|
||||
|
||||
$this->artisan('g7:bench', ['--profile' => ['core/ghost'], '--offsets' => '0', '--runs' => 1])
|
||||
->expectsOutputToContain('테이블이 없습니다')
|
||||
->assertExitCode(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 쓰기 축은 `--allow-write` 없이 실행을 거부합니다.
|
||||
*
|
||||
* @effects mutating_axes_refuse_without_allow_write
|
||||
*/
|
||||
#[Test]
|
||||
public function 쓰기_축은_allow_write_없이_거부된다(): void
|
||||
{
|
||||
$this->withCoreProfiles([
|
||||
'bench_write' => [
|
||||
'type' => 'write',
|
||||
'callback' => [BenchCommandWriteSubject::class, 'run'],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->artisan('g7:bench', ['--profile' => ['core/bench_write']])
|
||||
->expectsOutputToContain('--allow-write')
|
||||
->assertExitCode(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 데이터를 변경하는 배치도 `--allow-write` 없이 거부됩니다.
|
||||
*
|
||||
* @effects mutating_axes_refuse_without_allow_write
|
||||
*/
|
||||
#[Test]
|
||||
public function 변경하는_배치는_allow_write_없이_거부된다(): void
|
||||
{
|
||||
$this->withCoreProfiles([
|
||||
'bench_batch' => ['type' => 'batch', 'command' => 'seo:clear'],
|
||||
]);
|
||||
|
||||
$this->artisan('g7:bench', ['--profile' => ['core/bench_batch']])
|
||||
->expectsOutputToContain('--allow-write')
|
||||
->assertExitCode(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 쓰기 축 콜백에 클로저를 쓸 수 없다는 사유가 드러납니다.
|
||||
*
|
||||
* 코어 선언은 `config:cache` 대상이라 클로저를 담을 수 없으므로 형식을 통일합니다.
|
||||
*
|
||||
* @effects closure_callback_is_rejected_with_config_cache_reason
|
||||
*/
|
||||
#[Test]
|
||||
public function 쓰기_축_클로저_콜백은_사유와_함께_거부된다(): void
|
||||
{
|
||||
$this->withCoreProfiles([
|
||||
'bench_closure' => [
|
||||
'type' => 'write',
|
||||
'callback' => fn () => null,
|
||||
],
|
||||
]);
|
||||
|
||||
$this->artisan('g7:bench', [
|
||||
'--profile' => ['core/bench_closure'],
|
||||
'--allow-write' => true,
|
||||
])
|
||||
->expectsOutputToContain('클로저는 쓸 수 없습니다')
|
||||
->assertExitCode(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 알 수 없는 축 이름은 허용 목록과 함께 거부됩니다.
|
||||
*/
|
||||
#[Test]
|
||||
public function 알_수_없는_축_이름은_거부된다(): void
|
||||
{
|
||||
$this->withCoreProfiles([]);
|
||||
|
||||
$this->artisan('g7:bench', ['--axis' => 'nonsense'])
|
||||
->expectsOutputToContain('알 수 없는 축')
|
||||
->assertExitCode(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* `--json` 출력이 약속된 최상위 키와 결과 키를 담습니다.
|
||||
*
|
||||
* @effects json_output_carries_environment_options_warnings_results
|
||||
*/
|
||||
#[Test]
|
||||
public function json_출력이_약속된_스키마를_담는다(): void
|
||||
{
|
||||
$this->withCoreProfiles([
|
||||
'bench_users' => [
|
||||
'type' => 'list',
|
||||
'label' => '테스트 회원 목록',
|
||||
'table' => 'users',
|
||||
'columns' => ['id'],
|
||||
'order' => [['id', 'desc']],
|
||||
],
|
||||
]);
|
||||
|
||||
$exitCode = Artisan::call('g7:bench', [
|
||||
'--profile' => ['core/bench_users'],
|
||||
'--offsets' => '0',
|
||||
'--runs' => 1,
|
||||
'--json' => true,
|
||||
]);
|
||||
|
||||
$this->assertSame(0, $exitCode);
|
||||
|
||||
$payload = json_decode(Artisan::output(), true);
|
||||
|
||||
$this->assertIsArray($payload, 'JSON 출력이 파싱 가능해야 한다.');
|
||||
foreach (['generated_at', 'environment', 'options', 'warnings', 'results'] as $key) {
|
||||
$this->assertArrayHasKey($key, $payload);
|
||||
}
|
||||
|
||||
$result = $payload['results'][0];
|
||||
foreach (['profile', 'axis', 'label', 'source', 'skipped', 'headers', 'rows', 'metrics', 'notes'] as $key) {
|
||||
$this->assertArrayHasKey($key, $result);
|
||||
}
|
||||
$this->assertSame('core/bench_users', $result['profile']);
|
||||
$this->assertSame('list', $result['axis']);
|
||||
$this->assertFalse($result['skipped']);
|
||||
}
|
||||
|
||||
/**
|
||||
* `--report` 는 환경 정보와 축 절을 담은 마크다운을 지정 경로에 씁니다.
|
||||
*
|
||||
* @effects report_includes_environment_and_run_conditions, report_writes_to_given_path
|
||||
*/
|
||||
#[Test]
|
||||
public function report_는_환경_정보를_담은_마크다운을_쓴다(): void
|
||||
{
|
||||
$this->withCoreProfiles([
|
||||
'bench_users' => [
|
||||
'type' => 'list',
|
||||
'label' => '테스트 회원 목록',
|
||||
'table' => 'users',
|
||||
'columns' => ['id'],
|
||||
'order' => [['id', 'desc']],
|
||||
],
|
||||
]);
|
||||
|
||||
$path = storage_path('app/benchmarks/test-'.uniqid().'.md');
|
||||
|
||||
$this->artisan('g7:bench', [
|
||||
'--profile' => ['core/bench_users'],
|
||||
'--offsets' => '0',
|
||||
'--runs' => 1,
|
||||
'--report' => $path,
|
||||
])->assertExitCode(0);
|
||||
|
||||
$this->assertFileExists($path);
|
||||
|
||||
$markdown = (string) file_get_contents($path);
|
||||
|
||||
// 환경 정보가 빠진 리포트는 다른 리포트와 비교할 수 없으므로 필수 항목이다
|
||||
$this->assertStringContainsString('## 실행 환경', $markdown);
|
||||
$this->assertStringContainsString('DB 버전', $markdown);
|
||||
$this->assertStringContainsString('config:cache', $markdown);
|
||||
$this->assertStringContainsString('## 실행 조건', $markdown);
|
||||
$this->assertStringContainsString('## 목록 조회 (list)', $markdown);
|
||||
$this->assertStringContainsString('core/bench_users — 테스트 회원 목록', $markdown);
|
||||
|
||||
@unlink($path);
|
||||
}
|
||||
|
||||
/**
|
||||
* 운영 환경에서는 시딩/비움이 거부됩니다.
|
||||
*
|
||||
* @effects seeding_and_truncation_are_refused_in_production
|
||||
*/
|
||||
#[Test]
|
||||
public function 운영_환경에서는_시딩이_거부된다(): void
|
||||
{
|
||||
$this->withCoreProfiles([
|
||||
'bench_users' => ['type' => 'list', 'table' => 'users', 'columns' => ['id']],
|
||||
]);
|
||||
|
||||
// 계측 대상 테이블을 실제로 건드리기 전에 거부되는지를 본다
|
||||
$this->app->detectEnvironment(fn () => 'production');
|
||||
|
||||
try {
|
||||
$this->artisan('g7:bench', [
|
||||
'--profile' => ['core/bench_users'],
|
||||
'--offsets' => '0',
|
||||
'--runs' => 1,
|
||||
'--seed' => 10,
|
||||
])
|
||||
->expectsOutputToContain('운영 환경에서는 시딩/비움을 사용할 수 없습니다')
|
||||
->assertExitCode(1);
|
||||
} finally {
|
||||
$this->app->detectEnvironment(fn () => 'testing');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `--report` 를 값 없이 주면 저장소 미추적 기본 경로에 리포트를 씁니다.
|
||||
*
|
||||
* @effects report_defaults_to_untracked_storage_path
|
||||
*/
|
||||
#[Test]
|
||||
public function report_는_값_없이_주면_기본_경로에_쓴다(): void
|
||||
{
|
||||
$this->withCoreProfiles([
|
||||
'bench_users' => ['type' => 'list', 'table' => 'users', 'columns' => ['id']],
|
||||
]);
|
||||
|
||||
$directory = storage_path('app/benchmarks');
|
||||
$before = is_dir($directory) ? glob($directory.'/bench-*.md') : [];
|
||||
|
||||
$exitCode = Artisan::call('g7:bench', [
|
||||
'--profile' => ['core/bench_users'],
|
||||
'--offsets' => '0',
|
||||
'--runs' => 1,
|
||||
'--report' => null,
|
||||
]);
|
||||
|
||||
$this->assertSame(0, $exitCode);
|
||||
|
||||
$after = glob($directory.'/bench-*.md');
|
||||
$created = array_values(array_diff($after ?: [], $before ?: []));
|
||||
|
||||
$this->assertCount(1, $created, '기본 경로(storage/app/benchmarks)에 리포트가 생성되어야 한다.');
|
||||
$this->assertStringContainsString('## 실행 환경', (string) file_get_contents($created[0]));
|
||||
|
||||
@unlink($created[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* `--database` 는 계측에 사용할 연결을 다시 지목합니다.
|
||||
*
|
||||
* config 가 캐시된 환경에서 연결을 바꿀 유일한 수단이라, 이 치환이 동작하지 않으면
|
||||
* 대량 시딩이 개발 DB 로 들어갑니다.
|
||||
*
|
||||
* @effects database_override_option_repoints_the_connection
|
||||
*/
|
||||
#[Test]
|
||||
public function database_옵션이_연결을_다시_지목한다(): void
|
||||
{
|
||||
$this->withCoreProfiles([
|
||||
'bench_users' => ['type' => 'list', 'table' => 'users', 'columns' => ['id']],
|
||||
]);
|
||||
|
||||
$connection = (string) config('database.default');
|
||||
// 실제 접속이 끊기지 않도록 현재 스키마명으로 재지목한다 (치환 경로 자체를 검증)
|
||||
$current = (string) (config("database.connections.{$connection}.database")
|
||||
?: config("database.connections.{$connection}.write.database"));
|
||||
|
||||
Artisan::call('g7:bench', [
|
||||
'--profile' => ['core/bench_users'],
|
||||
'--offsets' => '0',
|
||||
'--runs' => 1,
|
||||
'--database' => $current,
|
||||
]);
|
||||
|
||||
// 최상위와 읽기/쓰기 하위 모두 지목되어야 한다 — 하나라도 남으면 그 경로만 다른 DB 를 본다
|
||||
$this->assertSame($current, config("database.connections.{$connection}.database"));
|
||||
$this->assertSame($current, config("database.connections.{$connection}.write.database"));
|
||||
$this->assertSame($current, config("database.connections.{$connection}.read.database"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 전부 건너뛴 실행은 실패로 끝납니다. (성공으로 보고하면 "측정했다"로 읽힘)
|
||||
*
|
||||
* @effects all_skipped_run_exits_nonzero, skipped_profiles_remain_in_output_with_reason
|
||||
*/
|
||||
#[Test]
|
||||
public function 전부_건너뛴_실행은_실패로_끝난다(): void
|
||||
{
|
||||
$this->withCoreProfiles([
|
||||
'ghost_a' => ['type' => 'list', 'table' => 'missing_table_a', 'columns' => ['id']],
|
||||
'ghost_b' => ['type' => 'list', 'table' => 'missing_table_b', 'columns' => ['id']],
|
||||
]);
|
||||
|
||||
$exitCode = Artisan::call('g7:bench', ['--axis' => 'list', '--offsets' => '0', '--runs' => 1]);
|
||||
|
||||
$this->assertSame(1, $exitCode);
|
||||
|
||||
$output = Artisan::output();
|
||||
|
||||
// 건너뛴 프로파일이 목록에서 빠지지 않고 사유와 함께 남는다
|
||||
$this->assertStringContainsString('core/ghost_a', $output);
|
||||
$this->assertStringContainsString('core/ghost_b', $output);
|
||||
$this->assertStringContainsString('테이블이 없습니다', $output);
|
||||
}
|
||||
|
||||
/**
|
||||
* 축 필터가 해당 축의 프로파일만 고릅니다.
|
||||
*
|
||||
* @effects axis_filter_selects_only_that_axis
|
||||
*/
|
||||
#[Test]
|
||||
public function 축_필터는_해당_축만_고른다(): void
|
||||
{
|
||||
$this->withCoreProfiles([
|
||||
'bench_users' => ['type' => 'list', 'table' => 'users', 'columns' => ['id']],
|
||||
'bench_screen' => ['type' => 'screen', 'route' => 'api.admin.users.index'],
|
||||
'bench_batch' => ['type' => 'batch', 'command' => 'seo:clear'],
|
||||
]);
|
||||
|
||||
$registry = app(BenchmarkProfileRegistry::class);
|
||||
|
||||
$this->assertSame(['core/bench_users'], array_keys($registry->byAxis(BenchmarkAxis::ListQuery)));
|
||||
$this->assertSame(['core/bench_screen'], array_keys($registry->byAxis(BenchmarkAxis::Screen)));
|
||||
$this->assertSame(['core/bench_batch'], array_keys($registry->byAxis(BenchmarkAxis::Batch)));
|
||||
$this->assertSame([], array_keys($registry->byAxis(BenchmarkAxis::Write)));
|
||||
}
|
||||
|
||||
/**
|
||||
* GET 화면은 변경으로 보지 않고, 비-GET 화면은 변경으로 봅니다.
|
||||
*/
|
||||
#[Test]
|
||||
public function screen_축의_변경_판정은_http_메서드를_따른다(): void
|
||||
{
|
||||
$this->withCoreProfiles([
|
||||
'get_screen' => ['type' => 'screen', 'route' => 'api.admin.users.index'],
|
||||
'post_screen' => ['type' => 'screen', 'route' => 'api.admin.users.store', 'method' => 'POST'],
|
||||
'declared_readonly' => ['type' => 'screen', 'route' => 'api.admin.users.store', 'method' => 'POST', 'mutating' => false],
|
||||
]);
|
||||
|
||||
$registry = app(BenchmarkProfileRegistry::class);
|
||||
|
||||
$this->assertFalse($registry->find('core/get_screen')->mutates());
|
||||
$this->assertTrue($registry->find('core/post_screen')->mutates());
|
||||
// 선언이 축 기본값을 덮어쓴다
|
||||
$this->assertFalse($registry->find('core/declared_readonly')->mutates());
|
||||
}
|
||||
|
||||
/**
|
||||
* 프로파일을 선언한 가짜 모듈을 모듈 매니저에 주입합니다.
|
||||
*
|
||||
* 특정 번들 확장 설치 여부에 의존하지 않고 "확장 선언이 수집된다"는 성질만 검증합니다.
|
||||
*
|
||||
* @param array<string, array<string, mixed>> $profiles 가짜 모듈이 선언할 프로파일
|
||||
*/
|
||||
private function fakeModuleWithProfiles(array $profiles): void
|
||||
{
|
||||
$this->fakeExtensionsWithProfiles($profiles, []);
|
||||
}
|
||||
|
||||
/**
|
||||
* 프로파일을 선언한 가짜 모듈/플러그인을 각 매니저에 주입합니다.
|
||||
*
|
||||
* @param array<string, array<string, mixed>> $modileProfiles 가짜 모듈이 선언할 프로파일
|
||||
* @param array<string, array<string, mixed>> $pluginProfiles 가짜 플러그인이 선언할 프로파일
|
||||
*/
|
||||
private function fakeExtensionsWithProfiles(array $modileProfiles, array $pluginProfiles): void
|
||||
{
|
||||
$this->bindExtensionManagers(
|
||||
$modileProfiles === [] ? [] : [$this->fakeExtension('vendor-fake', $modileProfiles)],
|
||||
$pluginProfiles === [] ? [] : [$this->fakeExtension('vendor-fake-plugin', $pluginProfiles)],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 프로파일만 선언하는 가짜 확장 인스턴스를 만듭니다.
|
||||
*
|
||||
* @param string $identifier 확장 식별자
|
||||
* @param array<string, array<string, mixed>> $profiles 선언할 프로파일
|
||||
* @return object 가짜 확장
|
||||
*/
|
||||
private function fakeExtension(string $identifier, array $profiles): object
|
||||
{
|
||||
return new class($identifier, $profiles)
|
||||
{
|
||||
/**
|
||||
* @param string $identifier 확장 식별자
|
||||
* @param array<string, array<string, mixed>> $profiles 선언할 프로파일
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly string $identifier,
|
||||
private readonly array $profiles,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return string 확장 식별자
|
||||
*/
|
||||
public function getIdentifier(): string
|
||||
{
|
||||
return $this->identifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array<string, mixed>> 선언한 프로파일
|
||||
*/
|
||||
public function getBenchmarkProfiles(): array
|
||||
{
|
||||
return $this->profiles;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 매니저를 가짜로 바인딩하고 레지스트리 캐시를 비웁니다.
|
||||
*
|
||||
* @param array<int, object> $modules 활성 모듈 목록
|
||||
* @param array<int, object> $plugins 활성 플러그인 목록
|
||||
*/
|
||||
private function bindExtensionManagers(array $modules, array $plugins): void
|
||||
{
|
||||
$moduleManager = \Mockery::mock(ModuleManagerInterface::class);
|
||||
$moduleManager->shouldReceive('getActiveModules')->andReturn($modules);
|
||||
|
||||
$pluginManager = \Mockery::mock(PluginManagerInterface::class);
|
||||
$pluginManager->shouldReceive('getActivePlugins')->andReturn($plugins);
|
||||
|
||||
$this->app->instance(ModuleManagerInterface::class, $moduleManager);
|
||||
$this->app->instance(PluginManagerInterface::class, $pluginManager);
|
||||
$this->app->forgetInstance(BenchmarkProfileRegistry::class);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 쓰기 축 콜백 형식 검증용 대상 (실행되지 않음 — 가드에서 먼저 막힘).
|
||||
*/
|
||||
class BenchCommandWriteSubject
|
||||
{
|
||||
/**
|
||||
* 계측 대상 자리표시자.
|
||||
*/
|
||||
public function run(mixed $context = null): void {}
|
||||
}
|
||||
@@ -0,0 +1,737 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Benchmark;
|
||||
|
||||
use App\Benchmark\Axes\BatchAxisRunner;
|
||||
use App\Benchmark\Axes\ListAxisRunner;
|
||||
use App\Benchmark\Axes\ScreenAxisRunner;
|
||||
use App\Benchmark\Axes\WriteAxisRunner;
|
||||
use App\Benchmark\DTO\BenchmarkProfile;
|
||||
use App\Benchmark\DTO\BenchmarkRunOptions;
|
||||
use App\Benchmark\QueryCollector;
|
||||
use App\Enums\BenchmarkAxis;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 축 실행기 단위 테스트.
|
||||
*
|
||||
* 계측 결과는 시간 값이라 **수치를 단언하지 않는다**. 단언 대상은 각 축이 무엇을 실행하고
|
||||
* 무엇을 산출하는지, 그리고 계측이 데이터에 흔적을 남기지 않는지다.
|
||||
*/
|
||||
class BenchmarkAxisRunnerTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* 프로파일을 만듭니다.
|
||||
*
|
||||
* @param BenchmarkAxis $axis 계측 축
|
||||
* @param array<string, mixed> $options 축 고유 옵션
|
||||
* @return BenchmarkProfile 프로파일
|
||||
*/
|
||||
private function profile(BenchmarkAxis $axis, array $options): BenchmarkProfile
|
||||
{
|
||||
return new BenchmarkProfile(
|
||||
key: 'sample',
|
||||
axis: $axis,
|
||||
sourceKind: 'core',
|
||||
sourceIdentifier: 'core',
|
||||
options: $options,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록 축은 컬럼 폭 3축을 재고 배수를 함께 산출합니다.
|
||||
*
|
||||
* @effects list_axis_reports_all_list_and_id_only_columns
|
||||
*/
|
||||
#[Test]
|
||||
public function 목록_축은_3축_결과와_배수를_산출한다(): void
|
||||
{
|
||||
$result = app(ListAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::ListQuery, [
|
||||
'table' => 'users',
|
||||
'columns' => ['id', 'email'],
|
||||
'order' => [['id', 'desc']],
|
||||
'soft_delete' => true,
|
||||
]),
|
||||
new BenchmarkRunOptions(offsets: [0], runs: 1),
|
||||
);
|
||||
|
||||
$this->assertFalse($result->skipped);
|
||||
$this->assertSame(['OFFSET', '전체 컬럼(ms)', '목록 컬럼(ms)', 'ID만(ms)', '전체÷ID'], $result->headers);
|
||||
$this->assertCount(1, $result->rows);
|
||||
$this->assertSame('users', $result->metrics['table']);
|
||||
$this->assertSame(['id', 'email'], $result->metrics['columns']);
|
||||
|
||||
$offset = $result->metrics['offsets'][0];
|
||||
foreach (['offset', 'all_ms', 'list_ms', 'id_only_ms', 'ratio'] as $key) {
|
||||
$this->assertArrayHasKey($key, $offset);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 배수는 키 컬럼 조회를 기준선으로 산출됩니다.
|
||||
*
|
||||
* 이 기준선이 지연 조인의 inner 쿼리에 해당하므로, 배수가 곧 적용 기대 효과입니다.
|
||||
*
|
||||
* @effects list_axis_ratio_is_derived_from_id_only_baseline
|
||||
*/
|
||||
#[Test]
|
||||
public function 배수는_키_컬럼_기준선으로_산출된다(): void
|
||||
{
|
||||
$result = app(ListAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::ListQuery, ['table' => 'users', 'columns' => ['*']]),
|
||||
new BenchmarkRunOptions(offsets: [0], runs: 1),
|
||||
);
|
||||
|
||||
$offset = $result->metrics['offsets'][0];
|
||||
|
||||
$this->assertSame(
|
||||
round($offset['all_ms'] / $offset['id_only_ms'], 1),
|
||||
$offset['ratio'],
|
||||
'배수는 전체 컬럼 ÷ 키 컬럼이어야 한다.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 선언된 필터와 소프트 삭제가 실제 계측 쿼리에 반영됩니다.
|
||||
*
|
||||
* 필터 없이 재면 인덱스 선택이 달라져 화면에서 일어나는 일과 다른 것을 잽니다.
|
||||
*
|
||||
* @effects declared_filters_are_applied_to_measured_query, soft_delete_declaration_adds_deleted_at_predicate
|
||||
*/
|
||||
#[Test]
|
||||
public function 선언된_필터와_소프트_삭제가_계측_쿼리에_반영된다(): void
|
||||
{
|
||||
// 확장 설치 여부에 의존하지 않도록 소프트 삭제 컬럼이 있는 코어 테이블로 검증한다.
|
||||
// 컬럼이 없는 테이블에서 술어가 붙지 않는 성질은 다음 테스트가 다룬다.
|
||||
$collected = app(QueryCollector::class)->collect(function () {
|
||||
app(ListAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::ListQuery, [
|
||||
'table' => 'attachments',
|
||||
'columns' => ['id'],
|
||||
'filters' => ['disk' => 'public'],
|
||||
'soft_delete' => true,
|
||||
]),
|
||||
new BenchmarkRunOptions(offsets: [0], runs: 1),
|
||||
);
|
||||
});
|
||||
|
||||
$sql = str_replace('`', '"', implode("\n", array_column($collected['queries'], 'sql')));
|
||||
|
||||
$this->assertStringContainsString('"deleted_at" is null', $sql);
|
||||
$this->assertStringContainsString('"disk" = ?', $sql);
|
||||
}
|
||||
|
||||
/**
|
||||
* 연산자 형태 필터가 계측 쿼리에 반영됩니다.
|
||||
*
|
||||
* 등가 비교만 지원하면 화면이 실제로 거는 필터를 선언할 수 없는 목록이 생깁니다 —
|
||||
* 주문 목록은 상태 미지정 시 임시 주문 상태를 `NOT IN` 으로 제외합니다.
|
||||
*
|
||||
* @effects operator_filters_are_applied_to_measured_query
|
||||
*/
|
||||
#[Test]
|
||||
public function 연산자_형태_필터가_계측_쿼리에_반영된다(): void
|
||||
{
|
||||
$collected = app(QueryCollector::class)->collect(function () {
|
||||
app(ListAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::ListQuery, [
|
||||
'table' => 'attachments',
|
||||
'columns' => ['id'],
|
||||
'filters' => [
|
||||
'disk' => ['not in', ['public', 'local']],
|
||||
'id' => ['>=', 10],
|
||||
],
|
||||
]),
|
||||
new BenchmarkRunOptions(offsets: [0], runs: 1),
|
||||
);
|
||||
});
|
||||
|
||||
$sql = str_replace('`', '"', implode("\n", array_column($collected['queries'], 'sql')));
|
||||
|
||||
$this->assertStringContainsString('"disk" not in (?, ?)', $sql);
|
||||
$this->assertStringContainsString('"id" >= ?', $sql);
|
||||
}
|
||||
|
||||
/**
|
||||
* 배열 값을 등가 비교로 선언하면 IN 으로 오해석하지 않습니다.
|
||||
*
|
||||
* 형태(2원소 + 첫 원소가 문자열)로만 연산자 선언을 판정하므로, 값 자체가 배열인 등가
|
||||
* 비교와 구분됩니다.
|
||||
*
|
||||
* @effects equality_filter_is_not_misread_as_operator_form
|
||||
*/
|
||||
#[Test]
|
||||
public function 세_원소_배열은_연산자_선언으로_보지_않는다(): void
|
||||
{
|
||||
$result = app(ListAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::ListQuery, [
|
||||
'table' => 'attachments',
|
||||
'columns' => ['id'],
|
||||
// 2원소가 아니라 연산자 선언 형태가 아니다 → 등가 비교로 처리(연산자 검증 통과)
|
||||
'filters' => ['disk' => ['a', 'b', 'c']],
|
||||
]),
|
||||
new BenchmarkRunOptions(offsets: [0], runs: 1),
|
||||
);
|
||||
|
||||
// 연산자 검증에 걸리지 않고 실행된다
|
||||
$this->assertFalse($result->skipped, '건너뜀 사유: '.(string) $result->skipReason);
|
||||
}
|
||||
|
||||
/**
|
||||
* 알 수 없는 연산자는 측정 전에 사유와 함께 거부됩니다.
|
||||
*
|
||||
* 조용히 무시하면 그 필터가 빠진 채로 측정되어, 화면과 다른 것을 재면서도 정상 측정으로
|
||||
* 보고됩니다.
|
||||
*
|
||||
* @effects unknown_filter_operator_is_refused_before_measuring
|
||||
*/
|
||||
#[Test]
|
||||
public function 알_수_없는_필터_연산자는_측정_전에_거부된다(): void
|
||||
{
|
||||
$result = app(ListAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::ListQuery, [
|
||||
'table' => 'attachments',
|
||||
'columns' => ['id'],
|
||||
'filters' => ['disk' => ['betwixt', ['a', 'b']]],
|
||||
]),
|
||||
new BenchmarkRunOptions(offsets: [0], runs: 1),
|
||||
);
|
||||
|
||||
$this->assertTrue($result->skipped);
|
||||
$this->assertStringContainsString('연산자를 알 수 없습니다', (string) $result->skipReason);
|
||||
$this->assertStringContainsString('betwixt', (string) $result->skipReason);
|
||||
}
|
||||
|
||||
/**
|
||||
* 소프트 삭제 컬럼이 없는 테이블에는 술어를 붙이지 않습니다.
|
||||
*
|
||||
* 선언을 그대로 믿고 붙이면 컬럼 없는 테이블에서 SQL 오류로 계측이 죽습니다.
|
||||
*
|
||||
* @effects soft_delete_declaration_adds_deleted_at_predicate
|
||||
*/
|
||||
#[Test]
|
||||
public function 소프트_삭제_컬럼이_없으면_술어를_붙이지_않는다(): void
|
||||
{
|
||||
$collected = app(QueryCollector::class)->collect(function () {
|
||||
app(ListAxisRunner::class)->run(
|
||||
// users 에는 deleted_at 이 없다 (탈퇴는 status 로 표현)
|
||||
$this->profile(BenchmarkAxis::ListQuery, [
|
||||
'table' => 'users',
|
||||
'columns' => ['id'],
|
||||
'soft_delete' => true,
|
||||
]),
|
||||
new BenchmarkRunOptions(offsets: [0], runs: 1),
|
||||
);
|
||||
});
|
||||
|
||||
$sql = str_replace('`', '"', implode("\n", array_column($collected['queries'], 'sql')));
|
||||
|
||||
$this->assertStringNotContainsString('"deleted_at" is null', $sql);
|
||||
}
|
||||
|
||||
/**
|
||||
* `--explain` 은 목록 컬럼과 키 컬럼 두 폭의 실행 계획을 모두 수집합니다.
|
||||
*
|
||||
* 키 컬럼 계획이 지연 조인 inner 의 계획이라, 인덱스 설계 근거는 두 계획의 대조입니다.
|
||||
*
|
||||
* @effects explain_option_collects_plans_for_both_column_widths
|
||||
*/
|
||||
#[Test]
|
||||
public function explain_은_두_폭의_실행_계획을_수집한다(): void
|
||||
{
|
||||
$result = app(ListAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::ListQuery, ['table' => 'users', 'columns' => ['id', 'email']]),
|
||||
new BenchmarkRunOptions(offsets: [0], runs: 1, explain: true),
|
||||
);
|
||||
|
||||
$notes = implode("\n", $result->notes);
|
||||
|
||||
$this->assertStringContainsString('EXPLAIN @ OFFSET 0 — 목록 컬럼', $notes);
|
||||
$this->assertStringContainsString('EXPLAIN @ OFFSET 0 — ID 만 (지연 조인 inner)', $notes);
|
||||
}
|
||||
|
||||
/**
|
||||
* `['*']` 선언은 실제 스키마 컬럼으로 펼쳐집니다.
|
||||
*
|
||||
* 응답 계약상 전 컬럼을 노출하는 목록의 비교축이 `select *` vs `select id` 임을 고정합니다.
|
||||
*
|
||||
* @effects wildcard_columns_expand_to_actual_schema_columns
|
||||
*/
|
||||
#[Test]
|
||||
public function 와일드카드_컬럼은_실제_스키마로_펼쳐진다(): void
|
||||
{
|
||||
$result = app(ListAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::ListQuery, ['table' => 'users', 'columns' => ['*']]),
|
||||
new BenchmarkRunOptions(offsets: [0], runs: 1),
|
||||
);
|
||||
|
||||
$this->assertContains('id', $result->metrics['columns']);
|
||||
$this->assertContains('email', $result->metrics['columns']);
|
||||
$this->assertGreaterThan(2, count($result->metrics['columns']));
|
||||
}
|
||||
|
||||
/**
|
||||
* 스키마에 없는 선언 컬럼은 걸러집니다.
|
||||
*
|
||||
* 확장 버전에 따라 컬럼 구성이 달라도 계측이 죽지 않아야 합니다.
|
||||
*
|
||||
* @effects nonexistent_declared_columns_are_filtered_out
|
||||
*/
|
||||
#[Test]
|
||||
public function 없는_컬럼은_걸러진다(): void
|
||||
{
|
||||
$result = app(ListAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::ListQuery, [
|
||||
'table' => 'users',
|
||||
'columns' => ['id', 'column_that_does_not_exist'],
|
||||
]),
|
||||
new BenchmarkRunOptions(offsets: [0], runs: 1),
|
||||
);
|
||||
|
||||
$this->assertSame(['id'], $result->metrics['columns']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 없는 테이블은 사유와 함께 건너뛰어집니다.
|
||||
*/
|
||||
#[Test]
|
||||
public function 없는_테이블은_사유와_함께_건너뛴다(): void
|
||||
{
|
||||
$result = app(ListAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::ListQuery, ['table' => 'nope_missing_table']),
|
||||
new BenchmarkRunOptions(offsets: [0], runs: 1),
|
||||
);
|
||||
|
||||
$this->assertTrue($result->skipped);
|
||||
$this->assertStringContainsString('테이블이 없습니다', (string) $result->skipReason);
|
||||
}
|
||||
|
||||
/**
|
||||
* 화면 축은 상태 코드·응답 시간·쿼리 건수를 산출하고 계측 흔적을 남기지 않습니다.
|
||||
*
|
||||
* @effects screen_axis_dispatches_through_http_kernel_with_middleware, screen_axis_reports_status_response_time_and_query_count, absence_of_n_plus_one_is_stated_explicitly, measurement_leaves_no_residual_rows_after_rollback, container_request_and_auth_guards_are_restored_after_each_dispatch, route_name_declaration_resolves_uri_without_prefix_assembly
|
||||
*/
|
||||
#[Test]
|
||||
public function 화면_축은_응답과_쿼리_요약을_산출하고_흔적을_남기지_않는다(): void
|
||||
{
|
||||
$usersBefore = User::count();
|
||||
|
||||
$result = app(ScreenAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::Screen, [
|
||||
'route' => 'api.admin.users.index',
|
||||
'query' => ['per_page' => 5],
|
||||
'permissions' => ['core.users.read'],
|
||||
]),
|
||||
new BenchmarkRunOptions(runs: 1),
|
||||
);
|
||||
|
||||
$this->assertFalse($result->skipped, '건너뜀 사유: '.(string) $result->skipReason);
|
||||
$this->assertSame(['요청', '상태', '응답(ms)', '쿼리(건)', 'DB(ms)'], $result->headers);
|
||||
$this->assertSame(200, $result->metrics['status']);
|
||||
$this->assertGreaterThan(0, $result->metrics['query_count'], '화면 1장은 최소 1건 이상 쿼리를 실행한다.');
|
||||
$this->assertTrue($result->metrics['acting_user']['ephemeral'], '기본은 계측용 임시 계정이다.');
|
||||
|
||||
// N+1 후보가 없으면 없다고 명시해야 한다 — 침묵은 "확인 안 함"과 구분되지 않는다
|
||||
$notes = implode("\n", $result->notes);
|
||||
$this->assertTrue(
|
||||
str_contains($notes, 'N+1 후보'),
|
||||
'N+1 후보 유무가 결과에 명시되어야 한다.'
|
||||
);
|
||||
|
||||
// 계측 계정 생성부터 요청 처리까지 롤백되므로 잔여 계정/역할/토큰이 없어야 한다
|
||||
$this->assertSame($usersBefore, User::count());
|
||||
$this->assertSame(0, DB::table('roles')->where('identifier', 'like', 'g7_bench_%')->count());
|
||||
$this->assertSame(0, DB::table('personal_access_tokens')->where('name', 'like', 'g7-bench-%')->count());
|
||||
|
||||
// 인증 가드가 복구되지 않으면 이어지는 계측이 앞 요청의 인증을 물려받는다
|
||||
$this->assertFalse(Auth::check(), '계측 후 인증 가드가 복구되어야 한다.');
|
||||
}
|
||||
|
||||
/**
|
||||
* 선언한 권한만 임시 계정에 부여됩니다.
|
||||
*
|
||||
* 전권 계정으로 재면 권한 검사 비용과 분기가 실제와 달라집니다.
|
||||
*
|
||||
* @effects ephemeral_admin_receives_only_declared_permissions
|
||||
*/
|
||||
#[Test]
|
||||
public function 임시_계정은_선언한_권한만_받는다(): void
|
||||
{
|
||||
// 선언한 권한이 없으면 관리자 목록 화면의 권한 미들웨어를 통과하지 못해야 한다
|
||||
$result = app(ScreenAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::Screen, [
|
||||
'route' => 'api.admin.users.index',
|
||||
'permissions' => [],
|
||||
]),
|
||||
new BenchmarkRunOptions(runs: 1),
|
||||
);
|
||||
|
||||
$this->assertFalse($result->skipped, '건너뜀 사유: '.(string) $result->skipReason);
|
||||
$this->assertSame(
|
||||
403,
|
||||
$result->metrics['status'],
|
||||
'권한을 선언하지 않으면 권한 미들웨어에서 막혀야 한다 — 전권 계정이 아니라는 실증.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* `--as` 로 지정한 기존 계정으로 계측할 수 있습니다.
|
||||
*
|
||||
* @effects as_option_measures_with_the_named_existing_account
|
||||
*/
|
||||
#[Test]
|
||||
public function as_옵션은_지정_계정으로_계측한다(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$result = app(ScreenAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::Screen, ['route' => 'api.admin.users.index']),
|
||||
new BenchmarkRunOptions(runs: 1, asUser: $user->email),
|
||||
);
|
||||
|
||||
$this->assertFalse($result->skipped, '건너뜀 사유: '.(string) $result->skipReason);
|
||||
$this->assertFalse($result->metrics['acting_user']['ephemeral']);
|
||||
$this->assertSame($user->email, $result->metrics['acting_user']['email']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 없는 계정을 지정하면 사유와 함께 건너뛰어집니다.
|
||||
*/
|
||||
#[Test]
|
||||
public function 없는_지정_계정은_사유와_함께_건너뛴다(): void
|
||||
{
|
||||
$result = app(ScreenAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::Screen, ['route' => 'api.admin.users.index']),
|
||||
new BenchmarkRunOptions(runs: 1, asUser: 'no-such-account@example.test'),
|
||||
);
|
||||
|
||||
$this->assertTrue($result->skipped);
|
||||
$this->assertStringContainsString('계정을 찾을 수 없습니다', (string) $result->skipReason);
|
||||
}
|
||||
|
||||
/**
|
||||
* 등록되지 않은 라우트명은 404 를 재는 대신 즉시 건너뛰어집니다.
|
||||
*
|
||||
* @effects missing_route_name_fails_instead_of_measuring_a_404
|
||||
*/
|
||||
#[Test]
|
||||
public function 없는_라우트명은_사유와_함께_건너뛴다(): void
|
||||
{
|
||||
$result = app(ScreenAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::Screen, ['route' => 'api.route.that.does.not.exist']),
|
||||
new BenchmarkRunOptions(runs: 1),
|
||||
);
|
||||
|
||||
$this->assertTrue($result->skipped);
|
||||
$this->assertStringContainsString('등록되지 않은 라우트명', (string) $result->skipReason);
|
||||
}
|
||||
|
||||
/**
|
||||
* 쓰기 축의 `prepare` 는 계측 구간 밖에서 회차마다 실행되고 결과가 콜백에 전달됩니다.
|
||||
*
|
||||
* @effects prepare_runs_once_per_iteration, callback_receives_prepare_result, write_axis_reports_first_run_and_median_separately
|
||||
*/
|
||||
#[Test]
|
||||
public function 쓰기_축은_prepare_를_회차마다_계측_밖에서_실행한다(): void
|
||||
{
|
||||
BenchmarkWriteSpy::reset();
|
||||
|
||||
$result = app(WriteAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::Write, [
|
||||
'prepare' => [BenchmarkWriteSpy::class, 'prepare'],
|
||||
'callback' => [BenchmarkWriteSpy::class, 'create'],
|
||||
'cleanup' => [BenchmarkWriteSpy::class, 'cleanup'],
|
||||
]),
|
||||
new BenchmarkRunOptions(runs: 3, allowWrite: true),
|
||||
);
|
||||
|
||||
$this->assertFalse($result->skipped, '건너뜀 사유: '.(string) $result->skipReason);
|
||||
$this->assertSame(3, BenchmarkWriteSpy::$prepareCalls, 'prepare 는 회차마다 실행된다.');
|
||||
$this->assertSame(3, BenchmarkWriteSpy::$createCalls);
|
||||
$this->assertSame([1, 2, 3], BenchmarkWriteSpy::$receivedContexts, 'prepare 반환값이 콜백에 전달된다.');
|
||||
$this->assertSame(1, BenchmarkWriteSpy::$cleanupCalls, 'cleanup 은 계측 종료 후 1회 실행된다.');
|
||||
|
||||
$this->assertSame(['첫 회(ms)', '중앙값(ms)', '회차', '쿼리(건)', 'DB(ms)'], $result->headers);
|
||||
$this->assertCount(3, $result->metrics['samples_ms']);
|
||||
}
|
||||
|
||||
/**
|
||||
* `prepare` 실행은 계측 창 밖이라 쿼리 집계에 섞이지 않습니다.
|
||||
*
|
||||
* 시간이 아니라 쿼리 건수로 확인합니다 — 시간 기반 확인은 실행 환경에 따라 흔들립니다.
|
||||
*
|
||||
* @effects prepare_runs_outside_the_measured_window
|
||||
*/
|
||||
#[Test]
|
||||
public function prepare_쿼리는_계측_집계에_섞이지_않는다(): void
|
||||
{
|
||||
BenchmarkWriteSpy::reset();
|
||||
BenchmarkWriteSpy::$prepareQueries = 3;
|
||||
BenchmarkWriteSpy::$createQueries = 1;
|
||||
|
||||
$result = app(WriteAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::Write, [
|
||||
'prepare' => [BenchmarkWriteSpy::class, 'prepare'],
|
||||
'callback' => [BenchmarkWriteSpy::class, 'create'],
|
||||
]),
|
||||
new BenchmarkRunOptions(runs: 1, allowWrite: true),
|
||||
);
|
||||
|
||||
$this->assertFalse($result->skipped, '건너뜀 사유: '.(string) $result->skipReason);
|
||||
$this->assertSame(
|
||||
1,
|
||||
$result->metrics['query_count'],
|
||||
'prepare 가 실행한 3건은 집계에서 빠지고 계측 대상 1건만 남아야 한다.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 쓰기 축은 `--allow-write` 없이 실행을 거부합니다.
|
||||
*/
|
||||
#[Test]
|
||||
public function 쓰기_축은_allow_write_없이_거부한다(): void
|
||||
{
|
||||
BenchmarkWriteSpy::reset();
|
||||
|
||||
$result = app(WriteAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::Write, ['callback' => [BenchmarkWriteSpy::class, 'create']]),
|
||||
new BenchmarkRunOptions(runs: 1),
|
||||
);
|
||||
|
||||
$this->assertTrue($result->skipped);
|
||||
$this->assertStringContainsString('--allow-write', (string) $result->skipReason);
|
||||
$this->assertSame(0, BenchmarkWriteSpy::$createCalls, '거부되면 콜백이 실행되지 않아야 한다.');
|
||||
}
|
||||
|
||||
/**
|
||||
* `cleanup` 실패가 계측 결과를 삼키지 않습니다.
|
||||
*
|
||||
* @effects cleanup_failure_does_not_swallow_the_measurement
|
||||
*/
|
||||
#[Test]
|
||||
public function cleanup_실패가_계측_결과를_삼키지_않는다(): void
|
||||
{
|
||||
BenchmarkWriteSpy::reset();
|
||||
BenchmarkWriteSpy::$cleanupThrows = true;
|
||||
|
||||
$messages = [];
|
||||
|
||||
$result = app(WriteAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::Write, [
|
||||
'callback' => [BenchmarkWriteSpy::class, 'create'],
|
||||
'cleanup' => [BenchmarkWriteSpy::class, 'cleanup'],
|
||||
]),
|
||||
new BenchmarkRunOptions(runs: 1, allowWrite: true),
|
||||
function (string $message) use (&$messages) {
|
||||
$messages[] = $message;
|
||||
},
|
||||
);
|
||||
|
||||
$this->assertFalse($result->skipped, '건너뜀 사유: '.(string) $result->skipReason);
|
||||
$this->assertStringContainsString('cleanup 실패', implode("\n", $messages));
|
||||
}
|
||||
|
||||
/**
|
||||
* 배치 축은 소요 시간과 피크 메모리(실행 전/후)를 산출합니다.
|
||||
*
|
||||
* @effects batch_axis_reports_elapsed_time_and_peak_memory, peak_memory_before_and_after_are_both_reported
|
||||
*/
|
||||
#[Test]
|
||||
public function 배치_축은_시간과_피크_메모리를_산출한다(): void
|
||||
{
|
||||
$result = app(BatchAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::Batch, ['command' => 'seo:clear']),
|
||||
new BenchmarkRunOptions(allowWrite: true),
|
||||
);
|
||||
|
||||
$this->assertFalse($result->skipped, '건너뜀 사유: '.(string) $result->skipReason);
|
||||
$this->assertSame(['커맨드', '종료코드', '소요(ms)', '피크 메모리', '메모리 증가', '쿼리(건)'], $result->headers);
|
||||
$this->assertSame('seo:clear', $result->metrics['command']);
|
||||
// 피크는 프로세스 누적값이라 실행 전 값이 함께 있어야 이 배치의 기여를 판정할 수 있다
|
||||
$this->assertArrayHasKey('peak_memory_before_bytes', $result->metrics);
|
||||
$this->assertArrayHasKey('peak_memory_after_bytes', $result->metrics);
|
||||
$this->assertGreaterThanOrEqual(
|
||||
$result->metrics['peak_memory_before_bytes'],
|
||||
$result->metrics['peak_memory_after_bytes'],
|
||||
'피크 메모리는 감소하지 않는다.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 실패 종료한 배치는 부분 측정임을 사유로 남깁니다.
|
||||
*
|
||||
* 실패를 감추면 "이 시간이 전체 처리 비용"으로 읽힙니다.
|
||||
*
|
||||
* @effects batch_axis_reports_nonzero_exit_code_as_partial_measurement
|
||||
*/
|
||||
#[Test]
|
||||
public function 실패_종료_배치는_부분_측정임을_남긴다(): void
|
||||
{
|
||||
Artisan::command('bench:always-fails', fn () => 3)->describe('계측 테스트용 실패 커맨드');
|
||||
|
||||
$result = app(BatchAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::Batch, ['command' => 'bench:always-fails']),
|
||||
new BenchmarkRunOptions(allowWrite: true),
|
||||
);
|
||||
|
||||
$this->assertFalse($result->skipped, '건너뜀 사유: '.(string) $result->skipReason);
|
||||
$this->assertSame(3, $result->metrics['exit_code']);
|
||||
$this->assertStringContainsString('실패 종료', implode("\n", $result->notes));
|
||||
}
|
||||
|
||||
/**
|
||||
* 등록되지 않은 커맨드는 사유와 함께 건너뛰어집니다.
|
||||
*
|
||||
* @effects unregistered_command_is_skipped_with_reason
|
||||
*/
|
||||
#[Test]
|
||||
public function 없는_커맨드는_사유와_함께_건너뛴다(): void
|
||||
{
|
||||
$result = app(BatchAxisRunner::class)->run(
|
||||
$this->profile(BenchmarkAxis::Batch, ['command' => 'no:such-command']),
|
||||
new BenchmarkRunOptions(allowWrite: true),
|
||||
);
|
||||
|
||||
$this->assertTrue($result->skipped);
|
||||
$this->assertStringContainsString('등록되지 않은 커맨드', (string) $result->skipReason);
|
||||
}
|
||||
|
||||
/**
|
||||
* 쿼리 수집기는 계측 구간의 쿼리만 모으고 반복 SQL 을 N+1 후보로 보고합니다.
|
||||
*
|
||||
* @effects repeated_identical_sql_is_reported_as_n_plus_one_candidate
|
||||
*/
|
||||
#[Test]
|
||||
public function 쿼리_수집기는_구간_밖_쿼리를_섞지_않는다(): void
|
||||
{
|
||||
$collector = app(QueryCollector::class);
|
||||
|
||||
// 구간 밖 쿼리
|
||||
DB::table('users')->limit(1)->get();
|
||||
|
||||
$collected = $collector->collect(function () {
|
||||
for ($i = 0; $i < 6; $i++) {
|
||||
DB::table('users')->where('id', $i)->limit(1)->get();
|
||||
}
|
||||
});
|
||||
|
||||
// 구간 밖 쿼리를 제외한 6건만 모인다
|
||||
$this->assertCount(6, $collected['queries']);
|
||||
|
||||
$summary = $collector->summarize($collected['queries']);
|
||||
$this->assertSame(6, $summary['count']);
|
||||
// 같은 SQL 6회(임계 5회 이상) → N+1 후보로 보고
|
||||
$this->assertNotEmpty($summary['n_plus_one']);
|
||||
$this->assertSame(6, $summary['n_plus_one'][0]['count']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 반복이 임계 미만이면 N+1 후보로 보고하지 않습니다.
|
||||
*/
|
||||
#[Test]
|
||||
public function 임계_미만_반복은_후보로_보고하지_않는다(): void
|
||||
{
|
||||
$collector = app(QueryCollector::class);
|
||||
|
||||
$collected = $collector->collect(function () {
|
||||
for ($i = 0; $i < 3; $i++) {
|
||||
DB::table('users')->where('id', $i)->limit(1)->get();
|
||||
}
|
||||
});
|
||||
|
||||
$this->assertSame([], $collector->summarize($collected['queries'])['n_plus_one']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 쓰기 축 계측 대상 스파이 — prepare/callback/cleanup 호출 순서와 인자 전달을 관찰한다.
|
||||
*/
|
||||
class BenchmarkWriteSpy
|
||||
{
|
||||
public static int $prepareCalls = 0;
|
||||
|
||||
public static int $createCalls = 0;
|
||||
|
||||
public static int $cleanupCalls = 0;
|
||||
|
||||
/**
|
||||
* @var array<int, mixed>
|
||||
*/
|
||||
public static array $receivedContexts = [];
|
||||
|
||||
public static bool $cleanupThrows = false;
|
||||
|
||||
public static int $prepareQueries = 0;
|
||||
|
||||
public static int $createQueries = 0;
|
||||
|
||||
/**
|
||||
* 관찰 상태를 초기화합니다.
|
||||
*/
|
||||
public static function reset(): void
|
||||
{
|
||||
self::$prepareCalls = 0;
|
||||
self::$createCalls = 0;
|
||||
self::$cleanupCalls = 0;
|
||||
self::$receivedContexts = [];
|
||||
self::$cleanupThrows = false;
|
||||
self::$prepareQueries = 0;
|
||||
self::$createQueries = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 선행 준비 (계측 구간 밖).
|
||||
*
|
||||
* @param int $run 회차 번호
|
||||
* @return int 회차 번호를 그대로 컨텍스트로 넘긴다
|
||||
*/
|
||||
public function prepare(int $run): int
|
||||
{
|
||||
self::$prepareCalls++;
|
||||
$this->runQueries(self::$prepareQueries);
|
||||
|
||||
return $run;
|
||||
}
|
||||
|
||||
/**
|
||||
* 계측 대상.
|
||||
*
|
||||
* @param mixed $context prepare 반환값
|
||||
*/
|
||||
public function create(mixed $context = null): void
|
||||
{
|
||||
self::$createCalls++;
|
||||
self::$receivedContexts[] = $context;
|
||||
$this->runQueries(self::$createQueries);
|
||||
}
|
||||
|
||||
/**
|
||||
* 관찰용 쿼리를 지정 횟수만큼 실행합니다.
|
||||
*
|
||||
* @param int $count 실행할 쿼리 수
|
||||
*/
|
||||
private function runQueries(int $count): void
|
||||
{
|
||||
for ($i = 0; $i < $count; $i++) {
|
||||
DB::table('users')->where('id', -($i + 1))->limit(1)->get();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 잔여물 정리.
|
||||
*/
|
||||
public function cleanup(): void
|
||||
{
|
||||
self::$cleanupCalls++;
|
||||
|
||||
if (self::$cleanupThrows) {
|
||||
throw new \RuntimeException('정리 실패 재현');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Benchmark;
|
||||
|
||||
use App\Benchmark\DTO\BenchmarkProfile;
|
||||
use App\Enums\BenchmarkAxis;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 계측 프로파일 VO 및 축 Enum 계약 단위 테스트.
|
||||
*
|
||||
* 축이 늘어나도 VO 를 고치지 않는다는 설계(축 고유 옵션은 `options` 에 남김)와, 변경 판정이
|
||||
* 어디서 결정되는지(축 기본값 → HTTP 메서드 → 선언 순)를 고정한다.
|
||||
*/
|
||||
class BenchmarkProfileTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* 프로파일을 만듭니다.
|
||||
*
|
||||
* @param BenchmarkAxis $axis 계측 축
|
||||
* @param array<string, mixed> $options 축 고유 옵션
|
||||
* @param string $sourceIdentifier 출처 식별자
|
||||
* @return BenchmarkProfile 프로파일
|
||||
*/
|
||||
private function profile(BenchmarkAxis $axis, array $options = [], string $sourceIdentifier = 'core'): BenchmarkProfile
|
||||
{
|
||||
return new BenchmarkProfile(
|
||||
key: 'sample',
|
||||
axis: $axis,
|
||||
sourceKind: $sourceIdentifier === 'core' ? 'core' : 'module',
|
||||
sourceIdentifier: $sourceIdentifier,
|
||||
options: $options,
|
||||
label: '샘플',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 정규화 키는 출처와 키를 합쳐 전역 고유해집니다.
|
||||
*/
|
||||
#[Test]
|
||||
public function 정규화_키는_출처를_포함한다(): void
|
||||
{
|
||||
$this->assertSame('core/sample', $this->profile(BenchmarkAxis::ListQuery)->qualifiedKey());
|
||||
$this->assertSame(
|
||||
'vendor-mod/sample',
|
||||
$this->profile(BenchmarkAxis::ListQuery, [], 'vendor-mod')->qualifiedKey()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 축 고유 옵션은 기본값과 함께 읽힙니다.
|
||||
*/
|
||||
#[Test]
|
||||
public function 옵션은_기본값과_함께_읽힌다(): void
|
||||
{
|
||||
$profile = $this->profile(BenchmarkAxis::ListQuery, ['table' => 'users']);
|
||||
|
||||
$this->assertSame('users', $profile->option('table'));
|
||||
$this->assertSame(['id'], $profile->option('columns', ['id']));
|
||||
$this->assertNull($profile->option('absent'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록/화면 축은 기본적으로 데이터를 변경하지 않고, 쓰기/배치 축은 변경합니다.
|
||||
*/
|
||||
#[Test]
|
||||
public function 축_기본_변경_판정(): void
|
||||
{
|
||||
$this->assertFalse($this->profile(BenchmarkAxis::ListQuery)->mutates());
|
||||
$this->assertFalse($this->profile(BenchmarkAxis::Screen)->mutates());
|
||||
$this->assertTrue($this->profile(BenchmarkAxis::Write)->mutates());
|
||||
$this->assertTrue($this->profile(BenchmarkAxis::Batch)->mutates());
|
||||
}
|
||||
|
||||
/**
|
||||
* 화면 축의 변경 판정은 선언된 HTTP 메서드를 따릅니다.
|
||||
*
|
||||
* @effects screen_mutation_verdict_follows_http_method
|
||||
*/
|
||||
#[Test]
|
||||
public function 화면_축은_http_메서드로_변경을_판정한다(): void
|
||||
{
|
||||
$this->assertFalse($this->profile(BenchmarkAxis::Screen, ['method' => 'GET'])->mutates());
|
||||
// 대소문자와 무관하게 판정한다
|
||||
$this->assertFalse($this->profile(BenchmarkAxis::Screen, ['method' => 'get'])->mutates());
|
||||
$this->assertTrue($this->profile(BenchmarkAxis::Screen, ['method' => 'POST'])->mutates());
|
||||
$this->assertTrue($this->profile(BenchmarkAxis::Screen, ['method' => 'DELETE'])->mutates());
|
||||
}
|
||||
|
||||
/**
|
||||
* 명시 선언이 축 기본값과 메서드 판정을 모두 덮어씁니다.
|
||||
*
|
||||
* 읽기 전용 배치(리포트 산출 등)를 `--allow-write` 없이 재려면 이 경로가 필요합니다.
|
||||
*
|
||||
* @effects explicit_mutating_declaration_overrides_axis_default
|
||||
*/
|
||||
#[Test]
|
||||
public function 명시_mutating_선언이_기본값을_덮는다(): void
|
||||
{
|
||||
$this->assertFalse($this->profile(BenchmarkAxis::Batch, ['mutating' => false])->mutates());
|
||||
$this->assertTrue($this->profile(BenchmarkAxis::ListQuery, ['mutating' => true])->mutates());
|
||||
$this->assertFalse(
|
||||
$this->profile(BenchmarkAxis::Screen, ['method' => 'POST', 'mutating' => false])->mutates()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 직렬화 결과가 리포트/JSON 이 기대하는 키를 담습니다.
|
||||
*/
|
||||
#[Test]
|
||||
public function 직렬화가_약속된_키를_담는다(): void
|
||||
{
|
||||
$payload = $this->profile(BenchmarkAxis::ListQuery, ['table' => 'users'])->toArray();
|
||||
|
||||
foreach (['key', 'qualified_key', 'axis', 'source', 'label', 'options'] as $key) {
|
||||
$this->assertArrayHasKey($key, $payload);
|
||||
}
|
||||
|
||||
$this->assertSame('list', $payload['axis']);
|
||||
$this->assertSame(['kind' => 'core', 'identifier' => 'core'], $payload['source']);
|
||||
$this->assertSame(['table' => 'users'], $payload['options']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 축마다 필수 옵션이 대안 그룹으로 선언됩니다.
|
||||
*
|
||||
* 화면 축이 라우트명 또는 URI 중 하나만 있으면 되는 성질이 이 구조에 담깁니다.
|
||||
*
|
||||
* @effects screen_axis_accepts_route_or_uri_alternative
|
||||
*/
|
||||
#[Test]
|
||||
public function 축별_필수_옵션은_대안_그룹으로_선언된다(): void
|
||||
{
|
||||
$this->assertSame([['table']], BenchmarkAxis::ListQuery->requiredOptions());
|
||||
$this->assertSame([['route', 'uri']], BenchmarkAxis::Screen->requiredOptions());
|
||||
$this->assertSame([['callback']], BenchmarkAxis::Write->requiredOptions());
|
||||
$this->assertSame([['command']], BenchmarkAxis::Batch->requiredOptions());
|
||||
}
|
||||
|
||||
/**
|
||||
* 축 값 목록과 라벨이 정의됩니다.
|
||||
*/
|
||||
#[Test]
|
||||
public function 축_값과_라벨이_정의된다(): void
|
||||
{
|
||||
$this->assertSame(['list', 'screen', 'write', 'batch'], BenchmarkAxis::values());
|
||||
|
||||
foreach (BenchmarkAxis::cases() as $axis) {
|
||||
$this->assertNotSame('', $axis->label());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
# audit:allow test-scenario-coverage reason: cross product 면제 전용. 10축 전개 61,200 조합은 docblock @scenario 1:1 매핑이 비현실적이라 면제하고, 회귀 가드는 test_files 4종(커맨드 표면 + 축 실행기 단위 + 프로파일 VO/Enum 계약 + 확장 선언 통합)으로 커버한다. effects 54건은 전수 @effects 마킹돼 있어 이 면제 줄을 지워도 effects 검사는 통과한다 — 면제가 숨기는 항목 없음.
|
||||
|
||||
feature: benchmark_infra
|
||||
|
||||
description: |
|
||||
성능 계측 인프라를 4축(목록 조회 / 화면 응답 / 쓰기 작업 / 배치 작업)으로 확장하고, 계측
|
||||
대상 선언을 커맨드 밖으로 빼낸다. 계측 대상을 커맨드에 하드코딩하면 확장이 설치·제거되는
|
||||
설치본마다 "실제로 존재하는 대상"과 어긋나므로, 소유자가 선언하고 코어가 수집한다.
|
||||
|
||||
핵심 설계:
|
||||
- 선언 지점 두 곳, 스키마 하나: 코어 `config/benchmark.php`, 확장 `getBenchmarkProfiles()`.
|
||||
- 잘못된 선언은 조용히 버리지 않는다 — 사유를 경고로 남기고 그 선언만 제외한다. 버려진
|
||||
선언은 곧 계측 사각이 된다.
|
||||
- 짧은 키가 여러 확장에서 겹치면 후보를 제시하고 거부한다. 임의로 하나를 고르면 어느
|
||||
확장의 대상을 잰 것인지 알 수 없다.
|
||||
- 화면 축은 라우트를 HTTP 커널로 내부 요청 처리한다. 라우트만 dispatch 하면 전역
|
||||
미들웨어(인증·권한·로케일)를 건너뛰어 화면과 다른 것을 잰다.
|
||||
- 화면 축 인증은 프로파일이 선언한 권한만 가진 임시 계정이 기본이며 `--as` 로 기존 계정을
|
||||
지목할 수 있다. 전권 계정으로 재면 권한 검사 비용과 분기가 실제와 달라진다.
|
||||
- 화면/쓰기 축은 계측 계정 생성부터 처리까지 롤백되는 트랜잭션 안에서 실행한다. 트랜잭션이
|
||||
열려 있으면 읽기 쿼리도 write PDO 로 가므로 읽기/쓰기 분리 환경에서도 인증이 성립한다.
|
||||
- 쓰기 축은 `prepare`(계측 제외) / `callback`(계측) / `cleanup` 세 단계다. 선행 상태 준비
|
||||
비용이 측정값에 섞이면 재려던 것을 재지 못한다.
|
||||
- 콜백은 `'Fqcn'` 또는 `['Fqcn','method']` 만 허용한다 — 코어 선언이 config:cache 대상이라
|
||||
클로저를 담을 수 없으므로 확장 선언도 형식을 통일한다.
|
||||
- 배치 축은 트랜잭션으로 감싸지 않는다. 배치는 내부에서 커밋/DDL 을 실행할 수 있고, 대량
|
||||
처리를 긴 트랜잭션에 담으면 락 보유가 계측보다 위험하다.
|
||||
- 데이터를 변경하는 축은 `--allow-write` 없이 거부한다. 화면 축의 변경 판정은 선언된 HTTP
|
||||
메서드를 따르며 `mutating` 선언이 그것을 덮어쓴다.
|
||||
- 측정하지 못한 프로파일은 목록에서 빠지지 않고 사유와 함께 남으며, 전부 건너뛴 실행은
|
||||
실패로 끝난다. 성공으로 보고하면 "측정했다"로 읽힌다.
|
||||
- 리포트에는 환경 정보(DB/PHP 버전·OPcache·config:cache·실행 머신)를 반드시 함께 적는다.
|
||||
환경이 빠진 수치는 다른 리포트와 비교할 수 없다. 문서로 옮길 수치는 이 경로로만 산출한다.
|
||||
|
||||
axes:
|
||||
source: [core_config, module_declaration, plugin_declaration]
|
||||
axis_type: [list, screen, write, batch]
|
||||
selection: [profile_key, qualified_key, axis_filter, all, none]
|
||||
declaration_validity: [valid, missing_type, unknown_type, missing_required_option, closure_callback]
|
||||
key_collision: [unique, ambiguous_short_key]
|
||||
target_presence: [present, table_missing, route_missing, command_missing]
|
||||
write_permission: [allow_write_given, allow_write_omitted]
|
||||
mutation_declaration: [axis_default, declared_mutating, declared_readonly]
|
||||
environment: [local, production]
|
||||
output: [table, json, report_default_path, report_given_path]
|
||||
|
||||
exclusions:
|
||||
- { axis_type: list, write_permission: allow_write_omitted, reason: "목록 축은 읽기 전용이라 --allow-write 판정 대상이 아니다 (시딩은 environment 축이 담당)" }
|
||||
- { axis_type: batch, target_presence: table_missing, reason: "배치 축은 테이블을 직접 지목하지 않는다 — 부재 판정은 command_missing" }
|
||||
- { axis_type: list, target_presence: route_missing, reason: "목록 축은 라우트를 쓰지 않는다" }
|
||||
- { declaration_validity: closure_callback, axis_type: list, reason: "콜백 선언은 write 축만 갖는다" }
|
||||
- { environment: production, axis_type: screen, reason: "운영 거부 가드는 시딩/비움(목록 축)에만 걸린다 — 화면 축은 롤백 트랜잭션으로 운영에서도 안전" }
|
||||
- { key_collision: ambiguous_short_key, source: core_config, reason: "충돌은 서로 다른 출처가 같은 키를 선언할 때만 발생 — 한 출처 안에서는 배열 키가 이미 유일" }
|
||||
|
||||
effects:
|
||||
# ── 선언 수집 (P0) ──
|
||||
- core_config_profiles_are_collected
|
||||
- module_declared_profiles_are_collected
|
||||
- plugin_declared_profiles_are_collected
|
||||
- profile_source_kind_and_identifier_are_recorded
|
||||
- extension_declaration_failure_is_isolated_to_that_extension
|
||||
# ── 선언 검증 (P0) ──
|
||||
- missing_type_declaration_is_rejected_with_reason
|
||||
- unknown_axis_type_is_rejected_with_allowed_values
|
||||
- missing_required_option_is_rejected_naming_the_option
|
||||
- screen_axis_accepts_route_or_uri_alternative
|
||||
- closure_callback_is_rejected_with_config_cache_reason
|
||||
- rejected_declarations_appear_in_warnings_not_silently_dropped
|
||||
# ── 대상 지목 (P0) ──
|
||||
- qualified_key_resolves_exactly
|
||||
- unique_short_key_resolves
|
||||
- ambiguous_short_key_lists_candidates_and_refuses
|
||||
- unknown_key_fails_with_list_profiles_hint
|
||||
- axis_filter_selects_only_that_axis
|
||||
- no_selection_fails_asking_for_profile_or_axis_or_all
|
||||
# ── 목록 축 (P0) ──
|
||||
- list_axis_reports_all_list_and_id_only_columns
|
||||
- list_axis_ratio_is_derived_from_id_only_baseline
|
||||
- wildcard_columns_expand_to_actual_schema_columns
|
||||
- nonexistent_declared_columns_are_filtered_out
|
||||
- declared_filters_are_applied_to_measured_query
|
||||
- operator_filters_are_applied_to_measured_query
|
||||
- equality_filter_is_not_misread_as_operator_form
|
||||
- unknown_filter_operator_is_refused_before_measuring
|
||||
- list_profile_filters_match_the_screen_default_predicate
|
||||
- soft_delete_declaration_adds_deleted_at_predicate
|
||||
- explain_option_collects_plans_for_both_column_widths
|
||||
# ── 화면 축 (P0) ──
|
||||
- screen_axis_dispatches_through_http_kernel_with_middleware
|
||||
- screen_axis_reports_status_response_time_and_query_count
|
||||
- repeated_identical_sql_is_reported_as_n_plus_one_candidate
|
||||
- absence_of_n_plus_one_is_stated_explicitly
|
||||
- ephemeral_admin_receives_only_declared_permissions
|
||||
- as_option_measures_with_the_named_existing_account
|
||||
- container_request_and_auth_guards_are_restored_after_each_dispatch
|
||||
- route_name_declaration_resolves_uri_without_prefix_assembly
|
||||
- missing_route_name_fails_instead_of_measuring_a_404
|
||||
# ── 쓰기 축 (P0) ──
|
||||
- prepare_runs_outside_the_measured_window
|
||||
- prepare_runs_once_per_iteration
|
||||
- callback_receives_prepare_result
|
||||
- write_axis_reports_first_run_and_median_separately
|
||||
- cleanup_failure_does_not_swallow_the_measurement
|
||||
# ── 배치 축 (P1) ──
|
||||
- batch_axis_reports_elapsed_time_and_peak_memory
|
||||
- peak_memory_before_and_after_are_both_reported
|
||||
- batch_axis_reports_nonzero_exit_code_as_partial_measurement
|
||||
- unregistered_command_is_skipped_with_reason
|
||||
# ── 안전장치 (P0) ──
|
||||
- mutating_axes_refuse_without_allow_write
|
||||
- screen_mutation_verdict_follows_http_method
|
||||
- explicit_mutating_declaration_overrides_axis_default
|
||||
- seeding_and_truncation_are_refused_in_production
|
||||
- measurement_leaves_no_residual_rows_after_rollback
|
||||
- database_override_option_repoints_the_connection
|
||||
# ── 출력 (P0) ──
|
||||
- skipped_profiles_remain_in_output_with_reason
|
||||
- all_skipped_run_exits_nonzero
|
||||
- json_output_carries_environment_options_warnings_results
|
||||
- report_includes_environment_and_run_conditions
|
||||
- report_defaults_to_untracked_storage_path
|
||||
- report_writes_to_given_path
|
||||
|
||||
test_files:
|
||||
# 코어 — 선언 수집 / 검증 / 대상 지목 / 축 분기 / 가드 / 출력 스키마
|
||||
- tests/Feature/Console/BenchCommandTest.php
|
||||
# 코어 — 축 실행기 단위 (화면 내부 요청·쿼리 수집·쓰기 prepare 분리·배치 메모리)
|
||||
- tests/Unit/Benchmark/BenchmarkAxisRunnerTest.php
|
||||
# 코어 — 프로파일 VO / 축 Enum 계약
|
||||
- tests/Unit/Benchmark/BenchmarkProfileTest.php
|
||||
# 이커머스 — 확장 선언 + 주문 생성 쓰기 축 대상
|
||||
- modules/_bundled/sirsoft-ecommerce/tests/Unit/Benchmark/OrderCreationBenchmarkTest.php
|
||||
Reference in new issue
Block a user