feat(api-docs): 요청/응답 예시 블록 + 8종 결함 근본 수정 + audit error 승격

API 레퍼런스에 요청 예시(raw HTTP)·응답 예시(envelope 전문)를 표준 포맷에
편입하고, 전 대상(코어+전 모듈+전 플러그인)에 방출했다. 예시 결함 8종
(multipart·Host 마스킹·write 실측·path 치환·현실적 바디·query 반영·중복
제거·민감값 마스킹)을 스캐폴더/프로브 공용 수정으로 근본 해소했다.

추가로 검증에서 드러난 결함을 마감했다:
- 응답 예시 body 의 절대 URL(페이지네이터·콜백) 호스트를 placeholder 로
 마스킹(maskResponseHost) — 요청 Host 헤더만 마스킹되던 누락 보완, 확장
 39건 정정
- api:docgen 커맨드 통합 테스트 신설(라우트 수집·확장 라우팅·rules 추출·
 멱등 재생성·check drift)
- module-routing.md URL 스킴 오류 정정(/api/admin → /api/modules)
- README·cheatsheet·api-documentation 에 API 문서 커맨드/레퍼런스 진입점 반영

전 대상 3칸 완료로 api-doc-coverage 룰을 warn→error 승격.
This commit is contained in:
HeuJung committed 2026-07-08 18:22:34 +09:00
1 parent 70452745c4
commit 56a78e1d55
114 files changed
+60782 -197

No files matched your search

@@ -0,0 +1,164 @@
<?php
namespace Tests\Feature\Console;
use App\Http\Controllers\Api\Auth\AuthController;
use App\Support\ApiDoc\ApiDocScaffolder;
use App\Support\ApiDoc\ApiRouteInventory;
use App\Support\ApiDoc\FormRequestIntrospector;
use Illuminate\Support\Facades\File;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* api:docgen 커맨드 통합 동작 Feature 테스트.
*
* 계획서(#447) 단계 5 가 명시한 커맨드 5대 동작을 검증한다:
* (a) 라우트 전수 수집, (b) 확장별 파일 라우팅, (c) FormRequest rules 추출,
* (d) idempotent 재생성(사람 서술 보존), (e) --check drift 검출.
*
* 라이브 실측(HTTP 프로브)에 의존하지 않는 결정론적 경로(--dry-run·정적 추출·
* 스캐폴더 병합)로 커맨드 표면을 검증한다. 실측 자체는 ApiDocPipelineTest·
* ApiDocSampleServiceTest 가 별도 커버한다.
*/
class ApiDocgenCommandTest extends TestCase
{
/**
* (a) 코어 스코프 실행 시 라우트를 전수 수집해 개수를 보고합니다.
*/
#[Test]
public function 코어_스코프는_라우트를_전수_수집한다(): void
{
// 인벤토리가 코어 라우트를 수집하는지 직접 확인 (커맨드가 이 결과를 소비).
$routes = app(ApiRouteInventory::class)->collect('core');
$this->assertNotEmpty($routes, '코어 API 라우트가 수집되어야 한다.');
// 대표 코어 라우트(사용자 목록)가 포함되는지 (전수 수집 실증).
$uris = array_column($routes, 'uri');
$this->assertContains('/api/admin/users', $uris);
// --dry-run 실행이 수집 개수를 보고하고 생성 없이 종료한다.
$this->artisan('api:docgen', ['--scope' => 'core', '--dry-run' => true])
->expectsOutputToContain('라우트 수집 (scope=core)')
->assertSuccessful();
}
/**
* (b) 확장 소유 라우트는 확장 디렉토리 파일로 라우팅됩니다.
*/
#[Test]
public function 확장_라우트는_확장_디렉토리_파일로_라우팅된다(): void
{
$inventory = app(ApiRouteInventory::class);
// 코어 라우트의 소유는 core, 출력 파일은 docs/backend/api 하위여야 한다.
$coreRoutes = $inventory->collect('core');
foreach ($coreRoutes as $route) {
$this->assertSame('core', $route['owner']['type']);
}
// 번들 확장 라우트가 있으면 그 소유 type 이 module/plugin 이고 id 가 있어야 한다
// (targetFile 이 이 owner 로 modules|plugins/_bundled/{id}/docs/api 경로를 만든다).
$all = $inventory->collect('all');
$extRoutes = array_filter($all, fn ($r) => $r['owner']['type'] !== 'core');
if ($extRoutes === []) {
// 이 환경에 활성 확장이 없으면(라우트 0) 스킵 — core 라우팅 검증만으로 충분.
$this->markTestSkipped('활성 확장 라우트 없음 — 확장 라우팅 검증 스킵.');
}
foreach ($extRoutes as $route) {
$this->assertContains($route['owner']['type'], ['module', 'plugin']);
$this->assertNotEmpty($route['owner']['id']);
}
}
/**
* (c) 컨트롤러 메서드의 FormRequest rules() 를 정적 리플렉션으로 추출합니다.
*/
#[Test]
public function form_request_rules를_정적_추출한다(): void
{
$introspector = app(FormRequestIntrospector::class);
// 로그인 컨트롤러는 email/password rules 를 가진 FormRequest 를 받는다.
$result = $introspector->introspect(
AuthController::class,
'login'
);
$names = array_column($result['params'], 'name');
$this->assertContains('email', $names, 'FormRequest rules 의 email 파라미터가 추출되어야 한다.');
$this->assertContains('password', $names);
}
/**
* (d) 재생성해도 사람이 채운 서술은 보존되고 추출 블록만 갱신됩니다(멱등).
*/
#[Test]
public function 재생성은_사람_서술을_보존하는_멱등_동작이다(): void
{
$scaffolder = new ApiDocScaffolder;
$route = [
'method' => 'GET', 'uri' => '/api/me', 'name' => 'api.me.show',
'controller' => 'C', 'controller_method' => 'show', 'permission' => null,
'middleware' => ['auth:sanctum'], 'path_params' => [],
];
$request = ['request_class' => null, 'params' => [], 'hook_filters' => []];
$schema = ['envelope' => ['success', 'data'], 'shape' => 'object', 'fields' => [['name' => 'id', 'type' => 'integer', 'sample' => '1']], 'pagination' => false];
$probeMeta = ['status' => 200, 'skipped_reason' => null, 'base_url' => 'https://api.example.com', 'resolved_uri' => '/api/me', 'body' => ['success' => true, 'data' => ['id' => 1], 'message' => null, 'error' => null]];
$section = $scaffolder->endpointSection($route, $request, $schema, $probeMeta);
$header = "# Me\n";
$first = $scaffolder->mergeDocument(null, $header, [$section], ['api.me.show']);
// @generated 블록 밖 `**설명**` 슬롯의 TODO 스텁을 사람 서술로 채운다
// (extractHumanProse 는 기본 TODO 스텁이 남아 있으면 보존 대상 없음으로 판정).
$human = str_replace(
'**설명** <!-- TODO: 이 엔드포인트의 용도·주의사항·예시 시나리오를 작성하세요 -->',
'**설명** 이 엔드포인트는 현재 로그인 사용자를 반환합니다. (사람 서술)',
$first
);
// 재생성 시 사람 서술은 보존되고 생성 블록만 갱신된다.
$second = $scaffolder->mergeDocument($human, $header, [$section], ['api.me.show']);
$this->assertStringContainsString('이 엔드포인트는 현재 로그인 사용자를 반환합니다. (사람 서술)', $second);
$this->assertStringNotContainsString('TODO: 이 엔드포인트의 용도', $second);
// 다시 병합해도 사람 서술 중복 없이 멱등.
$third = $scaffolder->mergeDocument($second, $header, [$section], ['api.me.show']);
$this->assertSame(
substr_count($second, '(사람 서술)'),
substr_count($third, '(사람 서술)'),
'재병합 시 사람 서술이 중복되지 않아야 한다.'
);
}
/**
* (e) --check 는 대응 문서가 없으면 drift 로 실패 코드를 반환합니다.
*/
#[Test]
public function check는_문서_누락을_drift로_검출한다(): void
{
// 존재하지 않는 확장 스코프(문서 파일 부재 보장)로 --check 실행.
// 라우트가 0이면 커맨드는 성공으로 조기 종료하므로, 라우트가 있는 core 로 검증한다.
// core 문서는 이미 존재하므로(35파일), 임시로 한 파일을 백업/삭제해 누락을 유발한다.
$target = base_path('docs/backend/api/me.md');
$backup = null;
if (File::exists($target)) {
$backup = File::get($target);
File::delete($target);
}
try {
// me.md 가 없으면 --check 는 "문서 파일 없음" drift 로 FAILURE 를 반환한다.
$this->artisan('api:docgen', ['--scope' => 'core', '--check' => true])
->assertFailed();
} finally {
if ($backup !== null) {
File::put($target, $backup);
}
}
}
}
@@ -0,0 +1,110 @@
<?php
namespace Tests\Feature\Console;
use App\Models\Role;
use App\Models\User;
use App\Support\ApiDoc\ApiDocSampleService;
use App\Support\ApiDoc\ApiEndpointProbe;
use Illuminate\Foundation\Testing\RefreshDatabase;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
/**
* ApiEndpointProbe 쓰기 메서드 in-process 실측 Feature 테스트.
*
* 쓰기 메서드(POST/PUT/DELETE)를 DB 트랜잭션 안에서 in-process dispatch 후 롤백해
* 응답 shape 만 관측하고 부수효과는 영속시키지 않는지, GET 실측이 오염되지 않는지 검증한다.
*/
class ApiEndpointProbeWriteTest extends TestCase
{
use RefreshDatabase;
/**
* 실측 프로브를 샘플 사용자 인증 상태로 준비합니다.
*
* @return array{0: ApiEndpointProbe, 1: User} 프로브와 인증 사용자
*/
private function preparedProbe(): array
{
$map = (new ApiDocSampleService)->seed();
$userId = User::where($map['users']['key'], $map['users']['value'])->value('id');
$probe = new ApiEndpointProbe(config('app.url'));
$probe->authenticate($userId);
return [$probe, User::find($userId)];
}
#[Test]
public function 쓰기_메서드는_트랜잭션_롤백으로_레코드를_영속시키지_않는다(): void
{
[$probe] = $this->preparedProbe();
$before = Role::count();
$result = $probe->probe('POST', '/api/admin/roles', [
'identifier' => 'probe_write_'.substr(uniqid(), 0, 8),
'name' => '실측 예시값',
'is_active' => true,
]);
// 응답은 관측되지만(성공 2xx) 레코드는 롤백되어 남지 않는다.
$this->assertNotNull($result['status']);
$this->assertSame($before, Role::count(), '쓰기 실측 후 레코드가 롤백되지 않고 남았습니다');
$probe->cleanup();
}
#[Test]
public function 성공한_쓰기_실측은_envelope_body_를_반환한다(): void
{
[$probe] = $this->preparedProbe();
$result = $probe->probe('POST', '/api/admin/roles', [
'identifier' => 'probe_env_'.substr(uniqid(), 0, 8),
'name' => '실측 예시값',
'is_active' => true,
]);
if ($result['ok']) {
$this->assertIsArray($result['body']);
$this->assertArrayHasKey('success', $result['body']);
$this->assertArrayHasKey('data', $result['body']);
} else {
// 검증 규칙이 도메인 특이해 실패할 수 있으나, 그 경우에도 skipped_reason 이 명확해야 한다.
$this->assertNotNull($result['skipped_reason']);
}
$probe->cleanup();
}
#[Test]
public function 연속_쓰기_실측이_서로_인증_컨텍스트를_오염시키지_않는다(): void
{
[$probe] = $this->preparedProbe();
// 연속 쓰기 실측(각각 guard 조작 후 forgetGuards)이 서로 오염되지 않아야 한다.
$first = $probe->probe('POST', '/api/admin/roles', ['identifier' => 'probe_a_'.uniqid(), 'name' => 'a', 'is_active' => true]);
$second = $probe->probe('POST', '/api/admin/roles', ['identifier' => 'probe_b_'.uniqid(), 'name' => 'b', 'is_active' => true]);
// 두 번째 실측이 첫 번째의 인증 컨텍스트 오염으로 401 이 되지 않아야 한다.
$this->assertNotSame(401, $first['status']);
$this->assertNotSame(401, $second['status']);
$probe->cleanup();
}
#[Test]
public function unresolved_path_는_실측하지_않고_사유를_남긴다(): void
{
[$probe] = $this->preparedProbe();
$result = $probe->probe('PUT', '/api/admin/roles/{role}', ['name' => 'x']);
$this->assertFalse($result['ok']);
$this->assertSame('unresolved-path-param', $result['skipped_reason']);
$probe->cleanup();
}
}
@@ -309,4 +309,535 @@ class ApiDocPipelineTest extends TestCase
$this->assertStringContainsString('실제 사람이 작성한 설명입니다.', $regenerated);
$this->assertStringNotContainsString('TODO: 이 엔드포인트의 용도', $regenerated);
}
#[Test]
public function ge_t_인증_엔드포인트_요청_예시가_raw_htt_p_요청이다(): void
{
$scaffolder = new ApiDocScaffolder;
$route = [
'method' => 'GET', 'uri' => '/api/me', 'name' => 'api.me.show',
'controller' => 'C', 'controller_method' => 'show', 'permission' => null,
'middleware' => ['auth:sanctum'], 'path_params' => [],
];
$request = ['request_class' => null, 'params' => [], 'hook_filters' => []];
$schema = ['envelope' => ['data'], 'shape' => 'object', 'fields' => [['name' => 'id', 'type' => 'integer', 'sample' => '1']], 'pagination' => false];
$probeMeta = [
'status' => 200, 'skipped_reason' => null,
'base_url' => 'https://g7.example.com', 'resolved_uri' => '/api/me',
'body' => ['success' => true, 'data' => ['id' => 1], 'message' => null, 'error' => null],
];
$section = $scaffolder->endpointSection($route, $request, $schema, $probeMeta);
$this->assertStringContainsString('**요청 예시**', $section);
// curl 이 아니라 raw HTTP 요청 라인 + 헤더
$this->assertStringNotContainsString('curl', $section);
$this->assertStringContainsString('GET /api/me HTTP/1.1', $section);
// Host 는 실측 기준 URL(g7.example.com)이 아니라 공개 placeholder 로 마스킹된다.
$this->assertStringContainsString('Host: api.example.com', $section);
$this->assertStringNotContainsString('g7.example.com', $section);
$this->assertStringContainsString('Accept: application/json', $section);
$this->assertStringContainsString('Authorization: Bearer {YOUR_TOKEN}', $section);
// 실측 토큰 평문이 유출되지 않아야 한다 (placeholder 마스킹)
$this->assertStringNotContainsString('Bearer eyJ', $section);
}
#[Test]
public function 바디_메서드_요청_예시가_json_바디를_가진_raw_htt_p_요청이다(): void
{
$scaffolder = new ApiDocScaffolder;
$route = [
'method' => 'POST', 'uri' => '/api/admin/users', 'name' => 'api.admin.users.store',
'controller' => 'C', 'controller_method' => 'store', 'permission' => 'core.users.create',
'middleware' => ['auth:sanctum'], 'path_params' => [],
];
$request = ['request_class' => 'X', 'params' => [
['name' => 'name', 'type' => 'string', 'required' => true, 'allowed' => 'max 255'],
['name' => 'age', 'type' => 'integer', 'required' => true, 'allowed' => ''],
['name' => 'nickname', 'type' => 'string', 'required' => false, 'allowed' => ''],
], 'hook_filters' => []];
// 쓰기 메서드는 실측 제외 → body null
$probeMeta = [
'status' => null, 'skipped_reason' => 'write-method',
'base_url' => 'https://g7.example.com', 'resolved_uri' => '/api/admin/users', 'body' => null,
];
$section = $scaffolder->endpointSection($route, $request, null, $probeMeta);
// curl 이 아니라 raw HTTP 요청 라인 + Content-Type 헤더 + JSON 바디
$this->assertStringNotContainsString('curl', $section);
$this->assertStringContainsString('POST /api/admin/users HTTP/1.1', $section);
$this->assertStringContainsString('Host: api.example.com', $section);
$this->assertStringContainsString('Content-Type: application/json', $section);
// 전체 파라미터를 바디로 조립하고, 이름 기반 현실적 값을 채운다(placeholder "string" 남발 방지).
$this->assertStringContainsString('"name": "예시 이름"', $section);
$this->assertStringContainsString('"age": 1', $section);
$this->assertStringContainsString('"nickname"', $section);
// 응답 예시는 실측 제외 마커
$this->assertStringContainsString('실측 제외: write-method — 응답 예시는 사람이 작성', $section);
}
#[Test]
public function 실측_body_응답_예시는_envelope_통짜_json_이다(): void
{
$scaffolder = new ApiDocScaffolder;
$route = [
'method' => 'GET', 'uri' => '/api/me', 'name' => 'api.me.show',
'controller' => 'C', 'controller_method' => 'show', 'permission' => null,
'middleware' => ['auth:sanctum'], 'path_params' => [],
];
$request = ['request_class' => null, 'params' => [], 'hook_filters' => []];
$schema = ['envelope' => ['success', 'data'], 'shape' => 'object', 'fields' => [['name' => 'id', 'type' => 'integer', 'sample' => '1']], 'pagination' => false];
$body = ['success' => true, 'data' => ['id' => 1, 'name' => '홍길동'], 'message' => null, 'error' => null];
$probeMeta = ['status' => 200, 'skipped_reason' => null, 'base_url' => 'https://g7.example.com', 'resolved_uri' => '/api/me', 'body' => $body];
$section = $scaffolder->endpointSection($route, $request, $schema, $probeMeta);
$this->assertStringContainsString('**응답 예시**', $section);
$this->assertStringContainsString('HTTP/1.1 200', $section);
$this->assertStringContainsString('"success": true', $section);
$this->assertStringContainsString('"홍길동"', $section);
$this->assertStringContainsString('"message": null', $section);
}
#[Test]
public function 목록_응답_예시는_2항목으로_절단된다(): void
{
$scaffolder = new ApiDocScaffolder;
$rows = [];
for ($i = 1; $i <= 5; $i++) {
$rows[] = ['id' => $i, 'name' => "user{$i}"];
}
$body = [
'success' => true,
'data' => ['data' => $rows, 'pagination' => ['total' => 5, 'current_page' => 1]],
'message' => null, 'error' => null,
];
$route = [
'method' => 'GET', 'uri' => '/api/admin/users', 'name' => 'api.admin.users.index',
'controller' => 'C', 'controller_method' => 'index', 'permission' => null,
'middleware' => ['auth:sanctum'], 'path_params' => [],
];
$request = ['request_class' => null, 'params' => [], 'hook_filters' => []];
$schema = ['envelope' => ['success', 'data'], 'shape' => 'collection', 'fields' => [['name' => 'id', 'type' => 'integer', 'sample' => '1']], 'pagination' => true];
$probeMeta = ['status' => 200, 'skipped_reason' => null, 'base_url' => 'https://g7.example.com', 'resolved_uri' => '/api/admin/users', 'body' => $body];
$section = $scaffolder->endpointSection($route, $request, $schema, $probeMeta);
// 대표 2항목 + 절단 주석 항목. user3~5 는 나타나지 않아야 한다.
$this->assertStringContainsString('"user1"', $section);
$this->assertStringContainsString('"user2"', $section);
$this->assertStringNotContainsString('"user3"', $section);
$this->assertStringContainsString('총 5건 중 2건 표시', $section);
}
#[Test]
public function 요청_응답_예시_블록은_generated_블록_내부에_있어_재생성_대상이다(): void
{
$scaffolder = new ApiDocScaffolder;
$route = [
'method' => 'GET', 'uri' => '/api/me', 'name' => 'api.me.show',
'controller' => 'C', 'controller_method' => 'show', 'permission' => null,
'middleware' => ['auth:sanctum'], 'path_params' => [],
];
$request = ['request_class' => null, 'params' => [], 'hook_filters' => []];
$schema = ['envelope' => ['success', 'data'], 'shape' => 'object', 'fields' => [['name' => 'id', 'type' => 'integer', 'sample' => '1']], 'pagination' => false];
$body = ['success' => true, 'data' => ['id' => 1], 'message' => null, 'error' => null];
$probeMeta = ['status' => 200, 'skipped_reason' => null, 'base_url' => 'https://g7.example.com', 'resolved_uri' => '/api/me', 'body' => $body];
$section = $scaffolder->endpointSection($route, $request, $schema, $probeMeta);
$genStart = strpos($section, '@generated:start');
$genEnd = strpos($section, '@generated:end');
$reqExample = strpos($section, '**요청 예시**');
$respExample = strpos($section, '**응답 예시**');
// 요청/응답 예시 블록은 모두 @generated 경계 내부(재생성 대상)
$this->assertGreaterThan($genStart, $reqExample);
$this->assertLessThan($genEnd, $reqExample);
$this->assertGreaterThan($genStart, $respExample);
$this->assertLessThan($genEnd, $respExample);
}
#[Test]
public function 요청_예시가_generated_블록_안이라_재생성해도_멱등이다(): void
{
$scaffolder = new ApiDocScaffolder;
$route = [
'method' => 'GET', 'uri' => '/api/me', 'name' => 'api.me.show',
'controller' => 'C', 'controller_method' => 'show', 'permission' => null,
'middleware' => ['auth:sanctum'], 'path_params' => [],
];
$request = ['request_class' => null, 'params' => [], 'hook_filters' => []];
$schema = ['envelope' => ['success', 'data'], 'shape' => 'object', 'fields' => [['name' => 'id', 'type' => 'integer', 'sample' => '1']], 'pagination' => false];
$body = ['success' => true, 'data' => ['id' => 1], 'message' => null, 'error' => null];
$probeMeta = ['status' => 200, 'skipped_reason' => null, 'base_url' => 'https://g7.example.com', 'resolved_uri' => '/api/me', 'body' => $body];
$section = $scaffolder->endpointSection($route, $request, $schema, $probeMeta);
$header = "# Me\n";
// 사람 서술을 채운 뒤 재생성해도 예시(생성 블록)는 갱신되고 서술은 보존된다.
$first = $scaffolder->mergeDocument(null, $header, [$section], ['api.me.show']);
$withProse = str_replace(
'**설명** <!-- TODO: 이 엔드포인트의 용도·주의사항·예시 시나리오를 작성하세요 -->',
'**설명** 내 프로필을 조회한다.',
$first
);
$regenerated = $scaffolder->mergeDocument($withProse, $header, [$section], ['api.me.show']);
$this->assertStringContainsString('내 프로필을 조회한다.', $regenerated);
$this->assertStringNotContainsString('curl', $regenerated);
$this->assertStringContainsString('GET /api/me HTTP/1.1', $regenerated);
}
#[Test]
public function insert_example_blocks_는_표와_서술을_건드리지_않고_예시만_삽입한다(): void
{
$scaffolder = new ApiDocScaffolder;
// 예시 블록이 아직 없는 기존 문서 (표에는 사람이 채운 도메인 서술 셀 포함)
$existing = <<<'MD'
# Me API 레퍼런스
### GET /api/me
<!-- @generated:start:api.me.show -->
- **라우트명**: `api.me.show`
- **인증/권한**: `auth:sanctum`
**요청 파라미터**
_요청 파라미터 없음._
**응답 필드** (`data` 내부)
| 필드 | 타입 | 실측 예시값 | 용도/설명 |
| --- | --- | --- | --- |
| uuid | string | `a231` | 외부 노출용 UUID (사람이 채운 도메인 서술) |
**에러 응답**
| 상태코드 | 의미 | 발생 조건 |
| --- | --- | --- |
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
<!-- @generated:end -->
**설명** 내 프로필을 조회한다. (사람이 채운 엔드포인트 서술)
MD;
$blocks = [
'api.me.show' => [
'request' => "```http\nGET /api/me HTTP/1.1\nHost: g7.example.com\nAccept: application/json\n```",
'response' => "```http\nHTTP/1.1 200\n```\n\n```json\n{\n \"success\": true\n}\n```",
],
];
[$updated, $inserted] = $scaffolder->insertExampleBlocks($existing, $blocks);
// 예시 2블록 삽입됨
$this->assertSame(2, $inserted);
$this->assertStringContainsString('**요청 예시**', $updated);
$this->assertStringContainsString('**응답 예시**', $updated);
$this->assertStringContainsString('GET /api/me HTTP/1.1', $updated);
// 표의 사람 서술 셀은 불변
$this->assertStringContainsString('외부 노출용 UUID (사람이 채운 도메인 서술)', $updated);
// 엔드포인트 서술도 불변
$this->assertStringContainsString('내 프로필을 조회한다. (사람이 채운 엔드포인트 서술)', $updated);
// 삽입 위치: 요청 예시는 응답 필드 앞, 응답 예시는 에러 응답 앞
$this->assertLessThan(strpos($updated, '**응답 필드**'), strpos($updated, '**요청 예시**'));
$this->assertLessThan(strpos($updated, '**에러 응답**'), strpos($updated, '**응답 예시**'));
// 예시는 @generated 블록 내부
$this->assertLessThan(strpos($updated, '@generated:end'), strpos($updated, '**요청 예시**'));
}
#[Test]
public function insert_example_blocks_는_재삽입_시_멱등이다(): void
{
$scaffolder = new ApiDocScaffolder;
$existing = <<<'MD'
### GET /api/me
<!-- @generated:start:api.me.show -->
- **인증/권한**: `auth:sanctum`
**요청 파라미터**
_요청 파라미터 없음._
**응답 필드** (`data` 내부)
_단건._
**에러 응답**
| 401 |
<!-- @generated:end -->
MD;
$blocks = [
'api.me.show' => [
'request' => "```http\nGET /api/me HTTP/1.1\nHost: x\n```",
'response' => "```json\n{}\n```",
],
];
[$once] = $scaffolder->insertExampleBlocks($existing, $blocks);
[$twice] = $scaffolder->insertExampleBlocks($once, $blocks);
// 2회 삽입해도 결과 동일 (요청/응답 예시가 중복 삽입되지 않음)
$this->assertSame($once, $twice);
$this->assertSame(1, substr_count($twice, '**요청 예시**'));
$this->assertSame(1, substr_count($twice, '**응답 예시**'));
}
#[Test]
public function 서술에_수기_응답예시가_있으면_블록에_응답예시를_넣지_않는다(): void
{
$scaffolder = new ApiDocScaffolder;
// @generated 밖 서술에 사람이 미리 작성한 응답 예시가 있는 문서
// (파일 업로드·미설치 정적 예시처럼 실측 불가라 수기로 채운 경우)
$existing = <<<'MD'
### GET /api/me/card
<!-- @generated:start:api.me.card -->
- **인증/권한**: `auth:sanctum`
**요청 파라미터**
_요청 파라미터 없음._
**응답 필드** (`data` 내부)
_단건._
**에러 응답**
| 401 |
<!-- @generated:end -->
**설명** 카드 조회.
**응답 예시** (정적 — 실측 불가라 사람이 작성)
```json
{ "success": true, "data": { "id": 1 } }
```
MD;
$blocks = [
'api.me.card' => [
'request' => "```http\nGET /api/me/card HTTP/1.1\nHost: api.example.com\n```",
'response' => '<!-- 실측 제외: http-500 — 응답 예시는 사람이 작성하세요. -->',
],
];
[$updated] = $scaffolder->insertExampleBlocks($existing, $blocks);
// 요청 예시는 블록 안에 삽입된다
$this->assertStringContainsString('**요청 예시**', $updated);
$this->assertStringContainsString('GET /api/me/card HTTP/1.1', $updated);
// 응답 예시 헤딩은 정확히 1개 (수기 예시만, 블록 안 마커 미삽입 → 중복 헤딩 없음)
$this->assertSame(1, substr_count($updated, '**응답 예시**'));
// 수기 응답 예시는 보존
$this->assertStringContainsString('정적 — 실측 불가라 사람이 작성', $updated);
// 블록 안에 실측 제외 마커가 들어가지 않아야 한다
$this->assertStringNotContainsString('실측 제외: http-500', $updated);
}
#[Test]
public function 과거_삽입된_블록내_응답예시는_서술에_수기예시가_생기면_제거된다(): void
{
$scaffolder = new ApiDocScaffolder;
// 과거 run 이 블록 안에 응답 예시 마커를 넣었고, 이후 서술에 수기 응답 예시가 추가된 상태
$existing = <<<'MD'
### GET /api/me/card
<!-- @generated:start:api.me.card -->
- **인증/권한**: `auth:sanctum`
**요청 파라미터**
_요청 파라미터 없음._
**응답 필드** (`data` 내부)
_단건._
**응답 예시**
<!-- 실측 제외: http-500 — 응답 예시는 사람이 작성하세요. -->
**에러 응답**
| 401 |
<!-- @generated:end -->
**응답 예시** (정적)
```json
{ "success": true }
```
MD;
$blocks = [
'api.me.card' => [
'request' => "```http\nGET /api/me/card HTTP/1.1\nHost: api.example.com\n```",
'response' => '<!-- 실측 제외: http-500 — 응답 예시는 사람이 작성하세요. -->',
],
];
[$updated] = $scaffolder->insertExampleBlocks($existing, $blocks);
// 블록 안 응답 예시가 제거되어 응답 예시 헤딩은 1개(수기 예시)만 남는다
$this->assertSame(1, substr_count($updated, '**응답 예시**'));
$this->assertStringNotContainsString('실측 제외: http-500', $updated);
// 수기 예시는 보존
$this->assertStringContainsString('**응답 예시** (정적)', $updated);
}
#[Test]
public function 파일_업로드_요청_예시는_multipart_form_data_다(): void
{
$scaffolder = new ApiDocScaffolder;
$route = [
'method' => 'POST', 'uri' => '/api/me/avatar', 'name' => 'api.me.avatar.upload',
'controller' => 'C', 'controller_method' => 'uploadAvatar', 'permission' => null,
'middleware' => ['auth:sanctum'], 'path_params' => [],
];
$request = ['request_class' => 'X', 'params' => [
['name' => 'avatar', 'type' => 'image', 'required' => true, 'allowed' => 'max 2048'],
], 'hook_filters' => []];
$probeMeta = ['status' => null, 'skipped_reason' => 'write-method', 'base_url' => 'https://g7.example.com', 'resolved_uri' => '/api/me/avatar', 'body' => null];
$section = $scaffolder->endpointSection($route, $request, null, $probeMeta);
// 파일(image) 파라미터는 application/json 이 아니라 multipart/form-data 로 표기된다.
$this->assertStringContainsString('Content-Type: multipart/form-data', $section);
$this->assertStringNotContainsString('"avatar": "string"', $section);
$this->assertStringContainsString('filename=', $section);
$this->assertStringContainsString('name="avatar"', $section);
}
#[Test]
public function ge_t_요청_예시는_query_파라미터를_url_쿼리스트링으로_붙인다(): void
{
$scaffolder = new ApiDocScaffolder;
$route = [
'method' => 'GET', 'uri' => '/api/search', 'name' => 'api.search.index',
'controller' => 'C', 'controller_method' => 'index', 'permission' => null,
'middleware' => ['api'], 'path_params' => [],
];
$request = ['request_class' => 'X', 'params' => [
['name' => 'q', 'type' => 'string', 'required' => true, 'allowed' => ''],
['name' => 'type', 'type' => 'string', 'required' => false, 'allowed' => '`post`, `product`'],
], 'hook_filters' => []];
$probeMeta = ['status' => 200, 'skipped_reason' => null, 'base_url' => 'https://g7.example.com', 'resolved_uri' => '/api/search', 'body' => ['success' => true, 'data' => []]];
$section = $scaffolder->endpointSection($route, $request, $schema = null, $probeMeta);
// query 파라미터가 URL 쿼리스트링으로 반영된다 (in: 열거는 첫 값 채택).
$this->assertMatchesRegularExpression('/GET \/api\/search\?[^ ]*q=/', $section);
$this->assertStringContainsString('type=post', $section);
}
#[Test]
public function 응답_예시는_토큰_비밀번호_등_민감값을_마스킹한다(): void
{
$scaffolder = new ApiDocScaffolder;
$route = [
'method' => 'POST', 'uri' => '/api/auth/login', 'name' => 'api.auth.login',
'controller' => 'C', 'controller_method' => 'login', 'permission' => null,
'middleware' => ['api'], 'path_params' => [],
];
$request = ['request_class' => null, 'params' => [], 'hook_filters' => []];
$schema = ['envelope' => ['success', 'data'], 'shape' => 'object', 'fields' => [['name' => 'token', 'type' => 'string', 'sample' => '69|abc']], 'pagination' => false];
$body = ['success' => true, 'data' => [
'token' => '69|NzX4qbOT4Xns28p6Ik7d7CvGiYn8kuyi8cS0J0AL5ad91266',
'token_type' => 'Bearer',
'user' => ['uuid' => 'abc', 'password' => '$2y$10$abcdefghijklmnop'],
], 'message' => null, 'error' => null];
$probeMeta = ['status' => 200, 'skipped_reason' => null, 'base_url' => 'https://g7.example.com', 'resolved_uri' => '/api/auth/login', 'body' => $body];
$section = $scaffolder->endpointSection($route, $request, $schema, $probeMeta);
// 실제 토큰/비밀번호 해시는 노출되지 않고 마스킹된다.
$this->assertStringNotContainsString('NzX4qbOT4Xns28p6', $section);
$this->assertStringNotContainsString('$2y$10$abcdefghijklmnop', $section);
$this->assertStringContainsString('{MASKED}', $section);
// token_type 은 민감값이 아니므로 보존된다.
$this->assertStringContainsString('"token_type": "Bearer"', $section);
}
#[Test]
public function 응답_예시_body의_절대_ur_l_호스트는_placeholder로_마스킹된다(): void
{
$scaffolder = new ApiDocScaffolder;
$route = [
'method' => 'GET', 'uri' => '/api/admin/users', 'name' => 'api.admin.users.index',
'controller' => 'C', 'controller_method' => 'index', 'permission' => null,
'middleware' => ['auth:sanctum'], 'path_params' => [],
];
$request = ['request_class' => null, 'params' => [], 'hook_filters' => []];
$schema = ['envelope' => ['success', 'data'], 'shape' => 'collection', 'fields' => [['name' => 'id', 'type' => 'integer', 'sample' => '1']], 'pagination' => true];
// 실측 응답의 페이지네이터 메타·콜백 URL 은 요청 base URL 의 호스트를 그대로 직렬화한다.
$body = ['success' => true, 'data' => [
'data' => [['id' => 1]],
'first_page_url' => 'https://g7_2.dev/api/admin/users?page=1',
'path' => 'https://g7_2.dev/api/admin/users',
'callback_url' => 'https://g7_2.dev:8443/callback',
], 'message' => null, 'error' => null];
$probeMeta = ['status' => 200, 'skipped_reason' => null, 'base_url' => 'https://g7_2.dev', 'resolved_uri' => '/api/admin/users', 'body' => $body];
$section = $scaffolder->endpointSection($route, $request, $schema, $probeMeta);
// 실측 기준 호스트(g7_2.dev)는 응답 예시 어디에도 노출되지 않고 placeholder 로 치환된다.
$this->assertStringNotContainsString('g7_2.dev', $section);
$this->assertStringContainsString('https://api.example.com/api/admin/users?page=1', $section);
// 포트가 붙은 절대 URL 도 호스트+포트 통째로 마스킹된다.
$this->assertStringContainsString('https://api.example.com/callback', $section);
}
#[Test]
public function 파라미터_표는_path와_form_request_의_동일_이름을_중복_출력하지_않는다(): void
{
$scaffolder = new ApiDocScaffolder;
$route = [
'method' => 'GET', 'uri' => '/api/templates/{identifier}/assets/{path}', 'name' => 'api.templates.assets',
'controller' => 'C', 'controller_method' => 'assets', 'permission' => null,
'middleware' => ['api'], 'path_params' => ['identifier', 'path'],
];
// FormRequest 에도 identifier/path 규칙이 있는 경우 (중복 유발 조건)
$request = ['request_class' => 'X', 'params' => [
['name' => 'identifier', 'type' => 'string', 'required' => true, 'allowed' => ''],
['name' => 'path', 'type' => 'string', 'required' => true, 'allowed' => ''],
], 'hook_filters' => []];
$probeMeta = ['status' => 200, 'skipped_reason' => null, 'base_url' => 'https://g7.example.com', 'resolved_uri' => '/api/templates/x/assets/y', 'body' => ['success' => true, 'data' => []]];
$section = $scaffolder->endpointSection($route, $request, null, $probeMeta);
// identifier/path 는 path 행으로만 1회 출력 (query 중복 행 없음).
$this->assertSame(1, substr_count($section, '| identifier | path |'));
$this->assertStringNotContainsString('| identifier | query |', $section);
$this->assertSame(1, substr_count($section, '| path | path |'));
}
}
@@ -85,19 +85,30 @@ class ResourceFieldDescriberTest extends TestCase
{
$describer = new ResourceFieldDescriber;
// 맥락 의존/도메인 특수 필드는 사전/패턴에 없어야 (TODO 로 폴백)
$this->assertNull($describer->describe('roles', 'array'));
// user/templates/modules/plugins/menus 는 맥락(객체 vs 목록)에 따라 의미가 갈려 제외
// (user 는 사용자 객체 vs 권한 그룹 객체로 다형적, updater 는 array 로 관계 객체 아님)
$this->assertNull($describer->describe('user', 'object'));
$this->assertNull($describer->describe('templates', 'array'));
// IDV/marketing 도메인 특이 필드는 제외
// IDV/marketing 도메인 특이 필드는 제외 (사전/패턴에 없어야 — TODO 로 폴백)
$this->assertNull($describer->describe('purpose', 'string'));
$this->assertNull($describer->describe('channels', 'array'));
$this->assertNull($describer->describe('render_hint', 'string'));
// status/type/code/category 는 값 집합이 도메인마다 달라 제외 (역할은 있으나 도메인 종속)
$this->assertNull($describer->describe('status', 'string'));
// type/code/category 는 값 집합이 도메인마다 달라 제외 (역할은 있으나 도메인 종속)
$this->assertNull($describer->describe('code', 'string'));
$this->assertNull($describer->describe('type', 'string'));
$this->assertNull($describer->describe('category', 'string'));
}
#[Test]
public function 쓰기_응답_공통_관계_실행이력_필드를_설명한다(): void
{
// 쓰기 메서드 실측 도입으로 응답에 자주 등장하는 공통 관계/실행이력/토큰 필드는
// 도메인 무관하게 역할이 고정되므로 설명한다(TODO 방치 금지).
$describer = new ResourceFieldDescriber;
$this->assertStringContainsString('역할', $describer->describe('roles', 'array'));
$this->assertStringContainsString('사용자', $describer->describe('user', 'object'));
$this->assertStringContainsString('토큰', $describer->describe('token', 'string'));
$this->assertStringContainsString('실행', $describer->describe('duration', 'integer'));
$this->assertStringContainsString('종료 코드', $describer->describe('exit_code', 'integer'));
// status 는 문자열/정수일 때 일반 설명(도메인 라벨은 status_label 참조)
$this->assertStringContainsString('상태 값', $describer->describe('status', 'string'));
}
#[Test]