feat(api-docs): API 레퍼런스 문서 전면화 — 추출 파이프라인·전 대상 문서화·audit 강제
코드에만 존재하던 REST API 계약(약 663 엔드포인트)을 코어/확장 책임별로
분리된 마크다운 레퍼런스로 전면 문서화한다. 674개 규모에서 수기 문서는
반드시 drift 하므로 "코드 추출 → 스캐폴딩 → 사람이 서술 채움 → 하네스가
커버리지 강제" 하이브리드로 구성했다.
추출 파이프라인 (app/Support/ApiDoc):
- ApiRouteInventory / FormRequestIntrospector / ApiEndpointProbe(실측 HTTP) /
ResponseSchemaInferrer / ApiDocScaffolder / ColumnCommentResolver /
ResourceFieldDescriber / ParameterDescriber
- api:docgen 커맨드(--scope/--seed/--check/--dry-run/--base-url/--user) +
응답/파라미터 in-place 백필 커맨드 2종(재생성 없이 TODO 셀만 치환, 멱등)
- ApiDocSampleSeeder 계약 + 코어/확장 시더로 실측용 완전 샘플 멱등 생성
문서화 (실측 기반, GET read-only 실호출):
- 코어 291엔드포인트 35파일(docs/backend/api) + 규정 docs/backend/api-documentation.md
- 확장: ecommerce(231)·board(80)·page(17)·hello_module(2)·pay_kginicis(22)·
gdpr(15)·ckeditor5(2)·marketing(2)·verification_kginicis(1)
- 표준 4구성(헤더·요청 파라미터·응답 필드·에러 표) + 엔드포인트 용도 서술
- 파라미터 용도·응답 필드 설명 셀 전수 채움(도메인 지식 수기)
하네스:
- audit 룰 api-doc-coverage — API 표면(라우트/컨트롤러/FormRequest/Resource)
변경 시 대응 문서 미동반이면 차단. 전 대상 문서 완비로 error 승격
- file-rules 리마인더(컨트롤러/라우트 편집 시), coverage.json, dev-dashboard 카드
- docs/backend/routing.md 확장 공개 API URL 스킴 정정(/api/modules|plugins/{id})
- /AGENTS.md/docs-index 동기
This commit is contained in:
1 parent
49b21e788c
commit
70452745c4
131 files changed
+32105
-21
No files matched your search
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Console;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Support\ApiDoc\ApiDocSampleService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* API 문서 실측용 완전 샘플 시더 Feature 테스트.
|
||||
*
|
||||
* 도메인별 완전 샘플이 생성되고, 재실행 시 중복 없이 멱등하며,
|
||||
* 완전 사용자 샘플의 프로필 필드가 채워지는지 검증한다.
|
||||
*/
|
||||
class ApiDocSampleServiceTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
#[Test]
|
||||
public function 도메인별_대표_샘플_맵을_반환한다(): void
|
||||
{
|
||||
$map = (new ApiDocSampleService)->seed();
|
||||
|
||||
$this->assertArrayHasKey('users', $map);
|
||||
$this->assertArrayHasKey('roles', $map);
|
||||
$this->assertArrayHasKey('menus', $map);
|
||||
$this->assertArrayHasKey('schedules', $map);
|
||||
|
||||
// 각 항목은 model/key/value 구조
|
||||
$this->assertSame(User::class, $map['users']['model']);
|
||||
$this->assertArrayHasKey('key', $map['users']);
|
||||
$this->assertNotEmpty($map['users']['value']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 완전_사용자_샘플은_프로필_필드가_채워진다(): void
|
||||
{
|
||||
(new ApiDocSampleService)->seed();
|
||||
|
||||
$user = User::where('email', 'apidoc-sample-user@example.com')->first();
|
||||
|
||||
$this->assertNotNull($user);
|
||||
$this->assertNotNull($user->nickname);
|
||||
$this->assertNotNull($user->mobile);
|
||||
$this->assertSame('KR', $user->country);
|
||||
$this->assertSame('ko', $user->language);
|
||||
$this->assertNotNull($user->bio);
|
||||
$this->assertGreaterThan(0, $user->roles()->count());
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 재실행_시_샘플이_중복_생성되지_않는다(): void
|
||||
{
|
||||
$service = new ApiDocSampleService;
|
||||
|
||||
$service->seed();
|
||||
$countAfterFirst = User::where('email', 'apidoc-sample-user@example.com')->count();
|
||||
|
||||
$service->seed();
|
||||
$countAfterSecond = User::where('email', 'apidoc-sample-user@example.com')->count();
|
||||
|
||||
$this->assertSame(1, $countAfterFirst);
|
||||
$this->assertSame(1, $countAfterSecond);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Console;
|
||||
|
||||
use App\Console\Commands\ApiDocBackfillFieldsCommand;
|
||||
use App\Support\ApiDoc\ResourceFieldDescriber;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use ReflectionMethod;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* ApiDocBackfillFieldsCommand 응답 필드 백필 로직 단위 테스트.
|
||||
*
|
||||
* 실제 문서 파일에 의존하지 않고, 응답 필드 표의 `<!-- TODO: 설명 -->` 셀만
|
||||
* 리소스 계약 사전 설명으로 치환되는지(파라미터 표·실측 예시값·타입은 불변) 검증한다.
|
||||
* 재실행 멱등성과 도메인 특이 필드 TODO 유지도 확인한다.
|
||||
*/
|
||||
class ApiDocBackfillFieldsCommandTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* 커맨드의 backfillFile private 메서드를 리플렉션으로 호출합니다.
|
||||
*
|
||||
* @param string $content 문서 내용
|
||||
* @return array{result: string, filled: int, skipped: int} 치환 결과와 카운트
|
||||
*/
|
||||
private function backfill(string $content): array
|
||||
{
|
||||
$command = app(ApiDocBackfillFieldsCommand::class);
|
||||
$ref = new ReflectionMethod($command, 'backfillFile');
|
||||
$ref->setAccessible(true);
|
||||
|
||||
$describer = new ResourceFieldDescriber;
|
||||
$filled = 0;
|
||||
$skipped = 0;
|
||||
$result = $ref->invokeArgs($command, [$content, $describer, &$filled, &$skipped]);
|
||||
|
||||
return ['result' => $result, 'filled' => $filled, 'skipped' => $skipped];
|
||||
}
|
||||
|
||||
/**
|
||||
* 응답 필드 표 뼈대를 만듭니다.
|
||||
*
|
||||
* @param string $rows 표 행들
|
||||
* @return string 마크다운
|
||||
*/
|
||||
private function fieldTable(string $rows): string
|
||||
{
|
||||
return "**응답 필드** (`data` 내부)\n\n"
|
||||
."| 필드 | 타입 | 실측 예시값 | 용도/설명 |\n"
|
||||
."| --- | --- | --- | --- |\n"
|
||||
.$rows."\n";
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 응답_필드_표의_todo_를_계약_설명으로_채운다(): void
|
||||
{
|
||||
$content = $this->fieldTable(
|
||||
"| created_at | string | `2026-07-07` | <!-- TODO: 설명 --> |\n"
|
||||
.'| is_owner | boolean | `true` | <!-- TODO: 설명 --> |'
|
||||
);
|
||||
|
||||
$out = $this->backfill($content);
|
||||
|
||||
$this->assertStringContainsString('생성 일시', $out['result']);
|
||||
$this->assertStringContainsString('소유자', $out['result']);
|
||||
$this->assertStringNotContainsString('<!-- TODO: 설명 -->', $out['result']);
|
||||
$this->assertSame(2, $out['filled']);
|
||||
$this->assertSame(0, $out['skipped']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 실측_예시값과_타입은_불변이다(): void
|
||||
{
|
||||
$content = $this->fieldTable(
|
||||
'| created_at | string | `2026-07-07 05:13:51` | <!-- TODO: 설명 --> |'
|
||||
);
|
||||
|
||||
$out = $this->backfill($content);
|
||||
|
||||
// 실측 예시값 셀과 타입 셀이 그대로 유지되어야 한다
|
||||
$this->assertStringContainsString('| created_at | string | `2026-07-07 05:13:51` |', $out['result']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 파라미터_표의_todo_는_건드리지_않는다(): void
|
||||
{
|
||||
// 응답 표 헤더가 아니므로 진입하지 않아야 한다 (파라미터 TODO 마커도 다름)
|
||||
$content = "**요청 파라미터**\n\n"
|
||||
."| 이름 | 위치 | 타입 | 필수 | 허용값 | 용도 |\n"
|
||||
."| --- | --- | --- | --- | --- | --- |\n"
|
||||
."| page | query | integer | 아니오 | — | <!-- TODO: 용도 --> |\n";
|
||||
|
||||
$out = $this->backfill($content);
|
||||
|
||||
$this->assertSame($content, $out['result']);
|
||||
$this->assertStringContainsString('<!-- TODO: 용도 -->', $out['result']);
|
||||
$this->assertSame(0, $out['filled']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 도메인_특이_필드는_todo_를_유지한다(): void
|
||||
{
|
||||
$content = $this->fieldTable(
|
||||
"| purpose | string | `login` | <!-- TODO: 설명 --> |\n"
|
||||
.'| channels | array | `[]` | <!-- TODO: 설명 --> |'
|
||||
);
|
||||
|
||||
$out = $this->backfill($content);
|
||||
|
||||
// ResourceFieldDescriber 가 null 반환 → TODO 유지
|
||||
$this->assertSame(2, substr_count($out['result'], '<!-- TODO: 설명 -->'));
|
||||
$this->assertSame(0, $out['filled']);
|
||||
$this->assertSame(2, $out['skipped']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 두번_실행해도_결과가_동일하다_멱등(): void
|
||||
{
|
||||
$content = $this->fieldTable(
|
||||
"| created_at | string | `2026-07-07` | <!-- TODO: 설명 --> |\n"
|
||||
.'| purpose | string | `login` | <!-- TODO: 설명 --> |'
|
||||
);
|
||||
|
||||
$first = $this->backfill($content)['result'];
|
||||
$second = $this->backfill($first)['result'];
|
||||
|
||||
$this->assertSame($first, $second);
|
||||
// 이미 채워진 셀은 다시 채우지 않음 (도메인 특이만 skipped 로 카운트)
|
||||
$this->assertSame(0, $this->backfill($first)['filled']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 표_밖의_todo_는_무시한다(): void
|
||||
{
|
||||
// 응답 필드 표가 끝난 뒤(사람 서술)의 동일 마커는 치환 대상이 아니다
|
||||
$content = $this->fieldTable(
|
||||
'| created_at | string | `2026-07-07` | <!-- TODO: 설명 --> |'
|
||||
)."\n본문 설명 <!-- TODO: 설명 --> 은 유지되어야 한다\n";
|
||||
|
||||
$out = $this->backfill($content);
|
||||
|
||||
$this->assertStringContainsString('본문 설명 <!-- TODO: 설명 --> 은 유지', $out['result']);
|
||||
$this->assertSame(1, $out['filled']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Console;
|
||||
|
||||
use App\Console\Commands\ApiDocgenCommand;
|
||||
use App\Models\User;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use ReflectionMethod;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* ApiDocgenCommand 확장 지원 로직 단위 테스트.
|
||||
*
|
||||
* 확장 컨트롤러 FQCN 에서 베이스 네임스페이스 추출, 도메인-파라미터 매칭
|
||||
* (미바인딩 path param 폴백 판정)의 순수 로직을 HTTP 의존 없이 검증한다.
|
||||
*/
|
||||
class ApiDocgenExtensionDiscoveryTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* 커맨드의 private 메서드를 리플렉션으로 호출합니다.
|
||||
*
|
||||
* @param string $method 메서드명
|
||||
* @param array<int, mixed> $args 인자
|
||||
* @return mixed 반환값
|
||||
*/
|
||||
private function invoke(string $method, array $args): mixed
|
||||
{
|
||||
$command = app(ApiDocgenCommand::class);
|
||||
$ref = new ReflectionMethod($command, $method);
|
||||
$ref->setAccessible(true);
|
||||
|
||||
return $ref->invokeArgs($command, $args);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 확장_컨트롤러_fqc_n에서_베이스_네임스페이스를_추출한다(): void
|
||||
{
|
||||
$base = $this->invoke('extensionBaseNamespace', [
|
||||
'Modules\\Sirsoft\\Page\\Http\\Controllers\\Admin\\PageController',
|
||||
]);
|
||||
|
||||
$this->assertSame('Modules\\Sirsoft\\Page', $base);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function http_controllers_없이_controllers_규약을_쓰는_확장도_베이스를_추출한다(): void
|
||||
{
|
||||
// pay_kginicis 는 `\Http\Controllers\` 대신 `\Controllers\` 배치를 쓴다.
|
||||
// 이 경우도 시더 발견을 위해 베이스 네임스페이스를 추출해야 한다.
|
||||
$base = $this->invoke('extensionBaseNamespace', [
|
||||
'Plugins\\Sirsoft\\PayKginicis\\Controllers\\PaymentSignatureController',
|
||||
]);
|
||||
|
||||
$this->assertSame('Plugins\\Sirsoft\\PayKginicis', $base);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function http_controllers_규약이_controllers_보다_우선한다(): void
|
||||
{
|
||||
// 두 세그먼트가 공존할 수 있는 경우 `\Http\Controllers\` 를 우선 판정한다.
|
||||
$base = $this->invoke('extensionBaseNamespace', [
|
||||
'Modules\\Sirsoft\\Board\\Http\\Controllers\\Admin\\BoardController',
|
||||
]);
|
||||
|
||||
$this->assertSame('Modules\\Sirsoft\\Board', $base);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 클로저_또는_컨트롤러_규약_밖이면_null을_반환한다(): void
|
||||
{
|
||||
$this->assertNull($this->invoke('extensionBaseNamespace', [null]));
|
||||
$this->assertNull($this->invoke('extensionBaseNamespace', ['SomeRandomClass']));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 파라미터명이_도메인_단수형과_일치하면_매칭이다(): void
|
||||
{
|
||||
// pages/{page} → 도메인 단수 리소스 폴백 대상
|
||||
$this->assertTrue($this->invoke('paramMatchesDomain', ['page', 'pages']));
|
||||
$this->assertTrue($this->invoke('paramMatchesDomain', ['pages', 'pages']));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 보조_문자열_파라미터는_도메인과_매칭되지_않는다(): void
|
||||
{
|
||||
// {slug}/{hash}/{versionId} 는 route key 가 달라 폴백 금지 (잘못된 404 회피)
|
||||
$this->assertFalse($this->invoke('paramMatchesDomain', ['slug', 'pages']));
|
||||
$this->assertFalse($this->invoke('paramMatchesDomain', ['hash', 'pages']));
|
||||
$this->assertFalse($this->invoke('paramMatchesDomain', ['versionId', 'pages']));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 도메인_샘플의_path_params_맵으로_문자열_파라미터를_치환한다(): void
|
||||
{
|
||||
// board 처럼 route-model binding 없는 slug/id 문자열 param 을
|
||||
// 도메인 대표 샘플의 path_params 맵(param 명 => 실제 값)으로 정확 일치 치환.
|
||||
$route = [
|
||||
'uri' => 'api/modules/sirsoft-board/boards/{slug}/posts/{id}',
|
||||
'method' => 'GET',
|
||||
'domain_group' => 'boards',
|
||||
'path_params' => ['slug', 'id'],
|
||||
'path_bindings' => [],
|
||||
];
|
||||
$sampleMap = [
|
||||
'boards' => [
|
||||
'model' => User::class,
|
||||
'key' => 'id',
|
||||
'value' => '1',
|
||||
'path_params' => ['slug' => 'qna', 'id' => '123'],
|
||||
],
|
||||
];
|
||||
|
||||
$uri = $this->invoke('resolvePathParams', [$route, $sampleMap]);
|
||||
|
||||
// slug/id 치환 후 중괄호가 모두 사라진 GET 은 목록 대표 샘플 확보용 per_page 가 부착됨
|
||||
$this->assertSame('api/modules/sirsoft-board/boards/qna/posts/123?per_page=25', $uri);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function path_params에_없는_파라미터는_치환하지_않고_원본을_유지한다(): void
|
||||
{
|
||||
// path_params 맵에 없는 param(hash) 은 미치환 → URI 에 남아 프로브가 실측 제외.
|
||||
$route = [
|
||||
'uri' => 'api/modules/sirsoft-board/boards/{slug}/attachment/{hash}',
|
||||
'method' => 'GET',
|
||||
'domain_group' => 'boards',
|
||||
'path_params' => ['slug', 'hash'],
|
||||
'path_bindings' => [],
|
||||
];
|
||||
$sampleMap = [
|
||||
'boards' => [
|
||||
'model' => User::class,
|
||||
'key' => 'id',
|
||||
'value' => '1',
|
||||
'path_params' => ['slug' => 'qna'],
|
||||
],
|
||||
];
|
||||
|
||||
$uri = $this->invoke('resolvePathParams', [$route, $sampleMap]);
|
||||
|
||||
// slug 는 치환되고 hash 는 미치환 → 중괄호가 남아 실측 대상에서 제외됨
|
||||
$this->assertStringContainsString('boards/qna/attachment/{hash}', $uri);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function path_params가_없는_기존_확장은_route_key_치환만_적용한다(): void
|
||||
{
|
||||
// page/gdpr 등 path_params 미제공 확장은 기존 동작 유지(회귀 방지):
|
||||
// 문자열 param 은 미치환 → 원본 중괄호 유지.
|
||||
$route = [
|
||||
'uri' => 'api/modules/sirsoft-page/pages/{slug}',
|
||||
'method' => 'GET',
|
||||
'domain_group' => 'pages',
|
||||
'path_params' => ['slug'],
|
||||
'path_bindings' => [],
|
||||
];
|
||||
$sampleMap = [
|
||||
'pages' => [
|
||||
'model' => User::class,
|
||||
'key' => 'slug',
|
||||
'value' => 'sample',
|
||||
],
|
||||
];
|
||||
|
||||
$uri = $this->invoke('resolvePathParams', [$route, $sampleMap]);
|
||||
|
||||
// path_params 미제공 + paramMatchesDomain('slug','pages')=false → 미치환
|
||||
$this->assertStringContainsString('pages/{slug}', $uri);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Support\ApiDoc;
|
||||
|
||||
use App\Support\ApiDoc\ApiDocScaffolder;
|
||||
use App\Support\ApiDoc\ResponseSchemaInferrer;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* API 문서 생성 파이프라인 단위 테스트.
|
||||
*
|
||||
* 실측 응답 스키마 추론과 스캐폴딩 병합(사람 서술 보존)의 순수 로직을
|
||||
* HTTP 의존 없이 검증한다.
|
||||
*/
|
||||
class ApiDocPipelineTest extends TestCase
|
||||
{
|
||||
#[Test]
|
||||
public function 목록_응답에서_배열_항목_필드와_페이지네이션을_추론한다(): void
|
||||
{
|
||||
$inferrer = new ResponseSchemaInferrer;
|
||||
|
||||
$body = [
|
||||
'success' => true,
|
||||
'message' => '조회 성공',
|
||||
'data' => [
|
||||
'data' => [
|
||||
['id' => 1, 'name' => '홍길동', 'is_active' => true, 'deleted' => null],
|
||||
],
|
||||
'pagination' => ['current_page' => 1, 'total' => 10],
|
||||
],
|
||||
];
|
||||
|
||||
$schema = $inferrer->infer($body);
|
||||
|
||||
$this->assertSame('collection', $schema['shape']);
|
||||
$this->assertTrue($schema['pagination']);
|
||||
$this->assertSame(['success', 'message', 'data'], $schema['envelope']);
|
||||
|
||||
$fields = collect($schema['fields'])->keyBy('name');
|
||||
$this->assertSame('integer', $fields['id']['type']);
|
||||
$this->assertSame('string', $fields['name']['type']);
|
||||
$this->assertSame('boolean', $fields['is_active']['type']);
|
||||
$this->assertSame('null', $fields['deleted']['type']);
|
||||
$this->assertSame('홍길동', $fields['name']['sample']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 단건_응답에서_객체_필드를_추론한다(): void
|
||||
{
|
||||
$inferrer = new ResponseSchemaInferrer;
|
||||
|
||||
$body = [
|
||||
'success' => true,
|
||||
'data' => ['total' => 155, 'ratio' => 0.5, 'labels' => ['ko' => 91]],
|
||||
];
|
||||
|
||||
$schema = $inferrer->infer($body);
|
||||
|
||||
$this->assertSame('object', $schema['shape']);
|
||||
$this->assertFalse($schema['pagination']);
|
||||
|
||||
$fields = collect($schema['fields'])->keyBy('name');
|
||||
$this->assertSame('integer', $fields['total']['type']);
|
||||
$this->assertSame('number', $fields['ratio']['type']);
|
||||
$this->assertSame('object', $fields['labels']['type']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 표_셀에서_파이프_문자를_이스케이프한다(): void
|
||||
{
|
||||
$inferrer = new ResponseSchemaInferrer;
|
||||
|
||||
$body = ['success' => true, 'data' => ['note' => 'a|b|c']];
|
||||
$schema = $inferrer->infer($body);
|
||||
|
||||
$fields = collect($schema['fields'])->keyBy('name');
|
||||
$this->assertStringNotContainsString('|b', str_replace('\\|', '', $fields['note']['sample']));
|
||||
$this->assertStringContainsString('\\|', $fields['note']['sample']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 스캐폴더가_엔드포인트_섹션을_표준_포맷으로_생성한다(): void
|
||||
{
|
||||
$scaffolder = new ApiDocScaffolder;
|
||||
|
||||
$route = [
|
||||
'method' => 'GET',
|
||||
'uri' => '/api/admin/users',
|
||||
'name' => 'api.admin.users.index',
|
||||
'controller' => 'App\\Http\\Controllers\\Api\\Admin\\UserController',
|
||||
'controller_method' => 'index',
|
||||
'permission' => 'core.users.read',
|
||||
'middleware' => ['auth:sanctum', 'App\\Http\\Middleware\\AdminMiddleware'],
|
||||
'path_params' => [],
|
||||
];
|
||||
|
||||
$request = ['request_class' => 'X', 'params' => [
|
||||
['name' => 'page', 'type' => 'integer', 'required' => false, 'allowed' => 'min 1'],
|
||||
], 'hook_filters' => ['core.user.list_validation_rules']];
|
||||
|
||||
$schema = [
|
||||
'envelope' => ['success', 'data'],
|
||||
'shape' => 'collection',
|
||||
'fields' => [['name' => 'id', 'type' => 'integer', 'sample' => '1']],
|
||||
'pagination' => true,
|
||||
];
|
||||
|
||||
$section = $scaffolder->endpointSection($route, $request, $schema, ['status' => 200, 'skipped_reason' => null]);
|
||||
|
||||
$this->assertStringContainsString('### GET /api/admin/users', $section);
|
||||
$this->assertStringContainsString('@generated:start:api.admin.users.index', $section);
|
||||
$this->assertStringContainsString('`auth:sanctum` + `admin` + `permission:core.users.read`', $section);
|
||||
$this->assertStringContainsString('| page | query | integer | 아니오 | min 1 |', $section);
|
||||
$this->assertStringContainsString('core.user.list_validation_rules', $section);
|
||||
$this->assertStringContainsString('| id | integer | `1` |', $section);
|
||||
// 에러 응답 표: auth:sanctum→401, admin+permission→403, FormRequest(params/hook)→422
|
||||
$this->assertStringContainsString('**에러 응답**', $section);
|
||||
$this->assertStringContainsString('| 401 | Unauthenticated |', $section);
|
||||
$this->assertStringContainsString('| 403 | Forbidden | 요구 권한(`core.users.read`)이 없는 경우 |', $section);
|
||||
$this->assertStringContainsString('| 422 | Unprocessable Entity |', $section);
|
||||
$this->assertStringContainsString('@generated:end', $section);
|
||||
// 에러 표는 @generated 블록 내부(재생성 대상)여야 한다
|
||||
$genStart = strpos($section, '@generated:start');
|
||||
$genEnd = strpos($section, '@generated:end');
|
||||
$errorPos = strpos($section, '**에러 응답**');
|
||||
$this->assertGreaterThan($genStart, $errorPos);
|
||||
$this->assertLessThan($genEnd, $errorPos);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 에러_섹션이_라우트_메타에서_대표_상태코드를_추론한다(): void
|
||||
{
|
||||
$scaffolder = new ApiDocScaffolder;
|
||||
|
||||
// path param 존재 + admin + permission + FormRequest → 401/403/422/404 전부
|
||||
$route = [
|
||||
'method' => 'PUT',
|
||||
'uri' => '/api/admin/users/{user}',
|
||||
'name' => 'api.admin.users.update',
|
||||
'controller' => 'C', 'controller_method' => 'update',
|
||||
'permission' => 'core.users.update',
|
||||
'middleware' => ['auth:sanctum', 'App\\Http\\Middleware\\AdminMiddleware'],
|
||||
'path_params' => ['user'],
|
||||
];
|
||||
$request = ['request_class' => 'X', 'params' => [
|
||||
['name' => 'name', 'type' => 'string', 'required' => true, 'allowed' => ''],
|
||||
], 'hook_filters' => []];
|
||||
|
||||
$section = $scaffolder->endpointSection($route, $request, null, ['status' => null, 'skipped_reason' => 'write-method']);
|
||||
|
||||
$this->assertStringContainsString('| 401 | Unauthenticated |', $section);
|
||||
$this->assertStringContainsString('| 403 | Forbidden | 요구 권한(`core.users.update`)이 없는 경우 |', $section);
|
||||
$this->assertStringContainsString('| 422 | Unprocessable Entity |', $section);
|
||||
$this->assertStringContainsString('| 404 | Not Found |', $section);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function optional_sanctum_공개조회는_401을_유발하지_않는다(): void
|
||||
{
|
||||
// optional.sanctum(선택 인증)은 미인증도 허용 → 401 없음.
|
||||
// path param 만 있으므로 404 만 노출.
|
||||
$scaffolder = new ApiDocScaffolder;
|
||||
|
||||
$route = [
|
||||
'method' => 'GET',
|
||||
'uri' => '/api/modules/sirsoft-board/boards/{slug}',
|
||||
'name' => 'api.modules.sirsoft-board.boards.show',
|
||||
'controller' => 'C', 'controller_method' => 'show',
|
||||
'permission' => null,
|
||||
'middleware' => ['api', 'optional.sanctum'],
|
||||
'path_params' => ['slug'],
|
||||
];
|
||||
$request = ['request_class' => null, 'params' => [], 'hook_filters' => []];
|
||||
$schema = ['envelope' => ['data'], 'shape' => 'object', 'fields' => [['name' => 'id', 'type' => 'integer', 'sample' => '1']], 'pagination' => false];
|
||||
|
||||
$section = $scaffolder->endpointSection($route, $request, $schema, ['status' => 200, 'skipped_reason' => null]);
|
||||
|
||||
$this->assertStringNotContainsString('| 401 |', $section);
|
||||
$this->assertStringNotContainsString('| 403 |', $section);
|
||||
$this->assertStringNotContainsString('| 422 |', $section);
|
||||
$this->assertStringContainsString('| 404 | Not Found |', $section);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 완전_공개_조회는_대표_에러_없음으로_표기한다(): void
|
||||
{
|
||||
// 인증·권한·FormRequest·path param 전무 → 대표 에러 없음.
|
||||
$scaffolder = new ApiDocScaffolder;
|
||||
|
||||
$route = [
|
||||
'method' => 'GET', 'uri' => '/api/locales', 'name' => 'api.locales.index',
|
||||
'controller' => 'C', 'controller_method' => 'index', 'permission' => null,
|
||||
'middleware' => ['api'], 'path_params' => [],
|
||||
];
|
||||
$request = ['request_class' => null, 'params' => [], 'hook_filters' => []];
|
||||
$schema = ['envelope' => ['data'], 'shape' => 'collection', 'fields' => [['name' => 'code', 'type' => 'string', 'sample' => 'ko']], 'pagination' => false];
|
||||
|
||||
$section = $scaffolder->endpointSection($route, $request, $schema, ['status' => 200, 'skipped_reason' => null]);
|
||||
|
||||
$this->assertStringContainsString('대표 에러 없음', $section);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function optional_sanctum_라우트는_선택적_인증으로_표기한다(): void
|
||||
{
|
||||
// optional.sanctum(회원/비회원 모두 접근)을 auth:sanctum(인증 필수)로
|
||||
// 오표기하면 공개 API 계약이 왜곡된다(게시판 공개 조회 등). 별도 표기 강제.
|
||||
$scaffolder = new ApiDocScaffolder;
|
||||
|
||||
$route = [
|
||||
'method' => 'GET',
|
||||
'uri' => '/api/modules/sirsoft-board/boards/{slug}/posts',
|
||||
'name' => 'api.modules.sirsoft-board.boards.posts.index',
|
||||
'controller' => 'C', 'controller_method' => 'index',
|
||||
'permission' => 'user,sirsoft-board.{slug}.posts.read',
|
||||
'middleware' => ['api', 'optional.sanctum', 'throttle:600,1'],
|
||||
'path_params' => ['slug'],
|
||||
];
|
||||
$request = ['request_class' => null, 'params' => [], 'hook_filters' => []];
|
||||
$schema = ['envelope' => ['data'], 'shape' => 'collection', 'fields' => [], 'pagination' => true];
|
||||
|
||||
$section = $scaffolder->endpointSection($route, $request, $schema, ['status' => 200, 'skipped_reason' => null]);
|
||||
|
||||
// optional.sanctum 은 선택적 인증으로 표기되고 auth:sanctum 으로 오표기되지 않는다
|
||||
$this->assertStringContainsString('optional.sanctum', $section);
|
||||
$this->assertStringNotContainsString('`auth:sanctum`', $section);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 컬럼_주석이_있으면_응답_필드_설명으로_채운다(): void
|
||||
{
|
||||
$scaffolder = new ApiDocScaffolder;
|
||||
|
||||
$route = [
|
||||
'method' => 'GET', 'uri' => '/api/admin/users', 'name' => 'api.admin.users.index',
|
||||
'controller' => 'C', 'controller_method' => 'index', 'permission' => null,
|
||||
'middleware' => [], 'path_params' => [],
|
||||
];
|
||||
$request = ['request_class' => null, 'params' => [], 'hook_filters' => []];
|
||||
$schema = [
|
||||
'envelope' => ['data'], 'shape' => 'object',
|
||||
'fields' => [
|
||||
['name' => 'nickname', 'type' => 'string', 'sample' => 'hong'],
|
||||
['name' => 'unknown_field', 'type' => 'string', 'sample' => 'x'],
|
||||
],
|
||||
'pagination' => false,
|
||||
];
|
||||
$commentMap = ['nickname' => '닉네임'];
|
||||
|
||||
$section = $scaffolder->endpointSection($route, $request, $schema, ['status' => 200, 'skipped_reason' => null], $commentMap);
|
||||
|
||||
// 주석 있는 필드는 설명이 채워지고, 없는 필드는 TODO 유지
|
||||
$this->assertStringContainsString('| nickname | string | `hong` | 닉네임 |', $section);
|
||||
$this->assertStringContainsString('| unknown_field | string | `x` | <!-- TODO: 설명 --> |', $section);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 쓰기_메서드는_응답_필드를_실측_제외로_표기한다(): 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' => [],
|
||||
];
|
||||
|
||||
$section = $scaffolder->endpointSection(
|
||||
$route,
|
||||
['request_class' => null, 'params' => [], 'hook_filters' => []],
|
||||
null,
|
||||
['status' => null, 'skipped_reason' => 'write-method']
|
||||
);
|
||||
|
||||
$this->assertStringContainsString('실측 제외: write-method', $section);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 재생성_시_사람이_작성한_설명을_보존한다(): void
|
||||
{
|
||||
$scaffolder = new ApiDocScaffolder;
|
||||
|
||||
$route = [
|
||||
'method' => 'GET', 'uri' => '/api/x', 'name' => 'api.x.index',
|
||||
'controller' => 'C', 'controller_method' => 'index', 'permission' => null,
|
||||
'middleware' => [], 'path_params' => [],
|
||||
];
|
||||
$request = ['request_class' => null, 'params' => [], 'hook_filters' => []];
|
||||
$schema = ['envelope' => ['data'], 'shape' => 'object', 'fields' => [['name' => 'a', 'type' => 'integer', 'sample' => '1']], 'pagination' => false];
|
||||
|
||||
$section = $scaffolder->endpointSection($route, $request, $schema, ['status' => 200, 'skipped_reason' => null]);
|
||||
$header = "# X\n";
|
||||
|
||||
// 최초 생성
|
||||
$first = $scaffolder->mergeDocument(null, $header, [$section], ['api.x.index']);
|
||||
$this->assertStringContainsString('TODO: 이 엔드포인트의 용도', $first);
|
||||
|
||||
// 사람이 설명을 채운 상태
|
||||
$withProse = str_replace(
|
||||
'**설명** <!-- TODO: 이 엔드포인트의 용도·주의사항·예시 시나리오를 작성하세요 -->',
|
||||
'**설명** 실제 사람이 작성한 설명입니다.',
|
||||
$first
|
||||
);
|
||||
|
||||
// 재생성: 새 섹션으로 병합해도 사람 서술 보존
|
||||
$regenerated = $scaffolder->mergeDocument($withProse, $header, [$section], ['api.x.index']);
|
||||
|
||||
$this->assertStringContainsString('실제 사람이 작성한 설명입니다.', $regenerated);
|
||||
$this->assertStringNotContainsString('TODO: 이 엔드포인트의 용도', $regenerated);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Support\ApiDoc;
|
||||
|
||||
use App\Support\ApiDoc\ApiRouteInventory;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* ApiRouteInventory 비활성/미설치 확장 폴백 수집 단위 테스트.
|
||||
*
|
||||
* route:list 는 활성 확장만 노출하므로, 명시 범위(module:{id}/plugin:{id})로
|
||||
* 지정한 확장이 미설치여서 등록 라우트가 0건일 때 번들 라우트 파일(src/routes/api.php)을
|
||||
* 프로바이더와 동일한 prefix/name 규약으로 로드해 수집하는지 검증한다.
|
||||
*
|
||||
* gnuboard7-hello_module 은 학습용 번들 샘플로 개발 DB 에 미설치 상태이므로,
|
||||
* route:list 에는 나타나지 않지만 번들 라우트 파일 폴백으로는 수집되어야 한다.
|
||||
*/
|
||||
class ApiRouteInventoryFallbackTest extends TestCase
|
||||
{
|
||||
#[Test]
|
||||
public function 미설치_모듈_범위는_번들_라우트_파일에서_폴백_수집한다(): void
|
||||
{
|
||||
$routes = app(ApiRouteInventory::class)->collect('module:gnuboard7-hello_module');
|
||||
|
||||
// api.php 의 공개 memos GET 2건(index/show)이 폴백으로 수집된다.
|
||||
$this->assertNotEmpty($routes, '미설치 모듈의 번들 라우트가 폴백으로 수집되어야 한다');
|
||||
|
||||
$names = array_column($routes, 'name');
|
||||
$this->assertContains('api.modules.gnuboard7-hello_module.memos.index', $names);
|
||||
$this->assertContains('api.modules.gnuboard7-hello_module.memos.show', $names);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 폴백_수집_라우트는_프로바이더와_동일한_ur_l_규약을_따른다(): void
|
||||
{
|
||||
$routes = app(ApiRouteInventory::class)->collect('module:gnuboard7-hello_module');
|
||||
|
||||
$index = collect($routes)->firstWhere('name', 'api.modules.gnuboard7-hello_module.memos.index');
|
||||
|
||||
$this->assertNotNull($index);
|
||||
$this->assertSame('GET', $index['method']);
|
||||
$this->assertSame('/api/modules/gnuboard7-hello_module/memos', $index['uri']);
|
||||
$this->assertSame('module', $index['owner']['type']);
|
||||
$this->assertSame('gnuboard7-hello_module', $index['owner']['id']);
|
||||
$this->assertSame('memos', $index['domain_group']);
|
||||
$this->assertSame(
|
||||
'Modules\\Gnuboard7\\HelloModule\\Http\\Controllers\\Api\\MemoController',
|
||||
$index['controller']
|
||||
);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function web_admin_라우트는_ap_i_문서_대상에서_제외된다(): void
|
||||
{
|
||||
// hello_module 의 admin CRUD 는 web.php(/modules/{id} prefix)라 api/ 로 시작하지 않아
|
||||
// API 문서 대상이 아니다. 폴백은 src/routes/api.php 만 로드한다.
|
||||
$routes = app(ApiRouteInventory::class)->collect('module:gnuboard7-hello_module');
|
||||
|
||||
foreach ($routes as $route) {
|
||||
$this->assertStringStartsWith('/api/', $route['uri']);
|
||||
}
|
||||
|
||||
$names = array_column($routes, 'name');
|
||||
$this->assertNotContains('api.modules.gnuboard7-hello_module.admin.memos.store', $names);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 라우트_파일이_없는_범위는_빈_배열을_반환한다(): void
|
||||
{
|
||||
$routes = app(ApiRouteInventory::class)->collect('module:nonexistent-module-xyz');
|
||||
|
||||
$this->assertSame([], $routes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Support\ApiDoc;
|
||||
|
||||
use App\Support\ApiDoc\ParameterDescriber;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 요청 파라미터 설명기 단위 테스트.
|
||||
*
|
||||
* 도메인 무관하게 의미가 고정된 공통 파라미터(페이지네이션·정렬·검색·필터·
|
||||
* 리소스 식별자 등)의 설명이 위치/명명 규칙대로 채워지는지, 그리고 도메인 특이
|
||||
* 파라미터는 null(사람 서술 폴백)로 남는지 검증한다.
|
||||
*/
|
||||
class ParameterDescriberTest extends TestCase
|
||||
{
|
||||
#[Test]
|
||||
public function 공통_페이지네이션_정렬_파라미터를_정확_사전으로_설명한다(): void
|
||||
{
|
||||
$describer = new ParameterDescriber;
|
||||
|
||||
$this->assertStringContainsString('페이지 번호', $describer->describe('page', 'query', 'integer'));
|
||||
$this->assertStringContainsString('페이지당', $describer->describe('per_page', 'query', 'integer'));
|
||||
$this->assertStringContainsString('정렬 기준 필드', $describer->describe('sort_by', 'query', 'string'));
|
||||
$this->assertStringContainsString('검색어', $describer->describe('search', 'query', 'string'));
|
||||
$this->assertStringContainsString('필터', $describer->describe('filters', 'query', 'array'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 기간_토글_파라미터를_설명한다(): void
|
||||
{
|
||||
$describer = new ParameterDescriber;
|
||||
|
||||
$this->assertStringContainsString('시작일', $describer->describe('start_date', 'query', 'date'));
|
||||
$this->assertStringContainsString('종료일', $describer->describe('end_date', 'query', 'date'));
|
||||
$this->assertStringContainsString('활성', $describer->describe('is_active', 'query', 'boolean'));
|
||||
$this->assertStringContainsString('강제', $describer->describe('force', 'body', 'boolean'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function sort_order_는_타입으로_방향과_순서값을_구분한다(): void
|
||||
{
|
||||
$describer = new ParameterDescriber;
|
||||
|
||||
// 문자열 asc/desc → 정렬 방향
|
||||
$this->assertStringContainsString('정렬 방향', $describer->describe('sort_order', 'query', 'string'));
|
||||
$this->assertStringContainsString('정렬 방향', $describer->describe('order', 'query', 'string'));
|
||||
// 정수 → 표시 순서 값
|
||||
$this->assertStringContainsString('표시 정렬 순서', $describer->describe('sort_order', 'body', 'integer'));
|
||||
$this->assertStringContainsString('표시 정렬 순서', $describer->describe('order', 'body', 'integer'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function path_식별자_파라미터를_위치_기반으로_설명한다(): void
|
||||
{
|
||||
$describer = new ParameterDescriber;
|
||||
|
||||
$this->assertSame('대상 리소스의 식별자', $describer->describe('id', 'path', 'string'));
|
||||
$this->assertStringContainsString('slug', $describer->describe('slug', 'path', 'string'));
|
||||
$this->assertSame('대상 리소스의 식별자', $describer->describe('identifier', 'path', 'string'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function path_카멜케이스_식별자를_패턴으로_설명한다(): void
|
||||
{
|
||||
$describer = new ParameterDescriber;
|
||||
|
||||
// *Id → "대상 {base}의 식별자"
|
||||
$this->assertSame('대상 post의 식별자', $describer->describe('postId', 'path', 'string'));
|
||||
$this->assertSame('대상 product의 식별자', $describer->describe('productId', 'path', 'string'));
|
||||
// *Name → "대상 {base}의 이름 (식별자)"
|
||||
$this->assertStringContainsString('template', $describer->describe('templateName', 'path', 'string'));
|
||||
$this->assertStringContainsString('이름', $describer->describe('pluginName', 'path', 'string'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function path_bare_리소스명은_route_model_binding_식별자로_설명한다(): void
|
||||
{
|
||||
$describer = new ParameterDescriber;
|
||||
|
||||
// Laravel route-model binding 세그먼트(`/{definition}`, `/{menu}`, `/{role}`)는
|
||||
// 대상 모델의 단수형을 그대로 쓰므로 대상 리소스의 식별자로 서술한다.
|
||||
$this->assertSame('대상 definition의 식별자', $describer->describe('definition', 'path', 'string'));
|
||||
$this->assertSame('대상 menu의 식별자', $describer->describe('menu', 'path', 'string'));
|
||||
$this->assertSame('대상 role의 식별자', $describer->describe('role', 'path', 'string'));
|
||||
$this->assertSame('대상 schedule의 식별자', $describer->describe('schedule', 'path', 'string'));
|
||||
$this->assertSame('대상 challenge의 식별자', $describer->describe('challenge', 'path', 'string'));
|
||||
// camelCase route-model binding (activityLog, notificationLog)
|
||||
$this->assertSame('대상 activity log의 식별자', $describer->describe('activityLog', 'path', 'string'));
|
||||
// *Identifier 접미
|
||||
$this->assertSame('대상 template의 식별자', $describer->describe('templateIdentifier', 'path', 'string'));
|
||||
// key/version 은 리소스가 아니라 설정 키/버전 값
|
||||
$this->assertStringContainsString('키', $describer->describe('key', 'path', 'string'));
|
||||
$this->assertStringContainsString('버전', $describer->describe('version', 'path', 'string'));
|
||||
// bare path 리소스명은 자동 서술되므로 query/body 위치에서만 도메인 특이 판정이 유지된다
|
||||
$this->assertNull($describer->describe('definition', 'body', 'string'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 연관_식별자_snake_패턴을_설명한다(): void
|
||||
{
|
||||
$describer = new ParameterDescriber;
|
||||
|
||||
// query/body 의 *_id 는 연관 리소스 식별자 참조
|
||||
$this->assertSame('user 식별자', $describer->describe('user_id', 'body', 'integer'));
|
||||
$this->assertSame('shipping policy 식별자', $describer->describe('shipping_policy_id', 'query', 'integer'));
|
||||
// *_ids 는 배열
|
||||
$this->assertStringContainsString('배열', $describer->describe('product_ids', 'body', 'array'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 불리언_날짜_접미_패턴을_설명한다(): void
|
||||
{
|
||||
$describer = new ParameterDescriber;
|
||||
|
||||
$this->assertSame('featured 여부', $describer->describe('is_featured', 'query', 'boolean'));
|
||||
$this->assertSame('paid 날짜', $describer->describe('paid_date', 'body', 'date'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 프로필_콘텐츠_공통_필드를_설명한다(): void
|
||||
{
|
||||
$describer = new ParameterDescriber;
|
||||
|
||||
$this->assertStringContainsString('이름', $describer->describe('name', 'body', 'string'));
|
||||
$this->assertStringContainsString('닉네임', $describer->describe('nickname', 'body', 'string'));
|
||||
$this->assertStringContainsString('설명', $describer->describe('description', 'body', 'string'));
|
||||
$this->assertStringContainsString('본문', $describer->describe('content', 'body', 'array'));
|
||||
$this->assertStringContainsString('제목', $describer->describe('subject', 'body', 'array'));
|
||||
$this->assertStringContainsString('전화', $describer->describe('phone', 'body', 'string'));
|
||||
$this->assertStringContainsString('휴대전화', $describer->describe('mobile', 'body', 'string'));
|
||||
$this->assertStringContainsString('자기소개', $describer->describe('bio', 'body', 'string'));
|
||||
$this->assertStringContainsString('경로', $describer->describe('path', 'query', 'string'));
|
||||
$this->assertStringContainsString('사용자명', $describer->describe('username', 'body', 'string'));
|
||||
// collection: 첨부 컬렉션 그룹명 (근거: UploadAttachmentRequest collection ?? 'default')
|
||||
$this->assertStringContainsString('첨부 컬렉션', $describer->describe('collection', 'body', 'string'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 확장_버전_공통_파라미터를_설명한다(): void
|
||||
{
|
||||
$describer = new ParameterDescriber;
|
||||
|
||||
$this->assertStringContainsString('확장 유형', $describer->describe('extension_type', 'body', 'string'));
|
||||
$this->assertStringContainsString('확장 식별자', $describer->describe('extension_identifier', 'body', 'string'));
|
||||
$this->assertStringContainsString('시작 버전', $describer->describe('from_version', 'query', 'string'));
|
||||
$this->assertStringContainsString('대상 버전', $describer->describe('to_version', 'query', 'string'));
|
||||
$this->assertStringContainsString('GitHub', $describer->describe('github_url', 'body', 'string'));
|
||||
$this->assertStringContainsString('체크섬', $describer->describe('checksum', 'body', 'string'));
|
||||
$this->assertStringContainsString('자동 활성화', $describer->describe('auto_activate', 'body', 'boolean'));
|
||||
// query/body identifier 는 확장/리소스 식별자
|
||||
$this->assertStringContainsString('식별자', $describer->describe('identifier', 'query', 'string'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 확장_이름_snake_패턴을_설명한다(): void
|
||||
{
|
||||
$describer = new ParameterDescriber;
|
||||
|
||||
$this->assertStringContainsString('이름', $describer->describe('template_name', 'body', 'string'));
|
||||
$this->assertStringContainsString('이름', $describer->describe('plugin_name', 'body', 'string'));
|
||||
$this->assertStringContainsString('이름', $describer->describe('module_name', 'body', 'string'));
|
||||
$this->assertStringContainsString('이름', $describer->describe('layout_name', 'query', 'string'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 스케줄_작업_공통_파라미터를_설명한다(): void
|
||||
{
|
||||
$describer = new ParameterDescriber;
|
||||
|
||||
$this->assertStringContainsString('아티즌 커맨드', $describer->describe('command', 'body', 'string'));
|
||||
$this->assertStringContainsString('주기', $describer->describe('frequency', 'body', 'string'));
|
||||
$this->assertStringContainsString('타임아웃', $describer->describe('timeout', 'body', 'integer'));
|
||||
$this->assertStringContainsString('점검 모드', $describer->describe('run_in_maintenance', 'body', 'boolean'));
|
||||
$this->assertStringContainsString('중복 실행', $describer->describe('without_overlapping', 'body', 'boolean'));
|
||||
$this->assertStringContainsString('잠금 버전', $describer->describe('expected_lock_version', 'body', 'integer'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 메일_드라이버_설정_파라미터를_설명한다(): void
|
||||
{
|
||||
$describer = new ParameterDescriber;
|
||||
|
||||
$this->assertStringContainsString('메일 발송 드라이버', $describer->describe('mailer', 'body', 'string'));
|
||||
$this->assertStringContainsString('발신자 주소', $describer->describe('from_address', 'body', 'email'));
|
||||
$this->assertStringContainsString('호스트', $describer->describe('host', 'body', 'string'));
|
||||
$this->assertStringContainsString('포트', $describer->describe('port', 'body', 'integer'));
|
||||
$this->assertStringContainsString('스토리지 드라이버', $describer->describe('storage_driver', 'body', 'string'));
|
||||
$this->assertStringContainsString('S3 버킷', $describer->describe('s3_bucket', 'body', 'string'));
|
||||
$this->assertStringContainsString('Redis 호스트', $describer->describe('redis_host', 'body', 'string'));
|
||||
$this->assertStringContainsString('WebSocket', $describer->describe('websocket_scheme', 'body', 'string'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 도메인_특이_파라미터는_null_로_남긴다(): void
|
||||
{
|
||||
$describer = new ParameterDescriber;
|
||||
|
||||
// 사전/패턴에 없는 도메인 특이 파라미터는 사람 서술(TODO)로 폴백
|
||||
$this->assertNull($describer->describe('refund_priority', 'body', 'string'));
|
||||
$this->assertNull($describer->describe('temp_key', 'body', 'string'));
|
||||
// 도메인마다 의미가 갈리는 파라미터는 계속 TODO 유지
|
||||
$this->assertNull($describer->describe('channels', 'body', 'array'));
|
||||
$this->assertNull($describer->describe('purpose', 'body', 'string'));
|
||||
$this->assertNull($describer->describe('scope_type', 'body', 'string'));
|
||||
$this->assertNull($describer->describe('conditions', 'body', 'array'));
|
||||
$this->assertNull($describer->describe('marketing_consent', 'body', 'boolean'));
|
||||
// source_type 은 Enum 기반으로 도메인마다 값 집합이 달라 TODO 유지
|
||||
$this->assertNull($describer->describe('source_type', 'body', 'string'));
|
||||
// body(생성/수정)의 status/type/category 는 여전히 TODO
|
||||
$this->assertNull($describer->describe('status', 'body', 'string'));
|
||||
$this->assertNull($describer->describe('type', 'body', 'string'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 공통_콘텐츠_주소_seo_파라미터를_설명한다(): void
|
||||
{
|
||||
$describer = new ParameterDescriber;
|
||||
|
||||
// title: board 게시글/memo/inquiry/page 등 전 도메인에서 "제목"으로 고정
|
||||
// (근거: sirsoft-board/page/hello_module/ecommerce Store/Update Request)
|
||||
$this->assertStringContainsString('제목', $describer->describe('title', 'body', 'string'));
|
||||
// slug: URL 친화 식별자 (위치 무관 동일 의미)
|
||||
$this->assertStringContainsString('slug', $describer->describe('slug', 'body', 'string'));
|
||||
$this->assertStringContainsString('라벨', $describer->describe('label', 'body', 'string'));
|
||||
|
||||
// 주소 확장 (국제 주소 표준 — 도메인 무관)
|
||||
$this->assertStringContainsString('주소', $describer->describe('address_line_1', 'body', 'string'));
|
||||
$this->assertStringContainsString('주소', $describer->describe('address_line_2', 'body', 'string'));
|
||||
$this->assertStringContainsString('도시', $describer->describe('intl_city', 'body', 'string'));
|
||||
$this->assertStringContainsString('지역', $describer->describe('region', 'query', 'string'));
|
||||
|
||||
// SEO 메타 (검색엔진 노출용 — 도메인 무관)
|
||||
$this->assertStringContainsString('SEO', $describer->describe('meta_title', 'body', 'string'));
|
||||
$this->assertStringContainsString('SEO', $describer->describe('meta_description', 'body', 'string'));
|
||||
$this->assertStringContainsString('대체 텍스트', $describer->describe('alt_text', 'body', 'array'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Support\ApiDoc;
|
||||
|
||||
use App\Support\ApiDoc\ResourceFieldDescriber;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* 리소스 계약 필드 설명기 단위 테스트.
|
||||
*
|
||||
* 컬럼 주석이 없는 accessor/computed 필드(status_label, is_owner, *_at 등)의
|
||||
* 설명이 코드에서 확인된 의미대로 채워지는지 검증한다.
|
||||
*/
|
||||
class ResourceFieldDescriberTest extends TestCase
|
||||
{
|
||||
#[Test]
|
||||
public function 표준_메타_필드를_정확_사전으로_설명한다(): void
|
||||
{
|
||||
$describer = new ResourceFieldDescriber;
|
||||
|
||||
$this->assertStringContainsString('소유자', $describer->describe('is_owner', 'boolean'));
|
||||
$this->assertStringContainsString('작업 불리언 맵', $describer->describe('abilities', 'object'));
|
||||
$this->assertStringContainsString('Enum label()', $describer->describe('status_label', 'string'));
|
||||
$this->assertStringContainsString('관리자', $describer->describe('is_admin', 'boolean'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 타임스탬프_접미_패턴을_설명한다(): void
|
||||
{
|
||||
$describer = new ResourceFieldDescriber;
|
||||
|
||||
$this->assertSame('생성 일시', $describer->describe('created_at', 'string'));
|
||||
$this->assertSame('최종 수정 일시', $describer->describe('updated_at', 'string'));
|
||||
// 사전에 없는 *_at 는 패턴으로 유추
|
||||
$this->assertSame('email verified 일시', $describer->describe('email_verified_at', 'string'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function label_variant_접미_패턴을_설명한다(): void
|
||||
{
|
||||
$describer = new ResourceFieldDescriber;
|
||||
|
||||
$desc = $describer->describe('priority_label', 'string');
|
||||
$this->assertStringContainsString('priority', $desc);
|
||||
$this->assertStringContainsString('라벨', $desc);
|
||||
|
||||
$variant = $describer->describe('priority_variant', 'string');
|
||||
$this->assertStringContainsString('변형', $variant);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function can_접두는_능력_불리언으로_설명한다(): void
|
||||
{
|
||||
$describer = new ResourceFieldDescriber;
|
||||
|
||||
$desc = $describer->describe('can_update', 'boolean');
|
||||
$this->assertStringContainsString('update', $desc);
|
||||
$this->assertStringContainsString('수행 가능', $desc);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function is_has_접두_불리언을_설명한다(): void
|
||||
{
|
||||
$describer = new ResourceFieldDescriber;
|
||||
|
||||
$this->assertStringContainsString('여부', $describer->describe('is_default', 'boolean'));
|
||||
$this->assertStringContainsString('여부', $describer->describe('has_children', 'boolean'));
|
||||
// boolean 이 아니면 패턴 미적용 (오설명 방지)
|
||||
$this->assertNull($describer->describe('is_default', 'string'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function count_접미_집계를_설명한다(): void
|
||||
{
|
||||
$describer = new ResourceFieldDescriber;
|
||||
|
||||
$this->assertStringContainsString('개수', $describer->describe('user_count', 'integer'));
|
||||
// integer/number 가 아니면 미적용
|
||||
$this->assertNull($describer->describe('user_count', 'string'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 알_수_없는_필드는_null_을_반환한다(): void
|
||||
{
|
||||
$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 도메인 특이 필드는 제외
|
||||
$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'));
|
||||
$this->assertNull($describer->describe('code', 'string'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 관계_연관_객체_필드를_설명한다(): void
|
||||
{
|
||||
$describer = new ResourceFieldDescriber;
|
||||
|
||||
$this->assertStringContainsString('생성자', $describer->describe('creator', 'object'));
|
||||
$this->assertStringContainsString('하위', $describer->describe('children', 'array'));
|
||||
$this->assertStringContainsString('상위', $describer->describe('parent', 'object'));
|
||||
$this->assertStringContainsString('권한', $describer->describe('permissions', 'array'));
|
||||
$this->assertStringContainsString('수신자', $describer->describe('recipient', 'object'));
|
||||
$this->assertStringContainsString('발신자', $describer->describe('sender', 'object'));
|
||||
$this->assertStringContainsString('작성자', $describer->describe('author', 'object'));
|
||||
$this->assertStringContainsString('행위', $describer->describe('actor_name', 'string'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 공통_콘텐츠_표시_필드를_설명한다(): void
|
||||
{
|
||||
$describer = new ResourceFieldDescriber;
|
||||
|
||||
// 도메인 무관하게 역할이 고정된 공통 콘텐츠/표시 필드 (요청 파라미터 대응물)
|
||||
$this->assertStringContainsString('이름', $describer->describe('name', 'object'));
|
||||
$this->assertStringContainsString('제목', $describer->describe('title', 'string'));
|
||||
$this->assertStringContainsString('본문', $describer->describe('content', 'string'));
|
||||
$this->assertStringContainsString('설명', $describer->describe('description', 'object'));
|
||||
$this->assertStringContainsString('slug', $describer->describe('slug', 'string'));
|
||||
$this->assertStringContainsString('라벨', $describer->describe('label', 'string'));
|
||||
$this->assertStringContainsString('아이콘', $describer->describe('icon', 'string'));
|
||||
$this->assertStringContainsString('썸네일', $describer->describe('thumbnail', 'string'));
|
||||
$this->assertStringContainsString('IP', $describer->describe('ip_address', 'string'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function sort_order_는_타입으로_분기한다(): void
|
||||
{
|
||||
$describer = new ResourceFieldDescriber;
|
||||
|
||||
// 정수: 표시 정렬 순서 값
|
||||
$this->assertStringContainsString('정렬 순서', $describer->describe('sort_order', 'integer'));
|
||||
// 문자열: 정렬 방향일 수 있어 도메인 특이 → null (오설명 방지)
|
||||
$this->assertNull($describer->describe('sort_order', 'string'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 시스템_집계_필드를_설명한다(): void
|
||||
{
|
||||
$describer = new ResourceFieldDescriber;
|
||||
|
||||
$this->assertStringContainsString('전체', $describer->describe('total', 'integer'));
|
||||
$this->assertStringContainsString('사용자', $describer->describe('total_users', 'object'));
|
||||
$this->assertStringContainsString('상대 시각', $describer->describe('time', 'string'));
|
||||
$this->assertStringContainsString('서버', $describer->describe('server_time', 'string'));
|
||||
$this->assertStringContainsString('순번', $describer->describe('number', 'integer'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function 확장_버전_로케일_필드를_설명한다(): void
|
||||
{
|
||||
$describer = new ResourceFieldDescriber;
|
||||
|
||||
$this->assertStringContainsString('타입', $describer->describe('extension_type', 'string'));
|
||||
$this->assertStringContainsString('식별자', $describer->describe('extension_identifier', 'string'));
|
||||
$this->assertStringContainsString('이름', $describer->describe('extension_name', 'string'));
|
||||
$this->assertStringContainsString('GitHub', $describer->describe('github_url', 'string'));
|
||||
$this->assertStringContainsString('변경 이력', $describer->describe('changelog', 'string'));
|
||||
$this->assertStringContainsString('코어', $describer->describe('current_core_version', 'string'));
|
||||
$this->assertStringContainsString('로케일', $describer->describe('locales', 'array'));
|
||||
$this->assertStringContainsString('표시명', $describer->describe('locale_names', 'object'));
|
||||
$this->assertStringContainsString('차단', $describer->describe('install_blocked_reason', 'string'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function raw_접미_패턴은_원본_값으로_설명한다(): void
|
||||
{
|
||||
$describer = new ResourceFieldDescriber;
|
||||
|
||||
$nameRaw = $describer->describe('name_raw', 'string');
|
||||
$this->assertStringContainsString('name', $nameRaw);
|
||||
$this->assertStringContainsString('원본', $nameRaw);
|
||||
|
||||
$descRaw = $describer->describe('description_raw', 'string');
|
||||
$this->assertStringContainsString('description', $descRaw);
|
||||
$this->assertStringContainsString('원본', $descRaw);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function formatted_접미는_표시용_포맷_문자열로_설명한다(): void
|
||||
{
|
||||
$describer = new ResourceFieldDescriber;
|
||||
|
||||
// 근거: size_formatted accessor, formatCurrencyPrice/formatFileSize/
|
||||
// formatCreatedAtFormat — 통화·용량·일시 포맷 파생
|
||||
$created = $describer->describe('created_at_formatted', 'string');
|
||||
$this->assertStringContainsString('created_at', $created);
|
||||
$this->assertStringContainsString('포맷', $created);
|
||||
|
||||
$price = $describer->describe('selling_price_formatted', 'string');
|
||||
$this->assertStringContainsString('selling_price', $price);
|
||||
$this->assertStringContainsString('포맷', $price);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function localized_접두_접미는_로케일_해석_값으로_설명한다(): void
|
||||
{
|
||||
$describer = new ResourceFieldDescriber;
|
||||
|
||||
// 근거: getLocalizedName() / getLocalizedOptionName()
|
||||
$localizedName = $describer->describe('localized_name', 'string');
|
||||
$this->assertStringContainsString('name', $localizedName);
|
||||
$this->assertStringContainsString('로케일', $localizedName);
|
||||
|
||||
$optionLocalized = $describer->describe('option_name_localized', 'string');
|
||||
$this->assertStringContainsString('option name', $optionLocalized);
|
||||
$this->assertStringContainsString('로케일', $optionLocalized);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function url_접미는_리소스_url로_설명한다(): void
|
||||
{
|
||||
$describer = new ResourceFieldDescriber;
|
||||
|
||||
// 근거: thumbnail_url => download_url / getThumbnailUrl()
|
||||
$thumb = $describer->describe('thumbnail_url', 'string');
|
||||
$this->assertStringContainsString('thumbnail', $thumb);
|
||||
$this->assertStringContainsString('URL', $thumb);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function id_접미는_참조_식별자로_설명한다(): void
|
||||
{
|
||||
$describer = new ResourceFieldDescriber;
|
||||
|
||||
// 응답의 *_id 는 예외 없이 연관 리소스 참조 식별자다 (parent_id/user_id 등)
|
||||
$parent = $describer->describe('parent_id', 'integer');
|
||||
$this->assertStringContainsString('parent', $parent);
|
||||
$this->assertStringContainsString('식별자', $parent);
|
||||
|
||||
$ids = $describer->describe('permission_ids', 'array');
|
||||
$this->assertStringContainsString('permission', $ids);
|
||||
$this->assertStringContainsString('배열', $ids);
|
||||
|
||||
// 예외: login_id 는 참조 식별자가 아니라 로그인 계정 아이디(문자열) → TODO 유지
|
||||
$this->assertNull($describer->describe('user_login_id', 'string'));
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function depth_는_계층_트리_깊이로_설명한다(): void
|
||||
{
|
||||
$describer = new ResourceFieldDescriber;
|
||||
|
||||
// 근거: CommentResource/CategoryResource 의 depth (children/parent 트리)
|
||||
$depth = $describer->describe('depth', 'integer');
|
||||
$this->assertStringContainsString('깊이', $depth);
|
||||
// 정수가 아니면 미적용 (오설명 방지)
|
||||
$this->assertNull($describer->describe('depth', 'string'));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user