GeneratorTestCase.php 37 KB

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