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