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