OutputTest.php 27 KB

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