Use ControllerContext non-statically
[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.fasterxml.jackson.databind.JsonNode;
17 import com.fasterxml.jackson.databind.node.ObjectNode;
18 import com.google.common.base.Preconditions;
19 import java.sql.Date;
20 import java.util.Arrays;
21 import java.util.HashSet;
22 import java.util.List;
23 import java.util.Set;
24 import java.util.TreeSet;
25 import javax.ws.rs.core.UriInfo;
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 ObjectNode models = doc.getModels();
168         assertNotNull(models);
169
170         final JsonNode configLstTop = models.get("toaster2(config)lst-TOP");
171         assertNotNull(configLstTop);
172
173         containsReferences(configLstTop, "toaster2:lst", "toaster2(config)");
174
175         final JsonNode configLst = models.get("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 JsonNode configLst1Top = models.get("toaster2/lst(config)lst1-TOP");
182         assertNotNull(configLst1Top);
183
184         containsReferences(configLst1Top, "toaster2:lst1", "toaster2/lst(config)");
185
186         final JsonNode configLst1 = models.get("toaster2/lst(config)lst1");
187         assertNotNull(configLst1);
188
189         final JsonNode configCont1Top = models.get("toaster2/lst(config)cont1-TOP");
190         assertNotNull(configCont1Top);
191
192         containsReferences(configCont1Top, "toaster2:cont1", "toaster2/lst(config)");
193         final JsonNode configCont1 = models.get("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 JsonNode configCont11Top = models.get("toaster2/lst/cont1(config)cont11-TOP");
200         assertNotNull(configCont11Top);
201
202         containsReferences(configCont11Top, "toaster2:cont11", "toaster2/lst/cont1(config)");
203         final JsonNode configCont11 = models.get("toaster2/lst/cont1(config)cont11");
204         assertNotNull(configCont11);
205
206         final JsonNode configlst11Top = models.get("toaster2/lst/cont1(config)lst11-TOP");
207         assertNotNull(configlst11Top);
208
209         containsReferences(configlst11Top, "toaster2:lst11", "toaster2/lst/cont1(config)");
210         final JsonNode configLst11 = models.get("toaster2/lst/cont1(config)lst11");
211         assertNotNull(configLst11);
212     }
213
214     /**
215      * Checks whether object {@code mainObject} contains in properties/items key $ref with concrete value.
216      */
217     private void containsReferences(final JsonNode mainObject, final String childObject, final String prefix) {
218         final JsonNode properties = mainObject.get("properties");
219         assertNotNull(properties);
220
221         final JsonNode nodeInProperties = properties.get(childObject);
222         assertNotNull(nodeInProperties);
223
224         final JsonNode itemsInNodeInProperties = nodeInProperties.get("items");
225         assertNotNull(itemsInNodeInProperties);
226
227         final String itemRef = itemsInNodeInProperties.get("$ref").asText();
228         assertEquals(prefix + childObject.split(":")[1], itemRef);
229     }
230
231     @Test
232     public void testEdgeCases() throws Exception {
233         Preconditions.checkArgument(this.helper.getModules() != null, "No modules found");
234
235         for (final Module m : this.helper.getModules()) {
236             if (m.getQNameModule().getNamespace().toString().equals(NAMESPACE_2)
237                     && m.getQNameModule().getRevision().equals(REVISION_2)) {
238                 final ApiDeclaration doc = this.generator.getSwaggerDocSpec(m, "http://localhost:8080/restconf", "",
239                         this.schemaContext);
240                 assertNotNull(doc);
241
242                 // testing bugs.opendaylight.org bug 1290. UnionType model type.
243                 final String jsonString = doc.getModels().toString();
244                 assertTrue(jsonString.contains("testUnion\":{\"required\":false,\"type\":\"-2147483648\","
245                         + "\"enum\":[\"-2147483648\",\"Some testUnion\"]}"));
246             }
247         }
248     }
249
250     @Test
251     public void testRPCsModel() throws Exception {
252         Preconditions.checkArgument(this.helper.getModules() != null, "No modules found");
253
254         for (final Module m : this.helper.getModules()) {
255             if (m.getQNameModule().getNamespace().toString().equals(NAMESPACE_2)
256                     && m.getQNameModule().getRevision().equals(REVISION_2)) {
257                 final ApiDeclaration doc = this.generator.getSwaggerDocSpec(m, "http://localhost:8080/restconf", "",
258                         this.schemaContext);
259                 assertNotNull(doc);
260
261                 final ObjectNode models = doc.getModels();
262                 final JsonNode inputTop = models.get("(make-toast)input-TOP");
263                 final String testString =
264                         "{\"toaster:input\":{\"type\":\"object\",\"items\":{\"$ref\":\"(make-toast)input\"}}}";
265                 assertEquals(testString, inputTop.get("properties").toString());
266                 final JsonNode input = models.get("(make-toast)input");
267                 final JsonNode properties = input.get("properties");
268                 assertTrue(properties.has("toaster:toasterDoneness"));
269                 assertTrue(properties.has("toaster:toasterToastType"));
270             }
271         }
272     }
273
274     /**
275      * Tests whether from yang files are generated all required paths for HTTP operations (GET, DELETE, PUT, POST)
276      *
277      * <p>
278      * If container | list is augmented then in path there should be specified module name followed with collon (e. g.
279      * "/config/module1:element1/element2/module2:element3")
280      *
281      * @param doc Api declaration
282      * @throws Exception if operation fails
283      */
284     private void validateToaster(final ApiDeclaration doc) throws Exception {
285         final Set<String> expectedUrls = new TreeSet<>(Arrays.asList(new String[]{"/config/toaster2:toaster",
286             "/operational/toaster2:toaster", "/operations/toaster2:cancel-toast",
287             "/operations/toaster2:make-toast", "/operations/toaster2:restock-toaster",
288             "/config/toaster2:toaster/toasterSlot/{slotId}/toaster-augmented:slotInfo"}));
289
290         final Set<String> actualUrls = new TreeSet<>();
291
292         Api configApi = null;
293         for (final Api api : doc.getApis()) {
294             actualUrls.add(api.getPath());
295             if (api.getPath().contains("/config/toaster2:toaster/")) {
296                 configApi = api;
297             }
298         }
299
300         boolean containsAll = actualUrls.containsAll(expectedUrls);
301         if (!containsAll) {
302             expectedUrls.removeAll(actualUrls);
303             fail("Missing expected urls: " + expectedUrls);
304         }
305
306         final Set<String> expectedConfigMethods = new TreeSet<>(Arrays.asList(new String[] { "GET", "PUT", "DELETE" }));
307         final Set<String> actualConfigMethods = new TreeSet<>();
308         for (final Operation oper : configApi.getOperations()) {
309             actualConfigMethods.add(oper.getMethod());
310         }
311
312         containsAll = actualConfigMethods.containsAll(expectedConfigMethods);
313         if (!containsAll) {
314             expectedConfigMethods.removeAll(actualConfigMethods);
315             fail("Missing expected method on config API: " + expectedConfigMethods);
316         }
317
318         // TODO: we should really do some more validation of the
319         // documentation...
320         /*
321          * Missing validation: Explicit validation of URLs, and their methods Input / output models.
322          */
323     }
324
325     @Test
326     public void testGetResourceListing() throws Exception {
327         final UriInfo info = this.helper.createMockUriInfo(HTTP_HOST);
328         final SchemaService mockSchemaService = this.helper.createMockSchemaService(this.schemaContext);
329
330         this.generator.setSchemaService(mockSchemaService);
331
332         final ResourceList resourceListing = this.generator.getResourceListing(info);
333
334         Resource toaster = null;
335         Resource toaster2 = null;
336         for (final Resource r : resourceListing.getApis()) {
337             final String path = r.getPath();
338             if (path.contains("toaster2")) {
339                 toaster2 = r;
340             } else if (path.contains("toaster")) {
341                 toaster = r;
342             }
343         }
344
345         assertNotNull(toaster2);
346         assertNotNull(toaster);
347
348         assertEquals(HTTP_HOST + "/toaster(2009-11-20)", toaster.getPath());
349         assertEquals(HTTP_HOST + "/toaster2(2009-11-20)", toaster2.getPath());
350     }
351
352     private void validateTosterDocContainsModulePrefixes(final ApiDeclaration doc) {
353         final ObjectNode topLevelJson = doc.getModels();
354
355         final JsonNode configToaster = topLevelJson.get("toaster2(config)toaster");
356         assertNotNull("(config)toaster JSON object missing", configToaster);
357         // without module prefix
358         containsProperties(configToaster, "toaster2:toasterSlot");
359
360         final JsonNode toasterSlot = topLevelJson.get("toaster2/toaster(config)toasterSlot");
361         assertNotNull("(config)toasterSlot JSON object missing", toasterSlot);
362         // with module prefix
363         containsProperties(toasterSlot, "toaster2:toaster-augmented:slotInfo");
364     }
365
366     private void containsProperties(final JsonNode jsonObject, final String... properties) {
367         for (final String property : properties) {
368             final JsonNode propertiesObject = jsonObject.get("properties");
369             assertNotNull("Properties object missing in ", propertiesObject);
370             final JsonNode concretePropertyObject = propertiesObject.get(property);
371             assertNotNull(property + " is missing", concretePropertyObject);
372         }
373     }
374 }