ExtractorTest.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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_deprecated_route_apply_rules()
  159. {
  160. $this->config['strategies']['responses'] = [Strategies\Responses\ResponseCalls::class];
  161. $route = $this->createRoute('GET', '/get', 'shouldFetchRouteResponse');
  162. $extractor = $this->makeExtractor();
  163. // Use the old routeApply rules rather than new settings
  164. $parsed = $extractor->processRoute($route, ['response_calls' => ['methods' => ['POST']]]);
  165. $this->assertEmpty($parsed->responses);
  166. $parsed = $extractor->processRoute($route, ['response_calls' => ['methods' => ['GET']]]);
  167. $this->assertNotEmpty($parsed->responses);
  168. }
  169. /** @test */
  170. public function invokes_strategy_based_on_new_strategy_configs()
  171. {
  172. $route = $this->createRoute('GET', '/get', 'shouldFetchRouteResponse');
  173. $this->config['strategies']['responses'] = [
  174. [
  175. Strategies\Responses\ResponseCalls::class,
  176. ['only' => 'POST *']
  177. ]
  178. ];
  179. $parsed = $this->process($route);
  180. $this->assertEmpty($parsed->responses);
  181. $this->config['strategies']['responses'] = [
  182. [
  183. Strategies\Responses\ResponseCalls::class,
  184. ['only' => 'GET *']
  185. ]
  186. ];
  187. $parsed = $this->process($route);
  188. $this->assertNotEmpty($parsed->responses);
  189. }
  190. /** @test */
  191. public function adds_override_for_headers_based_on_strategy_configs()
  192. {
  193. $route = $this->createRoute('GET', '/get', 'dummy');
  194. $this->config['strategies']['headers'] = [Strategies\Headers\GetFromHeaderAttribute::class];
  195. $parsed = $this->process($route);
  196. $this->assertEmpty($parsed->headers);
  197. $headers = [
  198. 'accept' => 'application/json',
  199. 'Content-Type' => 'application/json+vnd',
  200. ];
  201. $this->config['strategies']['headers'] = [
  202. Strategies\Headers\GetFromHeaderAttribute::class,
  203. [
  204. 'override', $headers
  205. ],
  206. ];
  207. $parsed = $this->process($route);
  208. $this->assertArraySubset($parsed->headers, $headers);
  209. }
  210. /**
  211. * @test
  212. * @dataProvider authRules
  213. */
  214. public function adds_appropriate_field_based_on_configured_auth_type($config, $expected)
  215. {
  216. $route = $this->createRouteOldSyntax('POST', '/withAuthenticatedTag', 'withAuthenticatedTag');
  217. $generator = $this->makeExtractor(array_merge($this->config, $config));
  218. $parsed = $generator->processRoute($route)->toArray();
  219. $this->assertNotNull($parsed[$expected['where']][$expected['name']]);
  220. $this->assertEquals($expected['where'], $parsed['auth'][0]);
  221. $this->assertEquals($expected['name'], $parsed['auth'][1]);
  222. }
  223. /** @test */
  224. public function generates_consistent_examples_when_faker_seed_is_set()
  225. {
  226. $route = $this->createRouteOldSyntax('POST', '/withBodyParameters', 'withBodyParameters');
  227. $paramName = 'room_id';
  228. $results = [];
  229. $results[$this->process($route)->cleanBodyParameters[$paramName]] = true;
  230. $results[$this->process($route)->cleanBodyParameters[$paramName]] = true;
  231. $results[$this->process($route)->cleanBodyParameters[$paramName]] = true;
  232. $results[$this->process($route)->cleanBodyParameters[$paramName]] = true;
  233. $results[$this->process($route)->cleanBodyParameters[$paramName]] = true;
  234. // Examples should have different values
  235. $this->assertNotCount(1, $results);
  236. $generator = $this->makeExtractor($this->config + ['examples' => ['faker_seed' => 12345]]);
  237. $results = [];
  238. $results[$generator->processRoute($route)->cleanBodyParameters[$paramName]] = true;
  239. $results[$generator->processRoute($route)->cleanBodyParameters[$paramName]] = true;
  240. $results[$generator->processRoute($route)->cleanBodyParameters[$paramName]] = true;
  241. $results[$generator->processRoute($route)->cleanBodyParameters[$paramName]] = true;
  242. // Examples should have same values
  243. $this->assertCount(1, $results);
  244. }
  245. /** @test */
  246. public function can_use_arrays_in_routes_uses()
  247. {
  248. $route = $this->createRoute('GET', '/api/array/test', 'withEndpointDescription');
  249. $parsed = $this->process($route);
  250. $this->assertSame('Example title.', $parsed->metadata->title);
  251. $this->assertSame("This will be the long description.\nIt can also be multiple lines long.", $parsed->metadata->description);
  252. }
  253. /** @test */
  254. public function can_use_closure_in_routes_uses()
  255. {
  256. /**
  257. * A short title.
  258. * A longer description.
  259. * Can be multiple lines.
  260. *
  261. * @queryParam location_id required The id of the location.
  262. * @bodyParam name required Name of the location
  263. */
  264. $handler = fn() => 'hi';
  265. $route = $this->createClosureRoute('POST', '/api/closure/test', $handler);
  266. $parsed = $this->process($route);
  267. $this->assertSame('A short title.', $parsed->metadata->title);
  268. $this->assertSame("A longer description.\nCan be multiple lines.", $parsed->metadata->description);
  269. $this->assertCount(1, $parsed->queryParameters);
  270. $this->assertCount(1, $parsed->bodyParameters);
  271. $this->assertSame('The id of the location.', $parsed->queryParameters['location_id']->description);
  272. $this->assertSame('Name of the location', $parsed->bodyParameters['name']->description);
  273. }
  274. /** @test */
  275. public function endpoint_metadata_supports_custom_declarations()
  276. {
  277. $route = $this->createRouteOldSyntax('POST', '/api/test', 'dummy');
  278. $parsed = $this->process($route);
  279. $this->assertSame('some custom metadata', $parsed->metadata->custom['myProperty']);
  280. }
  281. /** @test */
  282. public function can_override_data_for_inherited_methods()
  283. {
  284. $route = $this->createRoute('POST', '/api/test', 'endpoint', TestParentController::class);
  285. $parent = $this->process($route);
  286. $this->assertSame('Parent title', $parent->metadata->title);
  287. $this->assertSame('Parent group name', $parent->metadata->groupName);
  288. $this->assertSame('Parent description', $parent->metadata->description);
  289. $this->assertCount(1, $parent->responses);
  290. $this->assertCount(1, $parent->bodyParameters);
  291. $this->assertArraySubset(["type" => "integer"], $parent->bodyParameters['thing']->toArray());
  292. $this->assertEmpty($parent->queryParameters);
  293. $inheritedRoute = $this->createRoute('POST', '/api/test', 'endpoint', TestInheritedController::class);
  294. $inherited = $this->process($inheritedRoute);
  295. $this->assertSame('Overridden title', $inherited->metadata->title);
  296. $this->assertSame('Overridden group name', $inherited->metadata->groupName);
  297. $this->assertSame('Parent description', $inherited->metadata->description);
  298. $this->assertCount(0, $inherited->responses);
  299. $this->assertCount(2, $inherited->bodyParameters);
  300. $this->assertArraySubset(["type" => "integer"], $inherited->bodyParameters['thing']->toArray());
  301. $this->assertArraySubset(["type" => "string"], $inherited->bodyParameters["other_thing"]->toArray());
  302. $this->assertCount(1, $inherited->queryParameters);
  303. $this->assertArraySubset(["type" => "string"], $inherited->queryParameters["queryThing"]->toArray());
  304. }
  305. public function createRoute(string $httpMethod, string $path, string $controllerMethod, $class = TestController::class): Route
  306. {
  307. return new Route([$httpMethod], $path, ['uses' => [$class, $controllerMethod]]);
  308. }
  309. /** Uses the old Laravel syntax. I doubt anyone still uses it today, but no harm done. */
  310. public function createRouteOldSyntax(string $httpMethod, string $path, string $controllerMethod, $class = TestController::class): Route
  311. {
  312. return new Route([$httpMethod], $path, ['uses' => "$class@$controllerMethod"]);
  313. }
  314. public function createClosureRoute(string $httpMethod, string $path, callable $handler): Route
  315. {
  316. return new Route([$httpMethod], $path, ['uses' => $handler]);
  317. }
  318. public static function authRules()
  319. {
  320. return [
  321. [
  322. [
  323. 'auth' => [
  324. 'enabled' => true,
  325. 'in' => 'bearer',
  326. 'name' => 'dfadb',
  327. ],
  328. ],
  329. [
  330. 'name' => 'Authorization',
  331. 'where' => 'headers',
  332. ],
  333. ],
  334. [
  335. [
  336. 'auth' => [
  337. 'enabled' => true,
  338. 'in' => 'basic',
  339. 'name' => 'efwr',
  340. ],
  341. ],
  342. [
  343. 'name' => 'Authorization',
  344. 'where' => 'headers',
  345. ],
  346. ],
  347. [
  348. [
  349. 'auth' => [
  350. 'enabled' => true,
  351. 'in' => 'header',
  352. 'name' => 'Api-Key',
  353. ],
  354. ],
  355. [
  356. 'name' => 'Api-Key',
  357. 'where' => 'headers',
  358. ],
  359. ],
  360. [
  361. [
  362. 'auth' => [
  363. 'enabled' => true,
  364. 'in' => 'query',
  365. 'name' => 'apiKey',
  366. ],
  367. ],
  368. [
  369. 'name' => 'apiKey',
  370. 'where' => 'queryParameters',
  371. ],
  372. ],
  373. [
  374. [
  375. 'auth' => [
  376. 'enabled' => true,
  377. 'in' => 'body',
  378. 'name' => 'access_token',
  379. ],
  380. ],
  381. [
  382. 'name' => 'access_token',
  383. 'where' => 'bodyParameters',
  384. ],
  385. ],
  386. ];
  387. }
  388. protected function process(Route $route, mixed $config = null): ExtractedEndpointData
  389. {
  390. $extractor = $this->makeExtractor($config);
  391. return $extractor->processRoute($route);
  392. }
  393. protected function makeExtractor(mixed $config = null): Extractor
  394. {
  395. return new Extractor(new DocumentationConfig($config ?: $this->config));
  396. }
  397. }
  398. class TestParentController
  399. {
  400. /**
  401. * Parent title
  402. *
  403. * Parent description
  404. *
  405. * @group Parent group name
  406. *
  407. * @bodyParam thing integer
  408. * @response {"hello":"there"}
  409. */
  410. public function endpoint()
  411. {
  412. }
  413. }
  414. class TestInheritedController extends TestParentController
  415. {
  416. public static function inheritedDocsOverrides()
  417. {
  418. return [
  419. "endpoint" => [
  420. "metadata" => [
  421. "title" => "Overridden title",
  422. "groupName" => "Overridden group name",
  423. ],
  424. "queryParameters" => function (ExtractedEndpointData $endpointData) {
  425. // Overrides
  426. return [
  427. 'queryThing' => [
  428. 'type' => 'string',
  429. ],
  430. ];
  431. },
  432. "bodyParameters" => [
  433. // Merges
  434. "other_thing" => [
  435. "type" => "string",
  436. ],
  437. ],
  438. "responses" => function (ExtractedEndpointData $endpointData) {
  439. // Completely overrides responses
  440. return [];
  441. },
  442. ],
  443. ];
  444. }
  445. }