OutputTest.php 30 KB

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