GeneratorTestCase.php 36 KB

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