OutputTest.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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.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 defineEnvironment($app)
  44. {
  45. $app['config']->set('database.default', 'testbench');
  46. $app['config']->set('database.connections.testbench', [
  47. 'driver' => 'sqlite',
  48. 'database' => ':memory:',
  49. 'prefix' => '',
  50. ]);
  51. }
  52. protected function usesLaravelTypeDocs($app)
  53. {
  54. $app['config']->set('scribe.type', 'laravel');
  55. $app['config']->set('scribe.laravel.add_routes', true);
  56. $app['config']->set('scribe.laravel.docs_url', '/apidocs');
  57. }
  58. /**
  59. * @test
  60. * @define-env usesLaravelTypeDocs
  61. */
  62. public function generates_laravel_type_output()
  63. {
  64. RouteFacade::post('/api/withQueryParameters', [TestController::class, 'withQueryParameters']);
  65. config(['scribe.type' => 'laravel']);
  66. config(['scribe.postman.enabled' => true]);
  67. config(['scribe.openapi.enabled' => true]);
  68. $this->generate();
  69. $this->assertFileExists($this->postmanOutputPath(true));
  70. $this->assertFileExists($this->openapiOutputPath(true));
  71. $this->assertFileExists($this->bladeOutputPath());
  72. $response = $this->get('/apidocs/');
  73. $response->assertStatus(200);
  74. $response = $this->get('/apidocs.postman');
  75. $response->assertStatus(200);
  76. $response = $this->get('/apidocs.openapi');
  77. $response->assertStatus(200);
  78. config(['scribe.laravel.add_routes' => false]);
  79. config(['scribe.laravel.docs_url' => '/apidocs']);
  80. unlink($this->postmanOutputPath(true));
  81. unlink($this->openapiOutputPath(true));
  82. unlink($this->bladeOutputPath());
  83. }
  84. /** @test */
  85. public function generated_postman_collection_file_is_correct()
  86. {
  87. RouteFacade::post('/api/withBodyParametersAsArray', [TestController::class, 'withBodyParametersAsArray']);
  88. RouteFacade::post('/api/withFormDataParams', [TestController::class, 'withFormDataParams']);
  89. RouteFacade::post('/api/withBodyParameters', [TestController::class, 'withBodyParameters']);
  90. RouteFacade::get('/api/withQueryParameters', [TestController::class, 'withQueryParameters']);
  91. RouteFacade::get('/api/withAuthTag', [TestController::class, 'withAuthenticatedTag']);
  92. RouteFacade::get('/api/echoesUrlParameters/{param}/{param2}/{param3?}/{param4?}', [TestController::class, 'echoesUrlParameters']);
  93. config(['scribe.title' => 'GREAT API!']);
  94. config(['scribe.auth.enabled' => true]);
  95. config(['scribe.postman.overrides' => [
  96. 'info.version' => '3.9.9',
  97. ]]);
  98. config([
  99. 'scribe.routes.0.apply.headers' => [
  100. 'Custom-Header' => 'NotSoCustom',
  101. ],
  102. ]);
  103. config(['scribe.postman.enabled' => true]);
  104. $this->generate();
  105. $generatedCollection = json_decode(file_get_contents($this->postmanOutputPath()), true);
  106. // The Postman ID varies from call to call; erase it to make the test data reproducible.
  107. $generatedCollection['info']['_postman_id'] = '';
  108. $fixtureCollection = json_decode(file_get_contents(__DIR__ . '/../Fixtures/collection.json'), true);
  109. $this->assertEquals($fixtureCollection, $generatedCollection);
  110. }
  111. /** @test */
  112. public function generated_openapi_spec_file_is_correct()
  113. {
  114. RouteFacade::post('/api/withBodyParametersAsArray', [TestController::class, 'withBodyParametersAsArray']);
  115. RouteFacade::post('/api/withFormDataParams', [TestController::class, 'withFormDataParams']);
  116. RouteFacade::get('/api/withResponseTag', [TestController::class, 'withResponseTag']);
  117. RouteFacade::get('/api/withQueryParameters', [TestController::class, 'withQueryParameters']);
  118. RouteFacade::get('/api/withAuthTag', [TestController::class, 'withAuthenticatedTag']);
  119. RouteFacade::get('/api/echoesUrlParameters/{param}/{param2}/{param3?}/{param4?}', [TestController::class, 'echoesUrlParameters']);
  120. config(['scribe.openapi.enabled' => true]);
  121. config(['scribe.openapi.overrides' => [
  122. 'info.version' => '3.9.9',
  123. ]]);
  124. config([
  125. 'scribe.routes.0.apply.headers' => [
  126. 'Custom-Header' => 'NotSoCustom',
  127. ],
  128. ]);
  129. $this->generate();
  130. $generatedSpec = Yaml::parseFile($this->openapiOutputPath());
  131. $fixtureSpec = Yaml::parseFile(__DIR__ . '/../Fixtures/openapi.yaml');
  132. $this->assertEquals($fixtureSpec, $generatedSpec);
  133. }
  134. /** @test */
  135. public function can_append_custom_http_headers()
  136. {
  137. RouteFacade::get('/api/headers', [TestController::class, 'checkCustomHeaders']);
  138. config([
  139. 'scribe.routes.0.apply.headers' => [
  140. 'Authorization' => 'customAuthToken',
  141. 'Custom-Header' => 'NotSoCustom',
  142. ],
  143. ]);
  144. $this->generate();
  145. $endpointDetails = Yaml::parseFile('.scribe/endpoints/00.yaml')['endpoints'][0];
  146. $this->assertEquals("customAuthToken", $endpointDetails['headers']["Authorization"]);
  147. $this->assertEquals("NotSoCustom", $endpointDetails['headers']["Custom-Header"]);
  148. }
  149. /** @test */
  150. public function can_parse_utf8_response()
  151. {
  152. RouteFacade::get('/api/utf8', [TestController::class, 'withUtf8ResponseTag']);
  153. $this->generate();
  154. $generatedHtml = file_get_contents($this->htmlOutputPath());
  155. $this->assertStringContainsString('Лорем ипсум долор сит амет', $generatedHtml);
  156. }
  157. /** @test */
  158. public function sorts_group_naturally()
  159. {
  160. RouteFacade::get('/api/action1', TestGroupController::class . '@action1');
  161. RouteFacade::get('/api/action1b', TestGroupController::class . '@action1b');
  162. RouteFacade::get('/api/action2', TestGroupController::class . '@action2');
  163. RouteFacade::get('/api/action10', TestGroupController::class . '@action10');
  164. $this->generate();
  165. $this->assertEquals('1. Group 1', Yaml::parseFile('.scribe/endpoints/00.yaml')['name']);
  166. $this->assertEquals('2. Group 2', Yaml::parseFile('.scribe/endpoints/01.yaml')['name']);
  167. $this->assertEquals('10. Group 10', Yaml::parseFile('.scribe/endpoints/02.yaml')['name']);
  168. }
  169. /** @test */
  170. public function will_not_overwrite_manually_modified_content_unless_force_flag_is_set()
  171. {
  172. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  173. RouteFacade::get('/api/action1b', [TestGroupController::class, 'action1b']);
  174. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  175. $this->generate();
  176. $authFilePath = '.scribe/auth.md';
  177. $group1FilePath = '.scribe/endpoints/00.yaml';
  178. $group = Yaml::parseFile($group1FilePath);
  179. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  180. $this->assertEquals([], $group['endpoints'][0]['urlParameters']);
  181. $extraParam = [
  182. 'name' => 'a_param',
  183. 'description' => 'A URL param.',
  184. 'required' => true,
  185. 'example' => 6,
  186. 'type' => 'integer',
  187. 'custom' => [],
  188. ];
  189. $group['endpoints'][0]['urlParameters']['a_param'] = $extraParam;
  190. file_put_contents($group1FilePath, Yaml::dump(
  191. $group, 20, 2,
  192. Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE | Yaml::DUMP_OBJECT_AS_MAP
  193. ));
  194. file_put_contents($authFilePath, 'Some other useful stuff.', FILE_APPEND);
  195. $this->generate();
  196. $group = Yaml::parseFile($group1FilePath);
  197. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  198. $this->assertEquals(['a_param' => $extraParam], $group['endpoints'][0]['urlParameters']);
  199. $this->assertStringContainsString('Some other useful stuff.', file_get_contents($authFilePath));
  200. $this->generate(['--force' => true]);
  201. $group = Yaml::parseFile($group1FilePath);
  202. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  203. $this->assertEquals([], $group['endpoints'][0]['urlParameters']);
  204. $this->assertStringNotContainsString('Some other useful stuff.', file_get_contents($authFilePath));
  205. }
  206. /** @test */
  207. public function generates_correct_url_params_from_resource_routes_and_field_bindings()
  208. {
  209. RouteFacade::prefix('providers/{provider:slug}')->group(function () {
  210. RouteFacade::resource('users.addresses', TestPartialResourceController::class)->parameters([
  211. 'addresses' => 'address:uuid',
  212. ]);
  213. });
  214. config(['scribe.routes.0.match.prefixes' => ['*']]);
  215. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  216. $this->generate();
  217. $groupA = Yaml::parseFile('.scribe/endpoints/00.yaml');
  218. $this->assertEquals('providers/{provider_slug}/users/{user_id}/addresses', $groupA['endpoints'][0]['uri']);
  219. $groupB = Yaml::parseFile('.scribe/endpoints/01.yaml');
  220. $this->assertEquals('providers/{provider_slug}/users/{user_id}/addresses/{uuid}', $groupB['endpoints'][0]['uri']);
  221. }
  222. /** @test */
  223. public function generates_from_camel_dir_if_noExtraction_flag_is_set()
  224. {
  225. config(['scribe.routes.0.exclude' => ['*']]);
  226. Utils::copyDirectory(__DIR__.'/../Fixtures/.scribe', '.scribe');
  227. $output = $this->generate(['--no-extraction' => true]);
  228. $this->assertStringNotContainsString("Processing route", $output);
  229. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  230. [$intro, $auth] = $crawler->filter('h1 + p')->getIterator();
  231. $this->assertEquals('Heyaa introduction!👋', trim($intro->firstChild->textContent));
  232. $this->assertEquals('This is just a test.', trim($auth->firstChild->textContent));
  233. $group = $crawler->filter('h1')->getNode(2);
  234. $this->assertEquals('General', trim($group->textContent));
  235. $expectedEndpoint = $crawler->filter('h2');
  236. $this->assertCount(1, $expectedEndpoint);
  237. $this->assertEquals("Healthcheck", $expectedEndpoint->text());
  238. }
  239. /** @test */
  240. public function merges_and_correctly_sorts_user_defined_endpoints()
  241. {
  242. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  243. RouteFacade::get('/api/action2', [TestGroupController::class, 'action2']);
  244. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  245. if (!is_dir('.scribe/endpoints'))
  246. mkdir('.scribe/endpoints', 0777, true);
  247. copy(__DIR__ . '/../Fixtures/custom.0.yaml', '.scribe/endpoints/custom.0.yaml');
  248. $this->generate();
  249. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  250. $headings = $crawler->filter('h1')->getIterator();
  251. // There should only be six headings — intro, auth and four groups
  252. $this->assertCount(6, $headings);
  253. [$_, $_, $group1, $group2, $group3, $group4] = $headings;
  254. $this->assertEquals('1. Group 1', trim($group1->textContent));
  255. $this->assertEquals('5. Group 5', trim($group2->textContent));
  256. $this->assertEquals('4. Group 4', trim($group3->textContent));
  257. $this->assertEquals('2. Group 2', trim($group4->textContent));
  258. $expectedEndpoints = $crawler->filter('h2');
  259. $this->assertEquals(6, $expectedEndpoints->count());
  260. // Enforce the order of the endpoints
  261. // Ideally, we should also check the groups they're under
  262. $this->assertEquals("Some endpoint.", $expectedEndpoints->getNode(0)->textContent);
  263. $this->assertEquals("User defined", $expectedEndpoints->getNode(1)->textContent);
  264. $this->assertEquals("GET withBeforeGroup", $expectedEndpoints->getNode(2)->textContent);
  265. $this->assertEquals("GET belongingToAnEarlierBeforeGroup", $expectedEndpoints->getNode(3)->textContent);
  266. $this->assertEquals("GET withAfterGroup", $expectedEndpoints->getNode(4)->textContent);
  267. $this->assertEquals("GET api/action2", $expectedEndpoints->getNode(5)->textContent);
  268. }
  269. /** @test */
  270. public function respects_endpoints_and_group_sort_order()
  271. {
  272. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  273. RouteFacade::get('/api/action1b', [TestGroupController::class, 'action1b']);
  274. RouteFacade::get('/api/action2', [TestGroupController::class, 'action2']);
  275. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  276. $this->generate();
  277. // First: verify the current order of the groups and endpoints
  278. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  279. $h1s = $crawler->filter('h1');
  280. $this->assertEquals('1. Group 1', trim($h1s->getNode(2)->textContent));
  281. $this->assertEquals('2. Group 2', trim($h1s->getNode(3)->textContent));
  282. $expectedEndpoints = $crawler->filter('h2');
  283. $this->assertEquals("Some endpoint.", $expectedEndpoints->getNode(0)->textContent);
  284. $this->assertEquals("Another endpoint.", $expectedEndpoints->getNode(1)->textContent);
  285. $this->assertEquals("GET api/action2", $expectedEndpoints->getNode(2)->textContent);
  286. // Now swap the endpoints
  287. $group = Yaml::parseFile('.scribe/endpoints/00.yaml');
  288. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  289. $this->assertEquals('api/action1b', $group['endpoints'][1]['uri']);
  290. $action1 = $group['endpoints'][0];
  291. $group['endpoints'][0] = $group['endpoints'][1];
  292. $group['endpoints'][1] = $action1;
  293. file_put_contents('.scribe/endpoints/00.yaml', Yaml::dump(
  294. $group, 20, 2,
  295. Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE | Yaml::DUMP_OBJECT_AS_MAP
  296. ));
  297. // And then the groups
  298. rename('.scribe/endpoints/00.yaml', '.scribe/endpoints/temp.yaml');
  299. rename('.scribe/endpoints/01.yaml', '.scribe/endpoints/00.yaml');
  300. rename('.scribe/endpoints/temp.yaml', '.scribe/endpoints/1.yaml');
  301. $this->generate();
  302. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  303. $h1s = $crawler->filter('h1');
  304. $this->assertEquals('2. Group 2', trim($h1s->getNode(2)->textContent));
  305. $this->assertEquals('1. Group 1', trim($h1s->getNode(3)->textContent));
  306. $expectedEndpoints = $crawler->filter('h2');
  307. $this->assertEquals("GET api/action2", $expectedEndpoints->getNode(0)->textContent);
  308. $this->assertEquals("Another endpoint.", $expectedEndpoints->getNode(1)->textContent);
  309. $this->assertEquals("Some endpoint.", $expectedEndpoints->getNode(2)->textContent);
  310. }
  311. /** @test */
  312. public function will_auto_set_content_type_to_multipart_if_file_params_are_present()
  313. {
  314. /**
  315. * @bodyParam param string required
  316. */
  317. RouteFacade::post('no-file', fn() => null);
  318. /**
  319. * @bodyParam a_file file required
  320. */
  321. RouteFacade::post('top-level-file', fn() => null);
  322. /**
  323. * @bodyParam data object
  324. * @bodyParam data.thing string
  325. * @bodyParam data.a_file file
  326. */
  327. RouteFacade::post('nested-file', fn() => null);
  328. config(['scribe.routes.0.match.prefixes' => ['*']]);
  329. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  330. $this->generate();
  331. $group = Yaml::parseFile('.scribe/endpoints/00.yaml');
  332. $this->assertEquals('no-file', $group['endpoints'][0]['uri']);
  333. $this->assertEquals('application/json', $group['endpoints'][0]['headers']['Content-Type']);
  334. $this->assertEquals('top-level-file', $group['endpoints'][1]['uri']);
  335. $this->assertEquals('multipart/form-data', $group['endpoints'][1]['headers']['Content-Type']);
  336. $this->assertEquals('nested-file', $group['endpoints'][2]['uri']);
  337. $this->assertEquals('multipart/form-data', $group['endpoints'][2]['headers']['Content-Type']);
  338. }
  339. protected function postmanOutputPath(bool $laravelType = false): string
  340. {
  341. return $laravelType
  342. ? Storage::disk('local')->path('scribe/collection.json') : 'public/docs/collection.json';
  343. }
  344. protected function openapiOutputPath(bool $laravelType = false): string
  345. {
  346. return $laravelType
  347. ? Storage::disk('local')->path('scribe/openapi.yaml') : 'public/docs/openapi.yaml';
  348. }
  349. protected function htmlOutputPath(): string
  350. {
  351. return 'public/docs/index.html';
  352. }
  353. protected function bladeOutputPath(): string
  354. {
  355. return View::getFinder()->find('scribe/index');
  356. }
  357. }