OutputTest.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. <?php
  2. namespace Knuckles\Scribe\Tests\GenerateDocumentation;
  3. use Illuminate\Support\Facades\Route as RouteFacade;
  4. use Illuminate\Support\Facades\Storage;
  5. use Illuminate\Support\Facades\View;
  6. use Knuckles\Scribe\Tests\BaseLaravelTest;
  7. use Knuckles\Scribe\Tests\Fixtures\TestController;
  8. use Knuckles\Scribe\Tests\Fixtures\TestGroupController;
  9. use Knuckles\Scribe\Tests\Fixtures\TestPartialResourceController;
  10. use Knuckles\Scribe\Tests\Fixtures\TestUser;
  11. use Knuckles\Scribe\Tests\TestHelpers;
  12. use Knuckles\Scribe\Tools\Utils;
  13. use Symfony\Component\DomCrawler\Crawler;
  14. use Symfony\Component\Yaml\Yaml;
  15. class OutputTest extends BaseLaravelTest
  16. {
  17. use TestHelpers;
  18. protected function setUp(): void
  19. {
  20. parent::setUp();
  21. config(['scribe.database_connections_to_transact' => []]);
  22. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  23. // Skip these ones for faster tests
  24. config(['scribe.openapi.enabled' => false]);
  25. config(['scribe.postman.enabled' => false]);
  26. // We want to have the same values for params each time
  27. config(['scribe.examples.faker_seed' => 1234]);
  28. $factory = app(\Illuminate\Database\Eloquent\Factory::class);
  29. $factory->define(TestUser::class, function () {
  30. return [
  31. 'id' => 4,
  32. 'first_name' => 'Tested',
  33. 'last_name' => 'Again',
  34. 'email' => 'a@b.com',
  35. ];
  36. });
  37. }
  38. public function tearDown(): void
  39. {
  40. Utils::deleteDirectoryAndContents('public/docs');
  41. Utils::deleteDirectoryAndContents('.scribe');
  42. }
  43. protected function usingLaravelTypeDocs($app)
  44. {
  45. $app['config']->set('scribe.type', 'laravel');
  46. $app['config']->set('scribe.laravel.add_routes', true);
  47. $app['config']->set('scribe.laravel.docs_url', '/apidocs');
  48. }
  49. /**
  50. * @test
  51. * @define-env usingLaravelTypeDocs
  52. */
  53. public function generates_laravel_type_output()
  54. {
  55. RouteFacade::post('/api/withQueryParameters', [TestController::class, 'withQueryParameters']);
  56. config(['scribe.type' => 'laravel']);
  57. config(['scribe.postman.enabled' => true]);
  58. config(['scribe.openapi.enabled' => true]);
  59. $this->generate();
  60. $this->assertFileExists($this->postmanOutputPath(true));
  61. $this->assertFileExists($this->openapiOutputPath(true));
  62. $this->assertFileExists($this->bladeOutputPath());
  63. $response = $this->get('/apidocs/');
  64. $response->assertStatus(200);
  65. $response = $this->get('/apidocs.postman');
  66. $response->assertStatus(200);
  67. $response = $this->get('/apidocs.openapi');
  68. $response->assertStatus(200);
  69. config(['scribe.laravel.add_routes' => false]);
  70. config(['scribe.laravel.docs_url' => '/apidocs']);
  71. unlink($this->postmanOutputPath(true));
  72. unlink($this->openapiOutputPath(true));
  73. unlink($this->bladeOutputPath());
  74. }
  75. /** @test */
  76. public function generated_postman_collection_file_is_correct()
  77. {
  78. RouteFacade::post('/api/withBodyParametersAsArray', [TestController::class, 'withBodyParametersAsArray']);
  79. RouteFacade::post('/api/withFormDataParams', [TestController::class, 'withFormDataParams']);
  80. RouteFacade::post('/api/withBodyParameters', [TestController::class, 'withBodyParameters']);
  81. RouteFacade::get('/api/withQueryParameters', [TestController::class, 'withQueryParameters']);
  82. RouteFacade::get('/api/withAuthTag', [TestController::class, 'withAuthenticatedTag']);
  83. RouteFacade::get('/api/echoesUrlParameters/{param}/{param2}/{param3?}/{param4?}', [TestController::class, 'echoesUrlParameters']);
  84. config(['scribe.title' => 'GREAT API!']);
  85. config(['scribe.auth.enabled' => true]);
  86. config(['scribe.postman.overrides' => [
  87. 'info.version' => '3.9.9',
  88. ]]);
  89. config([
  90. 'scribe.routes.0.apply.headers' => [
  91. 'Custom-Header' => 'NotSoCustom',
  92. ],
  93. ]);
  94. config(['scribe.postman.enabled' => true]);
  95. $this->generate();
  96. $generatedCollection = json_decode(file_get_contents($this->postmanOutputPath()), true);
  97. // The Postman ID varies from call to call; erase it to make the test data reproducible.
  98. $generatedCollection['info']['_postman_id'] = '';
  99. $fixtureCollection = json_decode(file_get_contents(__DIR__ . '/../Fixtures/collection.json'), true);
  100. $this->assertEquals($fixtureCollection, $generatedCollection);
  101. }
  102. /** @test */
  103. public function generated_openapi_spec_file_is_correct()
  104. {
  105. RouteFacade::post('/api/withBodyParametersAsArray', [TestController::class, 'withBodyParametersAsArray']);
  106. RouteFacade::post('/api/withFormDataParams', [TestController::class, 'withFormDataParams']);
  107. RouteFacade::get('/api/withResponseTag', [TestController::class, 'withResponseTag']);
  108. RouteFacade::get('/api/withQueryParameters', [TestController::class, 'withQueryParameters']);
  109. RouteFacade::get('/api/withAuthTag', [TestController::class, 'withAuthenticatedTag']);
  110. RouteFacade::get('/api/echoesUrlParameters/{param}/{param2}/{param3?}/{param4?}', [TestController::class, 'echoesUrlParameters']);
  111. config(['scribe.openapi.enabled' => true]);
  112. config(['scribe.openapi.overrides' => [
  113. 'info.version' => '3.9.9',
  114. ]]);
  115. config([
  116. 'scribe.routes.0.apply.headers' => [
  117. 'Custom-Header' => 'NotSoCustom',
  118. ],
  119. ]);
  120. $this->generate();
  121. $generatedSpec = Yaml::parseFile($this->openapiOutputPath());
  122. $fixtureSpec = Yaml::parseFile(__DIR__ . '/../Fixtures/openapi.yaml');
  123. $this->assertEquals($fixtureSpec, $generatedSpec);
  124. }
  125. /** @test */
  126. public function can_append_custom_http_headers()
  127. {
  128. RouteFacade::get('/api/headers', [TestController::class, 'checkCustomHeaders']);
  129. config([
  130. 'scribe.routes.0.apply.headers' => [
  131. 'Authorization' => 'customAuthToken',
  132. 'Custom-Header' => 'NotSoCustom',
  133. ],
  134. ]);
  135. $this->generate();
  136. $endpointDetails = Yaml::parseFile('.scribe/endpoints/00.yaml')['endpoints'][0];
  137. $this->assertEquals("customAuthToken", $endpointDetails['headers']["Authorization"]);
  138. $this->assertEquals("NotSoCustom", $endpointDetails['headers']["Custom-Header"]);
  139. }
  140. /** @test */
  141. public function can_parse_utf8_response()
  142. {
  143. RouteFacade::get('/api/utf8', [TestController::class, 'withUtf8ResponseTag']);
  144. $this->generate();
  145. $generatedHtml = file_get_contents($this->htmlOutputPath());
  146. $this->assertStringContainsString('Лорем ипсум долор сит амет', $generatedHtml);
  147. }
  148. /** @test */
  149. public function sorts_group_naturally()
  150. {
  151. RouteFacade::get('/api/action1', TestGroupController::class . '@action1');
  152. RouteFacade::get('/api/action1b', TestGroupController::class . '@action1b');
  153. RouteFacade::get('/api/action2', TestGroupController::class . '@action2');
  154. RouteFacade::get('/api/action10', TestGroupController::class . '@action10');
  155. $this->generate();
  156. $this->assertEquals('1. Group 1', Yaml::parseFile('.scribe/endpoints/00.yaml')['name']);
  157. $this->assertEquals('2. Group 2', Yaml::parseFile('.scribe/endpoints/01.yaml')['name']);
  158. $this->assertEquals('10. Group 10', Yaml::parseFile('.scribe/endpoints/02.yaml')['name']);
  159. }
  160. /** @test */
  161. public function sorts_groups_and_endpoints_in_the_specified_order()
  162. {
  163. config(['scribe.groups.order' => [
  164. '10. Group 10',
  165. '1. Group 1' => [
  166. 'GET /api/action1b',
  167. 'GET /api/action1',
  168. ],
  169. '13. Group 13' => [
  170. 'SG B' => [
  171. 'POST /api/action13d',
  172. 'GET /api/action13a',
  173. ],
  174. 'SG A',
  175. 'PUT /api/action13c',
  176. 'POST /api/action13b',
  177. ],
  178. ]]);
  179. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  180. RouteFacade::get('/api/action1b', [TestGroupController::class, 'action1b']);
  181. RouteFacade::get('/api/action2', [TestGroupController::class, 'action2']);
  182. RouteFacade::get('/api/action10', [TestGroupController::class, 'action10']);
  183. RouteFacade::get('/api/action13a', [TestGroupController::class, 'action13a']);
  184. RouteFacade::post('/api/action13b', [TestGroupController::class, 'action13b']);
  185. RouteFacade::put('/api/action13c', [TestGroupController::class, 'action13c']);
  186. RouteFacade::post('/api/action13d', [TestGroupController::class, 'action13d']);
  187. RouteFacade::get('/api/action13e', [TestGroupController::class, 'action13e']);
  188. $this->generate();
  189. $this->assertEquals('10. Group 10', Yaml::parseFile('.scribe/endpoints/00.yaml')['name']);
  190. $secondGroup = Yaml::parseFile('.scribe/endpoints/01.yaml');
  191. $this->assertEquals('1. Group 1', $secondGroup['name']);
  192. $thirdGroup = Yaml::parseFile('.scribe/endpoints/02.yaml');
  193. $this->assertEquals('13. Group 13', $thirdGroup['name']);
  194. $this->assertEquals('2. Group 2', Yaml::parseFile('.scribe/endpoints/03.yaml')['name']);
  195. $this->assertEquals('api/action1b', $secondGroup['endpoints'][0]['uri']);
  196. $this->assertEquals('GET', $secondGroup['endpoints'][0]['httpMethods'][0]);
  197. $this->assertEquals('api/action1', $secondGroup['endpoints'][1]['uri']);
  198. $this->assertEquals('GET', $secondGroup['endpoints'][1]['httpMethods'][0]);
  199. $this->assertEquals('api/action13d', $thirdGroup['endpoints'][0]['uri']);
  200. $this->assertEquals('POST', $thirdGroup['endpoints'][0]['httpMethods'][0]);
  201. $this->assertEquals('api/action13a', $thirdGroup['endpoints'][1]['uri']);
  202. $this->assertEquals('GET', $thirdGroup['endpoints'][1]['httpMethods'][0]);
  203. $this->assertEquals('api/action13e', $thirdGroup['endpoints'][2]['uri']);
  204. $this->assertEquals('GET', $thirdGroup['endpoints'][2]['httpMethods'][0]);
  205. $this->assertEquals('api/action13c', $thirdGroup['endpoints'][3]['uri']);
  206. $this->assertEquals('PUT', $thirdGroup['endpoints'][3]['httpMethods'][0]);
  207. $this->assertEquals('api/action13b', $thirdGroup['endpoints'][4]['uri']);
  208. $this->assertEquals('POST', $thirdGroup['endpoints'][4]['httpMethods'][0]);
  209. }
  210. /** @test */
  211. public function will_not_overwrite_manually_modified_content_unless_force_flag_is_set()
  212. {
  213. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  214. RouteFacade::get('/api/action1b', [TestGroupController::class, 'action1b']);
  215. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  216. $this->generate();
  217. $authFilePath = '.scribe/auth.md';
  218. $group1FilePath = '.scribe/endpoints/00.yaml';
  219. $group = Yaml::parseFile($group1FilePath);
  220. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  221. $this->assertEquals([], $group['endpoints'][0]['urlParameters']);
  222. $extraParam = [
  223. 'name' => 'a_param',
  224. 'description' => 'A URL param.',
  225. 'required' => true,
  226. 'example' => 6,
  227. 'type' => 'integer',
  228. 'custom' => [],
  229. ];
  230. $group['endpoints'][0]['urlParameters']['a_param'] = $extraParam;
  231. file_put_contents($group1FilePath, Yaml::dump(
  232. $group, 20, 2,
  233. Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE | Yaml::DUMP_OBJECT_AS_MAP
  234. ));
  235. file_put_contents($authFilePath, 'Some other useful stuff.', FILE_APPEND);
  236. $this->generate();
  237. $group = Yaml::parseFile($group1FilePath);
  238. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  239. $this->assertEquals(['a_param' => $extraParam], $group['endpoints'][0]['urlParameters']);
  240. $this->assertStringContainsString('Some other useful stuff.', file_get_contents($authFilePath));
  241. $this->generate(['--force' => true]);
  242. $group = Yaml::parseFile($group1FilePath);
  243. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  244. $this->assertEquals([], $group['endpoints'][0]['urlParameters']);
  245. $this->assertStringNotContainsString('Some other useful stuff.', file_get_contents($authFilePath));
  246. }
  247. /** @test */
  248. public function generates_correct_url_params_from_resource_routes_and_field_bindings()
  249. {
  250. RouteFacade::prefix('providers/{provider:slug}')->group(function () {
  251. RouteFacade::resource('users.addresses', TestPartialResourceController::class)->parameters([
  252. 'addresses' => 'address:uuid',
  253. ]);
  254. });
  255. config(['scribe.routes.0.match.prefixes' => ['*']]);
  256. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  257. $this->generate();
  258. $groupA = Yaml::parseFile('.scribe/endpoints/00.yaml');
  259. $this->assertEquals('providers/{provider_slug}/users/{user_id}/addresses', $groupA['endpoints'][0]['uri']);
  260. $groupB = Yaml::parseFile('.scribe/endpoints/01.yaml');
  261. $this->assertEquals('providers/{provider_slug}/users/{user_id}/addresses/{uuid}', $groupB['endpoints'][0]['uri']);
  262. }
  263. /** @test */
  264. public function generates_from_camel_dir_if_noExtraction_flag_is_set()
  265. {
  266. config(['scribe.routes.0.exclude' => ['*']]);
  267. Utils::copyDirectory(__DIR__.'/../Fixtures/.scribe', '.scribe');
  268. $output = $this->generate(['--no-extraction' => true]);
  269. $this->assertStringNotContainsString("Processing route", $output);
  270. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  271. [$intro, $auth] = $crawler->filter('h1 + p')->getIterator();
  272. $this->assertEquals('Heyaa introduction!👋', trim($intro->firstChild->textContent));
  273. $this->assertEquals('This is just a test.', trim($auth->firstChild->textContent));
  274. $group = $crawler->filter('h1')->getNode(2);
  275. $this->assertEquals('General', trim($group->textContent));
  276. $expectedEndpoint = $crawler->filter('h2');
  277. $this->assertCount(1, $expectedEndpoint);
  278. $this->assertEquals("Healthcheck", $expectedEndpoint->text());
  279. }
  280. /** @test */
  281. public function merges_and_correctly_sorts_user_defined_endpoints()
  282. {
  283. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  284. RouteFacade::get('/api/action2', [TestGroupController::class, 'action2']);
  285. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  286. if (!is_dir('.scribe/endpoints'))
  287. mkdir('.scribe/endpoints', 0777, true);
  288. copy(__DIR__ . '/../Fixtures/custom.0.yaml', '.scribe/endpoints/custom.0.yaml');
  289. $this->generate();
  290. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  291. $headings = $crawler->filter('h1')->getIterator();
  292. // There should only be six headings — intro, auth and four groups
  293. $this->assertCount(6, $headings);
  294. [$_, $_, $group1, $group2, $group3, $group4] = $headings;
  295. $this->assertEquals('1. Group 1', trim($group1->textContent));
  296. $this->assertEquals('5. Group 5', trim($group2->textContent));
  297. $this->assertEquals('4. Group 4', trim($group3->textContent));
  298. $this->assertEquals('2. Group 2', trim($group4->textContent));
  299. $expectedEndpoints = $crawler->filter('h2');
  300. $this->assertEquals(6, $expectedEndpoints->count());
  301. // Enforce the order of the endpoints
  302. // Ideally, we should also check the groups they're under
  303. $this->assertEquals("Some endpoint.", $expectedEndpoints->getNode(0)->textContent);
  304. $this->assertEquals("User defined", $expectedEndpoints->getNode(1)->textContent);
  305. $this->assertEquals("GET withBeforeGroup", $expectedEndpoints->getNode(2)->textContent);
  306. $this->assertEquals("GET belongingToAnEarlierBeforeGroup", $expectedEndpoints->getNode(3)->textContent);
  307. $this->assertEquals("GET withAfterGroup", $expectedEndpoints->getNode(4)->textContent);
  308. $this->assertEquals("GET api/action2", $expectedEndpoints->getNode(5)->textContent);
  309. }
  310. /** @test */
  311. public function respects_endpoints_and_group_sort_order()
  312. {
  313. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  314. RouteFacade::get('/api/action1b', [TestGroupController::class, 'action1b']);
  315. RouteFacade::get('/api/action2', [TestGroupController::class, 'action2']);
  316. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  317. $this->generate();
  318. // First: verify the current order of the groups and endpoints
  319. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  320. $h1s = $crawler->filter('h1');
  321. $this->assertEquals('1. Group 1', trim($h1s->getNode(2)->textContent));
  322. $this->assertEquals('2. Group 2', trim($h1s->getNode(3)->textContent));
  323. $expectedEndpoints = $crawler->filter('h2');
  324. $this->assertEquals("Some endpoint.", $expectedEndpoints->getNode(0)->textContent);
  325. $this->assertEquals("Another endpoint.", $expectedEndpoints->getNode(1)->textContent);
  326. $this->assertEquals("GET api/action2", $expectedEndpoints->getNode(2)->textContent);
  327. // Now swap the endpoints
  328. $group = Yaml::parseFile('.scribe/endpoints/00.yaml');
  329. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  330. $this->assertEquals('api/action1b', $group['endpoints'][1]['uri']);
  331. $action1 = $group['endpoints'][0];
  332. $group['endpoints'][0] = $group['endpoints'][1];
  333. $group['endpoints'][1] = $action1;
  334. file_put_contents('.scribe/endpoints/00.yaml', Yaml::dump(
  335. $group, 20, 2,
  336. Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE | Yaml::DUMP_OBJECT_AS_MAP
  337. ));
  338. // And then the groups
  339. rename('.scribe/endpoints/00.yaml', '.scribe/endpoints/temp.yaml');
  340. rename('.scribe/endpoints/01.yaml', '.scribe/endpoints/00.yaml');
  341. rename('.scribe/endpoints/temp.yaml', '.scribe/endpoints/1.yaml');
  342. $this->generate();
  343. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  344. $h1s = $crawler->filter('h1');
  345. $this->assertEquals('2. Group 2', trim($h1s->getNode(2)->textContent));
  346. $this->assertEquals('1. Group 1', trim($h1s->getNode(3)->textContent));
  347. $expectedEndpoints = $crawler->filter('h2');
  348. $this->assertEquals("GET api/action2", $expectedEndpoints->getNode(0)->textContent);
  349. $this->assertEquals("Another endpoint.", $expectedEndpoints->getNode(1)->textContent);
  350. $this->assertEquals("Some endpoint.", $expectedEndpoints->getNode(2)->textContent);
  351. }
  352. /** @test */
  353. public function will_auto_set_content_type_to_multipart_if_file_params_are_present()
  354. {
  355. /**
  356. * @bodyParam param string required
  357. */
  358. RouteFacade::post('no-file', fn() => null);
  359. /**
  360. * @bodyParam a_file file required
  361. */
  362. RouteFacade::post('top-level-file', fn() => null);
  363. /**
  364. * @bodyParam data object
  365. * @bodyParam data.thing string
  366. * @bodyParam data.a_file file
  367. */
  368. RouteFacade::post('nested-file', fn() => null);
  369. config(['scribe.routes.0.match.prefixes' => ['*']]);
  370. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  371. $this->generate();
  372. $group = Yaml::parseFile('.scribe/endpoints/00.yaml');
  373. $this->assertEquals('no-file', $group['endpoints'][0]['uri']);
  374. $this->assertEquals('application/json', $group['endpoints'][0]['headers']['Content-Type']);
  375. $this->assertEquals('top-level-file', $group['endpoints'][1]['uri']);
  376. $this->assertEquals('multipart/form-data', $group['endpoints'][1]['headers']['Content-Type']);
  377. $this->assertEquals('nested-file', $group['endpoints'][2]['uri']);
  378. $this->assertEquals('multipart/form-data', $group['endpoints'][2]['headers']['Content-Type']);
  379. }
  380. protected function postmanOutputPath(bool $laravelType = false): string
  381. {
  382. return $laravelType
  383. ? Storage::disk('local')->path('scribe/collection.json') : 'public/docs/collection.json';
  384. }
  385. protected function openapiOutputPath(bool $laravelType = false): string
  386. {
  387. return $laravelType
  388. ? Storage::disk('local')->path('scribe/openapi.yaml') : 'public/docs/openapi.yaml';
  389. }
  390. protected function htmlOutputPath(): string
  391. {
  392. return 'public/docs/index.html';
  393. }
  394. protected function bladeOutputPath(): string
  395. {
  396. return View::getFinder()->find('scribe/index');
  397. }
  398. }