OutputTest.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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. dump($fixtureCollection == $generatedCollection);
  201. $this->assertEquals($fixtureCollection, $generatedCollection);
  202. }
  203. /** @test */
  204. public function generated_openapi_spec_file_is_correct()
  205. {
  206. RouteFacade::post('/api/withBodyParametersAsArray', [TestController::class, 'withBodyParametersAsArray']);
  207. RouteFacade::post('/api/withFormDataParams', [TestController::class, 'withFormDataParams']);
  208. RouteFacade::get('/api/withResponseTag', [TestController::class, 'withResponseTag']);
  209. RouteFacade::get('/api/withQueryParameters', [TestController::class, 'withQueryParameters']);
  210. RouteFacade::get('/api/withAuthTag', [TestController::class, 'withAuthenticatedTag']);
  211. RouteFacade::get('/api/echoesUrlParameters/{param}/{param2}/{param3?}/{param4?}', [TestController::class, 'echoesUrlParameters']);
  212. config(['scribe.openapi.enabled' => true]);
  213. config(['scribe.openapi.overrides' => [
  214. 'info.version' => '3.9.9',
  215. ]]);
  216. config([
  217. 'scribe.routes.0.apply.headers' => [
  218. 'Custom-Header' => 'NotSoCustom',
  219. ],
  220. ]);
  221. $this->generateAndExpectConsoleOutput(
  222. "Wrote HTML docs and assets to: public/docs/",
  223. "Wrote OpenAPI specification to: public/docs/openapi.yaml"
  224. );
  225. $generatedSpec = Yaml::parseFile($this->openapiOutputPath());
  226. $fixtureSpec = Yaml::parseFile(__DIR__ . '/../Fixtures/openapi.yaml');
  227. $this->assertEquals($fixtureSpec, $generatedSpec);
  228. }
  229. /** @test */
  230. public function can_append_custom_http_headers()
  231. {
  232. RouteFacade::get('/api/headers', [TestController::class, 'checkCustomHeaders']);
  233. config([
  234. 'scribe.routes.0.apply.headers' => [
  235. 'Authorization' => 'customAuthToken',
  236. 'Custom-Header' => 'NotSoCustom',
  237. ],
  238. ]);
  239. $this->generate();
  240. $endpointDetails = Yaml::parseFile('.scribe/endpoints/00.yaml')['endpoints'][0];
  241. $this->assertEquals("customAuthToken", $endpointDetails['headers']["Authorization"]);
  242. $this->assertEquals("NotSoCustom", $endpointDetails['headers']["Custom-Header"]);
  243. }
  244. /** @test */
  245. public function can_parse_utf8_response()
  246. {
  247. RouteFacade::get('/api/utf8', [TestController::class, 'withUtf8ResponseTag']);
  248. $this->generate();
  249. $generatedHtml = file_get_contents($this->htmlOutputPath());
  250. $this->assertStringContainsString('Лорем ипсум долор сит амет', $generatedHtml);
  251. }
  252. /** @test */
  253. public function sorts_group_naturally_if_no_order_specified()
  254. {
  255. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  256. RouteFacade::get('/api/action1b', [TestGroupController::class, 'action1b']);
  257. RouteFacade::get('/api/action2', [TestGroupController::class, 'action2']);
  258. RouteFacade::get('/api/action10', [TestGroupController::class, 'action10']);
  259. $this->generate();
  260. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  261. $headings = $crawler->filter('h1')->getIterator();
  262. $this->assertCount(5, $headings); // intro, auth, three groups
  263. [$_, $_, $firstGroup, $secondGroup, $thirdGroup] = $headings;
  264. $this->assertEquals('1. Group 1', $firstGroup->textContent);
  265. $this->assertEquals('2. Group 2', $secondGroup->textContent);
  266. $this->assertEquals('10. Group 10', $thirdGroup->textContent);
  267. }
  268. /** @test */
  269. public function sorts_groups_and_endpoints_in_the_specified_order()
  270. {
  271. config(['scribe.groups.order' => [
  272. '10. Group 10',
  273. '1. Group 1' => [
  274. 'GET /api/action1b',
  275. 'GET /api/action1',
  276. ],
  277. '13. Group 13' => [
  278. 'SG B' => [
  279. 'POST /api/action13d',
  280. 'GET /api/action13a',
  281. ],
  282. 'SG A',
  283. 'PUT /api/action13c',
  284. ],
  285. ]]);
  286. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  287. RouteFacade::get('/api/action1b', [TestGroupController::class, 'action1b']);
  288. RouteFacade::get('/api/action2', [TestGroupController::class, 'action2']);
  289. RouteFacade::get('/api/action10', [TestGroupController::class, 'action10']);
  290. RouteFacade::get('/api/action13a', [TestGroupController::class, 'action13a']);
  291. RouteFacade::post('/api/action13b', [TestGroupController::class, 'action13b']);
  292. RouteFacade::put('/api/action13c', [TestGroupController::class, 'action13c']);
  293. RouteFacade::post('/api/action13d', [TestGroupController::class, 'action13d']);
  294. RouteFacade::get('/api/action13e', [TestGroupController::class, 'action13e']);
  295. $this->generate();
  296. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  297. $headings = $crawler->filter('h1')->getIterator();
  298. $this->assertCount(6, $headings); // intro, auth, four groups
  299. [$_, $_, $firstGroup, $secondGroup, $thirdGroup, $fourthGroup] = $headings;
  300. $this->assertEquals('10. Group 10', $firstGroup->textContent);
  301. $this->assertEquals('1. Group 1', $secondGroup->textContent);
  302. $this->assertEquals('13. Group 13', $thirdGroup->textContent);
  303. $this->assertEquals('2. Group 2', $fourthGroup->textContent);
  304. $firstGroupEndpointsAndSubgroups = $crawler->filter('h2[id^="'.Str::slug($firstGroup->textContent).'"]');
  305. $this->assertEquals(1, $firstGroupEndpointsAndSubgroups->count());
  306. $this->assertEquals("GET api/action10", $firstGroupEndpointsAndSubgroups->getNode(0)->textContent);
  307. $secondGroupEndpointsAndSubgroups = $crawler->filter('h2[id^="'.Str::slug($secondGroup->textContent).'"]');
  308. $this->assertEquals(2, $secondGroupEndpointsAndSubgroups->count());
  309. $this->assertEquals("GET api/action1b", $secondGroupEndpointsAndSubgroups->getNode(0)->textContent);
  310. $this->assertEquals("GET api/action1", $secondGroupEndpointsAndSubgroups->getNode(1)->textContent);
  311. $thirdGroupEndpointsAndSubgroups = $crawler->filter('h2[id^="'.Str::slug($thirdGroup->textContent).'"]');
  312. $this->assertEquals(8, $thirdGroupEndpointsAndSubgroups->count());
  313. $this->assertEquals("SG B", $thirdGroupEndpointsAndSubgroups->getNode(0)->textContent);
  314. $this->assertEquals("POST api/action13d", $thirdGroupEndpointsAndSubgroups->getNode(1)->textContent);
  315. $this->assertEquals("GET api/action13a", $thirdGroupEndpointsAndSubgroups->getNode(2)->textContent);
  316. $this->assertEquals("SG A", $thirdGroupEndpointsAndSubgroups->getNode(3)->textContent);
  317. $this->assertEquals("GET api/action13e", $thirdGroupEndpointsAndSubgroups->getNode(4)->textContent);
  318. $this->assertEquals("PUT api/action13c", $thirdGroupEndpointsAndSubgroups->getNode(5)->textContent);
  319. $this->assertEquals("SG C", $thirdGroupEndpointsAndSubgroups->getNode(6)->textContent);
  320. $this->assertEquals("POST api/action13b", $thirdGroupEndpointsAndSubgroups->getNode(7)->textContent);
  321. }
  322. /** @test */
  323. public function sorts_groups_and_endpoints_in_the_specified_order_with_wildcard()
  324. {
  325. config(['scribe.groups.order' => [
  326. '10. Group 10',
  327. '*',
  328. '13. Group 13' => [
  329. 'SG B' => [
  330. 'POST /api/action13d',
  331. 'GET /api/action13a',
  332. ],
  333. 'SG A',
  334. 'PUT /api/action13c',
  335. ],
  336. ]]);
  337. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  338. RouteFacade::get('/api/action1b', [TestGroupController::class, 'action1b']);
  339. RouteFacade::get('/api/action2', [TestGroupController::class, 'action2']);
  340. RouteFacade::get('/api/action10', [TestGroupController::class, 'action10']);
  341. RouteFacade::get('/api/action13a', [TestGroupController::class, 'action13a']);
  342. RouteFacade::post('/api/action13b', [TestGroupController::class, 'action13b']);
  343. RouteFacade::put('/api/action13c', [TestGroupController::class, 'action13c']);
  344. RouteFacade::post('/api/action13d', [TestGroupController::class, 'action13d']);
  345. RouteFacade::get('/api/action13e', [TestGroupController::class, 'action13e']);
  346. $this->generate();
  347. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  348. $headings = $crawler->filter('h1')->getIterator();
  349. $this->assertCount(6, $headings); // intro, auth, four groups
  350. [$_, $_, $firstGroup, $secondGroup, $thirdGroup, $fourthGroup] = $headings;
  351. $this->assertEquals('10. Group 10', $firstGroup->textContent);
  352. $this->assertEquals('1. Group 1', $secondGroup->textContent);
  353. $this->assertEquals('2. Group 2', $thirdGroup->textContent);
  354. $this->assertEquals('13. Group 13', $fourthGroup->textContent);
  355. $firstGroupEndpointsAndSubgroups = $crawler->filter('h2[id^="'.Str::slug($firstGroup->textContent).'"]');
  356. $this->assertEquals(1, $firstGroupEndpointsAndSubgroups->count());
  357. $this->assertEquals("GET api/action10", $firstGroupEndpointsAndSubgroups->getNode(0)->textContent);
  358. $secondGroupEndpointsAndSubgroups = $crawler->filter('h2[id^="'.Str::slug($secondGroup->textContent).'"]');
  359. $this->assertEquals(2, $secondGroupEndpointsAndSubgroups->count());
  360. $this->assertEquals("GET api/action1", $secondGroupEndpointsAndSubgroups->getNode(0)->textContent);
  361. $this->assertEquals("GET api/action1b", $secondGroupEndpointsAndSubgroups->getNode(1)->textContent);
  362. $fourthGroupEndpointsAndSubgroups = $crawler->filter('h2[id^="'.Str::slug($fourthGroup->textContent).'"]');
  363. $this->assertEquals(8, $fourthGroupEndpointsAndSubgroups->count());
  364. $this->assertEquals("SG B", $fourthGroupEndpointsAndSubgroups->getNode(0)->textContent);
  365. $this->assertEquals("POST api/action13d", $fourthGroupEndpointsAndSubgroups->getNode(1)->textContent);
  366. $this->assertEquals("GET api/action13a", $fourthGroupEndpointsAndSubgroups->getNode(2)->textContent);
  367. $this->assertEquals("SG A", $fourthGroupEndpointsAndSubgroups->getNode(3)->textContent);
  368. $this->assertEquals("GET api/action13e", $fourthGroupEndpointsAndSubgroups->getNode(4)->textContent);
  369. $this->assertEquals("PUT api/action13c", $fourthGroupEndpointsAndSubgroups->getNode(5)->textContent);
  370. $this->assertEquals("SG C", $fourthGroupEndpointsAndSubgroups->getNode(6)->textContent);
  371. $this->assertEquals("POST api/action13b", $fourthGroupEndpointsAndSubgroups->getNode(7)->textContent);
  372. }
  373. /** @test */
  374. public function merges_and_correctly_sorts_user_defined_endpoints()
  375. {
  376. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  377. RouteFacade::get('/api/action2', [TestGroupController::class, 'action2']);
  378. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  379. config(['scribe.groups.order' => [
  380. '1. Group 1',
  381. '5. Group 5',
  382. '4. Group 4',
  383. '2. Group 2',
  384. ]]);
  385. if (!is_dir('.scribe/endpoints')) mkdir('.scribe/endpoints', 0777, true);
  386. copy(__DIR__ . '/../Fixtures/custom.0.yaml', '.scribe/endpoints/custom.0.yaml');
  387. $this->generate();
  388. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  389. $headings = $crawler->filter('h1')->getIterator();
  390. $this->assertCount(6, $headings); // intro, auth, four groups
  391. [$_, $_, $firstGroup, $secondGroup, $thirdGroup, $fourthGroup] = $headings;
  392. $this->assertEquals('1. Group 1', $firstGroup->textContent);
  393. $this->assertEquals('5. Group 5', $secondGroup->textContent);
  394. $this->assertEquals('4. Group 4', $thirdGroup->textContent);
  395. $this->assertEquals('2. Group 2', $fourthGroup->textContent);
  396. $firstGroupEndpointsAndSubgroups = $crawler->filter('h2[id^="'.Str::slug($firstGroup->textContent).'"]');
  397. $this->assertEquals(2, $firstGroupEndpointsAndSubgroups->count());
  398. $this->assertEquals("GET api/action1", $firstGroupEndpointsAndSubgroups->getNode(0)->textContent);
  399. $this->assertEquals("User defined", $firstGroupEndpointsAndSubgroups->getNode(1)->textContent);
  400. $secondGroupEndpointsAndSubgroups = $crawler->filter('h2[id^="'.Str::slug($secondGroup->textContent).'"]');
  401. $this->assertEquals(2, $secondGroupEndpointsAndSubgroups->count());
  402. $this->assertEquals("GET group5", $secondGroupEndpointsAndSubgroups->getNode(0)->textContent);
  403. $this->assertEquals("GET alsoGroup5", $secondGroupEndpointsAndSubgroups->getNode(1)->textContent);
  404. $thirdGroupEndpointsAndSubgroups = $crawler->filter('h2[id^="'.Str::slug($thirdGroup->textContent).'"]');
  405. $this->assertEquals(1, $thirdGroupEndpointsAndSubgroups->count());
  406. $this->assertEquals("GET group4", $thirdGroupEndpointsAndSubgroups->getNode(0)->textContent);
  407. $fourthGroupEndpointsAndSubgroups = $crawler->filter('h2[id^="'.Str::slug($fourthGroup->textContent).'"]');
  408. $this->assertEquals(1, $fourthGroupEndpointsAndSubgroups->count());
  409. $this->assertEquals("GET api/action2", $fourthGroupEndpointsAndSubgroups->getNode(0)->textContent);
  410. }
  411. /** @test */
  412. public function will_not_overwrite_manually_modified_content_unless_force_flag_is_set()
  413. {
  414. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  415. RouteFacade::get('/api/action1b', [TestGroupController::class, 'action1b']);
  416. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  417. $this->generate();
  418. $authFilePath = '.scribe/auth.md';
  419. $firstGroupFilePath = '.scribe/endpoints/00.yaml';
  420. $group = Yaml::parseFile($firstGroupFilePath);
  421. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  422. $this->assertEquals([], $group['endpoints'][0]['urlParameters']);
  423. $extraParam = [
  424. 'name' => 'a_param',
  425. 'description' => 'A URL param.',
  426. 'required' => true,
  427. 'example' => 6,
  428. 'type' => 'integer',
  429. 'enumValues' => [],
  430. 'custom' => [],
  431. 'exampleWasSpecified' => false,
  432. ];
  433. $group['endpoints'][0]['urlParameters']['a_param'] = $extraParam;
  434. file_put_contents($firstGroupFilePath, Yaml::dump(
  435. $group, 20, 2,
  436. Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE | Yaml::DUMP_OBJECT_AS_MAP
  437. ));
  438. file_put_contents($authFilePath, 'Some other useful stuff.', FILE_APPEND);
  439. $this->generate();
  440. $group = Yaml::parseFile($firstGroupFilePath);
  441. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  442. $this->assertEquals(['a_param' => $extraParam], $group['endpoints'][0]['urlParameters']);
  443. $this->assertStringContainsString('Some other useful stuff.', file_get_contents($authFilePath));
  444. $this->generate(['--force' => true]);
  445. $group = Yaml::parseFile($firstGroupFilePath);
  446. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  447. $this->assertEquals([], $group['endpoints'][0]['urlParameters']);
  448. $this->assertStringNotContainsString('Some other useful stuff.', file_get_contents($authFilePath));
  449. }
  450. /** @test */
  451. public function generates_correct_url_params_from_resource_routes_and_field_bindings()
  452. {
  453. RouteFacade::prefix('providers/{provider:slug}')->group(function () {
  454. RouteFacade::resource('users.addresses', TestPartialResourceController::class)->parameters([
  455. 'addresses' => 'address:uuid',
  456. ]);
  457. });
  458. config(['scribe.routes.0.match.prefixes' => ['*']]);
  459. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  460. $this->generate();
  461. $groupA = Yaml::parseFile('.scribe/endpoints/00.yaml');
  462. $this->assertEquals('providers/{provider_slug}/users/{user_id}/addresses', $groupA['endpoints'][0]['uri']);
  463. $groupB = Yaml::parseFile('.scribe/endpoints/01.yaml');
  464. $this->assertEquals('providers/{provider_slug}/users/{user_id}/addresses/{uuid}', $groupB['endpoints'][0]['uri']);
  465. }
  466. /** @test */
  467. public function generates_correct_url_params_from_resource_routes_and_model_binding()
  468. {
  469. RouteFacade::resource('posts', TestPostController::class)->only('update');
  470. RouteFacade::resource('posts.users', TestPostUserController::class)->only('update');
  471. config(['scribe.routes.0.match.prefixes' => ['*']]);
  472. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  473. $this->generate();
  474. $group = Yaml::parseFile('.scribe/endpoints/00.yaml');
  475. $this->assertEquals('posts/{slug}', $group['endpoints'][0]['uri']);
  476. $this->assertEquals('posts/{post_slug}/users/{id}', $group['endpoints'][1]['uri']);
  477. }
  478. /** @test */
  479. public function generates_correct_url_params_from_resource_routes_and_model_binding_with_bound_interfaces()
  480. {
  481. $this->app->bind(TestPostBoundInterface::class, fn() => new TestPost());
  482. RouteFacade::resource('posts', TestPostBoundInterfaceController::class)->only('update');
  483. config(['scribe.routes.0.match.prefixes' => ['*']]);
  484. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  485. $this->generate();
  486. $group = Yaml::parseFile('.scribe/endpoints/00.yaml');
  487. $this->assertEquals('posts/{slug}', $group['endpoints'][0]['uri']);
  488. }
  489. /** @test */
  490. public function generates_correct_url_params_from_non_resource_routes_and_model_binding()
  491. {
  492. RouteFacade::get('posts/{post}/users', function (TestPost $post) {
  493. });
  494. config(['scribe.routes.0.match.prefixes' => ['*']]);
  495. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  496. $this->generate();
  497. $group = Yaml::parseFile('.scribe/endpoints/00.yaml');
  498. $this->assertEquals('posts/{post_slug}/users', $group['endpoints'][0]['uri']);
  499. }
  500. /** @test */
  501. public function generates_from_camel_dir_if_noExtraction_flag_is_set()
  502. {
  503. config(['scribe.routes.0.exclude' => ['*']]);
  504. Utils::copyDirectory(__DIR__ . '/../Fixtures/.scribe', '.scribe');
  505. $output = $this->generate(['--no-extraction' => true]);
  506. $this->assertStringNotContainsString("Processing route", $output);
  507. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  508. [$intro, $auth] = $crawler->filter('h1 + p')->getIterator();
  509. $this->assertEquals('Heyaa introduction!👋', trim($intro->firstChild->textContent));
  510. $this->assertEquals('This is just a test.', trim($auth->firstChild->textContent));
  511. $group = $crawler->filter('h1')->getNode(2);
  512. $this->assertEquals('General', trim($group->textContent));
  513. $expectedEndpoint = $crawler->filter('h2');
  514. $this->assertCount(1, $expectedEndpoint);
  515. $this->assertEquals("Healthcheck", $expectedEndpoint->text());
  516. }
  517. /** @test */
  518. public function will_auto_set_content_type_to_multipart_if_file_params_are_present()
  519. {
  520. /**
  521. * @bodyParam param string required
  522. */
  523. RouteFacade::post('no-file', fn() => null);
  524. /**
  525. * @bodyParam a_file file required
  526. */
  527. RouteFacade::post('top-level-file', fn() => null);
  528. /**
  529. * @bodyParam data object
  530. * @bodyParam data.thing string
  531. * @bodyParam data.a_file file
  532. */
  533. RouteFacade::post('nested-file', fn() => null);
  534. config(['scribe.routes.0.match.prefixes' => ['*']]);
  535. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  536. $this->generate();
  537. $group = Yaml::parseFile('.scribe/endpoints/00.yaml');
  538. $this->assertEquals('no-file', $group['endpoints'][0]['uri']);
  539. $this->assertEquals('application/json', $group['endpoints'][0]['headers']['Content-Type']);
  540. $this->assertEquals('top-level-file', $group['endpoints'][1]['uri']);
  541. $this->assertEquals('multipart/form-data', $group['endpoints'][1]['headers']['Content-Type']);
  542. $this->assertEquals('nested-file', $group['endpoints'][2]['uri']);
  543. $this->assertEquals('multipart/form-data', $group['endpoints'][2]['headers']['Content-Type']);
  544. }
  545. protected function postmanOutputPath(bool $laravelType = false): string
  546. {
  547. return $laravelType
  548. ? Storage::disk('local')->path('scribe/collection.json') : 'public/docs/collection.json';
  549. }
  550. protected function openapiOutputPath(bool $laravelType = false): string
  551. {
  552. return $laravelType
  553. ? Storage::disk('local')->path('scribe/openapi.yaml') : 'public/docs/openapi.yaml';
  554. }
  555. protected function htmlOutputPath(): string
  556. {
  557. return 'public/docs/index.html';
  558. }
  559. protected function bladeOutputPath(): string
  560. {
  561. return View::getFinder()->find('scribe/index');
  562. }
  563. }