2 * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.sal.rest.doc.impl;
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;
16 import com.google.common.base.Preconditions;
18 import java.util.Arrays;
19 import java.util.HashSet;
20 import java.util.List;
21 import java.util.Map.Entry;
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;
44 public class ApiDocGeneratorTest {
46 public static final String HTTP_HOST = "http://host";
47 private ApiDocGenerator generator;
48 private DocGenTestHelper helper;
49 private SchemaContext schemaContext;
52 public void setUp() throws Exception {
53 generator = new ApiDocGenerator();
54 helper = new DocGenTestHelper();
56 schemaContext = new YangParserImpl().resolveSchemaContext(new HashSet<Module>(helper.getModules().values()));
60 public void after() throws Exception {
64 * Method: getApiDeclaration(String module, String revision, UriInfo uriInfo)
67 public void testGetModuleDoc() throws Exception {
68 Preconditions.checkArgument(helper.getModules() != null, "No modules found");
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", "",
75 validateTosterDocContainsModulePrefixes(doc);
76 validateSwaggerModules(doc);
77 validateSwaggerApisForPost(doc);
83 * Validate whether ApiDelcaration contains Apis with concrete path and whether this Apis contain specified POST
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"));
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"));
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());
106 * Tries to find operation with name {@code operationName} and with summary {@code summary}
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);
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);
127 return filteredOperations;
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;
138 if (!parameterFound) {
146 * Tries to find {@code Api} with path {@code path}
148 private Api findApi(final String path, final ApiDeclaration doc) {
149 for (Api api : doc.getApis()) {
150 if (api.getPath().equals(path)) {
158 * Validates whether doc {@code doc} contains concrete specified models.
160 private void validateSwaggerModules(ApiDeclaration doc) {
161 JSONObject models = doc.getModels();
162 assertNotNull(models);
164 JSONObject configLst = models.getJSONObject("(config)lst");
165 assertNotNull(configLst);
167 containsReferences(configLst, "lst1");
168 containsReferences(configLst, "cont1");
170 JSONObject configLst1 = models.getJSONObject("(config)lst1");
171 assertNotNull(configLst1);
173 JSONObject configCont1 = models.getJSONObject("(config)cont1");
174 assertNotNull(configCont1);
176 containsReferences(configCont1, "cont11");
177 containsReferences(configCont1, "lst11");
179 JSONObject configCont11 = models.getJSONObject("(config)cont11");
180 assertNotNull(configCont11);
182 JSONObject configLst11 = models.getJSONObject("(config)lst11");
183 assertNotNull(configLst11);
184 } catch (JSONException e) {
185 fail("JSONException wasn't expected");
191 * Checks whether object {@code mainObject} contains in properties/items key $ref with concrete value.
193 private void containsReferences(final JSONObject mainObject, final String childObject) throws JSONException {
194 JSONObject properties = mainObject.getJSONObject("properties");
195 assertNotNull(properties);
197 JSONObject nodeInProperties = properties.getJSONObject(childObject);
198 assertNotNull(nodeInProperties);
200 JSONObject itemsInNodeInProperties = nodeInProperties.getJSONObject("items");
201 assertNotNull(itemsInNodeInProperties);
203 String itemRef = itemsInNodeInProperties.getString("$ref");
204 assertEquals("(config)" + childObject, itemRef);
208 public void testEdgeCases() throws Exception {
209 Preconditions.checkArgument(helper.getModules() != null, "No modules found");
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", "",
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}"));
225 * Tests whether from yang files are generated all required paths for HTTP operations (GET, DELETE, PUT, POST)
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")
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/" }));
239 Set<String> actualUrls = new TreeSet<>();
241 Api configApi = null;
242 for (Api api : doc.getApis()) {
243 actualUrls.add(api.getPath());
244 if (api.getPath().contains("/config/toaster2:toaster/")) {
249 boolean containsAll = actualUrls.containsAll(expectedUrls);
251 expectedUrls.removeAll(actualUrls);
252 fail("Missing expected urls: " + expectedUrls);
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());
261 containsAll = actualConfigMethods.containsAll(expectedConfigMethods);
263 expectedConfigMethods.removeAll(actualConfigMethods);
264 fail("Missing expected method on config API: " + expectedConfigMethods);
267 // TODO: we should really do some more validation of the
270 * Missing validation: Explicit validation of URLs, and their methods Input / output models.
275 public void testGetResourceListing() throws Exception {
276 UriInfo info = helper.createMockUriInfo(HTTP_HOST);
277 SchemaService mockSchemaService = helper.createMockSchemaService(schemaContext);
279 generator.setSchemaService(mockSchemaService);
281 ResourceList resourceListing = generator.getResourceListing(info);
283 Resource toaster = null;
284 Resource toaster2 = null;
285 for (Resource r : resourceListing.getApis()) {
286 String path = r.getPath();
287 if (path.contains("toaster2")) {
289 } else if (path.contains("toaster")) {
294 assertNotNull(toaster2);
295 assertNotNull(toaster);
297 assertEquals(HTTP_HOST + "/toaster(2009-11-20)", toaster.getPath());
298 assertEquals(HTTP_HOST + "/toaster2(2009-11-20)", toaster2.getPath());
301 private void validateTosterDocContainsModulePrefixes(ApiDeclaration doc) {
302 JSONObject topLevelJson = doc.getModels();
304 JSONObject configToaster = topLevelJson.getJSONObject("(config)toaster");
305 assertNotNull("(config)toaster JSON object missing", configToaster);
306 // without module prefix
307 containsProperties(configToaster, "toasterSlot");
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");
314 } catch (JSONException e) {
315 fail("Json exception while reading JSON object. Original message " + e.getMessage());
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);