ExtractorTest.php 18 KB

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