GeneratorTestCase.php 36 KB

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