GenerateDocumentationTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. <?php
  2. namespace Knuckles\Scribe\Tests;
  3. use Illuminate\Support\Facades\Route as RouteFacade;
  4. use Knuckles\Scribe\ScribeServiceProvider;
  5. use Knuckles\Scribe\Tests\Fixtures\TestController;
  6. use Knuckles\Scribe\Tests\Fixtures\TestGroupController;
  7. use Knuckles\Scribe\Tests\Fixtures\TestIgnoreThisController;
  8. use Knuckles\Scribe\Tests\Fixtures\TestPartialResourceController;
  9. use Knuckles\Scribe\Tests\Fixtures\TestResourceController;
  10. use Knuckles\Scribe\Tests\Fixtures\TestUser;
  11. use Knuckles\Scribe\Tools\Utils;
  12. use Symfony\Component\Yaml\Yaml;
  13. class GenerateDocumentationTest extends BaseLaravelTest
  14. {
  15. use TestHelpers;
  16. protected function setUp(): void
  17. {
  18. parent::setUp();
  19. config(['scribe.database_connections_to_transact' => []]);
  20. $factory = app(\Illuminate\Database\Eloquent\Factory::class);
  21. $factory->define(TestUser::class, function () {
  22. return [
  23. 'id' => 4,
  24. 'first_name' => 'Tested',
  25. 'last_name' => 'Again',
  26. 'email' => 'a@b.com',
  27. ];
  28. });
  29. }
  30. public function tearDown(): void
  31. {
  32. Utils::deleteDirectoryAndContents('public/docs');
  33. Utils::deleteDirectoryAndContents('.scribe');
  34. }
  35. /**
  36. * @param \Illuminate\Foundation\Application $app
  37. *
  38. * @return array
  39. */
  40. protected function getPackageProviders($app)
  41. {
  42. $providers = [
  43. ScribeServiceProvider::class,
  44. ];
  45. if (class_exists(\Dingo\Api\Provider\LaravelServiceProvider::class)) {
  46. $providers[] = \Dingo\Api\Provider\LaravelServiceProvider::class;
  47. }
  48. return $providers;
  49. }
  50. /** @test */
  51. public function can_process_traditional_laravel_route_syntax()
  52. {
  53. RouteFacade::get('/api/test', [TestController::class, 'withEndpointDescription']);
  54. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  55. $output = $this->artisan('scribe:generate');
  56. $this->assertStringContainsString('Processed route: [GET] api/test', $output);
  57. }
  58. /** @test */
  59. public function can_process_traditional_laravel_head_routes()
  60. {
  61. RouteFacade::addRoute('HEAD', '/api/test', [TestController::class, 'withEndpointDescription']);
  62. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  63. $output = $this->artisan('scribe:generate');
  64. $this->assertStringContainsString('Processed route: [HEAD] api/test', $output);
  65. }
  66. /**
  67. * @test
  68. * @see https://github.com/knuckleswtf/scribe/issues/53
  69. */
  70. public function can_process_closure_routes()
  71. {
  72. RouteFacade::get('/api/closure', function () {
  73. return 'hi';
  74. });
  75. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  76. $output = $this->artisan('scribe:generate');
  77. $this->assertStringContainsString('Processed route: [GET] api/closure', $output);
  78. }
  79. /**
  80. * @group dingo
  81. * @test
  82. */
  83. public function can_process_routes_on_dingo()
  84. {
  85. $api = app(\Dingo\Api\Routing\Router::class);
  86. $api->version('v1', function ($api) {
  87. $api->get('/closure', function () {
  88. return 'foo';
  89. });
  90. $api->get('/test', [TestController::class, 'withEndpointDescription']);
  91. });
  92. config(['scribe.routes.0.match.prefixes' => ['*']]);
  93. config(['scribe.routes.0.match.versions' => ['v1']]);
  94. $output = $this->artisan('scribe:generate');
  95. $this->assertStringContainsString('Processed route: [GET] closure', $output);
  96. $this->assertStringContainsString('Processed route: [GET] test', $output);
  97. }
  98. /** @test */
  99. public function can_process_callable_tuple_syntax()
  100. {
  101. RouteFacade::get('/api/array/test', [TestController::class, 'withEndpointDescription']);
  102. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  103. $output = $this->artisan('scribe:generate');
  104. $this->assertStringContainsString('Processed route: [GET] api/array/test', $output);
  105. }
  106. /** @test */
  107. public function can_skip_methods_and_classes_with_hidefromapidocumentation_tag()
  108. {
  109. RouteFacade::get('/api/skip', [TestController::class, 'skip']);
  110. RouteFacade::get('/api/skipClass', TestIgnoreThisController::class . '@dummy');
  111. RouteFacade::get('/api/test', [TestController::class, 'withEndpointDescription']);
  112. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  113. $output = $this->artisan('scribe:generate');
  114. $this->assertStringContainsString('Skipping route: [GET] api/skip', $output);
  115. $this->assertStringContainsString('Skipping route: [GET] api/skipClass', $output);
  116. $this->assertStringContainsString('Processed route: [GET] api/test', $output);
  117. }
  118. /** @test */
  119. public function can_skip_nonexistent_response_files()
  120. {
  121. RouteFacade::get('/api/non-existent', [TestController::class, 'withNonExistentResponseFile']);
  122. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  123. $output = $this->artisan('scribe:generate');
  124. $this->assertStringContainsString('@responseFile i-do-not-exist.json does not exist', $output);
  125. }
  126. /** @test */
  127. public function can_parse_resource_routes()
  128. {
  129. RouteFacade::resource('/api/users', TestResourceController::class)
  130. ->only(['index', 'store']);
  131. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  132. config([
  133. 'scribe.routes.0.apply.headers' => [
  134. 'Accept' => 'application/json',
  135. ],
  136. ]);
  137. $output = $this->artisan('scribe:generate');
  138. $this->assertStringContainsString('Processed route: [GET] api/users', $output);
  139. $this->assertStringContainsString('Processed route: [POST] api/users', $output);
  140. $this->assertStringNotContainsString('Processed route: [PUT,PATCH] api/users/{user}', $output);
  141. $this->assertStringNotContainsString('Processed route: [DELETE] api/users/{user}', $output);
  142. RouteFacade::apiResource('/api/users', TestResourceController::class)
  143. ->only(['index', 'store']);
  144. $output = $this->artisan('scribe:generate');
  145. $this->assertStringContainsString('Processed route: [GET] api/users', $output);
  146. $this->assertStringContainsString('Processed route: [POST] api/users', $output);
  147. $this->assertStringNotContainsString('Processed route: [PUT,PATCH] api/users/{user}', $output);
  148. $this->assertStringNotContainsString('Processed route: [DELETE] api/users/{user}', $output);
  149. }
  150. /** @test */
  151. public function supports_partial_resource_controller()
  152. {
  153. RouteFacade::resource('/api/users', TestPartialResourceController::class);
  154. config(['scribe.routes.0.prefixes' => ['api/*']]);
  155. $output = $this->artisan('scribe:generate');
  156. $this->assertStringContainsString('Processed route: [GET] api/users', $output);
  157. $this->assertStringContainsString('Processed route: [PUT,PATCH] api/users/{user}', $output);
  158. }
  159. /** @test */
  160. public function generated_postman_collection_file_is_correct()
  161. {
  162. RouteFacade::post('/api/withBodyParametersAsArray', [TestController::class, 'withBodyParametersAsArray']);
  163. RouteFacade::post('/api/withFormDataParams', [TestController::class, 'withFormDataParams']);
  164. RouteFacade::post('/api/withBodyParameters', [TestController::class, 'withBodyParameters']);
  165. RouteFacade::get('/api/withQueryParameters', [TestController::class, 'withQueryParameters']);
  166. RouteFacade::get('/api/withAuthTag', [TestController::class, 'withAuthenticatedTag']);
  167. RouteFacade::get('/api/echoesUrlParameters/{param}/{param2}/{param3?}/{param4?}', [TestController::class, 'echoesUrlParameters']);
  168. // We want to have the same values for params each time
  169. config(['scribe.faker_seed' => 1234]);
  170. config(['scribe.title' => 'GREAT API!']);
  171. config(['scribe.auth.enabled' => true]);
  172. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  173. config(['scribe.postman.overrides' => [
  174. 'info.version' => '3.9.9',
  175. ]]);
  176. config([
  177. 'scribe.routes.0.apply.headers' => [
  178. 'Custom-Header' => 'NotSoCustom',
  179. ],
  180. ]);
  181. config(['scribe.postman.enabled' => true]);
  182. config(['scribe.openapi.enabled' => false]);
  183. $this->artisan('scribe:generate');
  184. $generatedCollection = json_decode(file_get_contents(__DIR__ . '/../public/docs/collection.json'), true);
  185. // The Postman ID varies from call to call; erase it to make the test data reproducible.
  186. $generatedCollection['info']['_postman_id'] = '';
  187. $fixtureCollection = json_decode(file_get_contents(__DIR__ . '/Fixtures/collection.json'), true);
  188. $this->assertEquals($fixtureCollection, $generatedCollection);
  189. }
  190. /** @test */
  191. public function generated_openapi_spec_file_is_correct()
  192. {
  193. RouteFacade::post('/api/withBodyParametersAsArray', [TestController::class, 'withBodyParametersAsArray']);
  194. RouteFacade::post('/api/withFormDataParams', [TestController::class, 'withFormDataParams']);
  195. RouteFacade::get('/api/withResponseTag', [TestController::class, 'withResponseTag']);
  196. RouteFacade::get('/api/withQueryParameters', [TestController::class, 'withQueryParameters']);
  197. RouteFacade::get('/api/withAuthTag', [TestController::class, 'withAuthenticatedTag']);
  198. RouteFacade::get('/api/echoesUrlParameters/{param}/{param2}/{param3?}/{param4?}', [TestController::class, 'echoesUrlParameters']);
  199. // We want to have the same values for params each time
  200. config(['scribe.faker_seed' => 1234]);
  201. config(['scribe.postman.enabled' => false]);
  202. config(['scribe.openapi.enabled' => true]);
  203. config(['scribe.openapi.overrides' => [
  204. 'info.version' => '3.9.9',
  205. ]]);
  206. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  207. config([
  208. 'scribe.routes.0.apply.headers' => [
  209. 'Custom-Header' => 'NotSoCustom',
  210. ],
  211. ]);
  212. $this->artisan('scribe:generate');
  213. $generatedCollection = Yaml::parseFile(__DIR__ . '/../public/docs/openapi.yaml');
  214. $fixtureCollection = Yaml::parseFile(__DIR__ . '/Fixtures/openapi.yaml');
  215. $this->assertEquals($fixtureCollection, $generatedCollection);
  216. }
  217. /** @test */
  218. public function can_append_custom_http_headers()
  219. {
  220. RouteFacade::get('/api/headers', [TestController::class, 'checkCustomHeaders']);
  221. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  222. config([
  223. 'scribe.routes.0.apply.headers' => [
  224. 'Authorization' => 'customAuthToken',
  225. 'Custom-Header' => 'NotSoCustom',
  226. ],
  227. ]);
  228. $this->artisan('scribe:generate');
  229. $endpointDetails = Yaml::parseFile(__DIR__ . '/../.scribe/endpoints/0.yaml')['endpoints'][0];
  230. $this->assertEquals("customAuthToken", $endpointDetails['headers']["Authorization"]);
  231. $this->assertEquals("NotSoCustom", $endpointDetails['headers']["Custom-Header"]);
  232. }
  233. /** @test */
  234. public function can_parse_utf8_response()
  235. {
  236. RouteFacade::get('/api/utf8', [TestController::class, 'withUtf8ResponseTag']);
  237. config(['scribe.routes.0.prefixes' => ['api/*']]);
  238. $this->artisan('scribe:generate');
  239. $generatedHtml = file_get_contents('public/docs/index.html');
  240. $this->assertStringContainsString('Лорем ипсум долор сит амет', $generatedHtml);
  241. }
  242. /** @test */
  243. public function sorts_group_naturally()
  244. {
  245. RouteFacade::get('/api/action1', TestGroupController::class . '@action1');
  246. RouteFacade::get('/api/action1b', TestGroupController::class . '@action1b');
  247. RouteFacade::get('/api/action2', TestGroupController::class . '@action2');
  248. RouteFacade::get('/api/action10', TestGroupController::class . '@action10');
  249. config(['scribe.routes.0.prefixes' => ['api/*']]);
  250. $this->artisan('scribe:generate');
  251. $this->assertFileExists(__DIR__ . '/../.scribe/endpoints/0.yaml');
  252. $this->assertFileExists(__DIR__ . '/../.scribe/endpoints/1.yaml');
  253. $this->assertFileExists(__DIR__ . '/../.scribe/endpoints/2.yaml');
  254. $this->assertEquals('1. Group 1', Yaml::parseFile(__DIR__ . '/../.scribe/endpoints/0.yaml')['name']);
  255. $this->assertEquals('2. Group 2', Yaml::parseFile(__DIR__ . '/../.scribe/endpoints/1.yaml')['name']);
  256. $this->assertEquals('10. Group 10', Yaml::parseFile(__DIR__ . '/../.scribe/endpoints/2.yaml')['name']);
  257. }
  258. /** @test */
  259. public function can_customise_static_output_path()
  260. {
  261. RouteFacade::get('/api/action1', TestGroupController::class . '@action1');
  262. config(['scribe.routes.0.prefixes' => ['*']]);
  263. config(['scribe.static.output_path' => 'static/docs']);
  264. $this->artisan('scribe:generate');
  265. $this->assertFileExists('static/docs/index.html');
  266. Utils::deleteDirectoryAndContents('static/');
  267. }
  268. /** @test */
  269. public function will_not_overwrite_manually_modified_content_unless_force_flag_is_set()
  270. {
  271. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  272. RouteFacade::get('/api/action1b', [TestGroupController::class, 'action1b']);
  273. config(['scribe.routes.0.prefixes' => ['api/*']]);
  274. $this->artisan('scribe:generate');
  275. $authFilePath = '.scribe/auth.md';
  276. $group1FilePath = '.scribe/endpoints/0.yaml';
  277. $group = Yaml::parseFile($group1FilePath);
  278. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  279. $this->assertEquals([], $group['endpoints'][0]['urlParameters']);
  280. $extraParam = [
  281. 'name' => 'a_param',
  282. 'description' => 'A URL param.',
  283. 'required' => true,
  284. 'example' => 6,
  285. 'type' => 'integer',
  286. ];
  287. $group['endpoints'][0]['urlParameters']['a_param'] = $extraParam;
  288. file_put_contents($group1FilePath, Yaml::dump(
  289. $group, 10, 2,
  290. Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE | Yaml::DUMP_OBJECT_AS_MAP
  291. ));
  292. file_put_contents($authFilePath, 'Some other useful stuff.', FILE_APPEND);
  293. $this->artisan('scribe:generate');
  294. $group = Yaml::parseFile($group1FilePath);
  295. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  296. $this->assertEquals(['a_param' => $extraParam], $group['endpoints'][0]['urlParameters']);
  297. $this->assertStringContainsString('Some other useful stuff.', file_get_contents($authFilePath));
  298. $this->artisan('scribe:generate', ['--force' => true]);
  299. $group = Yaml::parseFile($group1FilePath);
  300. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  301. $this->assertEquals([], $group['endpoints'][0]['urlParameters']);
  302. $this->assertStringNotContainsString('Some other useful stuff.', file_get_contents($authFilePath));
  303. }
  304. }