ExtractorTest.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. 'override', $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. ['override', ['with' => $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. ['override', ['with' => $headers, 'only' => [], 'except' => ['GET *']]],
  218. ];
  219. $parsed = $this->process($route);
  220. $this->assertEmpty($parsed->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. }