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.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;
45 public class ApiDocGeneratorTest {
47 public static final String HTTP_HOST = "http://host";
48 private ApiDocGenerator generator;
49 private DocGenTestHelper helper;
50 private SchemaContext schemaContext;
53 public void setUp() throws Exception {
54 generator = new ApiDocGenerator();
55 helper = new DocGenTestHelper();
57 schemaContext = new YangParserImpl().resolveSchemaContext(new HashSet<Module>(helper.getModules().values()));
61 public void after() throws Exception {
65 * Method: getApiDeclaration(String module, String revision, UriInfo uriInfo)
68 public void testGetModuleDoc() throws Exception {
69 Preconditions.checkArgument(helper.getModules() != null, "No modules found");
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", "",
76 validateTosterDocContainsModulePrefixes(doc);
77 validateSwaggerModules(doc);
78 validateSwaggerApisForPost(doc);
84 * Validate whether ApiDelcaration contains Apis with concrete path and whether this Apis contain specified POST
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"));
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"));
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());
107 * Tries to find operation with name {@code operationName} and with summary {@code summary}
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);
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);
128 return filteredOperations;
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;
139 if (!parameterFound) {
147 * Tries to find {@code Api} with path {@code path}
149 private Api findApi(final String path, final ApiDeclaration doc) {
150 for (Api api : doc.getApis()) {
151 if (api.getPath().equals(path)) {
159 * Validates whether doc {@code doc} contains concrete specified models.
161 private void validateSwaggerModules(ApiDeclaration doc) {
162 JSONObject models = doc.getModels();
163 assertNotNull(models);
165 JSONObject configLst = models.getJSONObject("(config)lst");
166 assertNotNull(configLst);
168 containsReferences(configLst, "lst1");
169 containsReferences(configLst, "cont1");
171 JSONObject configLst1 = models.getJSONObject("(config)lst1");
172 assertNotNull(configLst1);
174 JSONObject configCont1 = models.getJSONObject("(config)cont1");
175 assertNotNull(configCont1);
177 containsReferences(configCont1, "cont11");
178 containsReferences(configCont1, "lst11");
180 JSONObject configCont11 = models.getJSONObject("(config)cont11");
181 assertNotNull(configCont11);
183 JSONObject configLst11 = models.getJSONObject("(config)lst11");
184 assertNotNull(configLst11);
185 } catch (JSONException e) {
186 fail("JSONException wasn't expected");
192 * Checks whether object {@code mainObject} contains in properties/items key $ref with concrete value.
194 private void containsReferences(final JSONObject mainObject, final String childObject) throws JSONException {
195 JSONObject properties = mainObject.getJSONObject("properties");
196 assertNotNull(properties);
198 JSONObject nodeInProperties = properties.getJSONObject(childObject);
199 assertNotNull(nodeInProperties);
201 JSONObject itemsInNodeInProperties = nodeInProperties.getJSONObject("items");
202 assertNotNull(itemsInNodeInProperties);
204 String itemRef = itemsInNodeInProperties.getString("$ref");
205 assertEquals("(config)" + childObject, itemRef);
209 public void testEdgeCases() throws Exception {
210 Preconditions.checkArgument(helper.getModules() != null, "No modules found");
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", "",
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}"));
226 * Tests whether from yang files are generated all required paths for HTTP operations (GET, DELETE, PUT, POST)
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")
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/" }));
240 Set<String> actualUrls = new TreeSet<>();
242 Api configApi = null;
243 for (Api api : doc.getApis()) {
244 actualUrls.add(api.getPath());
245 if (api.getPath().contains("/config/toaster2:toaster/")) {
250 boolean containsAll = actualUrls.containsAll(expectedUrls);
252 expectedUrls.removeAll(actualUrls);
253 fail("Missing expected urls: " + expectedUrls);
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());
262 containsAll = actualConfigMethods.containsAll(expectedConfigMethods);
264 expectedConfigMethods.removeAll(actualConfigMethods);
265 fail("Missing expected method on config API: " + expectedConfigMethods);
268 // TODO: we should really do some more validation of the
271 * Missing validation: Explicit validation of URLs, and their methods Input / output models.
276 public void testGetResourceListing() throws Exception {
277 UriInfo info = helper.createMockUriInfo(HTTP_HOST);
278 SchemaService mockSchemaService = helper.createMockSchemaService(schemaContext);
280 generator.setSchemaService(mockSchemaService);
282 ResourceList resourceListing = generator.getResourceListing(info);
284 Resource toaster = null;
285 Resource toaster2 = null;
286 for (Resource r : resourceListing.getApis()) {
287 String path = r.getPath();
288 if (path.contains("toaster2")) {
290 } else if (path.contains("toaster")) {
295 assertNotNull(toaster2);
296 assertNotNull(toaster);
298 assertEquals(HTTP_HOST + "/toaster(2009-11-20)", toaster.getPath());
299 assertEquals(HTTP_HOST + "/toaster2(2009-11-20)", toaster2.getPath());
302 private void validateTosterDocContainsModulePrefixes(ApiDeclaration doc) {
303 JSONObject topLevelJson = doc.getModels();
305 JSONObject configToaster = topLevelJson.getJSONObject("(config)toaster");
306 assertNotNull("(config)toaster JSON object missing", configToaster);
307 // without module prefix
308 containsProperties(configToaster, "toasterSlot");
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");
315 } catch (JSONException e) {
316 fail("Json exception while reading JSON object. Original message " + e.getMessage());
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);