OpenAPISpecWriterTest.php 23 KB

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