GeneratorTestCase.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  1. <?php
  2. /** @noinspection ALL */
  3. namespace Mpociot\ApiDoc\Tests\Unit;
  4. use Illuminate\Support\Arr;
  5. use Orchestra\Testbench\TestCase;
  6. use Mpociot\ApiDoc\Tools\Generator;
  7. use Mpociot\ApiDoc\Tests\Fixtures\TestUser;
  8. use Mpociot\ApiDoc\Tools\DocumentationConfig;
  9. use Mpociot\ApiDoc\Tests\Fixtures\TestController;
  10. use Mpociot\ApiDoc\ApiDocGeneratorServiceProvider;
  11. use Mpociot\ApiDoc\Tests\Fixtures\TestResourceController;
  12. abstract class GeneratorTestCase extends TestCase
  13. {
  14. /**
  15. * @var \Mpociot\ApiDoc\Tools\Generator
  16. */
  17. protected $generator;
  18. private $config = [
  19. 'strategies' => [
  20. 'metadata' => [
  21. \Mpociot\ApiDoc\Strategies\Metadata\GetFromDocBlocks::class,
  22. ],
  23. 'urlParameters' => [
  24. \Mpociot\ApiDoc\Strategies\UrlParameters\GetFromUrlParamTag::class,
  25. ],
  26. 'queryParameters' => [
  27. \Mpociot\ApiDoc\Strategies\QueryParameters\GetFromQueryParamTag::class,
  28. ],
  29. 'bodyParameters' => [
  30. \Mpociot\ApiDoc\Strategies\BodyParameters\GetFromBodyParamTag::class,
  31. ],
  32. 'responses' => [
  33. \Mpociot\ApiDoc\Strategies\Responses\UseResponseTag::class,
  34. \Mpociot\ApiDoc\Strategies\Responses\UseResponseFileTag::class,
  35. \Mpociot\ApiDoc\Strategies\Responses\UseApiResourceTags::class,
  36. \Mpociot\ApiDoc\Strategies\Responses\UseTransformerTags::class,
  37. \Mpociot\ApiDoc\Strategies\Responses\ResponseCalls::class,
  38. ],
  39. ],
  40. 'default_group' => 'general',
  41. ];
  42. public static $globalValue = null;
  43. protected function getPackageProviders($app)
  44. {
  45. return [
  46. ApiDocGeneratorServiceProvider::class,
  47. ];
  48. }
  49. /**
  50. * Setup the test environment.
  51. */
  52. public function setUp(): void
  53. {
  54. parent::setUp();
  55. $factory = app(\Illuminate\Database\Eloquent\Factory::class);
  56. $factory->define(TestUser::class, function () {
  57. return [
  58. 'id' => 4,
  59. 'first_name' => 'Tested',
  60. 'last_name' => 'Again',
  61. 'email' => 'a@b.com',
  62. ];
  63. });
  64. $this->generator = new Generator(new DocumentationConfig($this->config));
  65. }
  66. /** @test */
  67. public function can_parse_endpoint_description()
  68. {
  69. $route = $this->createRoute('GET', '/api/test', 'withEndpointDescription');
  70. $parsed = $this->generator->processRoute($route);
  71. $this->assertSame('Example title.', $parsed['metadata']['title']);
  72. $this->assertSame("This will be the long description.\nIt can also be multiple lines long.", $parsed['metadata']['description']);
  73. }
  74. /** @test */
  75. public function can_parse_body_parameters()
  76. {
  77. $route = $this->createRoute('GET', '/api/test', 'withBodyParameters');
  78. $bodyParameters = $this->generator->processRoute($route)['bodyParameters'];
  79. $this->assertArraySubset([
  80. 'user_id' => [
  81. 'type' => 'integer',
  82. 'required' => true,
  83. 'description' => 'The id of the user.',
  84. 'value' => 9,
  85. ],
  86. 'room_id' => [
  87. 'type' => 'string',
  88. 'required' => false,
  89. 'description' => 'The id of the room.',
  90. ],
  91. 'forever' => [
  92. 'type' => 'boolean',
  93. 'required' => false,
  94. 'description' => 'Whether to ban the user forever.',
  95. 'value' => false,
  96. ],
  97. 'another_one' => [
  98. 'type' => 'number',
  99. 'required' => false,
  100. 'description' => 'Just need something here.',
  101. ],
  102. 'yet_another_param' => [
  103. 'type' => 'object',
  104. 'required' => true,
  105. 'description' => 'Some object params.',
  106. ],
  107. 'yet_another_param.name' => [
  108. 'type' => 'string',
  109. 'description' => 'Subkey in the object param.',
  110. 'required' => true,
  111. ],
  112. 'even_more_param' => [
  113. 'type' => 'array',
  114. 'required' => false,
  115. 'description' => 'Some array params.',
  116. ],
  117. 'even_more_param.*' => [
  118. 'type' => 'float',
  119. 'description' => 'Subkey in the array param.',
  120. 'required' => false,
  121. ],
  122. 'book.name' => [
  123. 'type' => 'string',
  124. 'description' => '',
  125. 'required' => false,
  126. ],
  127. 'book.author_id' => [
  128. 'type' => 'integer',
  129. 'description' => '',
  130. 'required' => false,
  131. ],
  132. 'book[pages_count]' => [
  133. 'type' => 'integer',
  134. 'description' => '',
  135. 'required' => false,
  136. ],
  137. 'ids.*' => [
  138. 'type' => 'integer',
  139. 'description' => '',
  140. 'required' => false,
  141. ],
  142. 'users.*.first_name' => [
  143. 'type' => 'string',
  144. 'description' => 'The first name of the user.',
  145. 'required' => false,
  146. 'value' => 'John',
  147. ],
  148. 'users.*.last_name' => [
  149. 'type' => 'string',
  150. 'description' => 'The last name of the user.',
  151. 'required' => false,
  152. 'value' => 'Doe',
  153. ],
  154. ], $bodyParameters);
  155. }
  156. /** @test */
  157. public function it_ignores_non_commented_form_request()
  158. {
  159. $route = $this->createRoute('GET', '/api/test', 'withNonCommentedFormRequestParameter');
  160. $bodyParameters = $this->generator->processRoute($route)['bodyParameters'];
  161. $this->assertArraySubset([
  162. 'direct_one' => [
  163. 'type' => 'string',
  164. 'description' => 'Is found directly on the method.',
  165. ],
  166. ], $bodyParameters);
  167. }
  168. /** @test */
  169. public function can_parse_form_request_body_parameters()
  170. {
  171. $route = $this->createRoute('GET', '/api/test', 'withFormRequestParameter');
  172. $bodyParameters = $this->generator->processRoute($route)['bodyParameters'];
  173. $this->assertArraySubset([
  174. 'user_id' => [
  175. 'type' => 'integer',
  176. 'required' => true,
  177. 'description' => 'The id of the user.',
  178. 'value' => 9,
  179. ],
  180. 'room_id' => [
  181. 'type' => 'string',
  182. 'required' => false,
  183. 'description' => 'The id of the room.',
  184. ],
  185. 'forever' => [
  186. 'type' => 'boolean',
  187. 'required' => false,
  188. 'description' => 'Whether to ban the user forever.',
  189. 'value' => false,
  190. ],
  191. 'another_one' => [
  192. 'type' => 'number',
  193. 'required' => false,
  194. 'description' => 'Just need something here.',
  195. ],
  196. 'yet_another_param' => [
  197. 'type' => 'object',
  198. 'required' => true,
  199. 'description' => '',
  200. ],
  201. 'even_more_param' => [
  202. 'type' => 'array',
  203. 'required' => false,
  204. 'description' => '',
  205. ],
  206. ], $bodyParameters);
  207. }
  208. /** @test */
  209. public function can_parse_multiple_form_request_body_parameters()
  210. {
  211. $route = $this->createRoute('GET', '/api/test', 'withMultipleFormRequestParameters');
  212. $bodyParameters = $this->generator->processRoute($route)['bodyParameters'];
  213. $this->assertArraySubset([
  214. 'user_id' => [
  215. 'type' => 'integer',
  216. 'required' => true,
  217. 'description' => 'The id of the user.',
  218. 'value' => 9,
  219. ],
  220. 'room_id' => [
  221. 'type' => 'string',
  222. 'required' => false,
  223. 'description' => 'The id of the room.',
  224. ],
  225. 'forever' => [
  226. 'type' => 'boolean',
  227. 'required' => false,
  228. 'description' => 'Whether to ban the user forever.',
  229. 'value' => false,
  230. ],
  231. 'another_one' => [
  232. 'type' => 'number',
  233. 'required' => false,
  234. 'description' => 'Just need something here.',
  235. ],
  236. 'yet_another_param' => [
  237. 'type' => 'object',
  238. 'required' => true,
  239. 'description' => '',
  240. ],
  241. 'even_more_param' => [
  242. 'type' => 'array',
  243. 'required' => false,
  244. 'description' => '',
  245. ],
  246. ], $bodyParameters);
  247. }
  248. /** @test */
  249. public function can_parse_query_parameters()
  250. {
  251. $route = $this->createRoute('GET', '/api/test', 'withQueryParameters');
  252. $queryParameters = $this->generator->processRoute($route)['queryParameters'];
  253. $this->assertArraySubset([
  254. 'location_id' => [
  255. 'required' => true,
  256. 'description' => 'The id of the location.',
  257. ],
  258. 'user_id' => [
  259. 'required' => true,
  260. 'description' => 'The id of the user.',
  261. 'value' => 'me',
  262. ],
  263. 'page' => [
  264. 'required' => true,
  265. 'description' => 'The page number.',
  266. 'value' => '4',
  267. ],
  268. 'filters' => [
  269. 'required' => false,
  270. 'description' => 'The filters.',
  271. ],
  272. ], $queryParameters);
  273. }
  274. /** @test */
  275. public function it_does_not_generate_values_for_excluded_params_and_excludes_them_from_clean_params()
  276. {
  277. $route = $this->createRoute('GET', '/api/test', 'withExcludedExamples');
  278. $parsed = $this->generator->processRoute($route);
  279. $cleanBodyParameters = $parsed['cleanBodyParameters'];
  280. $cleanQueryParameters = $parsed['cleanQueryParameters'];
  281. $bodyParameters = $parsed['bodyParameters'];
  282. $queryParameters = $parsed['queryParameters'];
  283. $this->assertArrayHasKey('included', $cleanBodyParameters);
  284. $this->assertArrayNotHasKey('excluded_body_param', $cleanBodyParameters);
  285. $this->assertEmpty($cleanQueryParameters);
  286. $this->assertArraySubset([
  287. 'included' => [
  288. 'required' => true,
  289. 'type' => 'string',
  290. 'description' => 'Exists in examples.',
  291. ],
  292. 'excluded_body_param' => [
  293. 'type' => 'integer',
  294. 'description' => 'Does not exist in examples.',
  295. ],
  296. ], $bodyParameters);
  297. $this->assertArraySubset([
  298. 'excluded_query_param' => [
  299. 'description' => 'Does not exist in examples.',
  300. ],
  301. ], $queryParameters);
  302. }
  303. /** @test */
  304. public function can_parse_route_group()
  305. {
  306. $route = $this->createRoute('GET', '/api/test', 'dummy');
  307. $routeGroup = $this->generator->processRoute($route)['metadata']['groupName'];
  308. $this->assertSame('Group A', $routeGroup);
  309. }
  310. /** @test */
  311. public function method_can_override_controller_group()
  312. {
  313. $route = $this->createRoute('GET', '/group/1', 'withGroupOverride');
  314. $parsedRoute = $this->generator->processRoute($route);
  315. $this->assertSame('Group B', $parsedRoute['metadata']['groupName']);
  316. $this->assertSame('', $parsedRoute['metadata']['groupDescription']);
  317. $route = $this->createRoute('GET', '/group/2', 'withGroupOverride2');
  318. $parsedRoute = $this->generator->processRoute($route);
  319. $this->assertSame('Group B', $parsedRoute['metadata']['groupName']);
  320. $this->assertSame('', $parsedRoute['metadata']['groupDescription']);
  321. $this->assertSame('This is also in Group B. No route description. Route title before gropp.', $parsedRoute['metadata']['title']);
  322. $route = $this->createRoute('GET', '/group/3', 'withGroupOverride3');
  323. $parsedRoute = $this->generator->processRoute($route);
  324. $this->assertSame('Group B', $parsedRoute['metadata']['groupName']);
  325. $this->assertSame('', $parsedRoute['metadata']['groupDescription']);
  326. $this->assertSame('This is also in Group B. Route title after group.', $parsedRoute['metadata']['title']);
  327. $route = $this->createRoute('GET', '/group/4', 'withGroupOverride4');
  328. $parsedRoute = $this->generator->processRoute($route);
  329. $this->assertSame('Group C', $parsedRoute['metadata']['groupName']);
  330. $this->assertSame('Group description after group.', $parsedRoute['metadata']['groupDescription']);
  331. $this->assertSame('This is in Group C. Route title before group.', $parsedRoute['metadata']['title']);
  332. }
  333. /** @test */
  334. public function can_parse_auth_tags()
  335. {
  336. $route = $this->createRoute('GET', '/api/test', 'withAuthenticatedTag');
  337. $authenticated = $this->generator->processRoute($route)['metadata']['authenticated'];
  338. $this->assertTrue($authenticated);
  339. $route = $this->createRoute('GET', '/api/test', 'dummy');
  340. $authenticated = $this->generator->processRoute($route)['metadata']['authenticated'];
  341. $this->assertFalse($authenticated);
  342. }
  343. /** @test */
  344. public function can_parse_route_methods()
  345. {
  346. $route = $this->createRoute('GET', '/get', 'withEndpointDescription');
  347. $parsed = $this->generator->processRoute($route);
  348. $this->assertSame(['GET'], $parsed['methods']);
  349. $route = $this->createRoute('POST', '/post', 'withEndpointDescription');
  350. $parsed = $this->generator->processRoute($route);
  351. $this->assertSame(['POST'], $parsed['methods']);
  352. $route = $this->createRoute('PUT', '/put', 'withEndpointDescription');
  353. $parsed = $this->generator->processRoute($route);
  354. $this->assertSame(['PUT'], $parsed['methods']);
  355. $route = $this->createRoute('DELETE', '/delete', 'withEndpointDescription');
  356. $parsed = $this->generator->processRoute($route);
  357. $this->assertSame(['DELETE'], $parsed['methods']);
  358. }
  359. /** @test */
  360. public function can_parse_apiresource_tags()
  361. {
  362. $route = $this->createRoute('POST', '/withEloquentApiResource', 'withEloquentApiResource');
  363. $config = $this->config;
  364. $config['strategies']['responses'] = [\Mpociot\ApiDoc\Strategies\Responses\UseApiResourceTags::class];
  365. $generator = new Generator(new DocumentationConfig($config));
  366. $parsed = $this->generator->processRoute($route);
  367. $response = Arr::first($parsed['responses']);
  368. $this->assertTrue(is_array($parsed));
  369. $this->assertArrayHasKey('showresponse', $parsed);
  370. $this->assertTrue($parsed['showresponse']);
  371. $this->assertTrue(is_array($response));
  372. $this->assertEquals(200, $response['status']);
  373. $this->assertArraySubset([
  374. 'id' => 4,
  375. 'name' => 'Tested Again',
  376. 'email' => 'a@b.com',
  377. ], json_decode($response['content'], true));
  378. }
  379. /** @test */
  380. public function can_parse_apiresourcecollection_tags()
  381. {
  382. $route = $this->createRoute('POST', '/withEloquentApiResourceCollection', 'withEloquentApiResourceCollection');
  383. $config = $this->config;
  384. $config['strategies']['responses'] = [\Mpociot\ApiDoc\Strategies\Responses\UseApiResourceTags::class];
  385. $generator = new Generator(new DocumentationConfig($config));
  386. $parsed = $this->generator->processRoute($route);
  387. $response = Arr::first($parsed['responses']);
  388. $this->assertTrue(is_array($parsed));
  389. $this->assertArrayHasKey('showresponse', $parsed);
  390. $this->assertTrue($parsed['showresponse']);
  391. $this->assertTrue(is_array($response));
  392. $this->assertEquals(200, $response['status']);
  393. $content = json_decode($response['content'], true);
  394. $this->assertIsArray($content);
  395. $this->assertArraySubset([
  396. 'id' => 4,
  397. 'name' => 'Tested Again',
  398. 'email' => 'a@b.com',
  399. ], $content[0]);
  400. $this->assertArraySubset([
  401. 'id' => 4,
  402. 'name' => 'Tested Again',
  403. 'email' => 'a@b.com',
  404. ], $content[1]);
  405. }
  406. /** @test */
  407. public function can_parse_apiresourcecollection_tags_with_collection_class()
  408. {
  409. $route = $this->createRoute('POST', '/withEloquentApiResourceCollectionClass', 'withEloquentApiResourceCollectionClass');
  410. $config = $this->config;
  411. $config['strategies']['responses'] = [\Mpociot\ApiDoc\Strategies\Responses\UseApiResourceTags::class];
  412. $generator = new Generator(new DocumentationConfig($config));
  413. $parsed = $this->generator->processRoute($route);
  414. $response = Arr::first($parsed['responses']);
  415. $this->assertTrue(is_array($parsed));
  416. $this->assertArrayHasKey('showresponse', $parsed);
  417. $this->assertTrue($parsed['showresponse']);
  418. $this->assertTrue(is_array($response));
  419. $this->assertEquals(200, $response['status']);
  420. $content = json_decode($response['content'], true);
  421. $this->assertIsArray($content);
  422. $this->assertArraySubset([
  423. 'data' => [
  424. [
  425. 'id' => 4,
  426. 'name' => 'Tested Again',
  427. 'email' => 'a@b.com',
  428. ],
  429. [
  430. 'id' => 4,
  431. 'name' => 'Tested Again',
  432. 'email' => 'a@b.com',
  433. ],
  434. ],
  435. 'links' => [
  436. 'self' => 'link-value',
  437. ],
  438. ], $content);
  439. }
  440. /** @test */
  441. public function can_parse_response_tag()
  442. {
  443. $route = $this->createRoute('POST', '/responseTag', 'withResponseTag');
  444. $parsed = $this->generator->processRoute($route);
  445. $response = Arr::first($parsed['responses']);
  446. $this->assertTrue(is_array($parsed));
  447. $this->assertArrayHasKey('showresponse', $parsed);
  448. $this->assertTrue($parsed['showresponse']);
  449. $this->assertTrue(is_array($response));
  450. $this->assertEquals(200, $response['status']);
  451. $this->assertArraySubset([
  452. 'id' => 4,
  453. 'name' => 'banana',
  454. 'color' => 'red',
  455. 'weight' => '1 kg',
  456. 'delicious' => true,
  457. ], json_decode($response['content'], true));
  458. }
  459. /** @test */
  460. public function can_parse_response_tag_with_status_code()
  461. {
  462. $route = $this->createRoute('POST', '/responseTag', 'withResponseTagAndStatusCode');
  463. $parsed = $this->generator->processRoute($route);
  464. $response = Arr::first($parsed['responses']);
  465. $this->assertTrue(is_array($parsed));
  466. $this->assertArrayHasKey('showresponse', $parsed);
  467. $this->assertTrue($parsed['showresponse']);
  468. $this->assertTrue(is_array($response));
  469. $this->assertEquals(422, $response['status']);
  470. $this->assertArraySubset([
  471. 'message' => 'Validation error',
  472. ], json_decode($response['content'], true));
  473. }
  474. /** @test */
  475. public function can_parse_multiple_response_tags()
  476. {
  477. $route = $this->createRoute('POST', '/responseTag', 'withMultipleResponseTagsAndStatusCode');
  478. $parsed = $this->generator->processRoute($route);
  479. $this->assertTrue(is_array($parsed));
  480. $this->assertArrayHasKey('showresponse', $parsed);
  481. $this->assertTrue($parsed['showresponse']);
  482. $this->assertTrue(is_array($parsed['responses'][0]));
  483. $this->assertEquals(200, $parsed['responses'][0]['status']);
  484. $this->assertArraySubset([
  485. 'id' => 4,
  486. 'name' => 'banana',
  487. 'color' => 'red',
  488. 'weight' => '1 kg',
  489. 'delicious' => true,
  490. ], json_decode($parsed['responses'][0]['content'], true));
  491. $this->assertTrue(is_array($parsed['responses'][1]));
  492. $this->assertEquals(401, $parsed['responses'][1]['status']);
  493. $this->assertArraySubset([
  494. 'message' => 'Unauthorized',
  495. ], json_decode($parsed['responses'][1]['content'], true));
  496. }
  497. /**
  498. * @param $serializer
  499. * @param $expected
  500. *
  501. * @test
  502. * @dataProvider dataResources
  503. */
  504. public function can_parse_transformer_tag($serializer, $expected)
  505. {
  506. config(['apidoc.fractal.serializer' => $serializer]);
  507. $route = $this->createRoute('GET', '/transformerTag', 'transformerTag');
  508. $parsed = $this->generator->processRoute($route);
  509. $response = Arr::first($parsed['responses']);
  510. $this->assertTrue(is_array($parsed));
  511. $this->assertArrayHasKey('showresponse', $parsed);
  512. $this->assertTrue($parsed['showresponse']);
  513. $this->assertTrue(is_array($response));
  514. $this->assertEquals(200, $response['status']);
  515. $this->assertSame(
  516. $expected,
  517. $response['content']
  518. );
  519. }
  520. /** @test */
  521. public function can_parse_transformer_tag_with_model()
  522. {
  523. $route = $this->createRoute('GET', '/transformerTagWithModel', 'transformerTagWithModel');
  524. $parsed = $this->generator->processRoute($route);
  525. $response = Arr::first($parsed['responses']);
  526. $this->assertTrue(is_array($parsed));
  527. $this->assertArrayHasKey('showresponse', $parsed);
  528. $this->assertTrue($parsed['showresponse']);
  529. $this->assertTrue(is_array($response));
  530. $this->assertEquals(200, $response['status']);
  531. $this->assertSame(
  532. '{"data":{"id":1,"description":"Welcome on this test versions","name":"TestName"}}',
  533. $response['content']
  534. );
  535. }
  536. /** @test */
  537. public function can_parse_transformer_tag_with_status_code()
  538. {
  539. $route = $this->createRoute('GET', '/transformerTagWithStatusCode', 'transformerTagWithStatusCode');
  540. $parsed = $this->generator->processRoute($route);
  541. $response = Arr::first($parsed['responses']);
  542. $this->assertTrue(is_array($parsed));
  543. $this->assertArrayHasKey('showresponse', $parsed);
  544. $this->assertTrue($parsed['showresponse']);
  545. $this->assertTrue(is_array($response));
  546. $this->assertEquals(201, $response['status']);
  547. $this->assertSame(
  548. '{"data":{"id":1,"description":"Welcome on this test versions","name":"TestName"}}',
  549. $response['content']
  550. );
  551. }
  552. /** @test */
  553. public function can_parse_transformer_collection_tag()
  554. {
  555. $route = $this->createRoute('GET', '/transformerCollectionTag', 'transformerCollectionTag');
  556. $parsed = $this->generator->processRoute($route);
  557. $response = Arr::first($parsed['responses']);
  558. $this->assertTrue(is_array($parsed));
  559. $this->assertArrayHasKey('showresponse', $parsed);
  560. $this->assertTrue($parsed['showresponse']);
  561. $this->assertTrue(is_array($response));
  562. $this->assertEquals(200, $response['status']);
  563. $this->assertSame(
  564. $response['content'],
  565. '{"data":[{"id":1,"description":"Welcome on this test versions","name":"TestName"},'.
  566. '{"id":1,"description":"Welcome on this test versions","name":"TestName"}]}'
  567. );
  568. }
  569. /** @test */
  570. public function can_parse_transformer_collection_tag_with_model()
  571. {
  572. $route = $this->createRoute('GET', '/transformerCollectionTagWithModel', 'transformerCollectionTagWithModel');
  573. $parsed = $this->generator->processRoute($route);
  574. $response = Arr::first($parsed['responses']);
  575. $this->assertTrue(is_array($parsed));
  576. $this->assertArrayHasKey('showresponse', $parsed);
  577. $this->assertTrue($parsed['showresponse']);
  578. $this->assertTrue(is_array($response));
  579. $this->assertEquals(200, $response['status']);
  580. $this->assertSame(
  581. $response['content'],
  582. '{"data":[{"id":1,"description":"Welcome on this test versions","name":"TestName"},'.
  583. '{"id":1,"description":"Welcome on this test versions","name":"TestName"}]}'
  584. );
  585. }
  586. /** @test */
  587. public function can_call_route_and_generate_response()
  588. {
  589. $route = $this->createRoute('POST', '/shouldFetchRouteResponse', 'shouldFetchRouteResponse', true);
  590. $rules = [
  591. 'headers' => [
  592. 'Content-Type' => 'application/json',
  593. 'Accept' => 'application/json',
  594. ],
  595. 'response_calls' => [
  596. 'methods' => ['*'],
  597. ],
  598. ];
  599. $parsed = $this->generator->processRoute($route, $rules);
  600. $response = Arr::first($parsed['responses']);
  601. $this->assertTrue(is_array($parsed));
  602. $this->assertArrayHasKey('showresponse', $parsed);
  603. $this->assertTrue($parsed['showresponse']);
  604. $this->assertTrue(is_array($response));
  605. $this->assertEquals(200, $response['status']);
  606. $this->assertArraySubset([
  607. 'id' => 4,
  608. 'name' => 'banana',
  609. 'color' => 'red',
  610. 'weight' => '1 kg',
  611. 'delicious' => true,
  612. ], json_decode($response['content'], true));
  613. }
  614. /** @test */
  615. public function does_not_make_response_call_if_success_response_already_gotten()
  616. {
  617. $route = $this->createRoute('POST', '/withResponseTag', 'withResponseTag', true);
  618. $rules = [
  619. 'headers' => [
  620. 'Content-Type' => 'application/json',
  621. 'Accept' => 'application/json',
  622. ],
  623. 'response_calls' => [
  624. 'methods' => ['*'],
  625. ],
  626. ];
  627. $config = [
  628. 'strategies' => [
  629. 'responses' => [
  630. \Mpociot\ApiDoc\Strategies\Responses\UseResponseTag::class,
  631. \Mpociot\ApiDoc\Strategies\Responses\ResponseCalls::class,
  632. ],
  633. ],
  634. ];
  635. $generator = new Generator(new DocumentationConfig($config));
  636. $parsed = $generator->processRoute($route, $rules);
  637. $this->assertCount(1, $parsed['responses']);
  638. $response = Arr::first($parsed['responses']);
  639. $this->assertTrue(is_array($parsed));
  640. $this->assertArrayHasKey('showresponse', $parsed);
  641. $this->assertTrue($parsed['showresponse']);
  642. $this->assertTrue(is_array($response));
  643. $this->assertEquals(200, $response['status']);
  644. $this->assertArraySubset([
  645. 'id' => 4,
  646. 'name' => 'banana',
  647. 'color' => 'red',
  648. 'weight' => '1 kg',
  649. 'delicious' => true,
  650. 'responseTag' => true,
  651. ], json_decode($response['content'], true));
  652. // This may probably not be the best way to test this, but 🤷‍♀️
  653. $this->assertNull(static::$globalValue);
  654. }
  655. /** @test */
  656. public function can_override_config_during_response_call()
  657. {
  658. $route = $this->createRoute('POST', '/echoesConfig', 'echoesConfig', true);
  659. $rules = [
  660. 'response_calls' => [
  661. 'methods' => ['*'],
  662. ],
  663. ];
  664. $parsed = $this->generator->processRoute($route, $rules);
  665. $response = json_decode(Arr::first($parsed['responses'])['content'], true);
  666. $originalValue = $response['app.env'];
  667. $now = time();
  668. $rules = [
  669. 'response_calls' => [
  670. 'methods' => ['*'],
  671. 'config' => [
  672. 'app.env' => $now,
  673. ],
  674. ],
  675. ];
  676. $parsed = $this->generator->processRoute($route, $rules);
  677. $response = json_decode(Arr::first($parsed['responses'])['content'], true);
  678. $newValue = $response['app.env'];
  679. $this->assertEquals($now, $newValue);
  680. $this->assertNotEquals($originalValue, $newValue);
  681. }
  682. /** @test */
  683. public function can_override_url_path_parameters_with_urlparam_annotation()
  684. {
  685. $route = $this->createRoute('POST', '/echoesUrlParameters/{param}', 'echoesUrlParameters', true);
  686. $rules = [
  687. 'response_calls' => [
  688. 'methods' => ['*'],
  689. ],
  690. ];
  691. $parsed = $this->generator->processRoute($route, $rules);
  692. $response = json_decode(Arr::first($parsed['responses'])['content'], true);
  693. $this->assertEquals(4, $response['param']);
  694. }
  695. /** @test */
  696. public function ignores_or_inserts_optional_url_path_parameters_according_to_annotations()
  697. {
  698. $route = $this->createRoute('POST', '/echoesUrlParameters/{param}/{param2?}/{param3}/{param4?}', 'echoesUrlParameters', true);
  699. $rules = [
  700. 'response_calls' => [
  701. 'methods' => ['*'],
  702. ],
  703. ];
  704. $parsed = $this->generator->processRoute($route, $rules);
  705. $response = json_decode(Arr::first($parsed['responses'])['content'], true);
  706. $this->assertEquals(4, $response['param']);
  707. $this->assertNotNull($response['param2']);
  708. $this->assertEquals(1, $response['param3']);
  709. $this->assertNull($response['param4']);
  710. }
  711. /** @test */
  712. public function can_parse_response_file_tag()
  713. {
  714. // copy file to storage
  715. $filePath = __DIR__.'/../Fixtures/response_test.json';
  716. $fixtureFileJson = file_get_contents($filePath);
  717. copy($filePath, storage_path('response_test.json'));
  718. $route = $this->createRoute('GET', '/responseFileTag', 'responseFileTag');
  719. $parsed = $this->generator->processRoute($route);
  720. $response = Arr::first($parsed['responses']);
  721. $this->assertTrue(is_array($parsed));
  722. $this->assertArrayHasKey('showresponse', $parsed);
  723. $this->assertTrue($parsed['showresponse']);
  724. $this->assertTrue(is_array($response));
  725. $this->assertEquals(200, $response['status']);
  726. $this->assertSame(
  727. $response['content'],
  728. $fixtureFileJson
  729. );
  730. unlink(storage_path('response_test.json'));
  731. }
  732. /** @test */
  733. public function can_add_or_replace_key_value_pair_in_response_file()
  734. {
  735. // copy file to storage
  736. $filePath = __DIR__.'/../Fixtures/response_test.json';
  737. $fixtureFileJson = file_get_contents($filePath);
  738. copy($filePath, storage_path('response_test.json'));
  739. $route = $this->createRoute('GET', '/responseFileTagAndCustomJson', 'responseFileTagAndCustomJson');
  740. $parsed = $this->generator->processRoute($route);
  741. $response = Arr::first($parsed['responses']);
  742. $this->assertTrue(is_array($parsed));
  743. $this->assertArrayHasKey('showresponse', $parsed);
  744. $this->assertTrue($parsed['showresponse']);
  745. $this->assertTrue(is_array($response));
  746. $this->assertEquals(200, $response['status']);
  747. $this->assertNotSame(
  748. $response['content'],
  749. $fixtureFileJson
  750. );
  751. unlink(storage_path('response_test.json'));
  752. }
  753. /** @test */
  754. public function can_parse_multiple_response_file_tags_with_status_codes()
  755. {
  756. // copy file to storage
  757. $successFilePath = __DIR__.'/../Fixtures/response_test.json';
  758. $successFixtureFileJson = file_get_contents($successFilePath);
  759. copy($successFilePath, storage_path('response_test.json'));
  760. $errorFilePath = __DIR__.'/../Fixtures/response_error_test.json';
  761. $errorFixtureFileJson = file_get_contents($errorFilePath);
  762. copy($errorFilePath, storage_path('response_error_test.json'));
  763. $route = $this->createRoute('GET', '/responseFileTag', 'withResponseFileTagAndStatusCode');
  764. $parsed = $this->generator->processRoute($route);
  765. $this->assertTrue(is_array($parsed));
  766. $this->assertArrayHasKey('showresponse', $parsed);
  767. $this->assertTrue($parsed['showresponse']);
  768. $this->assertTrue(is_array($parsed['responses'][0]));
  769. $this->assertEquals(200, $parsed['responses'][0]['status']);
  770. $this->assertSame(
  771. $parsed['responses'][0]['content'],
  772. $successFixtureFileJson
  773. );
  774. $this->assertTrue(is_array($parsed['responses'][1]));
  775. $this->assertEquals(401, $parsed['responses'][1]['status']);
  776. $this->assertSame(
  777. $parsed['responses'][1]['content'],
  778. $errorFixtureFileJson
  779. );
  780. unlink(storage_path('response_test.json'));
  781. unlink(storage_path('response_error_test.json'));
  782. }
  783. /** @test */
  784. public function generates_consistent_examples_when_faker_seed_is_set()
  785. {
  786. $route = $this->createRoute('GET', '/withBodyParameters', 'withBodyParameters');
  787. $paramName = 'room_id';
  788. $results = [];
  789. $results[$this->generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  790. $results[$this->generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  791. $results[$this->generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  792. $results[$this->generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  793. $results[$this->generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  794. // Examples should have different values
  795. $this->assertNotEquals(count($results), 1);
  796. $generator = new Generator(new DocumentationConfig($this->config + ['faker_seed' => 12345]));
  797. $results = [];
  798. $results[$generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  799. $results[$generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  800. $results[$generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  801. $results[$generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  802. // Examples should have same values
  803. $this->assertEquals(count($results), 1);
  804. }
  805. /** @test */
  806. public function uses_configured_settings_when_calling_route()
  807. {
  808. $route = $this->createRoute('PUT', '/echo/{id}', 'shouldFetchRouteResponseWithEchoedSettings', true);
  809. $rules = [
  810. 'headers' => [
  811. 'Content-Type' => 'application/json',
  812. 'Accept' => 'application/json',
  813. 'header' => 'value',
  814. ],
  815. 'response_calls' => [
  816. 'methods' => ['*'],
  817. 'queryParams' => [
  818. 'queryParam' => 'queryValue',
  819. ],
  820. 'bodyParams' => [
  821. 'bodyParam' => 'bodyValue',
  822. ],
  823. ],
  824. ];
  825. $parsed = $this->generator->processRoute($route, $rules);
  826. $response = Arr::first($parsed['responses']);
  827. $this->assertTrue(is_array($parsed));
  828. $this->assertArrayHasKey('showresponse', $parsed);
  829. $this->assertTrue($parsed['showresponse']);
  830. $this->assertTrue(is_array($response));
  831. $this->assertEquals(200, $response['status']);
  832. $responseContent = json_decode($response['content'], true);
  833. $this->assertEquals('queryValue', $responseContent['queryParam']);
  834. $this->assertEquals('bodyValue', $responseContent['bodyParam']);
  835. $this->assertEquals('value', $responseContent['header']);
  836. }
  837. /** @test */
  838. public function can_use_arrays_in_routes_uses()
  839. {
  840. $route = $this->createRouteUsesArray('GET', '/api/array/test', 'withEndpointDescription');
  841. $parsed = $this->generator->processRoute($route);
  842. $this->assertSame('Example title.', $parsed['metadata']['title']);
  843. $this->assertSame("This will be the long description.\nIt can also be multiple lines long.", $parsed['metadata']['description']);
  844. }
  845. abstract public function createRoute(string $httpMethod, string $path, string $controllerMethod, $register = false, $class = TestController::class);
  846. abstract public function createRouteUsesArray(string $httpMethod, string $path, string $controllerMethod, $register = false, $class = TestController::class);
  847. public function dataResources()
  848. {
  849. return [
  850. [
  851. null,
  852. '{"data":{"id":1,"description":"Welcome on this test versions","name":"TestName"}}',
  853. ],
  854. [
  855. 'League\Fractal\Serializer\JsonApiSerializer',
  856. '{"data":{"type":null,"id":"1","attributes":{"description":"Welcome on this test versions","name":"TestName"}}}',
  857. ],
  858. ];
  859. }
  860. }