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