GenerateDocumentationTest.php 16 KB

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