GeneratorTestCase.php 13 KB

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