ExtractorTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. <?php
  2. namespace Knuckles\Scribe\Tests\Unit;
  3. use Illuminate\Routing\Route;
  4. use Knuckles\Camel\Extraction\ExtractedEndpointData;
  5. use Knuckles\Camel\Extraction\Parameter;
  6. use Knuckles\Scribe\Extracting\Extractor;
  7. use Knuckles\Scribe\Extracting\Strategies;
  8. use Knuckles\Scribe\Tests\BaseLaravelTest;
  9. use Knuckles\Scribe\Tests\BaseUnitTest;
  10. use Knuckles\Scribe\Tests\Fixtures\TestController;
  11. use Knuckles\Scribe\Tools\DocumentationConfig;
  12. class ExtractorTest extends BaseLaravelTest
  13. {
  14. protected array $config = [
  15. 'strategies' => [
  16. 'metadata' => [
  17. Strategies\Metadata\GetFromDocBlocks::class,
  18. \Knuckles\Scribe\Tests\Fixtures\TestCustomEndpointMetadata::class,
  19. ],
  20. 'urlParameters' => [
  21. Strategies\UrlParameters\GetFromLaravelAPI::class,
  22. Strategies\UrlParameters\GetFromUrlParamTag::class,
  23. ],
  24. 'queryParameters' => [
  25. Strategies\QueryParameters\GetFromQueryParamTag::class,
  26. ],
  27. 'headers' => [
  28. Strategies\Headers\GetFromHeaderTag::class,
  29. ],
  30. 'bodyParameters' => [
  31. Strategies\BodyParameters\GetFromBodyParamTag::class,
  32. ],
  33. 'responses' => [
  34. Strategies\Responses\UseResponseTag::class,
  35. Strategies\Responses\UseResponseFileTag::class,
  36. ],
  37. 'responseFields' => [
  38. Strategies\ResponseFields\GetFromResponseFieldTag::class,
  39. ],
  40. ],
  41. ];
  42. /** @test */
  43. public function clean_can_properly_parse_array_keys()
  44. {
  45. $parameters = Parameter::arrayOf([
  46. 'object' => [
  47. 'name' => 'object',
  48. 'type' => 'object',
  49. 'example' => [],
  50. ],
  51. 'object.key1' => [
  52. 'name' => 'object.key1',
  53. 'type' => 'string',
  54. 'example' => '43',
  55. ],
  56. 'object.key2' => [
  57. 'name' => 'object.key2',
  58. 'type' => 'integer',
  59. 'example' => 77,
  60. ],
  61. 'object.key3' => [
  62. 'name' => 'object.key3',
  63. 'type' => 'object',
  64. 'example' => [],
  65. ],
  66. 'object.key3.key1' => [
  67. 'name' => 'object.key3.key1',
  68. 'type' => 'string',
  69. 'example' => 'hoho',
  70. ],
  71. 'list' => [
  72. 'name' => 'list',
  73. 'type' => 'integer[]',
  74. 'example' => [4],
  75. ],
  76. 'list_of_objects' => [
  77. 'name' => 'list_of_objects',
  78. 'type' => 'object[]',
  79. 'example' => [[]],
  80. ],
  81. 'list_of_objects[].key1' => [
  82. 'name' => 'list_of_objects.key1',
  83. 'type' => 'string',
  84. 'required' => true,
  85. 'example' => 'John',
  86. ],
  87. 'list_of_objects[].key2' => [
  88. 'name' => 'list_of_objects.key2',
  89. 'type' => 'boolean',
  90. 'required' => true,
  91. 'example' => false,
  92. ],
  93. ]);
  94. $cleanBodyParameters = Extractor::cleanParams($parameters);
  95. $this->assertEquals([
  96. 'object' => [
  97. 'key1' => '43',
  98. 'key2' => 77,
  99. 'key3' => [
  100. 'key1' => 'hoho',
  101. ],
  102. ],
  103. 'list' => [4],
  104. 'list_of_objects' => [
  105. [
  106. 'key1' => 'John',
  107. 'key2' => false,
  108. ],
  109. ],
  110. ], $cleanBodyParameters);
  111. }
  112. /** @test */
  113. public function does_not_generate_values_for_excluded_params_and_excludes_them_from_clean_params()
  114. {
  115. $route = $this->createRouteOldSyntax('POST', '/api/test', 'withExcludedExamples');
  116. $parsed = $this->process($route)->toArray();
  117. $cleanBodyParameters = $parsed['cleanBodyParameters'];
  118. $cleanQueryParameters = $parsed['cleanQueryParameters'];
  119. $bodyParameters = $parsed['bodyParameters'];
  120. $queryParameters = $parsed['queryParameters'];
  121. $this->assertArrayHasKey('included', $cleanBodyParameters);
  122. $this->assertArrayNotHasKey('excluded_body_param', $cleanBodyParameters);
  123. $this->assertEmpty($cleanQueryParameters);
  124. $this->assertArraySubset([
  125. 'included' => [
  126. 'required' => true,
  127. 'type' => 'string',
  128. 'description' => 'Exists in examples.',
  129. ],
  130. 'excluded_body_param' => [
  131. 'type' => 'integer',
  132. 'description' => 'Does not exist in examples.',
  133. ],
  134. ], $bodyParameters);
  135. $this->assertArraySubset([
  136. 'excluded_query_param' => [
  137. 'description' => 'Does not exist in examples.',
  138. ],
  139. ], $queryParameters);
  140. }
  141. /** @test */
  142. public function can_parse_route_methods()
  143. {
  144. $route = $this->createRouteOldSyntax('GET', '/get', 'withEndpointDescription');
  145. $parsed = $this->process($route);
  146. $this->assertEquals(['GET'], $parsed->httpMethods);
  147. $route = $this->createRouteOldSyntax('POST', '/post', 'withEndpointDescription');
  148. $parsed = $this->process($route);
  149. $this->assertEquals(['POST'], $parsed->httpMethods);
  150. $route = $this->createRouteOldSyntax('PUT', '/put', 'withEndpointDescription');
  151. $parsed = $this->process($route);
  152. $this->assertEquals(['PUT'], $parsed->httpMethods);
  153. $route = $this->createRouteOldSyntax('DELETE', '/delete', 'withEndpointDescription');
  154. $parsed = $this->process($route);
  155. $this->assertEquals(['DELETE'], $parsed->httpMethods);
  156. }
  157. /** @test */
  158. public function invokes_strategy_based_on_new_strategy_configs()
  159. {
  160. $route = $this->createRoute('GET', '/get', 'shouldFetchRouteResponse');
  161. $this->config['strategies']['responses'] = [
  162. [
  163. Strategies\Responses\ResponseCalls::class,
  164. ['only' => 'POST *']
  165. ]
  166. ];
  167. $parsed = $this->process($route);
  168. $this->assertEmpty($parsed->responses);
  169. $this->config['strategies']['responses'] = [
  170. [
  171. Strategies\Responses\ResponseCalls::class,
  172. ['only' => 'GET *']
  173. ]
  174. ];
  175. $parsed = $this->process($route);
  176. $this->assertNotEmpty($parsed->responses);
  177. }
  178. /** @test */
  179. public function overrides_headers_based_on_short_strategy_config()
  180. {
  181. $route = $this->createRoute('GET', '/get', 'dummy');
  182. $this->config['strategies']['headers'] = [Strategies\Headers\GetFromHeaderAttribute::class];
  183. $parsed = $this->process($route);
  184. $this->assertEmpty($parsed->headers);
  185. $headers = [
  186. 'accept' => 'application/json',
  187. 'Content-Type' => 'application/json+vnd',
  188. ];
  189. $this->config['strategies']['headers'] = [
  190. Strategies\Headers\GetFromHeaderAttribute::class,
  191. [
  192. 'static_data', $headers
  193. ],
  194. ];
  195. $parsed = $this->process($route);
  196. $this->assertArraySubset($parsed->headers, $headers);
  197. }
  198. /** @test */
  199. public function overrides_headers_based_on_extended_strategy_config()
  200. {
  201. $route = $this->createRoute('GET', '/get', 'dummy');
  202. $this->config['strategies']['headers'] = [Strategies\Headers\GetFromHeaderAttribute::class];
  203. $parsed = $this->process($route);
  204. $this->assertEmpty($parsed->headers);
  205. $headers = [
  206. 'accept' => 'application/json',
  207. 'Content-Type' => 'application/json+vnd',
  208. ];
  209. $this->config['strategies']['headers'] = [
  210. Strategies\Headers\GetFromHeaderAttribute::class,
  211. ['static_data', ['data' => $headers, 'only' => ['GET *']]],
  212. ];
  213. $parsed = $this->process($route);
  214. $this->assertArraySubset($parsed->headers, $headers);
  215. $this->config['strategies']['headers'] = [
  216. Strategies\Headers\GetFromHeaderAttribute::class,
  217. ['static_data', ['data' => $headers, 'only' => [], 'except' => ['GET *']]],
  218. ];
  219. $parsed = $this->process($route);
  220. $this->assertEmpty($parsed->headers);
  221. }
  222. /** @test */
  223. public function overrides_headers_based_on_full_strategy_config()
  224. {
  225. $route = $this->createRoute('GET', '/get', 'dummy');
  226. $this->config['strategies']['headers'] = [Strategies\Headers\GetFromHeaderAttribute::class];
  227. $parsed = $this->process($route);
  228. $this->assertEmpty($parsed->headers);
  229. $headers = [
  230. 'accept' => 'application/json',
  231. 'Content-Type' => 'application/json+vnd',
  232. ];
  233. $this->config['strategies']['headers'] = [
  234. Strategies\Headers\GetFromHeaderAttribute::class,
  235. Strategies\StaticData::withSettings(only: ['GET *'], data: $headers),
  236. ];
  237. $parsed = $this->process($route);
  238. $this->assertArraySubset($parsed->headers, $headers);
  239. $this->config['strategies']['headers'] = [
  240. Strategies\Headers\GetFromHeaderAttribute::class,
  241. Strategies\StaticData::withSettings(except: ['GET *'], data: $headers),
  242. ];
  243. $parsed = $this->process($route);
  244. $this->assertEmpty($parsed->headers);
  245. }
  246. /**
  247. * @test
  248. * @dataProvider authRules
  249. */
  250. public function adds_appropriate_field_based_on_configured_auth_type($config, $expected)
  251. {
  252. $route = $this->createRouteOldSyntax('POST', '/withAuthenticatedTag', 'withAuthenticatedTag');
  253. $generator = $this->makeExtractor(array_merge($this->config, $config));
  254. $parsed = $generator->processRoute($route)->toArray();
  255. $this->assertNotNull($parsed[$expected['where']][$expected['name']]);
  256. $this->assertEquals($expected['where'], $parsed['auth'][0]);
  257. $this->assertEquals($expected['name'], $parsed['auth'][1]);
  258. }
  259. /** @test */
  260. public function generates_consistent_examples_when_faker_seed_is_set()
  261. {
  262. $route = $this->createRouteOldSyntax('POST', '/withBodyParameters', 'withBodyParameters');
  263. $paramName = 'room_id';
  264. $results = [];
  265. $results[$this->process($route)->cleanBodyParameters[$paramName]] = true;
  266. $results[$this->process($route)->cleanBodyParameters[$paramName]] = true;
  267. $results[$this->process($route)->cleanBodyParameters[$paramName]] = true;
  268. $results[$this->process($route)->cleanBodyParameters[$paramName]] = true;
  269. $results[$this->process($route)->cleanBodyParameters[$paramName]] = true;
  270. // Examples should have different values
  271. $this->assertNotCount(1, $results);
  272. $generator = $this->makeExtractor($this->config + ['examples' => ['faker_seed' => 12345]]);
  273. $results = [];
  274. $results[$generator->processRoute($route)->cleanBodyParameters[$paramName]] = true;
  275. $results[$generator->processRoute($route)->cleanBodyParameters[$paramName]] = true;
  276. $results[$generator->processRoute($route)->cleanBodyParameters[$paramName]] = true;
  277. $results[$generator->processRoute($route)->cleanBodyParameters[$paramName]] = true;
  278. // Examples should have same values
  279. $this->assertCount(1, $results);
  280. }
  281. /** @test */
  282. public function can_use_arrays_in_routes_uses()
  283. {
  284. $route = $this->createRoute('GET', '/api/array/test', 'withEndpointDescription');
  285. $parsed = $this->process($route);
  286. $this->assertSame('Example title.', $parsed->metadata->title);
  287. $this->assertSame("This will be the long description.\nIt can also be multiple lines long.", $parsed->metadata->description);
  288. }
  289. /** @test */
  290. public function can_use_closure_in_routes_uses()
  291. {
  292. /**
  293. * A short title.
  294. * A longer description.
  295. * Can be multiple lines.
  296. *
  297. * @queryParam location_id required The id of the location.
  298. * @bodyParam name required Name of the location
  299. */
  300. $handler = fn() => 'hi';
  301. $route = $this->createClosureRoute('POST', '/api/closure/test', $handler);
  302. $parsed = $this->process($route);
  303. $this->assertSame('A short title.', $parsed->metadata->title);
  304. $this->assertSame("A longer description.\nCan be multiple lines.", $parsed->metadata->description);
  305. $this->assertCount(1, $parsed->queryParameters);
  306. $this->assertCount(1, $parsed->bodyParameters);
  307. $this->assertSame('The id of the location.', $parsed->queryParameters['location_id']->description);
  308. $this->assertSame('Name of the location', $parsed->bodyParameters['name']->description);
  309. }
  310. /** @test */
  311. public function endpoint_metadata_supports_custom_declarations()
  312. {
  313. $route = $this->createRouteOldSyntax('POST', '/api/test', 'dummy');
  314. $parsed = $this->process($route);
  315. $this->assertSame('some custom metadata', $parsed->metadata->custom['myProperty']);
  316. }
  317. /** @test */
  318. public function can_override_data_for_inherited_methods()
  319. {
  320. $route = $this->createRoute('POST', '/api/test', 'endpoint', TestParentController::class);
  321. $parent = $this->process($route);
  322. $this->assertSame('Parent title', $parent->metadata->title);
  323. $this->assertSame('Parent group name', $parent->metadata->groupName);
  324. $this->assertSame('Parent description', $parent->metadata->description);
  325. $this->assertCount(1, $parent->responses);
  326. $this->assertCount(1, $parent->bodyParameters);
  327. $this->assertArraySubset(["type" => "integer"], $parent->bodyParameters['thing']->toArray());
  328. $this->assertEmpty($parent->queryParameters);
  329. $inheritedRoute = $this->createRoute('POST', '/api/test', 'endpoint', TestInheritedController::class);
  330. $inherited = $this->process($inheritedRoute);
  331. $this->assertSame('Overridden title', $inherited->metadata->title);
  332. $this->assertSame('Overridden group name', $inherited->metadata->groupName);
  333. $this->assertSame('Parent description', $inherited->metadata->description);
  334. $this->assertCount(0, $inherited->responses);
  335. $this->assertCount(2, $inherited->bodyParameters);
  336. $this->assertArraySubset(["type" => "integer"], $inherited->bodyParameters['thing']->toArray());
  337. $this->assertArraySubset(["type" => "string"], $inherited->bodyParameters["other_thing"]->toArray());
  338. $this->assertCount(1, $inherited->queryParameters);
  339. $this->assertArraySubset(["type" => "string"], $inherited->queryParameters["queryThing"]->toArray());
  340. }
  341. public function createRoute(string $httpMethod, string $path, string $controllerMethod, $class = TestController::class): Route
  342. {
  343. return new Route([$httpMethod], $path, ['uses' => [$class, $controllerMethod]]);
  344. }
  345. /** Uses the old Laravel syntax. I doubt anyone still uses it today, but no harm done. */
  346. public function createRouteOldSyntax(string $httpMethod, string $path, string $controllerMethod, $class = TestController::class): Route
  347. {
  348. return new Route([$httpMethod], $path, ['uses' => "$class@$controllerMethod"]);
  349. }
  350. public function createClosureRoute(string $httpMethod, string $path, callable $handler): Route
  351. {
  352. return new Route([$httpMethod], $path, ['uses' => $handler]);
  353. }
  354. public static function authRules()
  355. {
  356. return [
  357. [
  358. [
  359. 'auth' => [
  360. 'enabled' => true,
  361. 'in' => 'bearer',
  362. 'name' => 'dfadb',
  363. ],
  364. ],
  365. [
  366. 'name' => 'Authorization',
  367. 'where' => 'headers',
  368. ],
  369. ],
  370. [
  371. [
  372. 'auth' => [
  373. 'enabled' => true,
  374. 'in' => 'basic',
  375. 'name' => 'efwr',
  376. ],
  377. ],
  378. [
  379. 'name' => 'Authorization',
  380. 'where' => 'headers',
  381. ],
  382. ],
  383. [
  384. [
  385. 'auth' => [
  386. 'enabled' => true,
  387. 'in' => 'header',
  388. 'name' => 'Api-Key',
  389. ],
  390. ],
  391. [
  392. 'name' => 'Api-Key',
  393. 'where' => 'headers',
  394. ],
  395. ],
  396. [
  397. [
  398. 'auth' => [
  399. 'enabled' => true,
  400. 'in' => 'query',
  401. 'name' => 'apiKey',
  402. ],
  403. ],
  404. [
  405. 'name' => 'apiKey',
  406. 'where' => 'queryParameters',
  407. ],
  408. ],
  409. [
  410. [
  411. 'auth' => [
  412. 'enabled' => true,
  413. 'in' => 'body',
  414. 'name' => 'access_token',
  415. ],
  416. ],
  417. [
  418. 'name' => 'access_token',
  419. 'where' => 'bodyParameters',
  420. ],
  421. ],
  422. ];
  423. }
  424. protected function process(Route $route, mixed $config = null): ExtractedEndpointData
  425. {
  426. $extractor = $this->makeExtractor($config);
  427. return $extractor->processRoute($route);
  428. }
  429. protected function makeExtractor(mixed $config = null): Extractor
  430. {
  431. return new Extractor(new DocumentationConfig($config ?: $this->config));
  432. }
  433. }
  434. class TestParentController
  435. {
  436. /**
  437. * Parent title
  438. *
  439. * Parent description
  440. *
  441. * @group Parent group name
  442. *
  443. * @bodyParam thing integer
  444. * @response {"hello":"there"}
  445. */
  446. public function endpoint()
  447. {
  448. }
  449. }
  450. class TestInheritedController extends TestParentController
  451. {
  452. public static function inheritedDocsOverrides()
  453. {
  454. return [
  455. "endpoint" => [
  456. "metadata" => [
  457. "title" => "Overridden title",
  458. "groupName" => "Overridden group name",
  459. ],
  460. "queryParameters" => function (ExtractedEndpointData $endpointData) {
  461. // Overrides
  462. return [
  463. 'queryThing' => [
  464. 'type' => 'string',
  465. ],
  466. ];
  467. },
  468. "bodyParameters" => [
  469. // Merges
  470. "other_thing" => [
  471. "type" => "string",
  472. ],
  473. ],
  474. "responses" => function (ExtractedEndpointData $endpointData) {
  475. // Completely overrides responses
  476. return [];
  477. },
  478. ],
  479. ];
  480. }
  481. }