1 package org.opendaylight.controller.sal.rest.doc.impl;
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;
8 import com.google.common.base.Preconditions;
10 import java.util.Arrays;
11 import java.util.HashSet;
12 import java.util.List;
13 import java.util.Map.Entry;
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;
37 public class ApiDocGeneratorTest {
39 public static final String HTTP_HOST = "http://host";
40 private ApiDocGenerator generator;
41 private DocGenTestHelper helper;
42 private SchemaContext schemaContext;
45 public void setUp() throws Exception {
46 generator = new ApiDocGenerator();
47 helper = new DocGenTestHelper();
49 schemaContext = new YangParserImpl().resolveSchemaContext(new HashSet<Module>(helper.getModules().values()));
53 public void after() throws Exception {
57 * Method: getApiDeclaration(String module, String revision, UriInfo uriInfo)
60 public void testGetModuleDoc() throws Exception {
61 Preconditions.checkArgument(helper.getModules() != null, "No modules found");
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", "",
68 validateTosterDocContainsModulePrefixes(doc);
69 validateSwaggerModules(doc);
70 validateSwaggerApisForPost(doc);
76 * Validate whether ApiDelcaration contains Apis with concrete path and whether this Apis contain specified POST
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"));
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"));
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());
99 * Tries to find operation with name {@code operationName} and with summary {@code summary}
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);
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);
120 return filteredOperations;
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;
131 if (!parameterFound) {
139 * Tries to find {@code Api} with path {@code path}
141 private Api findApi(final String path, final ApiDeclaration doc) {
142 for (Api api : doc.getApis()) {
143 if (api.getPath().equals(path)) {
151 * Validates whether doc {@code doc} contains concrete specified models.
153 private void validateSwaggerModules(ApiDeclaration doc) {
154 JSONObject models = doc.getModels();
155 assertNotNull(models);
157 JSONObject configLst = models.getJSONObject("(config)lst");
158 assertNotNull(configLst);
160 containsReferences(configLst, "lst1");
161 containsReferences(configLst, "cont1");
163 JSONObject configLst1 = models.getJSONObject("(config)lst1");
164 assertNotNull(configLst1);
166 JSONObject configCont1 = models.getJSONObject("(config)cont1");
167 assertNotNull(configCont1);
169 containsReferences(configCont1, "cont11");
170 containsReferences(configCont1, "lst11");
172 JSONObject configCont11 = models.getJSONObject("(config)cont11");
173 assertNotNull(configCont11);
175 JSONObject configLst11 = models.getJSONObject("(config)lst11");
176 assertNotNull(configLst11);
177 } catch (JSONException e) {
178 fail("JSONException wasn't expected");
184 * Checks whether object {@code mainObject} contains in properties/items key $ref with concrete value.
186 private void containsReferences(final JSONObject mainObject, final String childObject) throws JSONException {
187 JSONObject properties = mainObject.getJSONObject("properties");
188 assertNotNull(properties);
190 JSONObject nodeInProperties = properties.getJSONObject(childObject);
191 assertNotNull(nodeInProperties);
193 JSONObject itemsInNodeInProperties = nodeInProperties.getJSONObject("items");
194 assertNotNull(itemsInNodeInProperties);
196 String itemRef = itemsInNodeInProperties.getString("$ref");
197 assertEquals("(config)" + childObject, itemRef);
201 public void testEdgeCases() throws Exception {
202 Preconditions.checkArgument(helper.getModules() != null, "No modules found");
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", "",
208 Assert.assertNotNull(doc);
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}"));
218 * Tests whether from yang files are generated all required paths for HTTP operations (GET, DELETE, PUT, POST)
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")
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/" }));
232 Set<String> actualUrls = new TreeSet<>();
234 Api configApi = null;
235 for (Api api : doc.getApis()) {
236 actualUrls.add(api.getPath());
237 if (api.getPath().contains("/config/toaster2:toaster/")) {
242 boolean containsAll = actualUrls.containsAll(expectedUrls);
244 expectedUrls.removeAll(actualUrls);
245 fail("Missing expected urls: " + expectedUrls);
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());
254 containsAll = actualConfigMethods.containsAll(expectedConfigMethods);
256 expectedConfigMethods.removeAll(actualConfigMethods);
257 fail("Missing expected method on config API: " + expectedConfigMethods);
260 // TODO: we should really do some more validation of the
263 * Missing validation: Explicit validation of URLs, and their methods Input / output models.
268 public void testGetResourceListing() throws Exception {
269 UriInfo info = helper.createMockUriInfo(HTTP_HOST);
270 SchemaService mockSchemaService = helper.createMockSchemaService(schemaContext);
272 generator.setSchemaService(mockSchemaService);
274 ResourceList resourceListing = generator.getResourceListing(info);
276 Resource toaster = null;
277 Resource toaster2 = null;
278 for (Resource r : resourceListing.getApis()) {
279 String path = r.getPath();
280 if (path.contains("toaster2")) {
282 } else if (path.contains("toaster")) {
287 assertNotNull(toaster2);
288 assertNotNull(toaster);
290 assertEquals(HTTP_HOST + "/toaster(2009-11-20)", toaster.getPath());
291 assertEquals(HTTP_HOST + "/toaster2(2009-11-20)", toaster2.getPath());
294 private void validateTosterDocContainsModulePrefixes(ApiDeclaration doc) {
295 JSONObject topLevelJson = doc.getModels();
297 JSONObject configToaster = topLevelJson.getJSONObject("(config)toaster");
298 assertNotNull("(config)toaster JSON object missing", configToaster);
299 // without module prefix
300 containsProperties(configToaster, "toasterSlot");
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");
307 } catch (JSONException e) {
308 fail("Json exception while reading JSON object. Original message " + e.getMessage());
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);