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.fasterxml.jackson.databind.JsonNode;
17 import com.fasterxml.jackson.databind.node.ObjectNode;
18 import com.google.common.base.Preconditions;
20 import java.util.Arrays;
21 import java.util.HashSet;
22 import java.util.List;
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;
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 ObjectNode models = doc.getModels();
168 assertNotNull(models);
170 final JsonNode configLstTop = models.get("toaster2(config)lst-TOP");
171 assertNotNull(configLstTop);
173 containsReferences(configLstTop, "toaster2:lst", "toaster2(config)");
175 final JsonNode configLst = models.get("toaster2(config)lst");
176 assertNotNull(configLst);
178 containsReferences(configLst, "toaster2:lst1", "toaster2/lst(config)");
179 containsReferences(configLst, "toaster2:cont1", "toaster2/lst(config)");
181 final JsonNode configLst1Top = models.get("toaster2/lst(config)lst1-TOP");
182 assertNotNull(configLst1Top);
184 containsReferences(configLst1Top, "toaster2:lst1", "toaster2/lst(config)");
186 final JsonNode configLst1 = models.get("toaster2/lst(config)lst1");
187 assertNotNull(configLst1);
189 final JsonNode configCont1Top = models.get("toaster2/lst(config)cont1-TOP");
190 assertNotNull(configCont1Top);
192 containsReferences(configCont1Top, "toaster2:cont1", "toaster2/lst(config)");
193 final JsonNode configCont1 = models.get("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 JsonNode configCont11Top = models.get("toaster2/lst/cont1(config)cont11-TOP");
200 assertNotNull(configCont11Top);
202 containsReferences(configCont11Top, "toaster2:cont11", "toaster2/lst/cont1(config)");
203 final JsonNode configCont11 = models.get("toaster2/lst/cont1(config)cont11");
204 assertNotNull(configCont11);
206 final JsonNode configlst11Top = models.get("toaster2/lst/cont1(config)lst11-TOP");
207 assertNotNull(configlst11Top);
209 containsReferences(configlst11Top, "toaster2:lst11", "toaster2/lst/cont1(config)");
210 final JsonNode configLst11 = models.get("toaster2/lst/cont1(config)lst11");
211 assertNotNull(configLst11);
215 * Checks whether object {@code mainObject} contains in properties/items key $ref with concrete value.
217 private void containsReferences(final JsonNode mainObject, final String childObject, final String prefix) {
218 final JsonNode properties = mainObject.get("properties");
219 assertNotNull(properties);
221 final JsonNode nodeInProperties = properties.get(childObject);
222 assertNotNull(nodeInProperties);
224 final JsonNode itemsInNodeInProperties = nodeInProperties.get("items");
225 assertNotNull(itemsInNodeInProperties);
227 final String itemRef = itemsInNodeInProperties.get("$ref").asText();
228 assertEquals(prefix + childObject.split(":")[1], itemRef);
232 public void testEdgeCases() throws Exception {
233 Preconditions.checkArgument(this.helper.getModules() != null, "No modules found");
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", "",
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\"]}"));
251 public void testRPCsModel() throws Exception {
252 Preconditions.checkArgument(this.helper.getModules() != null, "No modules found");
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", "",
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"));
275 * Tests whether from yang files are generated all required paths for HTTP operations (GET, DELETE, PUT, POST)
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")
281 * @param doc Api declaration
282 * @throws Exception if operation fails
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"}));
290 final Set<String> actualUrls = new TreeSet<>();
292 Api configApi = null;
293 for (final Api api : doc.getApis()) {
294 actualUrls.add(api.getPath());
295 if (api.getPath().contains("/config/toaster2:toaster/")) {
300 boolean containsAll = actualUrls.containsAll(expectedUrls);
302 expectedUrls.removeAll(actualUrls);
303 fail("Missing expected urls: " + expectedUrls);
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());
312 containsAll = actualConfigMethods.containsAll(expectedConfigMethods);
314 expectedConfigMethods.removeAll(actualConfigMethods);
315 fail("Missing expected method on config API: " + expectedConfigMethods);
318 // TODO: we should really do some more validation of the
321 * Missing validation: Explicit validation of URLs, and their methods Input / output models.
326 public void testGetResourceListing() throws Exception {
327 final UriInfo info = this.helper.createMockUriInfo(HTTP_HOST);
328 final SchemaService mockSchemaService = this.helper.createMockSchemaService(this.schemaContext);
330 this.generator.setSchemaService(mockSchemaService);
332 final ResourceList resourceListing = this.generator.getResourceListing(info);
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")) {
340 } else if (path.contains("toaster")) {
345 assertNotNull(toaster2);
346 assertNotNull(toaster);
348 assertEquals(HTTP_HOST + "/toaster(2009-11-20)", toaster.getPath());
349 assertEquals(HTTP_HOST + "/toaster2(2009-11-20)", toaster2.getPath());
352 private void validateTosterDocContainsModulePrefixes(final ApiDeclaration doc) {
353 final ObjectNode topLevelJson = doc.getModels();
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");
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");
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);