GeneratorTestCase.php 13 KB

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