GeneratorTestCase.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  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\UseResponseTag::class,
  33. \Mpociot\ApiDoc\Extracting\Strategies\Responses\UseResponseFileTag::class,
  34. \Mpociot\ApiDoc\Extracting\Strategies\Responses\UseApiResourceTags::class,
  35. \Mpociot\ApiDoc\Extracting\Strategies\Responses\UseTransformerTags::class,
  36. \Mpociot\ApiDoc\Extracting\Strategies\Responses\ResponseCalls::class,
  37. ],
  38. 'requestHeaders' => [
  39. \Mpociot\ApiDoc\Extracting\Strategies\RequestHeaders\GetFromRouteRules::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. 'id' => 4,
  377. 'name' => 'Tested Again',
  378. 'email' => 'a@b.com',
  379. ], json_decode($response['content'], true));
  380. }
  381. /** @test */
  382. public function can_parse_apiresourcecollection_tags()
  383. {
  384. $route = $this->createRoute('POST', '/withEloquentApiResourceCollection', 'withEloquentApiResourceCollection');
  385. $config = $this->config;
  386. $config['strategies']['responses'] = [\Mpociot\ApiDoc\Extracting\Strategies\Responses\UseApiResourceTags::class];
  387. $generator = new Generator(new DocumentationConfig($config));
  388. $parsed = $this->generator->processRoute($route);
  389. $response = Arr::first($parsed['responses']);
  390. $this->assertTrue(is_array($parsed));
  391. $this->assertArrayHasKey('showresponse', $parsed);
  392. $this->assertTrue($parsed['showresponse']);
  393. $this->assertTrue(is_array($response));
  394. $this->assertEquals(200, $response['status']);
  395. $content = json_decode($response['content'], true);
  396. $this->assertIsArray($content);
  397. $this->assertArraySubset([
  398. 'id' => 4,
  399. 'name' => 'Tested Again',
  400. 'email' => 'a@b.com',
  401. ], $content[0]);
  402. $this->assertArraySubset([
  403. 'id' => 4,
  404. 'name' => 'Tested Again',
  405. 'email' => 'a@b.com',
  406. ], $content[1]);
  407. }
  408. /** @test */
  409. public function can_parse_apiresourcecollection_tags_with_collection_class()
  410. {
  411. $route = $this->createRoute('POST', '/withEloquentApiResourceCollectionClass', 'withEloquentApiResourceCollectionClass');
  412. $config = $this->config;
  413. $config['strategies']['responses'] = [\Mpociot\ApiDoc\Extracting\Strategies\Responses\UseApiResourceTags::class];
  414. $generator = new Generator(new DocumentationConfig($config));
  415. $parsed = $this->generator->processRoute($route);
  416. $response = Arr::first($parsed['responses']);
  417. $this->assertTrue(is_array($parsed));
  418. $this->assertArrayHasKey('showresponse', $parsed);
  419. $this->assertTrue($parsed['showresponse']);
  420. $this->assertTrue(is_array($response));
  421. $this->assertEquals(200, $response['status']);
  422. $content = json_decode($response['content'], true);
  423. $this->assertIsArray($content);
  424. $this->assertArraySubset([
  425. 'data' => [
  426. [
  427. 'id' => 4,
  428. 'name' => 'Tested Again',
  429. 'email' => 'a@b.com',
  430. ],
  431. [
  432. 'id' => 4,
  433. 'name' => 'Tested Again',
  434. 'email' => 'a@b.com',
  435. ],
  436. ],
  437. 'links' => [
  438. 'self' => 'link-value',
  439. ],
  440. ], $content);
  441. }
  442. /** @test */
  443. public function can_parse_response_tag()
  444. {
  445. $route = $this->createRoute('POST', '/responseTag', 'withResponseTag');
  446. $parsed = $this->generator->processRoute($route);
  447. $response = Arr::first($parsed['responses']);
  448. $this->assertTrue(is_array($parsed));
  449. $this->assertArrayHasKey('showresponse', $parsed);
  450. $this->assertTrue($parsed['showresponse']);
  451. $this->assertTrue(is_array($response));
  452. $this->assertEquals(200, $response['status']);
  453. $this->assertArraySubset([
  454. 'id' => 4,
  455. 'name' => 'banana',
  456. 'color' => 'red',
  457. 'weight' => '1 kg',
  458. 'delicious' => true,
  459. ], json_decode($response['content'], true));
  460. }
  461. /** @test */
  462. public function can_parse_response_tag_with_status_code()
  463. {
  464. $route = $this->createRoute('POST', '/responseTag', 'withResponseTagAndStatusCode');
  465. $parsed = $this->generator->processRoute($route);
  466. $response = Arr::first($parsed['responses']);
  467. $this->assertTrue(is_array($parsed));
  468. $this->assertArrayHasKey('showresponse', $parsed);
  469. $this->assertTrue($parsed['showresponse']);
  470. $this->assertTrue(is_array($response));
  471. $this->assertEquals(422, $response['status']);
  472. $this->assertArraySubset([
  473. 'message' => 'Validation error',
  474. ], json_decode($response['content'], true));
  475. }
  476. /** @test */
  477. public function can_parse_multiple_response_tags()
  478. {
  479. $route = $this->createRoute('POST', '/responseTag', 'withMultipleResponseTagsAndStatusCode');
  480. $parsed = $this->generator->processRoute($route);
  481. $this->assertTrue(is_array($parsed));
  482. $this->assertArrayHasKey('showresponse', $parsed);
  483. $this->assertTrue($parsed['showresponse']);
  484. $this->assertTrue(is_array($parsed['responses'][0]));
  485. $this->assertEquals(200, $parsed['responses'][0]['status']);
  486. $this->assertArraySubset([
  487. 'id' => 4,
  488. 'name' => 'banana',
  489. 'color' => 'red',
  490. 'weight' => '1 kg',
  491. 'delicious' => true,
  492. ], json_decode($parsed['responses'][0]['content'], true));
  493. $this->assertTrue(is_array($parsed['responses'][1]));
  494. $this->assertEquals(401, $parsed['responses'][1]['status']);
  495. $this->assertArraySubset([
  496. 'message' => 'Unauthorized',
  497. ], json_decode($parsed['responses'][1]['content'], true));
  498. }
  499. /**
  500. * @param $serializer
  501. * @param $expected
  502. *
  503. * @test
  504. * @dataProvider dataResources
  505. */
  506. public function can_parse_transformer_tag($serializer, $expected)
  507. {
  508. config(['apidoc.fractal.serializer' => $serializer]);
  509. $route = $this->createRoute('GET', '/transformerTag', 'transformerTag');
  510. $parsed = $this->generator->processRoute($route);
  511. $response = Arr::first($parsed['responses']);
  512. $this->assertTrue(is_array($parsed));
  513. $this->assertArrayHasKey('showresponse', $parsed);
  514. $this->assertTrue($parsed['showresponse']);
  515. $this->assertTrue(is_array($response));
  516. $this->assertEquals(200, $response['status']);
  517. $this->assertSame(
  518. $expected,
  519. $response['content']
  520. );
  521. }
  522. /** @test */
  523. public function can_parse_transformer_tag_with_model()
  524. {
  525. $route = $this->createRoute('GET', '/transformerTagWithModel', 'transformerTagWithModel');
  526. $parsed = $this->generator->processRoute($route);
  527. $response = Arr::first($parsed['responses']);
  528. $this->assertTrue(is_array($parsed));
  529. $this->assertArrayHasKey('showresponse', $parsed);
  530. $this->assertTrue($parsed['showresponse']);
  531. $this->assertTrue(is_array($response));
  532. $this->assertEquals(200, $response['status']);
  533. $this->assertSame(
  534. '{"data":{"id":1,"description":"Welcome on this test versions","name":"TestName"}}',
  535. $response['content']
  536. );
  537. }
  538. /** @test */
  539. public function can_parse_transformer_tag_with_status_code()
  540. {
  541. $route = $this->createRoute('GET', '/transformerTagWithStatusCode', 'transformerTagWithStatusCode');
  542. $parsed = $this->generator->processRoute($route);
  543. $response = Arr::first($parsed['responses']);
  544. $this->assertTrue(is_array($parsed));
  545. $this->assertArrayHasKey('showresponse', $parsed);
  546. $this->assertTrue($parsed['showresponse']);
  547. $this->assertTrue(is_array($response));
  548. $this->assertEquals(201, $response['status']);
  549. $this->assertSame(
  550. '{"data":{"id":1,"description":"Welcome on this test versions","name":"TestName"}}',
  551. $response['content']
  552. );
  553. }
  554. /** @test */
  555. public function can_parse_transformer_collection_tag()
  556. {
  557. $route = $this->createRoute('GET', '/transformerCollectionTag', 'transformerCollectionTag');
  558. $parsed = $this->generator->processRoute($route);
  559. $response = Arr::first($parsed['responses']);
  560. $this->assertTrue(is_array($parsed));
  561. $this->assertArrayHasKey('showresponse', $parsed);
  562. $this->assertTrue($parsed['showresponse']);
  563. $this->assertTrue(is_array($response));
  564. $this->assertEquals(200, $response['status']);
  565. $this->assertSame(
  566. $response['content'],
  567. '{"data":[{"id":1,"description":"Welcome on this test versions","name":"TestName"},'.
  568. '{"id":1,"description":"Welcome on this test versions","name":"TestName"}]}'
  569. );
  570. }
  571. /** @test */
  572. public function can_parse_transformer_collection_tag_with_model()
  573. {
  574. $route = $this->createRoute('GET', '/transformerCollectionTagWithModel', 'transformerCollectionTagWithModel');
  575. $parsed = $this->generator->processRoute($route);
  576. $response = Arr::first($parsed['responses']);
  577. $this->assertTrue(is_array($parsed));
  578. $this->assertArrayHasKey('showresponse', $parsed);
  579. $this->assertTrue($parsed['showresponse']);
  580. $this->assertTrue(is_array($response));
  581. $this->assertEquals(200, $response['status']);
  582. $this->assertSame(
  583. $response['content'],
  584. '{"data":[{"id":1,"description":"Welcome on this test versions","name":"TestName"},'.
  585. '{"id":1,"description":"Welcome on this test versions","name":"TestName"}]}'
  586. );
  587. }
  588. /** @test */
  589. public function can_call_route_and_generate_response()
  590. {
  591. $route = $this->createRoute('POST', '/shouldFetchRouteResponse', 'shouldFetchRouteResponse', true);
  592. $rules = [
  593. 'headers' => [
  594. 'Content-Type' => 'application/json',
  595. 'Accept' => 'application/json',
  596. ],
  597. 'response_calls' => [
  598. 'methods' => ['*'],
  599. ],
  600. ];
  601. $parsed = $this->generator->processRoute($route, $rules);
  602. $response = Arr::first($parsed['responses']);
  603. $this->assertTrue(is_array($parsed));
  604. $this->assertArrayHasKey('showresponse', $parsed);
  605. $this->assertTrue($parsed['showresponse']);
  606. $this->assertTrue(is_array($response));
  607. $this->assertEquals(200, $response['status']);
  608. $this->assertArraySubset([
  609. 'id' => 4,
  610. 'name' => 'banana',
  611. 'color' => 'red',
  612. 'weight' => '1 kg',
  613. 'delicious' => true,
  614. ], json_decode($response['content'], true));
  615. }
  616. /** @test */
  617. public function does_not_make_response_call_if_success_response_already_gotten()
  618. {
  619. $route = $this->createRoute('POST', '/withResponseTag', 'withResponseTag', true);
  620. $rules = [
  621. 'headers' => [
  622. 'Content-Type' => 'application/json',
  623. 'Accept' => 'application/json',
  624. ],
  625. 'response_calls' => [
  626. 'methods' => ['*'],
  627. ],
  628. ];
  629. $config = [
  630. 'strategies' => [
  631. 'responses' => [
  632. \Mpociot\ApiDoc\Extracting\Strategies\Responses\UseResponseTag::class,
  633. \Mpociot\ApiDoc\Extracting\Strategies\Responses\ResponseCalls::class,
  634. ],
  635. ],
  636. ];
  637. $generator = new Generator(new DocumentationConfig($config));
  638. $parsed = $generator->processRoute($route, $rules);
  639. $this->assertCount(1, $parsed['responses']);
  640. $response = Arr::first($parsed['responses']);
  641. $this->assertTrue(is_array($parsed));
  642. $this->assertArrayHasKey('showresponse', $parsed);
  643. $this->assertTrue($parsed['showresponse']);
  644. $this->assertTrue(is_array($response));
  645. $this->assertEquals(200, $response['status']);
  646. $this->assertArraySubset([
  647. 'id' => 4,
  648. 'name' => 'banana',
  649. 'color' => 'red',
  650. 'weight' => '1 kg',
  651. 'delicious' => true,
  652. 'responseTag' => true,
  653. ], json_decode($response['content'], true));
  654. // This may probably not be the best way to test this, but 🤷‍♀️
  655. $this->assertNull(static::$globalValue);
  656. }
  657. /** @test */
  658. public function can_override_config_during_response_call()
  659. {
  660. $route = $this->createRoute('POST', '/echoesConfig', 'echoesConfig', true);
  661. $rules = [
  662. 'response_calls' => [
  663. 'methods' => ['*'],
  664. ],
  665. ];
  666. $parsed = $this->generator->processRoute($route, $rules);
  667. $response = json_decode(Arr::first($parsed['responses'])['content'], true);
  668. $originalValue = $response['app.env'];
  669. $now = time();
  670. $rules = [
  671. 'response_calls' => [
  672. 'methods' => ['*'],
  673. 'config' => [
  674. 'app.env' => $now,
  675. ],
  676. ],
  677. ];
  678. $parsed = $this->generator->processRoute($route, $rules);
  679. $response = json_decode(Arr::first($parsed['responses'])['content'], true);
  680. $newValue = $response['app.env'];
  681. $this->assertEquals($now, $newValue);
  682. $this->assertNotEquals($originalValue, $newValue);
  683. }
  684. /** @test */
  685. public function can_override_url_path_parameters_with_urlparam_annotation()
  686. {
  687. $route = $this->createRoute('POST', '/echoesUrlParameters/{param}', 'echoesUrlParameters', true);
  688. $rules = [
  689. 'response_calls' => [
  690. 'methods' => ['*'],
  691. ],
  692. ];
  693. $parsed = $this->generator->processRoute($route, $rules);
  694. $response = json_decode(Arr::first($parsed['responses'])['content'], true);
  695. $this->assertEquals(4, $response['param']);
  696. }
  697. /** @test */
  698. public function ignores_or_inserts_optional_url_path_parameters_according_to_annotations()
  699. {
  700. $route = $this->createRoute('POST', '/echoesUrlParameters/{param}/{param2?}/{param3}/{param4?}', 'echoesUrlParameters', true);
  701. $rules = [
  702. 'response_calls' => [
  703. 'methods' => ['*'],
  704. ],
  705. ];
  706. $parsed = $this->generator->processRoute($route, $rules);
  707. $response = json_decode(Arr::first($parsed['responses'])['content'], true);
  708. $this->assertEquals(4, $response['param']);
  709. $this->assertNotNull($response['param2']);
  710. $this->assertEquals(1, $response['param3']);
  711. $this->assertNull($response['param4']);
  712. }
  713. /** @test */
  714. public function can_parse_response_file_tag()
  715. {
  716. // copy file to storage
  717. $filePath = __DIR__.'/../Fixtures/response_test.json';
  718. $fixtureFileJson = file_get_contents($filePath);
  719. copy($filePath, storage_path('response_test.json'));
  720. $route = $this->createRoute('GET', '/responseFileTag', 'responseFileTag');
  721. $parsed = $this->generator->processRoute($route);
  722. $response = Arr::first($parsed['responses']);
  723. $this->assertTrue(is_array($parsed));
  724. $this->assertArrayHasKey('showresponse', $parsed);
  725. $this->assertTrue($parsed['showresponse']);
  726. $this->assertTrue(is_array($response));
  727. $this->assertEquals(200, $response['status']);
  728. $this->assertSame(
  729. $response['content'],
  730. $fixtureFileJson
  731. );
  732. unlink(storage_path('response_test.json'));
  733. }
  734. /** @test */
  735. public function can_add_or_replace_key_value_pair_in_response_file()
  736. {
  737. // copy file to storage
  738. $filePath = __DIR__.'/../Fixtures/response_test.json';
  739. $fixtureFileJson = file_get_contents($filePath);
  740. copy($filePath, storage_path('response_test.json'));
  741. $route = $this->createRoute('GET', '/responseFileTagAndCustomJson', 'responseFileTagAndCustomJson');
  742. $parsed = $this->generator->processRoute($route);
  743. $response = Arr::first($parsed['responses']);
  744. $this->assertTrue(is_array($parsed));
  745. $this->assertArrayHasKey('showresponse', $parsed);
  746. $this->assertTrue($parsed['showresponse']);
  747. $this->assertTrue(is_array($response));
  748. $this->assertEquals(200, $response['status']);
  749. $this->assertNotSame(
  750. $response['content'],
  751. $fixtureFileJson
  752. );
  753. unlink(storage_path('response_test.json'));
  754. }
  755. /** @test */
  756. public function can_parse_multiple_response_file_tags_with_status_codes()
  757. {
  758. // copy file to storage
  759. $successFilePath = __DIR__.'/../Fixtures/response_test.json';
  760. $successFixtureFileJson = file_get_contents($successFilePath);
  761. copy($successFilePath, storage_path('response_test.json'));
  762. $errorFilePath = __DIR__.'/../Fixtures/response_error_test.json';
  763. $errorFixtureFileJson = file_get_contents($errorFilePath);
  764. copy($errorFilePath, storage_path('response_error_test.json'));
  765. $route = $this->createRoute('GET', '/responseFileTag', 'withResponseFileTagAndStatusCode');
  766. $parsed = $this->generator->processRoute($route);
  767. $this->assertTrue(is_array($parsed));
  768. $this->assertArrayHasKey('showresponse', $parsed);
  769. $this->assertTrue($parsed['showresponse']);
  770. $this->assertTrue(is_array($parsed['responses'][0]));
  771. $this->assertEquals(200, $parsed['responses'][0]['status']);
  772. $this->assertSame(
  773. $parsed['responses'][0]['content'],
  774. $successFixtureFileJson
  775. );
  776. $this->assertTrue(is_array($parsed['responses'][1]));
  777. $this->assertEquals(401, $parsed['responses'][1]['status']);
  778. $this->assertSame(
  779. $parsed['responses'][1]['content'],
  780. $errorFixtureFileJson
  781. );
  782. unlink(storage_path('response_test.json'));
  783. unlink(storage_path('response_error_test.json'));
  784. }
  785. /** @test */
  786. public function generates_consistent_examples_when_faker_seed_is_set()
  787. {
  788. $route = $this->createRoute('GET', '/withBodyParameters', 'withBodyParameters');
  789. $paramName = 'room_id';
  790. $results = [];
  791. $results[$this->generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  792. $results[$this->generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  793. $results[$this->generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  794. $results[$this->generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  795. $results[$this->generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  796. // Examples should have different values
  797. $this->assertNotEquals(count($results), 1);
  798. $generator = new Generator(new DocumentationConfig($this->config + ['faker_seed' => 12345]));
  799. $results = [];
  800. $results[$generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  801. $results[$generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  802. $results[$generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  803. $results[$generator->processRoute($route)['cleanBodyParameters'][$paramName]] = true;
  804. // Examples should have same values
  805. $this->assertEquals(count($results), 1);
  806. }
  807. /** @test */
  808. public function uses_configured_settings_when_calling_route()
  809. {
  810. $route = $this->createRoute('PUT', '/echo/{id}', 'shouldFetchRouteResponseWithEchoedSettings', true);
  811. $rules = [
  812. 'headers' => [
  813. 'Content-Type' => 'application/json',
  814. 'Accept' => 'application/json',
  815. 'header' => 'value',
  816. ],
  817. 'response_calls' => [
  818. 'methods' => ['*'],
  819. 'queryParams' => [
  820. 'queryParam' => 'queryValue',
  821. ],
  822. 'bodyParams' => [
  823. 'bodyParam' => 'bodyValue',
  824. ],
  825. ],
  826. ];
  827. $parsed = $this->generator->processRoute($route, $rules);
  828. $response = Arr::first($parsed['responses']);
  829. $this->assertTrue(is_array($parsed));
  830. $this->assertArrayHasKey('showresponse', $parsed);
  831. $this->assertTrue($parsed['showresponse']);
  832. $this->assertTrue(is_array($response));
  833. $this->assertEquals(200, $response['status']);
  834. $responseContent = json_decode($response['content'], true);
  835. $this->assertEquals('queryValue', $responseContent['queryParam']);
  836. $this->assertEquals('bodyValue', $responseContent['bodyParam']);
  837. $this->assertEquals('value', $responseContent['header']);
  838. }
  839. /** @test */
  840. public function can_use_arrays_in_routes_uses()
  841. {
  842. $route = $this->createRouteUsesArray('GET', '/api/array/test', 'withEndpointDescription');
  843. $parsed = $this->generator->processRoute($route);
  844. $this->assertSame('Example title.', $parsed['metadata']['title']);
  845. $this->assertSame("This will be the long description.\nIt can also be multiple lines long.", $parsed['metadata']['description']);
  846. }
  847. abstract public function createRoute(string $httpMethod, string $path, string $controllerMethod, $register = false, $class = TestController::class);
  848. abstract public function createRouteUsesArray(string $httpMethod, string $path, string $controllerMethod, $register = false, $class = TestController::class);
  849. public function dataResources()
  850. {
  851. return [
  852. [
  853. null,
  854. '{"data":{"id":1,"description":"Welcome on this test versions","name":"TestName"}}',
  855. ],
  856. [
  857. 'League\Fractal\Serializer\JsonApiSerializer',
  858. '{"data":{"type":null,"id":"1","attributes":{"description":"Welcome on this test versions","name":"TestName"}}}',
  859. ],
  860. ];
  861. }
  862. }