GeneratorTestCase.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. <?php
  2. namespace Knuckles\Scribe\Tests\Unit;
  3. use DMS\PHPUnitExtensions\ArraySubset\ArraySubsetAsserts;
  4. use Illuminate\Support\Arr;
  5. use Knuckles\Scribe\ScribeServiceProvider;
  6. use Knuckles\Scribe\Extracting\Generator;
  7. use Knuckles\Scribe\Tests\Fixtures\TestController;
  8. use Knuckles\Scribe\Tools\DocumentationConfig;
  9. use Orchestra\Testbench\TestCase;
  10. abstract class GeneratorTestCase extends TestCase
  11. {
  12. use ArraySubsetAsserts;
  13. /**
  14. * @var \Knuckles\Scribe\Extracting\Generator
  15. */
  16. protected $generator;
  17. private $config = [
  18. 'strategies' => [
  19. 'metadata' => [
  20. \Knuckles\Scribe\Extracting\Strategies\Metadata\GetFromDocBlocks::class,
  21. ],
  22. 'urlParameters' => [
  23. \Knuckles\Scribe\Extracting\Strategies\UrlParameters\GetFromUrlParamTag::class,
  24. ],
  25. 'queryParameters' => [
  26. \Knuckles\Scribe\Extracting\Strategies\QueryParameters\GetFromQueryParamTag::class,
  27. ],
  28. 'headers' => [
  29. \Knuckles\Scribe\Extracting\Strategies\Headers\GetFromRouteRules::class,
  30. ],
  31. 'bodyParameters' => [
  32. \Knuckles\Scribe\Extracting\Strategies\BodyParameters\GetFromBodyParamTag::class,
  33. ],
  34. 'responses' => [
  35. \Knuckles\Scribe\Extracting\Strategies\Responses\UseTransformerTags::class,
  36. \Knuckles\Scribe\Extracting\Strategies\Responses\UseResponseTag::class,
  37. \Knuckles\Scribe\Extracting\Strategies\Responses\UseResponseFileTag::class,
  38. \Knuckles\Scribe\Extracting\Strategies\Responses\UseApiResourceTags::class,
  39. \Knuckles\Scribe\Extracting\Strategies\Responses\ResponseCalls::class,
  40. ],
  41. 'responseFields' => [
  42. \Knuckles\Scribe\Extracting\Strategies\ResponseFields\GetFromResponseFieldTag::class,
  43. ],
  44. ],
  45. 'default_group' => 'general',
  46. ];
  47. public static $globalValue = null;
  48. protected function getPackageProviders($app)
  49. {
  50. return [
  51. ScribeServiceProvider::class,
  52. ];
  53. }
  54. /**
  55. * Setup the test environment.
  56. */
  57. public function setUp(): void
  58. {
  59. parent::setUp();
  60. $this->generator = new Generator(new DocumentationConfig($this->config));
  61. }
  62. /** @test */
  63. public function clean_can_properly_parse_array_keys()
  64. {
  65. $parameters = [
  66. 'object' => [
  67. 'type' => 'object',
  68. 'value' => [],
  69. ],
  70. 'object_with_keys.key1' => [
  71. 'type' => 'string',
  72. 'value' => '43',
  73. ],
  74. 'object_with_keys[key2]' => [
  75. 'type' => 'integer',
  76. 'value' => 77,
  77. ],
  78. 'list' => [
  79. 'type' => 'array',
  80. 'value' => [],
  81. ],
  82. 'list_with_types.*' => [
  83. 'type' => 'integer',
  84. 'value' => 4,
  85. ],
  86. 'list_of_objects.*.key1' => [
  87. 'type' => 'string',
  88. 'value' => 'John',
  89. ],
  90. 'list_of_objects.*.key2' => [
  91. 'type' => 'boolean',
  92. 'value' => false,
  93. ],
  94. ];
  95. $cleanBodyParameters = Generator::cleanParams($parameters);
  96. $this->assertEquals([
  97. 'object' => [],
  98. 'object_with_keys' => [
  99. 'key1' => '43',
  100. 'key2' => 77,
  101. ],
  102. 'list' => [],
  103. 'list_with_types' => [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->createRoute('GET', '/api/test', 'withExcludedExamples');
  116. $parsed = $this->generator->processRoute($route);
  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->createRoute('GET', '/get', 'withEndpointDescription');
  145. $parsed = $this->generator->processRoute($route);
  146. $this->assertEquals(['GET'], $parsed['methods']);
  147. $route = $this->createRoute('POST', '/post', 'withEndpointDescription');
  148. $parsed = $this->generator->processRoute($route);
  149. $this->assertEquals(['POST'], $parsed['methods']);
  150. $route = $this->createRoute('PUT', '/put', 'withEndpointDescription');
  151. $parsed = $this->generator->processRoute($route);
  152. $this->assertEquals(['PUT'], $parsed['methods']);
  153. $route = $this->createRoute('DELETE', '/delete', 'withEndpointDescription');
  154. $parsed = $this->generator->processRoute($route);
  155. $this->assertEquals(['DELETE'], $parsed['methods']);
  156. }
  157. /** @test */
  158. public function can_override_url_path_parameters_with_urlparam_annotation()
  159. {
  160. $route = $this->createRoute('POST', '/echoesUrlParameters/{param}', 'echoesUrlParameters', true);
  161. $rules = [
  162. 'response_calls' => [
  163. 'methods' => ['*'],
  164. ],
  165. ];
  166. $parsed = $this->generator->processRoute($route, $rules);
  167. $response = json_decode(Arr::first($parsed['responses'])['content'], true);
  168. $this->assertEquals(4, $response['param']);
  169. }
  170. /** @test */
  171. public function ignores_or_inserts_optional_url_path_parameters_according_to_annotations()
  172. {
  173. $route = $this->createRoute('POST', '/echoesUrlParameters/{param}/{param2?}/{param3}/{param4?}', 'echoesUrlParameters', true);
  174. $rules = [
  175. 'response_calls' => [
  176. 'methods' => ['*'],
  177. ],
  178. ];
  179. $parsed = $this->generator->processRoute($route, $rules);
  180. $response = json_decode(Arr::first($parsed['responses'])['content'], true);
  181. $this->assertEquals(4, $response['param']);
  182. $this->assertNotNull($response['param2']);
  183. $this->assertEquals(1, $response['param3']);
  184. $this->assertNull($response['param4']);
  185. }
  186. /**
  187. * @test
  188. * @dataProvider authRules
  189. */
  190. public function adds_appropriate_field_based_on_configured_auth_type($config, $expected)
  191. {
  192. $route = $this->createRoute('POST', '/withAuthenticatedTag', 'withAuthenticatedTag', true);
  193. $generator = new Generator(new DocumentationConfig($config));
  194. $parsed = $generator->processRoute($route, []);
  195. $this->assertNotNull($parsed[$expected['where']][$expected['name']]);
  196. $this->assertStringStartsWith("{$expected['where']}.{$expected['name']}.", $parsed['auth']);
  197. }
  198. /** @test */
  199. public function generates_consistent_examples_when_faker_seed_is_set()
  200. {
  201. $route = $this->createRoute('GET', '/withBodyParameters', 'withBodyParameters');
  202. $paramName = 'room_id';
  203. $results = [];
  204. $results[$this->generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  205. $results[$this->generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  206. $results[$this->generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  207. $results[$this->generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  208. $results[$this->generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  209. // Examples should have different values
  210. $this->assertNotEquals(count($results), 1);
  211. $generator = new Generator(new DocumentationConfig($this->config + ['faker_seed' => 12345]));
  212. $results = [];
  213. $results[$generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  214. $results[$generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  215. $results[$generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  216. $results[$generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  217. // Examples should have same values
  218. $this->assertEquals(count($results), 1);
  219. }
  220. /** @test */
  221. public function can_use_arrays_in_routes_uses()
  222. {
  223. $route = $this->createRouteUsesArray('GET', '/api/array/test', 'withEndpointDescription');
  224. $parsed = $this->generator->processRoute($route);
  225. $this->assertSame('Example title.', $parsed['metadata']['title']);
  226. $this->assertSame("This will be the long description.\nIt can also be multiple lines long.", $parsed['metadata']['description']);
  227. }
  228. /** @test */
  229. public function can_use_closure_in_routes_uses()
  230. {
  231. /**
  232. * A short title.
  233. * A longer description.
  234. * Can be multiple lines.
  235. *
  236. * @queryParam location_id required The id of the location.
  237. * @bodyParam name required Name of the location
  238. */
  239. $handler = function () {
  240. return 'hi';
  241. };
  242. $route = $this->createRouteUsesCallable('GET', '/api/closure/test', $handler);
  243. $parsed = $this->generator->processRoute($route);
  244. $this->assertSame('A short title.', $parsed['metadata']['title']);
  245. $this->assertSame("A longer description.\nCan be multiple lines.", $parsed['metadata']['description']);
  246. $this->assertCount(1, $parsed['queryParameters']);
  247. $this->assertCount(1, $parsed['bodyParameters']);
  248. $this->assertSame('The id of the location.', $parsed['queryParameters']['location_id']['description']);
  249. $this->assertSame('Name of the location', $parsed['bodyParameters']['name']['description']);
  250. }
  251. abstract public function createRoute(string $httpMethod, string $path, string $controllerMethod, $register = false, $class = TestController::class);
  252. abstract public function createRouteUsesArray(string $httpMethod, string $path, string $controllerMethod, $register = false, $class = TestController::class);
  253. abstract public function createRouteUsesCallable(string $httpMethod, string $path, callable $handler, $register = false);
  254. public function authRules()
  255. {
  256. return [
  257. [
  258. array_merge($this->config, [
  259. 'auth' => [
  260. 'enabled' => true,
  261. 'in' => 'bearer',
  262. 'name' => 'dfadb',
  263. ]
  264. ]),
  265. [
  266. 'name' => 'Authorization',
  267. 'where' => 'headers',
  268. ]
  269. ],
  270. [
  271. array_merge($this->config, [
  272. 'auth' => [
  273. 'enabled' => true,
  274. 'in' => 'basic',
  275. 'name' => 'efwr',
  276. ]
  277. ]),
  278. [
  279. 'name' => 'Authorization',
  280. 'where' => 'headers',
  281. ]
  282. ],
  283. [
  284. array_merge($this->config, [
  285. 'auth' => [
  286. 'enabled' => true,
  287. 'in' => 'header',
  288. 'name' => 'Api-Key',
  289. ]
  290. ]),
  291. [
  292. 'name' => 'Api-Key',
  293. 'where' => 'headers',
  294. ]
  295. ],
  296. [
  297. array_merge($this->config, [
  298. 'auth' => [
  299. 'enabled' => true,
  300. 'in' => 'query',
  301. 'name' => 'apiKey',
  302. ]
  303. ]),
  304. [
  305. 'name' => 'apiKey',
  306. 'where' => 'cleanQueryParameters',
  307. ]
  308. ],
  309. [
  310. array_merge($this->config, [
  311. 'auth' => [
  312. 'enabled' => true,
  313. 'in' => 'body',
  314. 'name' => 'access_token',
  315. ]
  316. ]),
  317. [
  318. 'name' => 'access_token',
  319. 'where' => 'cleanBodyParameters',
  320. ]
  321. ],
  322. ];
  323. }
  324. }