ExtractorTest.php 15 KB

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