GenerateDocumentationTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. <?php
  2. namespace Knuckles\Scribe\Tests;
  3. use Illuminate\Support\Facades\App;
  4. use Illuminate\Support\Facades\Config;
  5. use Illuminate\Support\Facades\Route as RouteFacade;
  6. use Illuminate\Support\Str;
  7. use Knuckles\Scribe\ScribeServiceProvider;
  8. use Knuckles\Scribe\Tests\Fixtures\TestController;
  9. use Knuckles\Scribe\Tests\Fixtures\TestGroupController;
  10. use Knuckles\Scribe\Tests\Fixtures\TestIgnoreThisController;
  11. use Knuckles\Scribe\Tests\Fixtures\TestPartialResourceController;
  12. use Knuckles\Scribe\Tests\Fixtures\TestResourceController;
  13. use Knuckles\Scribe\Tests\Fixtures\TestUser;
  14. use Knuckles\Scribe\Tools\Utils;
  15. use Orchestra\Testbench\TestCase;
  16. use ReflectionException;
  17. class GenerateDocumentationTest extends TestCase
  18. {
  19. use TestHelpers;
  20. protected function setUp(): void
  21. {
  22. parent::setUp();
  23. $factory = app(\Illuminate\Database\Eloquent\Factory::class);
  24. $factory->define(TestUser::class, function () {
  25. return [
  26. 'id' => 4,
  27. 'first_name' => 'Tested',
  28. 'last_name' => 'Again',
  29. 'email' => 'a@b.com',
  30. ];
  31. });
  32. }
  33. public function tearDown(): void
  34. {
  35. Utils::deleteDirectoryAndContents('/public/docs');
  36. Utils::deleteDirectoryAndContents('/resources/docs');
  37. }
  38. /**
  39. * @param \Illuminate\Foundation\Application $app
  40. *
  41. * @return array
  42. */
  43. protected function getPackageProviders($app)
  44. {
  45. $providers = [
  46. ScribeServiceProvider::class,
  47. ];
  48. if (class_exists(\Dingo\Api\Provider\LaravelServiceProvider::class)) {
  49. $providers[] = \Dingo\Api\Provider\LaravelServiceProvider::class;
  50. }
  51. return $providers;
  52. }
  53. /** @test */
  54. public function can_process_traditional_laravel_route_syntax()
  55. {
  56. RouteFacade::get('/api/test', TestController::class . '@withEndpointDescription');
  57. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  58. $output = $this->artisan('scribe:generate');
  59. $this->assertStringContainsString('Processed route: [GET] api/test', $output);
  60. }
  61. /** @test */
  62. public function can_process_closure_routes()
  63. {
  64. RouteFacade::get('/api/closure', function () {
  65. return 'hi';
  66. });
  67. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  68. $output = $this->artisan('scribe:generate');
  69. $this->assertStringContainsString('Processed route: [GET] api/closure', $output);
  70. }
  71. /**
  72. * @group dingo
  73. * @test
  74. */
  75. public function can_process_routes_on_dingo()
  76. {
  77. $api = app(\Dingo\Api\Routing\Router::class);
  78. $api->version('v1', function ($api) {
  79. $api->get('/closure', function () {
  80. return 'foo';
  81. });
  82. $api->get('/test', TestController::class . '@withEndpointDescription');
  83. });
  84. config(['scribe.router' => 'dingo']);
  85. config(['scribe.routes.0.match.prefixes' => ['*']]);
  86. config(['scribe.routes.0.match.versions' => ['v1']]);
  87. $output = $this->artisan('scribe:generate');
  88. $this->assertStringContainsString('Processed route: [GET] closure', $output);
  89. $this->assertStringContainsString('Processed route: [GET] test', $output);
  90. }
  91. /** @test */
  92. public function can_process_callable_tuple_syntax()
  93. {
  94. RouteFacade::get('/api/array/test', [TestController::class, 'withEndpointDescription']);
  95. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  96. $output = $this->artisan('scribe:generate');
  97. $this->assertStringContainsString('Processed route: [GET] api/array/test', $output);
  98. }
  99. /** @test */
  100. public function can_skip_methods_and_classes_with_hidefromapidocumentation_tag()
  101. {
  102. RouteFacade::get('/api/skip', TestController::class . '@skip');
  103. RouteFacade::get('/api/skipClass', TestIgnoreThisController::class . '@dummy');
  104. RouteFacade::get('/api/test', TestController::class . '@withEndpointDescription');
  105. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  106. $output = $this->artisan('scribe:generate');
  107. $this->assertStringContainsString('Skipping route: [GET] api/skip', $output);
  108. $this->assertStringContainsString('Skipping route: [GET] api/skipClass', $output);
  109. $this->assertStringContainsString('Processed route: [GET] api/test', $output);
  110. }
  111. /** @test */
  112. public function can_skip_nonexistent_response_files()
  113. {
  114. RouteFacade::get('/api/non-existent', TestController::class . '@withNonExistentResponseFile');
  115. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  116. $output = $this->artisan('scribe:generate');
  117. $this->assertStringContainsString('Skipping route: [GET] api/non-existent', $output);
  118. $this->assertStringContainsString('@responseFile i-do-not-exist.json does not exist', $output);
  119. }
  120. /** @test */
  121. public function can_parse_resource_routes()
  122. {
  123. RouteFacade::resource('/api/users', TestResourceController::class);
  124. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  125. config([
  126. 'scribe.routes.0.apply.headers' => [
  127. 'Accept' => 'application/json',
  128. ],
  129. ]);
  130. $output = $this->artisan('scribe:generate');
  131. $this->assertStringContainsString('Processed route: [GET] api/users', $output);
  132. $this->assertStringContainsString('Processed route: [GET] api/users/create', $output);
  133. $this->assertStringContainsString('Processed route: [GET] api/users/{user}', $output);
  134. $this->assertStringContainsString('Processed route: [GET] api/users/{user}/edit', $output);
  135. $this->assertStringContainsString('Processed route: [POST] api/users', $output);
  136. $this->assertStringContainsString('Processed route: [PUT,PATCH] api/users/{user}', $output);
  137. $this->assertStringContainsString('Processed route: [DELETE] api/users/{user}', $output);
  138. }
  139. /** @test */
  140. public function can_parse_partial_resource_routes()
  141. {
  142. RouteFacade::resource('/api/users', TestResourceController::class)
  143. ->only(['index', 'store']);
  144. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  145. config([
  146. 'scribe.routes.0.apply.headers' => [
  147. 'Accept' => 'application/json',
  148. ],
  149. ]);
  150. $output = $this->artisan('scribe:generate');
  151. $this->assertStringContainsString('Processed route: [GET] api/users', $output);
  152. $this->assertStringContainsString('Processed route: [POST] api/users', $output);
  153. $this->assertStringNotContainsString('Processed route: [PUT,PATCH] api/users/{user}', $output);
  154. $this->assertStringNotContainsString('Processed route: [DELETE] api/users/{user}', $output);
  155. RouteFacade::apiResource('/api/users', TestResourceController::class)
  156. ->only(['index', 'store']);
  157. $output = $this->artisan('scribe:generate');
  158. $this->assertStringContainsString('Processed route: [GET] api/users', $output);
  159. $this->assertStringContainsString('Processed route: [POST] api/users', $output);
  160. $this->assertStringNotContainsString('Processed route: [PUT,PATCH] api/users/{user}', $output);
  161. $this->assertStringNotContainsString('Processed route: [DELETE] api/users/{user}', $output);
  162. }
  163. /** @test */
  164. public function supports_partial_resource_controller()
  165. {
  166. RouteFacade::resource('/api/users', TestPartialResourceController::class);
  167. config(['scribe.routes.0.prefixes' => ['api/*']]);
  168. $output = $this->artisan('scribe:generate');
  169. $this->assertStringContainsString('Processed route: [GET] api/users', $output);
  170. $this->assertStringContainsString('Processed route: [PUT,PATCH] api/users/{user}', $output);
  171. }
  172. /** @test */
  173. public function generated_postman_collection_file_is_correct()
  174. {
  175. RouteFacade::get('/api/withDescription', [TestController::class, 'withEndpointDescription']);
  176. RouteFacade::get('/api/withResponseTag', TestController::class . '@withResponseTag');
  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/withEloquentApiResource', [TestController::class, 'withEloquentApiResource']);
  181. RouteFacade::get('/api/withEloquentApiResourceCollectionClass', [TestController::class, 'withEloquentApiResourceCollectionClass']);
  182. RouteFacade::post('/api/withMultipleResponseTagsAndStatusCode', [TestController::class, 'withMultipleResponseTagsAndStatusCode']);
  183. RouteFacade::get('/api/echoesUrlParameters/{param}-{param2}/{param3?}', [TestController::class, 'echoesUrlParameters']);
  184. // We want to have the same values for params each time
  185. config(['scribe.faker_seed' => 1234]);
  186. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  187. config([
  188. 'scribe.routes.0.apply.headers' => [
  189. 'Authorization' => 'customAuthToken',
  190. 'Custom-Header' => 'NotSoCustom',
  191. 'Accept' => 'application/json',
  192. 'Content-Type' => 'application/json',
  193. ],
  194. ]);
  195. $this->artisan('scribe:generate');
  196. $generatedCollection = json_decode(file_get_contents(__DIR__ . '/../public/docs/collection.json'), true);
  197. // The Postman ID varies from call to call; erase it to make the test data reproducible.
  198. $generatedCollection['info']['_postman_id'] = '';
  199. $fixtureCollection = json_decode(file_get_contents(__DIR__ . '/Fixtures/collection.json'), true);
  200. $this->assertEquals($fixtureCollection, $generatedCollection);
  201. }
  202. /** @test */
  203. public function generated_postman_collection_domain_is_correct()
  204. {
  205. $domain = 'http://somedomain.test';
  206. RouteFacade::get('/api/test', TestController::class . '@withEndpointDescription');
  207. config(['scribe.base_url' => $domain]);
  208. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  209. $this->artisan('scribe:generate');
  210. $generatedCollection = json_decode(file_get_contents(__DIR__ . '/../public/docs/collection.json'));
  211. $endpointUrl = $generatedCollection->item[0]->item[0]->request->url->host;
  212. $this->assertTrue(Str::startsWith($endpointUrl, 'somedomain.test'));
  213. }
  214. /** @test */
  215. public function generated_postman_collection_can_have_custom_url()
  216. {
  217. Config::set('scribe.base_url', 'http://yourapp.app');
  218. RouteFacade::get('/api/test', TestController::class . '@withEndpointDescription');
  219. RouteFacade::post('/api/responseTag', TestController::class . '@withResponseTag');
  220. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  221. $this->artisan('scribe:generate');
  222. $generatedCollection = json_decode(file_get_contents(__DIR__ . '/../public/docs/collection.json'), true);
  223. // The Postman ID varies from call to call; erase it to make the test data reproducible.
  224. $generatedCollection['info']['_postman_id'] = '';
  225. $fixtureCollection = json_decode(file_get_contents(__DIR__ . '/Fixtures/collection_custom_url.json'), true);
  226. $this->assertEquals($fixtureCollection, $generatedCollection);
  227. }
  228. /** @test */
  229. public function generated_postman_collection_can_have_secure_url()
  230. {
  231. Config::set('scribe.base_url', 'https://yourapp.app');
  232. RouteFacade::get('/api/test', TestController::class . '@withEndpointDescription');
  233. RouteFacade::post('/api/responseTag', TestController::class . '@withResponseTag');
  234. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  235. $this->artisan('scribe:generate');
  236. $generatedCollection = json_decode(file_get_contents(__DIR__ . '/../public/docs/collection.json'), true);
  237. // The Postman ID varies from call to call; erase it to make the test data reproducible.
  238. $generatedCollection['info']['_postman_id'] = '';
  239. $fixtureCollection = json_decode(file_get_contents(__DIR__ . '/Fixtures/collection_with_secure_url.json'), true);
  240. $this->assertEquals($fixtureCollection, $generatedCollection);
  241. }
  242. /** @test */
  243. public function generated_postman_collection_can_append_custom_http_headers()
  244. {
  245. RouteFacade::get('/api/headers', TestController::class . '@checkCustomHeaders');
  246. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  247. config([
  248. 'scribe.routes.0.apply.headers' => [
  249. 'Authorization' => 'customAuthToken',
  250. 'Custom-Header' => 'NotSoCustom',
  251. ],
  252. ]);
  253. $this->artisan('scribe:generate');
  254. $generatedCollection = json_decode(file_get_contents(__DIR__ . '/../public/docs/collection.json'), true);
  255. // The Postman ID varies from call to call; erase it to make the test data reproducible.
  256. $generatedCollection['info']['_postman_id'] = '';
  257. $fixtureCollection = json_decode(file_get_contents(__DIR__ . '/Fixtures/collection_with_custom_headers.json'), true);
  258. $this->assertEquals($fixtureCollection, $generatedCollection);
  259. }
  260. /** @test */
  261. public function generated_postman_collection_can_have_query_parameters()
  262. {
  263. RouteFacade::get('/api/withQueryParameters', TestController::class . '@withQueryParameters');
  264. // We want to have the same values for params each time
  265. config(['scribe.faker_seed' => 1234]);
  266. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  267. $this->artisan('scribe:generate');
  268. $generatedCollection = json_decode(file_get_contents(__DIR__ . '/../public/docs/collection.json'), true);
  269. // The Postman ID varies from call to call; erase it to make the test data reproducible.
  270. $generatedCollection['info']['_postman_id'] = '';
  271. $fixtureCollection = json_decode(file_get_contents(__DIR__ . '/Fixtures/collection_with_query_parameters.json'), true);
  272. $this->assertEquals($fixtureCollection, $generatedCollection);
  273. }
  274. /** @test */
  275. public function generated_postman_collection_can_add_body_parameters()
  276. {
  277. RouteFacade::get('/api/withBodyParameters', TestController::class . '@withBodyParameters');
  278. // We want to have the same values for params each time
  279. config(['scribe.faker_seed' => 1234]);
  280. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  281. $this->artisan('scribe:generate');
  282. $generatedCollection = json_decode(file_get_contents(__DIR__ . '/../public/docs/collection.json'), true);
  283. // The Postman ID varies from call to call; erase it to make the test data reproducible.
  284. $generatedCollection['info']['_postman_id'] = '';
  285. $fixtureCollection = json_decode(file_get_contents(__DIR__ . '/Fixtures/collection_with_body_parameters.json'), true);
  286. $this->assertEquals($fixtureCollection, $generatedCollection);
  287. }
  288. /** @test */
  289. public function can_append_custom_http_headers()
  290. {
  291. RouteFacade::get('/api/headers', TestController::class . '@checkCustomHeaders');
  292. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  293. config([
  294. 'scribe.routes.0.apply.headers' => [
  295. 'Authorization' => 'customAuthToken',
  296. 'Custom-Header' => 'NotSoCustom',
  297. ],
  298. ]);
  299. $this->artisan('scribe:generate');
  300. $generatedMarkdown = $this->getFileContents(__DIR__ . '/../resources/docs/groups/group-a.md');
  301. $this->assertContainsIgnoringWhitespace('"Authorization": "customAuthToken","Custom-Header":"NotSoCustom"', $generatedMarkdown);
  302. }
  303. /** @test */
  304. public function can_parse_utf8_response()
  305. {
  306. RouteFacade::get('/api/utf8', TestController::class . '@withUtf8ResponseTag');
  307. config(['scribe.routes.0.prefixes' => ['api/*']]);
  308. $this->artisan('scribe:generate');
  309. $generatedMarkdown = file_get_contents(__DIR__ . '/../resources/docs/groups/group-a.md');
  310. $this->assertStringContainsString('Лорем ипсум долор сит амет', $generatedMarkdown);
  311. }
  312. /** @test */
  313. public function sorts_group_naturally()
  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. config(['scribe.routes.0.prefixes' => ['api/*']]);
  320. $this->artisan('scribe:generate');
  321. $this->assertFileExists(__DIR__ . '/../resources/docs/groups/1-group-1.md');
  322. $this->assertFileExists(__DIR__ . '/../resources/docs/groups/2-group-2.md');
  323. $this->assertFileExists(__DIR__ . '/../resources/docs/groups/10-group-10.md');
  324. }
  325. /** @test */
  326. public function will_not_overwrite_manually_modified_markdown_files_unless_force_flag_is_set()
  327. {
  328. RouteFacade::get('/api/action1', TestGroupController::class . '@action1');
  329. RouteFacade::get('/api/action1b', TestGroupController::class . '@action1b');
  330. RouteFacade::get('/api/action2', TestGroupController::class . '@action2');
  331. config(['scribe.routes.0.prefixes' => ['api/*']]);
  332. $this->artisan('scribe:generate');
  333. $group1FilePath = realpath(__DIR__ . '/../resources/docs/groups/1-group-1.md');
  334. $group2FilePath = realpath(__DIR__ . '/../resources/docs/groups/2-group-2.md');
  335. $authFilePath = realpath(__DIR__ . '/../resources/docs/authentication.md');
  336. $file1MtimeAfterFirstGeneration = filemtime($group1FilePath);
  337. $file2MtimeAfterFirstGeneration = filemtime($group2FilePath);
  338. $authFileMtimeAfterFirstGeneration = filemtime($authFilePath);
  339. sleep(1);
  340. touch($group1FilePath);
  341. touch($authFilePath);
  342. $file1MtimeAfterManualModification = filemtime($group1FilePath);
  343. $authFileMtimeAfterManualModification = filemtime($authFilePath);
  344. $this->assertGreaterThan($file1MtimeAfterFirstGeneration, $file1MtimeAfterManualModification);
  345. $this->assertGreaterThan($authFileMtimeAfterFirstGeneration, $authFileMtimeAfterManualModification);
  346. $this->artisan('scribe:generate');
  347. $file1MtimeAfterSecondGeneration = filemtime($group1FilePath);
  348. $file2MtimeAfterSecondGeneration = filemtime($group2FilePath);
  349. $authFileMtimeAfterSecondGeneration = filemtime($authFilePath);
  350. $this->assertEquals($file1MtimeAfterManualModification, $file1MtimeAfterSecondGeneration);
  351. $this->assertNotEquals($file2MtimeAfterFirstGeneration, $file2MtimeAfterSecondGeneration);
  352. $this->assertNotEquals($authFileMtimeAfterFirstGeneration, $authFileMtimeAfterSecondGeneration);
  353. }
  354. }