Bug 6382 - add apidoc for latest restconf draft
[netconf.git] / restconf / sal-rest-docgen / src / test / java / org / opendaylight / controller / sal / rest / doc / impl / ApiDocGeneratorTest.java
1 /*
2  * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.controller.sal.rest.doc.impl;
10
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertNotNull;
13 import static org.junit.Assert.assertTrue;
14 import static org.junit.Assert.fail;
15
16 import com.google.common.base.Preconditions;
17 import java.sql.Date;
18 import java.util.Arrays;
19 import java.util.HashSet;
20 import java.util.List;
21 import java.util.Set;
22 import java.util.TreeSet;
23 import javax.ws.rs.core.UriInfo;
24 import org.json.JSONException;
25 import org.json.JSONObject;
26 import org.junit.After;
27 import org.junit.Before;
28 import org.junit.Test;
29 import org.opendaylight.controller.sal.core.api.model.SchemaService;
30 import org.opendaylight.netconf.sal.rest.doc.impl.ApiDocGenerator;
31 import org.opendaylight.netconf.sal.rest.doc.swagger.Api;
32 import org.opendaylight.netconf.sal.rest.doc.swagger.ApiDeclaration;
33 import org.opendaylight.netconf.sal.rest.doc.swagger.Operation;
34 import org.opendaylight.netconf.sal.rest.doc.swagger.Parameter;
35 import org.opendaylight.netconf.sal.rest.doc.swagger.Resource;
36 import org.opendaylight.netconf.sal.rest.doc.swagger.ResourceList;
37 import org.opendaylight.yangtools.yang.model.api.Module;
38 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
39
40 public class ApiDocGeneratorTest {
41
42     public static final String HTTP_HOST = "http://host";
43     private static final String NAMESPACE = "http://netconfcentral.org/ns/toaster2";
44     private static final String STRING_DATE = "2009-11-20";
45     private static final Date DATE = Date.valueOf(STRING_DATE);
46     private static final String NAMESPACE_2 = "http://netconfcentral.org/ns/toaster";
47     private static final Date REVISION_2 = Date.valueOf(STRING_DATE);
48     private ApiDocGenerator generator;
49     private DocGenTestHelper helper;
50     private SchemaContext schemaContext;
51
52     @Before
53     public void setUp() throws Exception {
54         this.generator = new ApiDocGenerator();
55         generator.setDraft(false);
56         this.helper = new DocGenTestHelper();
57         this.helper.setUp();
58
59         this.schemaContext = this.helper.getSchemaContext();
60     }
61
62     @After
63     public void after() throws Exception {
64     }
65
66     /**
67      * Method: getApiDeclaration(String module, String revision, UriInfo uriInfo)
68      */
69     @Test
70     public void testGetModuleDoc() throws Exception {
71         Preconditions.checkArgument(this.helper.getModules() != null, "No modules found");
72
73         for (final Module m : this.helper.getSchemaContext().getModules()) {
74             if (m.getQNameModule().getNamespace().toString().equals(NAMESPACE)
75                     && m.getQNameModule().getRevision().equals(DATE)) {
76                 final ApiDeclaration doc = this.generator.getSwaggerDocSpec(m, "http://localhost:8080/restconf", "",
77                         this.schemaContext);
78                 validateToaster(doc);
79                 validateTosterDocContainsModulePrefixes(doc);
80                 validateSwaggerModules(doc);
81                 validateSwaggerApisForPost(doc);
82             }
83         }
84     }
85
86     /**
87      * Validate whether ApiDelcaration contains Apis with concrete path and whether this Apis contain specified POST
88      * operations.
89      */
90     private void validateSwaggerApisForPost(final ApiDeclaration doc) {
91         // two POST URI with concrete schema name in summary
92         final Api lstApi = findApi("/config/toaster2:lst", doc);
93         assertNotNull("Api /config/toaster2:lst wasn't found", lstApi);
94         assertTrue("POST for cont1 in lst is missing",
95                 findOperation(lstApi.getOperations(), "POST", "(config)lstPOST", "toaster2/lst(config)lst1-TOP",
96                         "toaster2/lst(config)cont1-TOP"));
97
98         final Api cont1Api = findApi("/config/toaster2:lst/cont1", doc);
99         assertNotNull("Api /config/toaster2:lst/cont1 wasn't found", cont1Api);
100         assertTrue("POST for cont11 in cont1 is missing",
101                 findOperation(cont1Api.getOperations(), "POST", "(config)cont1POST", "toaster2/lst/cont1(config)cont11-TOP",
102                         "toaster2/lst/cont1(config)lst11-TOP"));
103
104         // no POST URI
105         final Api cont11Api = findApi("/config/toaster2:lst/cont1/cont11", doc);
106         assertNotNull("Api /config/toaster2:lst/cont1/cont11 wasn't found", cont11Api);
107         assertTrue("POST operation shouldn't be present.", findOperations(cont11Api.getOperations(), "POST").isEmpty());
108
109     }
110
111     /**
112      * Tries to find operation with name {@code operationName} and with summary {@code summary}
113      */
114     private boolean findOperation(final List<Operation> operations, final String operationName, final String type,
115                                   final String... searchedParameters) {
116         final Set<Operation> filteredOperations = findOperations(operations, operationName);
117         for (final Operation operation : filteredOperations) {
118             if (operation.getType().equals(type)) {
119                 final List<Parameter> parameters = operation.getParameters();
120                 return containAllParameters(parameters, searchedParameters);
121             }
122         }
123         return false;
124     }
125
126     private Set<Operation> findOperations(final List<Operation> operations, final String operationName) {
127         final Set<Operation> filteredOperations = new HashSet<>();
128         for (final Operation operation : operations) {
129             if (operation.getMethod().equals(operationName)) {
130                 filteredOperations.add(operation);
131             }
132         }
133         return filteredOperations;
134     }
135
136     private boolean containAllParameters(final List<Parameter> searchedIns, final String[] searchedWhats) {
137         for (final String searchedWhat : searchedWhats) {
138             boolean parameterFound = false;
139             for (final Parameter searchedIn : searchedIns) {
140                 if (searchedIn.getType().equals(searchedWhat)) {
141                     parameterFound = true;
142                 }
143             }
144             if (!parameterFound) {
145                 return false;
146             }
147         }
148         return true;
149     }
150
151     /**
152      * Tries to find {@code Api} with path {@code path}
153      */
154     private Api findApi(final String path, final ApiDeclaration doc) {
155         for (final Api api : doc.getApis()) {
156             if (api.getPath().equals(path)) {
157                 return api;
158             }
159         }
160         return null;
161     }
162
163     /**
164      * Validates whether doc {@code doc} contains concrete specified models.
165      */
166     private void validateSwaggerModules(final ApiDeclaration doc) {
167         final JSONObject models = doc.getModels();
168         assertNotNull(models);
169         try {
170             final JSONObject configLstTop = models.getJSONObject("toaster2(config)lst-TOP");
171             assertNotNull(configLstTop);
172
173             containsReferences(configLstTop, "toaster2:lst", "toaster2(config)");
174
175             final JSONObject configLst = models.getJSONObject("toaster2(config)lst");
176             assertNotNull(configLst);
177
178             containsReferences(configLst, "toaster2:lst1", "toaster2/lst(config)");
179             containsReferences(configLst, "toaster2:cont1", "toaster2/lst(config)");
180
181             final JSONObject configLst1Top = models.getJSONObject("toaster2/lst(config)lst1-TOP");
182             assertNotNull(configLst1Top);
183
184             containsReferences(configLst1Top, "toaster2:lst1", "toaster2/lst(config)");
185
186             final JSONObject configLst1 = models.getJSONObject("toaster2/lst(config)lst1");
187             assertNotNull(configLst1);
188
189             final JSONObject configCont1Top = models.getJSONObject("toaster2/lst(config)cont1-TOP");
190             assertNotNull(configCont1Top);
191
192             containsReferences(configCont1Top, "toaster2:cont1", "toaster2/lst(config)");
193             final JSONObject configCont1 = models.getJSONObject("toaster2/lst(config)cont1");
194             assertNotNull(configCont1);
195
196             containsReferences(configCont1, "toaster2:cont11", "toaster2/lst/cont1(config)");
197             containsReferences(configCont1, "toaster2:lst11", "toaster2/lst/cont1(config)");
198
199             final JSONObject configCont11Top = models.getJSONObject("toaster2/lst/cont1(config)cont11-TOP");
200             assertNotNull(configCont11Top);
201
202             containsReferences(configCont11Top, "toaster2:cont11", "toaster2/lst/cont1(config)");
203             final JSONObject configCont11 = models.getJSONObject("toaster2/lst/cont1(config)cont11");
204             assertNotNull(configCont11);
205
206             final JSONObject configlst11Top = models.getJSONObject("toaster2/lst/cont1(config)lst11-TOP");
207             assertNotNull(configlst11Top);
208
209             containsReferences(configlst11Top, "toaster2:lst11", "toaster2/lst/cont1(config)");
210             final JSONObject configLst11 = models.getJSONObject("toaster2/lst/cont1(config)lst11");
211             assertNotNull(configLst11);
212         } catch (final JSONException e) {
213             fail("JSONException wasn't expected");
214         }
215
216     }
217
218     /**
219      * Checks whether object {@code mainObject} contains in properties/items key $ref with concrete value.
220      */
221     private void containsReferences(final JSONObject mainObject, final String childObject, final String prefix)
222             throws JSONException {
223         final JSONObject properties = mainObject.getJSONObject("properties");
224         assertNotNull(properties);
225
226         final JSONObject nodeInProperties = properties.getJSONObject(childObject);
227         assertNotNull(nodeInProperties);
228
229         final JSONObject itemsInNodeInProperties = nodeInProperties.getJSONObject("items");
230         assertNotNull(itemsInNodeInProperties);
231
232         final String itemRef = itemsInNodeInProperties.getString("$ref");
233         assertEquals(prefix + childObject.split(":")[1], itemRef);
234     }
235
236     @Test
237     public void testEdgeCases() throws Exception {
238         Preconditions.checkArgument(this.helper.getModules() != null, "No modules found");
239
240         for (final Module m : this.helper.getModules()) {
241             if (m.getQNameModule().getNamespace().toString().equals(NAMESPACE_2)
242                     && m.getQNameModule().getRevision().equals(REVISION_2)) {
243                 final ApiDeclaration doc = this.generator.getSwaggerDocSpec(m, "http://localhost:8080/restconf", "",
244                         this.schemaContext);
245                 assertNotNull(doc);
246
247                 // testing bugs.opendaylight.org bug 1290. UnionType model type.
248                 final String jsonString = doc.getModels().toString();
249                 assertTrue(jsonString.contains(
250                         "testUnion\":{\"type\":\"-2147483648\",\"required\":false,\"enum\":[\"-2147483648\",\"Some testUnion\"]}"));
251             }
252         }
253     }
254
255     @Test
256     public void testRPCsModel() throws Exception {
257         Preconditions.checkArgument(this.helper.getModules() != null, "No modules found");
258
259         for (final Module m : this.helper.getModules()) {
260             if (m.getQNameModule().getNamespace().toString().equals(NAMESPACE_2)
261                     && m.getQNameModule().getRevision().equals(REVISION_2)) {
262                 final ApiDeclaration doc = this.generator.getSwaggerDocSpec(m, "http://localhost:8080/restconf", "",
263                         this.schemaContext);
264                 assertNotNull(doc);
265
266                 final JSONObject models = doc.getModels();
267                 final JSONObject inputTop = models.getJSONObject("(make-toast)input-TOP");
268                 final String testString = "{\"toaster:input\":{\"type\":\"object\",\"items\":{\"$ref\":\"(make-toast)input\"}}}";
269                 assertEquals(testString, inputTop.getJSONObject("properties").toString());
270                 final JSONObject input = models.getJSONObject("(make-toast)input");
271                 final JSONObject properties = input.getJSONObject("properties");
272                 assertTrue(properties.has("toaster:toasterDoneness"));
273                 assertTrue(properties.has("toaster:toasterToastType"));
274             }
275         }
276     }
277
278     /**
279      * Tests whether from yang files are generated all required paths for HTTP operations (GET, DELETE, PUT, POST)
280      *
281      * If container | list is augmented then in path there should be specified module name followed with collon (e. g.
282      * "/config/module1:element1/element2/module2:element3")
283      *
284      * @param doc
285      * @throws Exception
286      */
287     private void validateToaster(final ApiDeclaration doc) throws Exception {
288         final Set<String> expectedUrls = new TreeSet<>(Arrays.asList(new String[]{"/config/toaster2:toaster",
289                 "/operational/toaster2:toaster", "/operations/toaster2:cancel-toast",
290                 "/operations/toaster2:make-toast", "/operations/toaster2:restock-toaster",
291                 "/config/toaster2:toaster/toasterSlot/{slotId}/toaster-augmented:slotInfo"}));
292
293         final Set<String> actualUrls = new TreeSet<>();
294
295         Api configApi = null;
296         for (final Api api : doc.getApis()) {
297             actualUrls.add(api.getPath());
298             if (api.getPath().contains("/config/toaster2:toaster/")) {
299                 configApi = api;
300             }
301         }
302
303         boolean containsAll = actualUrls.containsAll(expectedUrls);
304         if (!containsAll) {
305             expectedUrls.removeAll(actualUrls);
306             fail("Missing expected urls: " + expectedUrls);
307         }
308
309         final Set<String> expectedConfigMethods = new TreeSet<>(Arrays.asList(new String[] { "GET", "PUT", "DELETE" }));
310         final Set<String> actualConfigMethods = new TreeSet<>();
311         for (final Operation oper : configApi.getOperations()) {
312             actualConfigMethods.add(oper.getMethod());
313         }
314
315         containsAll = actualConfigMethods.containsAll(expectedConfigMethods);
316         if (!containsAll) {
317             expectedConfigMethods.removeAll(actualConfigMethods);
318             fail("Missing expected method on config API: " + expectedConfigMethods);
319         }
320
321         // TODO: we should really do some more validation of the
322         // documentation...
323         /**
324          * Missing validation: Explicit validation of URLs, and their methods Input / output models.
325          */
326     }
327
328     @Test
329     public void testGetResourceListing() throws Exception {
330         final UriInfo info = this.helper.createMockUriInfo(HTTP_HOST);
331         final SchemaService mockSchemaService = this.helper.createMockSchemaService(this.schemaContext);
332
333         this.generator.setSchemaService(mockSchemaService);
334
335         final ResourceList resourceListing = this.generator.getResourceListing(info);
336
337         Resource toaster = null;
338         Resource toaster2 = null;
339         for (final Resource r : resourceListing.getApis()) {
340             final String path = r.getPath();
341             if (path.contains("toaster2")) {
342                 toaster2 = r;
343             } else if (path.contains("toaster")) {
344                 toaster = r;
345             }
346         }
347
348         assertNotNull(toaster2);
349         assertNotNull(toaster);
350
351         assertEquals(HTTP_HOST + "/toaster(2009-11-20)", toaster.getPath());
352         assertEquals(HTTP_HOST + "/toaster2(2009-11-20)", toaster2.getPath());
353     }
354
355     private void validateTosterDocContainsModulePrefixes(final ApiDeclaration doc) {
356         final JSONObject topLevelJson = doc.getModels();
357         try {
358             final JSONObject configToaster = topLevelJson.getJSONObject("toaster2(config)toaster");
359             assertNotNull("(config)toaster JSON object missing", configToaster);
360             // without module prefix
361             containsProperties(configToaster, "toaster2:toasterSlot");
362
363             final JSONObject toasterSlot = topLevelJson.getJSONObject("toaster2/toaster(config)toasterSlot");
364             assertNotNull("(config)toasterSlot JSON object missing", toasterSlot);
365             // with module prefix
366             containsProperties(toasterSlot, "toaster2:toaster-augmented:slotInfo");
367
368         } catch (final JSONException e) {
369             fail("Json exception while reading JSON object. Original message " + e.getMessage());
370         }
371     }
372
373     private void containsProperties(final JSONObject jsonObject, final String... properties) throws JSONException {
374         for (final String property : properties) {
375             final JSONObject propertiesObject = jsonObject.getJSONObject("properties");
376             assertNotNull("Properties object missing in ", propertiesObject);
377             final JSONObject concretePropertyObject = propertiesObject.getJSONObject(property);
378             assertNotNull(property + " is missing", concretePropertyObject);
379         }
380     }
381 }