GeneratorTestCase.php 38 KB

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