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