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;
22 import java.util.TreeSet;
23 import javax.ws.rs.core.UriInfo;
24 import org.json.JSONException;
25 import org.json.JSONObject;
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;
40 public class ApiDocGeneratorTest {
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;
53 public void setUp() throws Exception {
54 this.generator = new ApiDocGenerator();
55 generator.setDraft(false);
56 this.helper = new DocGenTestHelper();
59 this.schemaContext = this.helper.getSchemaContext();
63 public void after() throws Exception {
67 * Method: getApiDeclaration(String module, String revision, UriInfo uriInfo).
70 public void testGetModuleDoc() throws Exception {
71 Preconditions.checkArgument(this.helper.getModules() != null, "No modules found");
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", "",
79 validateTosterDocContainsModulePrefixes(doc);
80 validateSwaggerModules(doc);
81 validateSwaggerApisForPost(doc);
87 * Validate whether ApiDelcaration contains Apis with concrete path and whether this Apis contain specified POST
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"));
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"));
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());
112 * Tries to find operation with name {@code operationName} and with summary {@code summary}.
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);
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);
133 return filteredOperations;
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;
144 if (!parameterFound) {
152 * Tries to find {@code Api} with path {@code path}.
154 private Api findApi(final String path, final ApiDeclaration doc) {
155 for (final Api api : doc.getApis()) {
156 if (api.getPath().equals(path)) {
164 * Validates whether doc {@code doc} contains concrete specified models.
166 private void validateSwaggerModules(final ApiDeclaration doc) {
167 final JSONObject models = doc.getModels();
168 assertNotNull(models);
170 final JSONObject configLstTop = models.getJSONObject("toaster2(config)lst-TOP");
171 assertNotNull(configLstTop);
173 containsReferences(configLstTop, "toaster2:lst", "toaster2(config)");
175 final JSONObject configLst = models.getJSONObject("toaster2(config)lst");
176 assertNotNull(configLst);
178 containsReferences(configLst, "toaster2:lst1", "toaster2/lst(config)");
179 containsReferences(configLst, "toaster2:cont1", "toaster2/lst(config)");
181 final JSONObject configLst1Top = models.getJSONObject("toaster2/lst(config)lst1-TOP");
182 assertNotNull(configLst1Top);
184 containsReferences(configLst1Top, "toaster2:lst1", "toaster2/lst(config)");
186 final JSONObject configLst1 = models.getJSONObject("toaster2/lst(config)lst1");
187 assertNotNull(configLst1);
189 final JSONObject configCont1Top = models.getJSONObject("toaster2/lst(config)cont1-TOP");
190 assertNotNull(configCont1Top);
192 containsReferences(configCont1Top, "toaster2:cont1", "toaster2/lst(config)");
193 final JSONObject configCont1 = models.getJSONObject("toaster2/lst(config)cont1");
194 assertNotNull(configCont1);
196 containsReferences(configCont1, "toaster2:cont11", "toaster2/lst/cont1(config)");
197 containsReferences(configCont1, "toaster2:lst11", "toaster2/lst/cont1(config)");
199 final JSONObject configCont11Top = models.getJSONObject("toaster2/lst/cont1(config)cont11-TOP");
200 assertNotNull(configCont11Top);
202 containsReferences(configCont11Top, "toaster2:cont11", "toaster2/lst/cont1(config)");
203 final JSONObject configCont11 = models.getJSONObject("toaster2/lst/cont1(config)cont11");
204 assertNotNull(configCont11);
206 final JSONObject configlst11Top = models.getJSONObject("toaster2/lst/cont1(config)lst11-TOP");
207 assertNotNull(configlst11Top);
209 containsReferences(configlst11Top, "toaster2:lst11", "toaster2/lst/cont1(config)");
210 final JSONObject configLst11 = models.getJSONObject("toaster2/lst/cont1(config)lst11");
211 assertNotNull(configLst11);
212 } catch (final JSONException e) {
213 fail("JSONException wasn't expected");
219 * Checks whether object {@code mainObject} contains in properties/items key $ref with concrete value.
221 private void containsReferences(final JSONObject mainObject, final String childObject, final String prefix)
222 throws JSONException {
223 final JSONObject properties = mainObject.getJSONObject("properties");
224 assertNotNull(properties);
226 final JSONObject nodeInProperties = properties.getJSONObject(childObject);
227 assertNotNull(nodeInProperties);
229 final JSONObject itemsInNodeInProperties = nodeInProperties.getJSONObject("items");
230 assertNotNull(itemsInNodeInProperties);
232 final String itemRef = itemsInNodeInProperties.getString("$ref");
233 assertEquals(prefix + childObject.split(":")[1], itemRef);
237 public void testEdgeCases() throws Exception {
238 Preconditions.checkArgument(this.helper.getModules() != null, "No modules found");
240 for (final Module m : this.helper.getModules()) {
241 if (m.getQNameModule().getNamespace().toString().equals(NAMESPACE_2)
242 && m.getQNameModule().getRevision().equals(REVISION_2)) {
243 final ApiDeclaration doc = this.generator.getSwaggerDocSpec(m, "http://localhost:8080/restconf", "",
247 // testing bugs.opendaylight.org bug 1290. UnionType model type.
248 final String jsonString = doc.getModels().toString();
249 assertTrue(jsonString.contains("testUnion\":{\"type\":\"-2147483648\",\"required\":false,"
250 + "\"enum\":[\"-2147483648\",\"Some testUnion\"]}"));
256 public void testRPCsModel() throws Exception {
257 Preconditions.checkArgument(this.helper.getModules() != null, "No modules found");
259 for (final Module m : this.helper.getModules()) {
260 if (m.getQNameModule().getNamespace().toString().equals(NAMESPACE_2)
261 && m.getQNameModule().getRevision().equals(REVISION_2)) {
262 final ApiDeclaration doc = this.generator.getSwaggerDocSpec(m, "http://localhost:8080/restconf", "",
266 final JSONObject models = doc.getModels();
267 final JSONObject inputTop = models.getJSONObject("(make-toast)input-TOP");
268 final String testString =
269 "{\"toaster:input\":{\"type\":\"object\",\"items\":{\"$ref\":\"(make-toast)input\"}}}";
270 assertEquals(testString, inputTop.getJSONObject("properties").toString());
271 final JSONObject input = models.getJSONObject("(make-toast)input");
272 final JSONObject properties = input.getJSONObject("properties");
273 assertTrue(properties.has("toaster:toasterDoneness"));
274 assertTrue(properties.has("toaster:toasterToastType"));
280 * Tests whether from yang files are generated all required paths for HTTP operations (GET, DELETE, PUT, POST)
283 * If container | list is augmented then in path there should be specified module name followed with collon (e. g.
284 * "/config/module1:element1/element2/module2:element3")
286 * @param doc Api declaration
287 * @throws Exception if operation fails
289 private void validateToaster(final ApiDeclaration doc) throws Exception {
290 final Set<String> expectedUrls = new TreeSet<>(Arrays.asList(new String[]{"/config/toaster2:toaster",
291 "/operational/toaster2:toaster", "/operations/toaster2:cancel-toast",
292 "/operations/toaster2:make-toast", "/operations/toaster2:restock-toaster",
293 "/config/toaster2:toaster/toasterSlot/{slotId}/toaster-augmented:slotInfo"}));
295 final Set<String> actualUrls = new TreeSet<>();
297 Api configApi = null;
298 for (final Api api : doc.getApis()) {
299 actualUrls.add(api.getPath());
300 if (api.getPath().contains("/config/toaster2:toaster/")) {
305 boolean containsAll = actualUrls.containsAll(expectedUrls);
307 expectedUrls.removeAll(actualUrls);
308 fail("Missing expected urls: " + expectedUrls);
311 final Set<String> expectedConfigMethods = new TreeSet<>(Arrays.asList(new String[] { "GET", "PUT", "DELETE" }));
312 final Set<String> actualConfigMethods = new TreeSet<>();
313 for (final Operation oper : configApi.getOperations()) {
314 actualConfigMethods.add(oper.getMethod());
317 containsAll = actualConfigMethods.containsAll(expectedConfigMethods);
319 expectedConfigMethods.removeAll(actualConfigMethods);
320 fail("Missing expected method on config API: " + expectedConfigMethods);
323 // TODO: we should really do some more validation of the
326 * Missing validation: Explicit validation of URLs, and their methods Input / output models.
331 public void testGetResourceListing() throws Exception {
332 final UriInfo info = this.helper.createMockUriInfo(HTTP_HOST);
333 final SchemaService mockSchemaService = this.helper.createMockSchemaService(this.schemaContext);
335 this.generator.setSchemaService(mockSchemaService);
337 final ResourceList resourceListing = this.generator.getResourceListing(info);
339 Resource toaster = null;
340 Resource toaster2 = null;
341 for (final Resource r : resourceListing.getApis()) {
342 final String path = r.getPath();
343 if (path.contains("toaster2")) {
345 } else if (path.contains("toaster")) {
350 assertNotNull(toaster2);
351 assertNotNull(toaster);
353 assertEquals(HTTP_HOST + "/toaster(2009-11-20)", toaster.getPath());
354 assertEquals(HTTP_HOST + "/toaster2(2009-11-20)", toaster2.getPath());
357 private void validateTosterDocContainsModulePrefixes(final ApiDeclaration doc) {
358 final JSONObject topLevelJson = doc.getModels();
360 final JSONObject configToaster = topLevelJson.getJSONObject("toaster2(config)toaster");
361 assertNotNull("(config)toaster JSON object missing", configToaster);
362 // without module prefix
363 containsProperties(configToaster, "toaster2:toasterSlot");
365 final JSONObject toasterSlot = topLevelJson.getJSONObject("toaster2/toaster(config)toasterSlot");
366 assertNotNull("(config)toasterSlot JSON object missing", toasterSlot);
367 // with module prefix
368 containsProperties(toasterSlot, "toaster2:toaster-augmented:slotInfo");
370 } catch (final JSONException e) {
371 fail("Json exception while reading JSON object. Original message " + e.getMessage());
375 private void containsProperties(final JSONObject jsonObject, final String... properties) throws JSONException {
376 for (final String property : properties) {
377 final JSONObject propertiesObject = jsonObject.getJSONObject("properties");
378 assertNotNull("Properties object missing in ", propertiesObject);
379 final JSONObject concretePropertyObject = propertiesObject.getJSONObject(property);
380 assertNotNull(property + " is missing", concretePropertyObject);