OutputTest.php 29 KB

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