OutputTest.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  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 Illuminate\Support\Str;
  7. use Knuckles\Scribe\Tests\BaseLaravelTest;
  8. use Knuckles\Scribe\Tests\Fixtures\TestController;
  9. use Knuckles\Scribe\Tests\Fixtures\TestGroupController;
  10. use Knuckles\Scribe\Tests\Fixtures\TestPartialResourceController;
  11. use Knuckles\Scribe\Tests\Fixtures\TestPost;
  12. use Knuckles\Scribe\Tests\Fixtures\TestPostBoundInterface;
  13. use Knuckles\Scribe\Tests\Fixtures\TestPostController;
  14. use Knuckles\Scribe\Tests\Fixtures\TestPostBoundInterfaceController;
  15. use Knuckles\Scribe\Tests\Fixtures\TestPostUserController;
  16. use Knuckles\Scribe\Tests\Fixtures\TestUser;
  17. use Knuckles\Scribe\Tests\TestHelpers;
  18. use Knuckles\Scribe\Tools\Utils;
  19. use Symfony\Component\DomCrawler\Crawler;
  20. use Symfony\Component\Yaml\Yaml;
  21. use Knuckles\Scribe\Extracting\Strategies;
  22. class OutputTest extends BaseLaravelTest
  23. {
  24. use TestHelpers;
  25. protected function setUp(): void
  26. {
  27. parent::setUp();
  28. config(['scribe.strategies' => [
  29. 'metadata' => [
  30. Strategies\Metadata\GetFromDocBlocks::class,
  31. Strategies\Metadata\GetFromMetadataAttributes::class,
  32. ],
  33. 'urlParameters' => [
  34. Strategies\UrlParameters\GetFromLaravelAPI::class,
  35. Strategies\UrlParameters\GetFromLumenAPI::class,
  36. Strategies\UrlParameters\GetFromUrlParamAttribute::class,
  37. Strategies\UrlParameters\GetFromUrlParamTag::class,
  38. ],
  39. 'queryParameters' => [
  40. Strategies\QueryParameters\GetFromFormRequest::class,
  41. Strategies\QueryParameters\GetFromInlineValidator::class,
  42. Strategies\QueryParameters\GetFromQueryParamAttribute::class,
  43. Strategies\QueryParameters\GetFromQueryParamTag::class,
  44. ],
  45. 'headers' => [
  46. Strategies\Headers\GetFromRouteRules::class,
  47. Strategies\Headers\GetFromHeaderAttribute::class,
  48. Strategies\Headers\GetFromHeaderTag::class,
  49. ],
  50. 'bodyParameters' => [
  51. Strategies\BodyParameters\GetFromFormRequest::class,
  52. Strategies\BodyParameters\GetFromInlineValidator::class,
  53. Strategies\BodyParameters\GetFromBodyParamAttribute::class,
  54. Strategies\BodyParameters\GetFromBodyParamTag::class,
  55. ],
  56. 'responses' => [
  57. Strategies\Responses\UseResponseAttributes::class,
  58. Strategies\Responses\UseTransformerTags::class,
  59. Strategies\Responses\UseApiResourceTags::class,
  60. Strategies\Responses\UseResponseTag::class,
  61. Strategies\Responses\UseResponseFileTag::class,
  62. Strategies\Responses\ResponseCalls::class,
  63. ],
  64. 'responseFields' => [
  65. Strategies\ResponseFields\GetFromResponseFieldAttribute::class,
  66. Strategies\ResponseFields\GetFromResponseFieldTag::class,
  67. ],
  68. ],
  69. ]);
  70. config(['scribe.database_connections_to_transact' => []]);
  71. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  72. // Skip these ones for faster tests
  73. config(['scribe.openapi.enabled' => false]);
  74. config(['scribe.postman.enabled' => false]);
  75. // We want to have the same values for params each time
  76. config(['scribe.examples.faker_seed' => 1234]);
  77. $factory = app(\Illuminate\Database\Eloquent\Factory::class);
  78. $factory->define(TestUser::class, function () {
  79. return [
  80. 'id' => 4,
  81. 'first_name' => 'Tested',
  82. 'last_name' => 'Again',
  83. 'email' => 'a@b.com',
  84. ];
  85. });
  86. }
  87. public function tearDown(): void
  88. {
  89. Utils::deleteDirectoryAndContents('public/docs');
  90. Utils::deleteDirectoryAndContents('.scribe');
  91. }
  92. protected function usingLaravelTypeDocs($app)
  93. {
  94. $app['config']->set('scribe.type', 'laravel');
  95. $app['config']->set('scribe.laravel.add_routes', true);
  96. $app['config']->set('scribe.laravel.docs_url', '/apidocs');
  97. }
  98. /**
  99. * @test
  100. * @define-env usingLaravelTypeDocs
  101. */
  102. public function generates_laravel_type_output()
  103. {
  104. RouteFacade::post('/api/withQueryParameters', [TestController::class, 'withQueryParameters']);
  105. config(['scribe.postman.enabled' => true]);
  106. config(['scribe.openapi.enabled' => true]);
  107. $this->generateAndExpectConsoleOutput(
  108. "Wrote Blade docs to: vendor/orchestra/testbench-core/laravel/resources/views/scribe",
  109. "Wrote Laravel assets to: vendor/orchestra/testbench-core/laravel/public/vendor/scribe",
  110. "Wrote Postman collection to: vendor/orchestra/testbench-core/laravel/storage/app/scribe/collection.json",
  111. "Wrote OpenAPI specification to: vendor/orchestra/testbench-core/laravel/storage/app/scribe/openapi.yaml",
  112. );
  113. $this->assertFileExists($this->postmanOutputPath(true));
  114. $this->assertFileExists($this->openapiOutputPath(true));
  115. $this->assertFileExists($this->bladeOutputPath());
  116. $response = $this->get('/apidocs/');
  117. $response->assertStatus(200);
  118. $response = $this->get('/apidocs.postman');
  119. $response->assertStatus(200);
  120. $response = $this->get('/apidocs.openapi');
  121. $response->assertStatus(200);
  122. unlink($this->postmanOutputPath(true));
  123. unlink($this->openapiOutputPath(true));
  124. unlink($this->bladeOutputPath());
  125. }
  126. /** @test */
  127. public function supports_multi_docs_in_laravel_type_output()
  128. {
  129. $this->generate_with_paths(configName: "scribe_admin");
  130. }
  131. /** @test */
  132. public function supports_custom_scribe_directory()
  133. {
  134. $this->generate_with_paths(configName: "scribe_admin", intermediateOutputDirectory: '5.5/Apple/26');
  135. }
  136. private function generate_with_paths($configName, $intermediateOutputDirectory = null)
  137. {
  138. RouteFacade::post('/api/withQueryParameters', [TestController::class, 'withQueryParameters']);
  139. config([$configName => config('scribe')]);
  140. $title = "The Real Admin API";
  141. config(["{$configName}.title" => $title]);
  142. config(["{$configName}.type" => 'laravel']);
  143. config(["{$configName}.postman.enabled" => true]);
  144. config(["{$configName}.openapi.enabled" => true]);
  145. $pathOptions = ["--config" => $configName];
  146. if ($intermediateOutputDirectory) {
  147. $pathOptions["--scribe-dir"] = $intermediateOutputDirectory;
  148. }
  149. $output = $this->generate($pathOptions);
  150. $this->assertStringContainsString(
  151. "Wrote Blade docs to: vendor/orchestra/testbench-core/laravel/resources/views/{$configName}", $output
  152. );
  153. $this->assertStringContainsString(
  154. "Wrote Laravel assets to: vendor/orchestra/testbench-core/laravel/public/vendor/{$configName}", $output
  155. );
  156. $this->assertStringContainsString(
  157. "Wrote Postman collection to: vendor/orchestra/testbench-core/laravel/storage/app/{$configName}/collection.json", $output
  158. );
  159. $this->assertStringContainsString(
  160. "Wrote OpenAPI specification to: vendor/orchestra/testbench-core/laravel/storage/app/{$configName}/openapi.yaml", $output
  161. );
  162. $paths = collect([
  163. Storage::disk('local')->path("{$configName}/collection.json"),
  164. Storage::disk('local')->path("{$configName}/openapi.yaml"),
  165. View::getFinder()->find("{$configName}/index"),
  166. ]);
  167. $paths->each(fn($path) => $this->assertFileContainsString($path, $title));
  168. $paths->each(fn($path) => unlink($path));
  169. $this->assertDirectoryExists($intermediateOutputDirectory ?: ".{$configName}");
  170. Utils::deleteDirectoryAndContents($intermediateOutputDirectory ?: ".{$configName}");
  171. }
  172. /** @test */
  173. public function generated_postman_collection_file_is_correct()
  174. {
  175. RouteFacade::post('/api/withBodyParametersAsArray', [TestController::class, 'withBodyParametersAsArray']);
  176. RouteFacade::post('/api/withFormDataParams', [TestController::class, 'withFormDataParams']);
  177. RouteFacade::post('/api/withBodyParameters', [TestController::class, 'withBodyParameters']);
  178. RouteFacade::get('/api/withQueryParameters', [TestController::class, 'withQueryParameters']);
  179. RouteFacade::get('/api/withAuthTag', [TestController::class, 'withAuthenticatedTag']);
  180. RouteFacade::get('/api/echoesUrlParameters/{param}/{param2}/{param3?}/{param4?}', [TestController::class, 'echoesUrlParameters']);
  181. config(['scribe.title' => 'GREAT API!']);
  182. config(['scribe.auth.enabled' => true]);
  183. config(['scribe.postman.overrides' => [
  184. 'info.version' => '3.9.9',
  185. ]]);
  186. config([
  187. 'scribe.routes.0.apply.headers' => [
  188. 'Custom-Header' => 'NotSoCustom',
  189. ],
  190. ]);
  191. config(['scribe.postman.enabled' => true]);
  192. $this->generateAndExpectConsoleOutput(
  193. "Wrote HTML docs and assets to: public/docs/",
  194. "Wrote Postman collection to: public/docs/collection.json"
  195. );
  196. $generatedCollection = json_decode(file_get_contents($this->postmanOutputPath()), true);
  197. // The Postman ID varies from call to call; erase it to make the test data reproducible.
  198. $generatedCollection['info']['_postman_id'] = '';
  199. $fixtureCollection = json_decode(file_get_contents(__DIR__ . '/../Fixtures/collection.json'), true);
  200. $this->assertEquals($fixtureCollection, $generatedCollection);
  201. }
  202. /** @test */
  203. public function generated_openapi_spec_file_is_correct()
  204. {
  205. RouteFacade::post('/api/withBodyParametersAsArray', [TestController::class, 'withBodyParametersAsArray']);
  206. RouteFacade::post('/api/withFormDataParams', [TestController::class, 'withFormDataParams']);
  207. RouteFacade::get('/api/withResponseTag', [TestController::class, 'withResponseTag']);
  208. RouteFacade::get('/api/withQueryParameters', [TestController::class, 'withQueryParameters']);
  209. RouteFacade::get('/api/withAuthTag', [TestController::class, 'withAuthenticatedTag']);
  210. RouteFacade::get('/api/echoesUrlParameters/{param}/{param2}/{param3?}/{param4?}', [TestController::class, 'echoesUrlParameters']);
  211. config(['scribe.openapi.enabled' => true]);
  212. config(['scribe.openapi.overrides' => [
  213. 'info.version' => '3.9.9',
  214. ]]);
  215. config([
  216. 'scribe.routes.0.apply.headers' => [
  217. 'Custom-Header' => 'NotSoCustom',
  218. ],
  219. ]);
  220. $this->generateAndExpectConsoleOutput(
  221. "Wrote HTML docs and assets to: public/docs/",
  222. "Wrote OpenAPI specification to: public/docs/openapi.yaml"
  223. );
  224. $generatedSpec = Yaml::parseFile($this->openapiOutputPath());
  225. $fixtureSpec = Yaml::parseFile(__DIR__ . '/../Fixtures/openapi.yaml');
  226. $this->assertEquals($fixtureSpec, $generatedSpec);
  227. }
  228. /** @test */
  229. public function can_append_custom_http_headers()
  230. {
  231. RouteFacade::get('/api/headers', [TestController::class, 'checkCustomHeaders']);
  232. config([
  233. 'scribe.routes.0.apply.headers' => [
  234. 'Authorization' => 'customAuthToken',
  235. 'Custom-Header' => 'NotSoCustom',
  236. ],
  237. ]);
  238. $this->generate();
  239. $endpointDetails = Yaml::parseFile('.scribe/endpoints/00.yaml')['endpoints'][0];
  240. $this->assertEquals("customAuthToken", $endpointDetails['headers']["Authorization"]);
  241. $this->assertEquals("NotSoCustom", $endpointDetails['headers']["Custom-Header"]);
  242. }
  243. /** @test */
  244. public function can_parse_utf8_response()
  245. {
  246. RouteFacade::get('/api/utf8', [TestController::class, 'withUtf8ResponseTag']);
  247. $this->generate();
  248. $generatedHtml = file_get_contents($this->htmlOutputPath());
  249. $this->assertStringContainsString('Лорем ипсум долор сит амет', $generatedHtml);
  250. }
  251. /** @test */
  252. public function sorts_group_naturally_if_no_order_specified()
  253. {
  254. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  255. RouteFacade::get('/api/action1b', [TestGroupController::class, 'action1b']);
  256. RouteFacade::get('/api/action2', [TestGroupController::class, 'action2']);
  257. RouteFacade::get('/api/action10', [TestGroupController::class, 'action10']);
  258. $this->generate();
  259. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  260. $headings = $crawler->filter('h1')->getIterator();
  261. $this->assertCount(5, $headings); // intro, auth, three groups
  262. [$_, $_, $firstGroup, $secondGroup, $thirdGroup] = $headings;
  263. $this->assertEquals('1. Group 1', $firstGroup->textContent);
  264. $this->assertEquals('2. Group 2', $secondGroup->textContent);
  265. $this->assertEquals('10. Group 10', $thirdGroup->textContent);
  266. }
  267. /** @test */
  268. public function sorts_groups_and_endpoints_in_the_specified_order()
  269. {
  270. config(['scribe.groups.order' => [
  271. '10. Group 10',
  272. '1. Group 1' => [
  273. 'GET /api/action1b',
  274. 'GET /api/action1',
  275. ],
  276. '13. Group 13' => [
  277. 'SG B' => [
  278. 'POST /api/action13d',
  279. 'GET /api/action13a',
  280. ],
  281. 'SG A',
  282. 'PUT /api/action13c',
  283. ],
  284. ]]);
  285. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  286. RouteFacade::get('/api/action1b', [TestGroupController::class, 'action1b']);
  287. RouteFacade::get('/api/action2', [TestGroupController::class, 'action2']);
  288. RouteFacade::get('/api/action10', [TestGroupController::class, 'action10']);
  289. RouteFacade::get('/api/action13a', [TestGroupController::class, 'action13a']);
  290. RouteFacade::post('/api/action13b', [TestGroupController::class, 'action13b']);
  291. RouteFacade::put('/api/action13c', [TestGroupController::class, 'action13c']);
  292. RouteFacade::post('/api/action13d', [TestGroupController::class, 'action13d']);
  293. RouteFacade::get('/api/action13e', [TestGroupController::class, 'action13e']);
  294. $this->generate();
  295. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  296. $headings = $crawler->filter('h1')->getIterator();
  297. $this->assertCount(6, $headings); // intro, auth, four groups
  298. [$_, $_, $firstGroup, $secondGroup, $thirdGroup, $fourthGroup] = $headings;
  299. $this->assertEquals('10. Group 10', $firstGroup->textContent);
  300. $this->assertEquals('1. Group 1', $secondGroup->textContent);
  301. $this->assertEquals('13. Group 13', $thirdGroup->textContent);
  302. $this->assertEquals('2. Group 2', $fourthGroup->textContent);
  303. $firstGroupEndpointsAndSubgroups = $crawler->filter('h2[id^="'.Str::slug($firstGroup->textContent).'"]');
  304. $this->assertEquals(1, $firstGroupEndpointsAndSubgroups->count());
  305. $this->assertEquals("GET api/action10", $firstGroupEndpointsAndSubgroups->getNode(0)->textContent);
  306. $secondGroupEndpointsAndSubgroups = $crawler->filter('h2[id^="'.Str::slug($secondGroup->textContent).'"]');
  307. $this->assertEquals(2, $secondGroupEndpointsAndSubgroups->count());
  308. $this->assertEquals("GET api/action1b", $secondGroupEndpointsAndSubgroups->getNode(0)->textContent);
  309. $this->assertEquals("GET api/action1", $secondGroupEndpointsAndSubgroups->getNode(1)->textContent);
  310. $thirdGroupEndpointsAndSubgroups = $crawler->filter('h2[id^="'.Str::slug($thirdGroup->textContent).'"]');
  311. $this->assertEquals(8, $thirdGroupEndpointsAndSubgroups->count());
  312. $this->assertEquals("SG B", $thirdGroupEndpointsAndSubgroups->getNode(0)->textContent);
  313. $this->assertEquals("POST api/action13d", $thirdGroupEndpointsAndSubgroups->getNode(1)->textContent);
  314. $this->assertEquals("GET api/action13a", $thirdGroupEndpointsAndSubgroups->getNode(2)->textContent);
  315. $this->assertEquals("SG A", $thirdGroupEndpointsAndSubgroups->getNode(3)->textContent);
  316. $this->assertEquals("GET api/action13e", $thirdGroupEndpointsAndSubgroups->getNode(4)->textContent);
  317. $this->assertEquals("PUT api/action13c", $thirdGroupEndpointsAndSubgroups->getNode(5)->textContent);
  318. $this->assertEquals("SG C", $thirdGroupEndpointsAndSubgroups->getNode(6)->textContent);
  319. $this->assertEquals("POST api/action13b", $thirdGroupEndpointsAndSubgroups->getNode(7)->textContent);
  320. }
  321. /** @test */
  322. public function sorts_groups_and_endpoints_in_the_specified_order_with_wildcard()
  323. {
  324. config(['scribe.groups.order' => [
  325. '10. Group 10',
  326. '*',
  327. '13. Group 13' => [
  328. 'SG B' => [
  329. 'POST /api/action13d',
  330. 'GET /api/action13a',
  331. ],
  332. 'SG A',
  333. 'PUT /api/action13c',
  334. ],
  335. ]]);
  336. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  337. RouteFacade::get('/api/action1b', [TestGroupController::class, 'action1b']);
  338. RouteFacade::get('/api/action2', [TestGroupController::class, 'action2']);
  339. RouteFacade::get('/api/action10', [TestGroupController::class, 'action10']);
  340. RouteFacade::get('/api/action13a', [TestGroupController::class, 'action13a']);
  341. RouteFacade::post('/api/action13b', [TestGroupController::class, 'action13b']);
  342. RouteFacade::put('/api/action13c', [TestGroupController::class, 'action13c']);
  343. RouteFacade::post('/api/action13d', [TestGroupController::class, 'action13d']);
  344. RouteFacade::get('/api/action13e', [TestGroupController::class, 'action13e']);
  345. $this->generate();
  346. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  347. $headings = $crawler->filter('h1')->getIterator();
  348. $this->assertCount(6, $headings); // intro, auth, four groups
  349. [$_, $_, $firstGroup, $secondGroup, $thirdGroup, $fourthGroup] = $headings;
  350. $this->assertEquals('10. Group 10', $firstGroup->textContent);
  351. $this->assertEquals('1. Group 1', $secondGroup->textContent);
  352. $this->assertEquals('2. Group 2', $thirdGroup->textContent);
  353. $this->assertEquals('13. Group 13', $fourthGroup->textContent);
  354. $firstGroupEndpointsAndSubgroups = $crawler->filter('h2[id^="'.Str::slug($firstGroup->textContent).'"]');
  355. $this->assertEquals(1, $firstGroupEndpointsAndSubgroups->count());
  356. $this->assertEquals("GET api/action10", $firstGroupEndpointsAndSubgroups->getNode(0)->textContent);
  357. $secondGroupEndpointsAndSubgroups = $crawler->filter('h2[id^="'.Str::slug($secondGroup->textContent).'"]');
  358. $this->assertEquals(2, $secondGroupEndpointsAndSubgroups->count());
  359. $this->assertEquals("GET api/action1", $secondGroupEndpointsAndSubgroups->getNode(0)->textContent);
  360. $this->assertEquals("GET api/action1b", $secondGroupEndpointsAndSubgroups->getNode(1)->textContent);
  361. $fourthGroupEndpointsAndSubgroups = $crawler->filter('h2[id^="'.Str::slug($fourthGroup->textContent).'"]');
  362. $this->assertEquals(8, $fourthGroupEndpointsAndSubgroups->count());
  363. $this->assertEquals("SG B", $fourthGroupEndpointsAndSubgroups->getNode(0)->textContent);
  364. $this->assertEquals("POST api/action13d", $fourthGroupEndpointsAndSubgroups->getNode(1)->textContent);
  365. $this->assertEquals("GET api/action13a", $fourthGroupEndpointsAndSubgroups->getNode(2)->textContent);
  366. $this->assertEquals("SG A", $fourthGroupEndpointsAndSubgroups->getNode(3)->textContent);
  367. $this->assertEquals("GET api/action13e", $fourthGroupEndpointsAndSubgroups->getNode(4)->textContent);
  368. $this->assertEquals("PUT api/action13c", $fourthGroupEndpointsAndSubgroups->getNode(5)->textContent);
  369. $this->assertEquals("SG C", $fourthGroupEndpointsAndSubgroups->getNode(6)->textContent);
  370. $this->assertEquals("POST api/action13b", $fourthGroupEndpointsAndSubgroups->getNode(7)->textContent);
  371. }
  372. /** @test */
  373. public function merges_and_correctly_sorts_user_defined_endpoints()
  374. {
  375. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  376. RouteFacade::get('/api/action2', [TestGroupController::class, 'action2']);
  377. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  378. config(['scribe.groups.order' => [
  379. '1. Group 1',
  380. '5. Group 5',
  381. '4. Group 4',
  382. '2. Group 2',
  383. ]]);
  384. if (!is_dir('.scribe/endpoints')) mkdir('.scribe/endpoints', 0777, true);
  385. copy(__DIR__ . '/../Fixtures/custom.0.yaml', '.scribe/endpoints/custom.0.yaml');
  386. $this->generate();
  387. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  388. $headings = $crawler->filter('h1')->getIterator();
  389. $this->assertCount(6, $headings); // intro, auth, four groups
  390. [$_, $_, $firstGroup, $secondGroup, $thirdGroup, $fourthGroup] = $headings;
  391. $this->assertEquals('1. Group 1', $firstGroup->textContent);
  392. $this->assertEquals('5. Group 5', $secondGroup->textContent);
  393. $this->assertEquals('4. Group 4', $thirdGroup->textContent);
  394. $this->assertEquals('2. Group 2', $fourthGroup->textContent);
  395. $firstGroupEndpointsAndSubgroups = $crawler->filter('h2[id^="'.Str::slug($firstGroup->textContent).'"]');
  396. $this->assertEquals(2, $firstGroupEndpointsAndSubgroups->count());
  397. $this->assertEquals("GET api/action1", $firstGroupEndpointsAndSubgroups->getNode(0)->textContent);
  398. $this->assertEquals("User defined", $firstGroupEndpointsAndSubgroups->getNode(1)->textContent);
  399. $secondGroupEndpointsAndSubgroups = $crawler->filter('h2[id^="'.Str::slug($secondGroup->textContent).'"]');
  400. $this->assertEquals(2, $secondGroupEndpointsAndSubgroups->count());
  401. $this->assertEquals("GET group5", $secondGroupEndpointsAndSubgroups->getNode(0)->textContent);
  402. $this->assertEquals("GET alsoGroup5", $secondGroupEndpointsAndSubgroups->getNode(1)->textContent);
  403. $thirdGroupEndpointsAndSubgroups = $crawler->filter('h2[id^="'.Str::slug($thirdGroup->textContent).'"]');
  404. $this->assertEquals(1, $thirdGroupEndpointsAndSubgroups->count());
  405. $this->assertEquals("GET group4", $thirdGroupEndpointsAndSubgroups->getNode(0)->textContent);
  406. $fourthGroupEndpointsAndSubgroups = $crawler->filter('h2[id^="'.Str::slug($fourthGroup->textContent).'"]');
  407. $this->assertEquals(1, $fourthGroupEndpointsAndSubgroups->count());
  408. $this->assertEquals("GET api/action2", $fourthGroupEndpointsAndSubgroups->getNode(0)->textContent);
  409. }
  410. /** @test */
  411. public function will_not_overwrite_manually_modified_content_unless_force_flag_is_set()
  412. {
  413. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  414. RouteFacade::get('/api/action1b', [TestGroupController::class, 'action1b']);
  415. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  416. $this->generate();
  417. $authFilePath = '.scribe/auth.md';
  418. $firstGroupFilePath = '.scribe/endpoints/00.yaml';
  419. $group = Yaml::parseFile($firstGroupFilePath);
  420. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  421. $this->assertEquals([], $group['endpoints'][0]['urlParameters']);
  422. $extraParam = [
  423. 'name' => 'a_param',
  424. 'description' => 'A URL param.',
  425. 'required' => true,
  426. 'example' => 6,
  427. 'type' => 'integer',
  428. 'enumValues' => [],
  429. 'custom' => [],
  430. 'exampleWasSpecified' => false,
  431. ];
  432. $group['endpoints'][0]['urlParameters']['a_param'] = $extraParam;
  433. file_put_contents($firstGroupFilePath, Yaml::dump(
  434. $group, 20, 2,
  435. Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE | Yaml::DUMP_OBJECT_AS_MAP
  436. ));
  437. file_put_contents($authFilePath, 'Some other useful stuff.', FILE_APPEND);
  438. $this->generate();
  439. $group = Yaml::parseFile($firstGroupFilePath);
  440. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  441. $this->assertEquals(['a_param' => $extraParam], $group['endpoints'][0]['urlParameters']);
  442. $this->assertStringContainsString('Some other useful stuff.', file_get_contents($authFilePath));
  443. $this->generate(['--force' => true]);
  444. $group = Yaml::parseFile($firstGroupFilePath);
  445. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  446. $this->assertEquals([], $group['endpoints'][0]['urlParameters']);
  447. $this->assertStringNotContainsString('Some other useful stuff.', file_get_contents($authFilePath));
  448. }
  449. /** @test */
  450. public function generates_correct_url_params_from_resource_routes_and_field_bindings()
  451. {
  452. RouteFacade::prefix('providers/{provider:slug}')->group(function () {
  453. RouteFacade::resource('users.addresses', TestPartialResourceController::class)->parameters([
  454. 'addresses' => 'address:uuid',
  455. ]);
  456. });
  457. config(['scribe.routes.0.match.prefixes' => ['*']]);
  458. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  459. $this->generate();
  460. $groupA = Yaml::parseFile('.scribe/endpoints/00.yaml');
  461. $this->assertEquals('providers/{provider_slug}/users/{user_id}/addresses', $groupA['endpoints'][0]['uri']);
  462. $groupB = Yaml::parseFile('.scribe/endpoints/01.yaml');
  463. $this->assertEquals('providers/{provider_slug}/users/{user_id}/addresses/{uuid}', $groupB['endpoints'][0]['uri']);
  464. }
  465. /** @test */
  466. public function generates_correct_url_params_from_resource_routes_and_model_binding()
  467. {
  468. RouteFacade::resource('posts', TestPostController::class)->only('update');
  469. RouteFacade::resource('posts.users', TestPostUserController::class)->only('update');
  470. config(['scribe.routes.0.match.prefixes' => ['*']]);
  471. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  472. $this->generate();
  473. $group = Yaml::parseFile('.scribe/endpoints/00.yaml');
  474. $this->assertEquals('posts/{slug}', $group['endpoints'][0]['uri']);
  475. $this->assertEquals('posts/{post_slug}/users/{id}', $group['endpoints'][1]['uri']);
  476. }
  477. /** @test */
  478. public function generates_correct_url_params_from_resource_routes_and_model_binding_with_bound_interfaces()
  479. {
  480. $this->app->bind(TestPostBoundInterface::class, fn() => new TestPost());
  481. RouteFacade::resource('posts', TestPostBoundInterfaceController::class)->only('update');
  482. config(['scribe.routes.0.match.prefixes' => ['*']]);
  483. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  484. $this->generate();
  485. $group = Yaml::parseFile('.scribe/endpoints/00.yaml');
  486. $this->assertEquals('posts/{slug}', $group['endpoints'][0]['uri']);
  487. }
  488. /** @test */
  489. public function generates_correct_url_params_from_non_resource_routes_and_model_binding()
  490. {
  491. RouteFacade::get('posts/{post}/users', function (TestPost $post) {
  492. });
  493. config(['scribe.routes.0.match.prefixes' => ['*']]);
  494. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  495. $this->generate();
  496. $group = Yaml::parseFile('.scribe/endpoints/00.yaml');
  497. $this->assertEquals('posts/{post_slug}/users', $group['endpoints'][0]['uri']);
  498. }
  499. /** @test */
  500. public function generates_from_camel_dir_if_noExtraction_flag_is_set()
  501. {
  502. config(['scribe.routes.0.exclude' => ['*']]);
  503. Utils::copyDirectory(__DIR__ . '/../Fixtures/.scribe', '.scribe');
  504. $output = $this->generate(['--no-extraction' => true]);
  505. $this->assertStringNotContainsString("Processing route", $output);
  506. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  507. [$intro, $auth] = $crawler->filter('h1 + p')->getIterator();
  508. $this->assertEquals('Heyaa introduction!👋', trim($intro->firstChild->textContent));
  509. $this->assertEquals('This is just a test.', trim($auth->firstChild->textContent));
  510. $group = $crawler->filter('h1')->getNode(2);
  511. $this->assertEquals('General', trim($group->textContent));
  512. $expectedEndpoint = $crawler->filter('h2');
  513. $this->assertCount(1, $expectedEndpoint);
  514. $this->assertEquals("Healthcheck", $expectedEndpoint->text());
  515. }
  516. /** @test */
  517. public function will_auto_set_content_type_to_multipart_if_file_params_are_present()
  518. {
  519. /**
  520. * @bodyParam param string required
  521. */
  522. RouteFacade::post('no-file', fn() => null);
  523. /**
  524. * @bodyParam a_file file required
  525. */
  526. RouteFacade::post('top-level-file', fn() => null);
  527. /**
  528. * @bodyParam data object
  529. * @bodyParam data.thing string
  530. * @bodyParam data.a_file file
  531. */
  532. RouteFacade::post('nested-file', fn() => null);
  533. config(['scribe.routes.0.match.prefixes' => ['*']]);
  534. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  535. $this->generate();
  536. $group = Yaml::parseFile('.scribe/endpoints/00.yaml');
  537. $this->assertEquals('no-file', $group['endpoints'][0]['uri']);
  538. $this->assertEquals('application/json', $group['endpoints'][0]['headers']['Content-Type']);
  539. $this->assertEquals('top-level-file', $group['endpoints'][1]['uri']);
  540. $this->assertEquals('multipart/form-data', $group['endpoints'][1]['headers']['Content-Type']);
  541. $this->assertEquals('nested-file', $group['endpoints'][2]['uri']);
  542. $this->assertEquals('multipart/form-data', $group['endpoints'][2]['headers']['Content-Type']);
  543. }
  544. protected function postmanOutputPath(bool $laravelType = false): string
  545. {
  546. return $laravelType
  547. ? Storage::disk('local')->path('scribe/collection.json') : 'public/docs/collection.json';
  548. }
  549. protected function openapiOutputPath(bool $laravelType = false): string
  550. {
  551. return $laravelType
  552. ? Storage::disk('local')->path('scribe/openapi.yaml') : 'public/docs/openapi.yaml';
  553. }
  554. protected function htmlOutputPath(): string
  555. {
  556. return 'public/docs/index.html';
  557. }
  558. protected function bladeOutputPath(): string
  559. {
  560. return View::getFinder()->find('scribe/index');
  561. }
  562. }