ExtractorTest.php 17 KB

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