OpenAPISpecWriterTest.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. <?php
  2. namespace Knuckles\Scribe\Tests\Unit;
  3. use DMS\PHPUnitExtensions\ArraySubset\ArraySubsetAsserts;
  4. use Faker\Factory;
  5. use Illuminate\Support\Arr;
  6. use Knuckles\Camel\Camel;
  7. use Knuckles\Camel\Output\OutputEndpointData;
  8. use Knuckles\Scribe\Tools\DocumentationConfig;
  9. use Knuckles\Scribe\Writing\OpenAPISpecWriter;
  10. use PHPUnit\Framework\TestCase;
  11. /**
  12. * See https://swagger.io/specification/
  13. */
  14. class OpenAPISpecWriterTest extends TestCase
  15. {
  16. use ArraySubsetAsserts;
  17. protected $config = [
  18. 'title' => 'My Testy Testes API',
  19. 'description' => 'All about testy testes.',
  20. 'base_url' => 'http://api.api.dev',
  21. ];
  22. /** @test */
  23. public function follows_correct_spec_structure()
  24. {
  25. $endpointData1 = $this->createMockEndpointData();
  26. $endpointData2 = $this->createMockEndpointData();
  27. $groups = [$this->createGroup([$endpointData1, $endpointData2])];
  28. $results = $this->generate($groups);
  29. $this->assertEquals(OpenAPISpecWriter::VERSION, $results['openapi']);
  30. $this->assertEquals($this->config['title'], $results['info']['title']);
  31. $this->assertEquals($this->config['description'], $results['info']['description']);
  32. $this->assertNotEmpty($results['info']['version']);
  33. $this->assertEquals($this->config['base_url'], $results['servers'][0]['url']);
  34. $this->assertIsArray($results['paths']);
  35. $this->assertGreaterThan(0, count($results['paths']));
  36. }
  37. /** @test */
  38. public function adds_endpoints_correctly_as_operations_under_paths()
  39. {
  40. $endpointData1 = $this->createMockEndpointData(['uri' => 'path1', 'httpMethods' => ['GET']]);
  41. $endpointData2 = $this->createMockEndpointData(['uri' => 'path1', 'httpMethods' => ['POST']]);
  42. $endpointData3 = $this->createMockEndpointData(['uri' => 'path1/path2']);
  43. $groups = [$this->createGroup([$endpointData1, $endpointData2, $endpointData3])];
  44. $results = $this->generate($groups);
  45. $this->assertIsArray($results['paths']);
  46. $this->assertCount(2, $results['paths']);
  47. $this->assertCount(2, $results['paths']['/path1']);
  48. $this->assertCount(1, $results['paths']['/path1/path2']);
  49. $this->assertArrayHasKey('get', $results['paths']['/path1']);
  50. $this->assertArrayHasKey('post', $results['paths']['/path1']);
  51. $this->assertArrayHasKey(strtolower($endpointData3->httpMethods[0]), $results['paths']['/path1/path2']);
  52. collect([$endpointData1, $endpointData2, $endpointData3])->each(function (OutputEndpointData $endpoint) use ($groups, $results) {
  53. $endpointSpec = $results['paths']['/' . $endpoint->uri][strtolower($endpoint->httpMethods[0])];
  54. $tags = $endpointSpec['tags'];
  55. $containingGroup = Arr::first($groups, function ($group) use ($endpoint) {
  56. return Camel::doesGroupContainEndpoint($group, $endpoint);
  57. });
  58. $this->assertEquals([$containingGroup['name']], $tags);
  59. $this->assertEquals($endpoint->metadata->title, $endpointSpec['summary']);
  60. $this->assertEquals($endpoint->metadata->description, $endpointSpec['description']);
  61. });
  62. }
  63. /** @test */
  64. public function adds_authentication_details_correctly_as_security_info()
  65. {
  66. $endpointData1 = $this->createMockEndpointData(['uri' => 'path1', 'httpMethods' => ['GET'], 'metadata.authenticated' => true]);
  67. $endpointData2 = $this->createMockEndpointData(['uri' => 'path1', 'httpMethods' => ['POST'], 'metadata.authenticated' => false]);
  68. $groups = [$this->createGroup([$endpointData1, $endpointData2])];
  69. $config = array_merge($this->config, ['auth' => ['enabled' => true, 'in' => 'bearer']]);
  70. $writer = new OpenAPISpecWriter(new DocumentationConfig($config));
  71. $results = $writer->generateSpecContent($groups);
  72. $this->assertCount(1, $results['components']['securitySchemes']);
  73. $this->assertArrayHasKey('default', $results['components']['securitySchemes']);
  74. $this->assertEquals('http', $results['components']['securitySchemes']['default']['type']);
  75. $this->assertEquals('bearer', $results['components']['securitySchemes']['default']['scheme']);
  76. $this->assertCount(1, $results['security']);
  77. $this->assertCount(1, $results['security'][0]);
  78. $this->assertArrayHasKey('default', $results['security'][0]);
  79. $this->assertArrayNotHasKey('security', $results['paths']['/path1']['get']);
  80. $this->assertArrayHasKey('security', $results['paths']['/path1']['post']);
  81. $this->assertCount(0, $results['paths']['/path1']['post']['security']);
  82. // Next try: auth with a query parameter
  83. $config = array_merge($this->config, ['auth' => ['enabled' => true, 'in' => 'query', 'name' => 'token']]);
  84. $writer = new OpenAPISpecWriter(new DocumentationConfig($config));
  85. $results = $writer->generateSpecContent($groups);
  86. $this->assertCount(1, $results['components']['securitySchemes']);
  87. $this->assertArrayHasKey('default', $results['components']['securitySchemes']);
  88. $this->assertEquals('apiKey', $results['components']['securitySchemes']['default']['type']);
  89. $this->assertEquals($config['auth']['name'], $results['components']['securitySchemes']['default']['name']);
  90. $this->assertEquals('query', $results['components']['securitySchemes']['default']['in']);
  91. $this->assertCount(1, $results['security']);
  92. $this->assertCount(1, $results['security'][0]);
  93. $this->assertArrayHasKey('default', $results['security'][0]);
  94. $this->assertArrayNotHasKey('security', $results['paths']['/path1']['get']);
  95. $this->assertArrayHasKey('security', $results['paths']['/path1']['post']);
  96. $this->assertCount(0, $results['paths']['/path1']['post']['security']);
  97. }
  98. /** @test */
  99. public function adds_url_parameters_correctly_as_parameters_on_path_item_object()
  100. {
  101. $endpointData1 = $this->createMockEndpointData([
  102. 'httpMethods' => ['POST'],
  103. 'uri' => 'path1/{param}/{optionalParam?}',
  104. 'urlParameters.param' => [
  105. 'description' => 'Something',
  106. 'required' => true,
  107. 'example' => 56,
  108. 'type' => 'integer',
  109. 'name' => 'param',
  110. ],
  111. 'urlParameters.optionalParam' => [
  112. 'description' => 'Another',
  113. 'required' => false,
  114. 'example' => '69',
  115. 'type' => 'string',
  116. 'name' => 'optionalParam',
  117. ],
  118. ]);
  119. $endpointData2 = $this->createMockEndpointData(['uri' => 'path1', 'httpMethods' => ['POST']]);
  120. $groups = [$this->createGroup([$endpointData1, $endpointData2])];
  121. $results = $this->generate($groups);
  122. $this->assertArrayNotHasKey('parameters', $results['paths']['/path1']);
  123. $this->assertCount(2, $results['paths']['/path1/{param}/{optionalParam}']['parameters']);
  124. $this->assertEquals([
  125. 'in' => 'path',
  126. 'required' => true,
  127. 'name' => 'param',
  128. 'description' => 'Something',
  129. 'example' => 56,
  130. 'schema' => ['type' => 'integer'],
  131. ], $results['paths']['/path1/{param}/{optionalParam}']['parameters'][0]);
  132. $this->assertEquals([
  133. 'in' => 'path',
  134. 'required' => true,
  135. 'name' => 'optionalParam',
  136. 'description' => 'Optional parameter. Another',
  137. 'examples' => [
  138. 'omitted' => ['summary' => 'When the value is omitted', 'value' => ''],
  139. 'present' => [
  140. 'summary' => 'When the value is present', 'value' => '69'],
  141. ],
  142. 'schema' => ['type' => 'string'],
  143. ], $results['paths']['/path1/{param}/{optionalParam}']['parameters'][1]);
  144. }
  145. /** @test */
  146. public function adds_headers_correctly_as_parameters_on_operation_object()
  147. {
  148. $endpointData1 = $this->createMockEndpointData(['httpMethods' => ['POST'], 'uri' => 'path1', 'headers.Extra-Header' => 'Some-example']);
  149. $endpointData2 = $this->createMockEndpointData(['uri' => 'path1', 'httpMethods' => ['GET'], 'headers' => []]);
  150. $groups = [$this->createGroup([$endpointData1, $endpointData2])];
  151. $results = $this->generate($groups);
  152. $this->assertEquals([], $results['paths']['/path1']['get']['parameters']);
  153. $this->assertCount(2, $results['paths']['/path1']['post']['parameters']);
  154. $this->assertEquals([
  155. 'in' => 'header',
  156. 'name' => 'Content-Type',
  157. 'description' => '',
  158. 'example' => 'application/json',
  159. 'schema' => ['type' => 'string'],
  160. ], $results['paths']['/path1']['post']['parameters'][0]);
  161. $this->assertEquals([
  162. 'in' => 'header',
  163. 'name' => 'Extra-Header',
  164. 'description' => '',
  165. 'example' => 'Some-example',
  166. 'schema' => ['type' => 'string'],
  167. ], $results['paths']['/path1']['post']['parameters'][1]);
  168. }
  169. /** @test */
  170. public function adds_query_parameters_correctly_as_parameters_on_operation_object()
  171. {
  172. $endpointData1 = $this->createMockEndpointData([
  173. 'httpMethods' => ['GET'],
  174. 'uri' => '/path1',
  175. 'headers' => [], // Emptying headers so it doesn't interfere with parameters object
  176. 'queryParameters' => [
  177. 'param' => [
  178. 'description' => 'A query param',
  179. 'required' => false,
  180. 'example' => 'hahoho',
  181. 'type' => 'string',
  182. 'name' => 'param',
  183. ],
  184. ],
  185. ]);
  186. $endpointData2 = $this->createMockEndpointData(['headers' => [], 'httpMethods' => ['POST'], 'uri' => '/path1',]);
  187. $groups = [$this->createGroup([$endpointData1, $endpointData2])];
  188. $results = $this->generate($groups);
  189. $this->assertEquals([], $results['paths']['/path1']['post']['parameters']);
  190. $this->assertArrayHasKey('parameters', $results['paths']['/path1']['get']);
  191. $this->assertCount(1, $results['paths']['/path1']['get']['parameters']);
  192. $this->assertEquals([
  193. 'in' => 'query',
  194. 'required' => false,
  195. 'name' => 'param',
  196. 'description' => 'A query param',
  197. 'example' => 'hahoho',
  198. 'schema' => [
  199. 'type' => 'string',
  200. 'description' => 'A query param',
  201. 'example' => 'hahoho',
  202. ],
  203. ], $results['paths']['/path1']['get']['parameters'][0]);
  204. }
  205. /** @test */
  206. public function adds_body_parameters_correctly_as_requestBody_on_operation_object()
  207. {
  208. $endpointData1 = $this->createMockEndpointData([
  209. 'httpMethods' => ['POST'],
  210. 'uri' => '/path1',
  211. 'bodyParameters' => [
  212. 'stringParam' => [
  213. 'name' => 'stringParam',
  214. 'description' => 'String param',
  215. 'required' => false,
  216. 'example' => 'hahoho',
  217. 'type' => 'string',
  218. ],
  219. 'integerParam' => [
  220. 'name' => 'integerParam',
  221. 'description' => 'Integer param',
  222. 'required' => true,
  223. 'example' => 99,
  224. 'type' => 'integer',
  225. ],
  226. 'booleanParam' => [
  227. 'name' => 'booleanParam',
  228. 'description' => 'Boolean param',
  229. 'required' => true,
  230. 'example' => false,
  231. 'type' => 'boolean',
  232. ],
  233. 'objectParam' => [
  234. 'name' => 'objectParam',
  235. 'description' => 'Object param',
  236. 'required' => false,
  237. 'example' => [],
  238. 'type' => 'object',
  239. ],
  240. 'objectParam.field' => [
  241. 'name' => 'objectParam.field',
  242. 'description' => 'Object param field',
  243. 'required' => false,
  244. 'example' => 119.0,
  245. 'type' => 'number',
  246. ],
  247. ],
  248. ]);
  249. $endpointData2 = $this->createMockEndpointData(['httpMethods' => ['GET'], 'uri' => '/path1']);
  250. $endpointData3 = $this->createMockEndpointData([
  251. 'httpMethods' => ['PUT'],
  252. 'uri' => '/path2',
  253. 'bodyParameters' => [
  254. 'fileParam' => [
  255. 'name' => 'fileParam',
  256. 'description' => 'File param',
  257. 'required' => false,
  258. 'example' => null,
  259. 'type' => 'file',
  260. ],
  261. 'numberArrayParam' => [
  262. 'name' => 'numberArrayParam',
  263. 'description' => 'Number array param',
  264. 'required' => false,
  265. 'example' => [186.9],
  266. 'type' => 'number[]',
  267. ],
  268. 'objectArrayParam' => [
  269. 'name' => 'objectArrayParam',
  270. 'description' => 'Object array param',
  271. 'required' => false,
  272. 'example' => [[]],
  273. 'type' => 'object[]',
  274. ],
  275. 'objectArrayParam[].field1' => [
  276. 'name' => 'objectArrayParam[].field1',
  277. 'description' => 'Object array param first field',
  278. 'required' => true,
  279. 'example' => ["hello"],
  280. 'type' => 'string[]',
  281. ],
  282. 'objectArrayParam[].field2' => [
  283. 'name' => 'objectArrayParam[].field2',
  284. 'description' => '',
  285. 'required' => false,
  286. 'example' => "hi",
  287. 'type' => 'string',
  288. ],
  289. ],
  290. ]);
  291. $groups = [$this->createGroup([$endpointData1, $endpointData2, $endpointData3])];
  292. $results = $this->generate($groups);
  293. $this->assertArrayNotHasKey('requestBody', $results['paths']['/path1']['get']);
  294. $this->assertArrayHasKey('requestBody', $results['paths']['/path1']['post']);
  295. $this->assertEquals([
  296. 'required' => true,
  297. 'content' => [
  298. 'application/json' => [
  299. 'schema' => [
  300. 'type' => 'object',
  301. 'properties' => [
  302. 'stringParam' => [
  303. 'description' => 'String param',
  304. 'example' => 'hahoho',
  305. 'type' => 'string',
  306. ],
  307. 'booleanParam' => [
  308. 'description' => 'Boolean param',
  309. 'example' => false,
  310. 'type' => 'boolean',
  311. ],
  312. 'integerParam' => [
  313. 'description' => 'Integer param',
  314. 'example' => 99,
  315. 'type' => 'integer',
  316. ],
  317. 'objectParam' => [
  318. 'description' => 'Object param',
  319. 'example' => [],
  320. 'type' => 'object',
  321. 'properties' => [
  322. 'field' => [
  323. 'description' => 'Object param field',
  324. 'example' => 119.0,
  325. 'type' => 'number',
  326. ],
  327. ],
  328. ],
  329. ],
  330. 'required' => [
  331. 'integerParam',
  332. 'booleanParam',
  333. ],
  334. ],
  335. ],
  336. ],
  337. ], $results['paths']['/path1']['post']['requestBody']);
  338. $this->assertEquals([
  339. 'required' => false,
  340. 'content' => [
  341. 'multipart/form-data' => [
  342. 'schema' => [
  343. 'type' => 'object',
  344. 'properties' => [
  345. 'fileParam' => [
  346. 'description' => 'File param',
  347. 'type' => 'string',
  348. 'format' => 'binary',
  349. ],
  350. 'numberArrayParam' => [
  351. 'description' => 'Number array param',
  352. 'example' => [186.9],
  353. 'type' => 'array',
  354. 'items' => [
  355. 'type' => 'number',
  356. ],
  357. ],
  358. 'objectArrayParam' => [
  359. 'description' => 'Object array param',
  360. 'example' => [[]],
  361. 'type' => 'array',
  362. 'items' => [
  363. 'type' => 'object',
  364. 'required' => ['field1'],
  365. 'properties' => [
  366. 'field1' => [
  367. 'type' => 'array',
  368. 'items' => [
  369. 'type' => 'string',
  370. ],
  371. 'description' => 'Object array param first field',
  372. 'example' => ["hello"],
  373. ],
  374. 'field2' => [
  375. 'type' => 'string',
  376. 'description' => '',
  377. 'example' => "hi",
  378. ],
  379. ],
  380. ],
  381. ],
  382. ],
  383. ],
  384. ],
  385. ],
  386. ], $results['paths']['/path2']['put']['requestBody']);
  387. }
  388. /** @test */
  389. public function adds_responses_correctly_as_responses_on_operation_object()
  390. {
  391. $endpointData1 = $this->createMockEndpointData([
  392. 'httpMethods' => ['POST'],
  393. 'uri' => '/path1',
  394. 'responses' => [
  395. [
  396. 'status' => 204,
  397. 'description' => 'Successfully updated.',
  398. 'content' => '{"this": "should be ignored"}',
  399. ],
  400. [
  401. 'status' => 201,
  402. 'description' => '',
  403. 'content' => '{"this": "shouldn\'t be ignored", "and this": "too"}',
  404. ],
  405. ],
  406. 'responseFields' => [
  407. 'and this' => [
  408. 'name' => 'and this',
  409. 'type' => 'string',
  410. 'description' => 'Parameter description, ha!',
  411. ],
  412. ],
  413. ]);
  414. $endpointData2 = $this->createMockEndpointData([
  415. 'httpMethods' => ['PUT'],
  416. 'uri' => '/path2',
  417. 'responses' => [
  418. [
  419. 'status' => 200,
  420. 'description' => '',
  421. 'content' => '<<binary>> The cropped image',
  422. ],
  423. ],
  424. ]);
  425. $groups = [$this->createGroup([$endpointData1, $endpointData2])];
  426. $results = $this->generate($groups);
  427. $this->assertCount(2, $results['paths']['/path1']['post']['responses']);
  428. $this->assertArraySubset([
  429. '204' => [
  430. 'description' => 'Successfully updated.',
  431. ],
  432. '201' => [
  433. 'content' => [
  434. 'application/json' => [
  435. 'schema' => [
  436. 'type' => 'object',
  437. 'properties' => [
  438. 'this' => [
  439. 'example' => "shouldn't be ignored",
  440. 'type' => 'string',
  441. ],
  442. 'and this' => [
  443. 'description' => 'Parameter description, ha!',
  444. 'example' => "too",
  445. 'type' => 'string',
  446. ],
  447. ],
  448. ],
  449. ],
  450. ],
  451. ],
  452. ], $results['paths']['/path1']['post']['responses']);
  453. $this->assertCount(1, $results['paths']['/path2']['put']['responses']);
  454. $this->assertEquals([
  455. '200' => [
  456. 'description' => 'The cropped image',
  457. 'content' => [
  458. 'application/octet-stream' => [
  459. 'schema' => [
  460. 'type' => 'string',
  461. 'format' => 'binary',
  462. ],
  463. ],
  464. ],
  465. ],
  466. ], $results['paths']['/path2']['put']['responses']);
  467. }
  468. protected function createMockEndpointData(array $custom = []): OutputEndpointData
  469. {
  470. $faker = Factory::create();
  471. $path = '/' . $faker->word();
  472. $data = [
  473. 'uri' => $path,
  474. 'httpMethods' => $faker->randomElements(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], 1),
  475. 'headers' => [
  476. 'Content-Type' => 'application/json',
  477. ],
  478. 'metadata' => [
  479. 'title' => $faker->sentence(),
  480. 'description' => $faker->randomElement([$faker->sentence(), '']),
  481. 'authenticated' => $faker->boolean(),
  482. ],
  483. 'urlParameters' => [], // Should be set by caller (along with custom path)
  484. 'queryParameters' => [],
  485. 'bodyParameters' => [],
  486. 'responses' => [
  487. [
  488. 'status' => 200,
  489. 'content' => '{"random": "json"}',
  490. 'description' => 'Okayy',
  491. ],
  492. ],
  493. 'responseFields' => [],
  494. ];
  495. foreach ($custom as $key => $value) {
  496. data_set($data, $key, $value);
  497. }
  498. return OutputEndpointData::create($data);
  499. }
  500. protected function createGroup(array $endpoints)
  501. {
  502. $faker = Factory::create();
  503. return [
  504. 'description' => '',
  505. 'name' => $faker->randomElement(['Endpoints', 'Group A', 'Group B']),
  506. 'endpoints' => $endpoints,
  507. ];
  508. }
  509. protected function generate(array $groups): array
  510. {
  511. $writer = new OpenAPISpecWriter(new DocumentationConfig($this->config));
  512. return $writer->generateSpecContent($groups);
  513. }
  514. }