ExtractorTest.php 18 KB

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