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 org.json.JSONException;
18 import org.json.JSONObject;
19 import org.junit.After;
20 import org.junit.Before;
21 import org.junit.Test;
22 import org.opendaylight.controller.sal.core.api.model.SchemaService;
23 import org.opendaylight.controller.sal.rest.doc.swagger.Api;
24 import org.opendaylight.controller.sal.rest.doc.swagger.ApiDeclaration;
25 import org.opendaylight.controller.sal.rest.doc.swagger.Operation;
26 import org.opendaylight.controller.sal.rest.doc.swagger.Parameter;
27 import org.opendaylight.controller.sal.rest.doc.swagger.Resource;
28 import org.opendaylight.controller.sal.rest.doc.swagger.ResourceList;
29 import org.opendaylight.yangtools.yang.model.api.Module;
30 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
31 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
36 public class ApiDocGeneratorTest {
38 public static final String HTTP_HOST = "http://host";
39 private ApiDocGenerator generator;
40 private DocGenTestHelper helper;
41 private SchemaContext schemaContext;
44 public void setUp() throws Exception {
45 generator = new ApiDocGenerator();
46 helper = new DocGenTestHelper();
48 schemaContext = new YangParserImpl().resolveSchemaContext(new HashSet<Module>(helper.getModules().values()));
52 public void after() throws Exception {
56 * Method: getApiDeclaration(String module, String revision, UriInfo uriInfo)
59 public void testGetModuleDoc() throws Exception {
60 Preconditions.checkArgument(helper.getModules() != null, "No modules found");
62 for (Entry<File, Module> m : helper.getModules().entrySet()) {
63 if (m.getKey().getAbsolutePath().endsWith("toaster_short.yang")) {
64 ApiDeclaration doc = generator.getSwaggerDocSpec(m.getValue(), "http://localhost:8080/restconf", "",
67 validateTosterDocContainsModulePrefixes(doc);
68 validateSwaggerModules(doc);
69 validateSwaggerApisForPost(doc);
75 * Validate whether ApiDelcaration contains Apis with concrete path and whether this Apis contain specified POST
78 private void validateSwaggerApisForPost(final ApiDeclaration doc) {
79 // two POST URI with concrete schema name in summary
80 Api lstApi = findApi("/config/toaster2:lst/", doc);
81 assertNotNull("Api /config/toaster2:lst/ wasn't found", lstApi);
82 assertTrue("POST for cont1 in lst is missing",
83 findOperation(lstApi.getOperations(), "POST", "(config)lstPOST", "(config)lst1", "(config)cont1"));
85 Api cont1Api = findApi("/config/toaster2:lst/cont1/", doc);
86 assertNotNull("Api /config/toaster2:lst/cont1/ wasn't found", cont1Api);
87 assertTrue("POST for cont11 in cont1 is missing",
88 findOperation(cont1Api.getOperations(), "POST", "(config)cont1POST", "(config)cont11", "(config)lst11"));
91 Api cont11Api = findApi("/config/toaster2:lst/cont1/cont11/", doc);
92 assertNotNull("Api /config/toaster2:lst/cont1/cont11/ wasn't found", cont11Api);
93 assertTrue("POST operation shouldn't be present.", findOperations(cont11Api.getOperations(), "POST").isEmpty());
98 * Tries to find operation with name {@code operationName} and with summary {@code summary}
100 private boolean findOperation(List<Operation> operations, String operationName, String type,
101 String... searchedParameters) {
102 Set<Operation> filteredOperations = findOperations(operations, operationName);
103 for (Operation operation : filteredOperations) {
104 if (operation.getType().equals(type)) {
105 List<Parameter> parameters = operation.getParameters();
106 return containAllParameters(parameters, searchedParameters);
112 private Set<Operation> findOperations(final List<Operation> operations, final String operationName) {
113 final Set<Operation> filteredOperations = new HashSet<>();
114 for (Operation operation : operations) {
115 if (operation.getMethod().equals(operationName)) {
116 filteredOperations.add(operation);
119 return filteredOperations;
122 private boolean containAllParameters(final List<Parameter> searchedIns, String[] searchedWhats) {
123 for (String searchedWhat : searchedWhats) {
124 boolean parameterFound = false;
125 for (Parameter searchedIn : searchedIns) {
126 if (searchedIn.getType().equals(searchedWhat)) {
127 parameterFound = true;
130 if (!parameterFound) {
138 * Tries to find {@code Api} with path {@code path}
140 private Api findApi(final String path, final ApiDeclaration doc) {
141 for (Api api : doc.getApis()) {
142 if (api.getPath().equals(path)) {
150 * Validates whether doc {@code doc} contains concrete specified models.
152 private void validateSwaggerModules(ApiDeclaration doc) {
153 JSONObject models = doc.getModels();
154 assertNotNull(models);
156 JSONObject configLst = models.getJSONObject("(config)lst");
157 assertNotNull(configLst);
159 containsReferences(configLst, "lst1");
160 containsReferences(configLst, "cont1");
162 JSONObject configLst1 = models.getJSONObject("(config)lst1");
163 assertNotNull(configLst1);
165 JSONObject configCont1 = models.getJSONObject("(config)cont1");
166 assertNotNull(configCont1);
168 containsReferences(configCont1, "cont11");
169 containsReferences(configCont1, "lst11");
171 JSONObject configCont11 = models.getJSONObject("(config)cont11");
172 assertNotNull(configCont11);
174 JSONObject configLst11 = models.getJSONObject("(config)lst11");
175 assertNotNull(configLst11);
176 } catch (JSONException e) {
177 fail("JSONException wasn't expected");
183 * Checks whether object {@code mainObject} contains in properties/items key $ref with concrete value.
185 private void containsReferences(final JSONObject mainObject, final String childObject) throws JSONException {
186 JSONObject properties = mainObject.getJSONObject("properties");
187 assertNotNull(properties);
189 JSONObject nodeInProperties = properties.getJSONObject(childObject);
190 assertNotNull(nodeInProperties);
192 JSONObject itemsInNodeInProperties = nodeInProperties.getJSONObject("items");
193 assertNotNull(itemsInNodeInProperties);
195 String itemRef = itemsInNodeInProperties.getString("$ref");
196 assertEquals("(config)" + childObject, itemRef);
200 public void testEdgeCases() throws Exception {
201 Preconditions.checkArgument(helper.getModules() != null, "No modules found");
203 for (Entry<File, Module> m : helper.getModules().entrySet()) {
204 if (m.getKey().getAbsolutePath().endsWith("toaster.yang")) {
205 ApiDeclaration doc = generator.getSwaggerDocSpec(m.getValue(), "http://localhost:8080/restconf", "",
209 // testing bugs.opendaylight.org bug 1290. UnionType model type.
210 String jsonString = doc.getModels().toString();
211 assertTrue(jsonString.contains("testUnion\":{\"type\":\"integer or string\",\"required\":false}"));
217 * Tests whether from yang files are generated all required paths for HTTP operations (GET, DELETE, PUT, POST)
219 * If container | list is augmented then in path there should be specified module name followed with collon (e. g.
220 * "/config/module1:element1/element2/module2:element3")
225 private void validateToaster(ApiDeclaration doc) throws Exception {
226 Set<String> expectedUrls = new TreeSet<>(Arrays.asList(new String[] { "/config/toaster2:toaster/",
227 "/operational/toaster2:toaster/", "/operations/toaster2:cancel-toast",
228 "/operations/toaster2:make-toast", "/operations/toaster2:restock-toaster",
229 "/config/toaster2:toaster/toasterSlot/{slotId}/toaster-augmented:slotInfo/" }));
231 Set<String> actualUrls = new TreeSet<>();
233 Api configApi = null;
234 for (Api api : doc.getApis()) {
235 actualUrls.add(api.getPath());
236 if (api.getPath().contains("/config/toaster2:toaster/")) {
241 boolean containsAll = actualUrls.containsAll(expectedUrls);
243 expectedUrls.removeAll(actualUrls);
244 fail("Missing expected urls: " + expectedUrls);
247 Set<String> expectedConfigMethods = new TreeSet<>(Arrays.asList(new String[] { "GET", "PUT", "DELETE" }));
248 Set<String> actualConfigMethods = new TreeSet<>();
249 for (Operation oper : configApi.getOperations()) {
250 actualConfigMethods.add(oper.getMethod());
253 containsAll = actualConfigMethods.containsAll(expectedConfigMethods);
255 expectedConfigMethods.removeAll(actualConfigMethods);
256 fail("Missing expected method on config API: " + expectedConfigMethods);
259 // TODO: we should really do some more validation of the
262 * Missing validation: Explicit validation of URLs, and their methods Input / output models.
267 public void testGetResourceListing() throws Exception {
268 UriInfo info = helper.createMockUriInfo(HTTP_HOST);
269 SchemaService mockSchemaService = helper.createMockSchemaService(schemaContext);
271 generator.setSchemaService(mockSchemaService);
273 ResourceList resourceListing = generator.getResourceListing(info);
275 Resource toaster = null;
276 Resource toaster2 = null;
277 for (Resource r : resourceListing.getApis()) {
278 String path = r.getPath();
279 if (path.contains("toaster2")) {
281 } else if (path.contains("toaster")) {
286 assertNotNull(toaster2);
287 assertNotNull(toaster);
289 assertEquals(HTTP_HOST + "/toaster(2009-11-20)", toaster.getPath());
290 assertEquals(HTTP_HOST + "/toaster2(2009-11-20)", toaster2.getPath());
293 private void validateTosterDocContainsModulePrefixes(ApiDeclaration doc) {
294 JSONObject topLevelJson = doc.getModels();
296 JSONObject configToaster = topLevelJson.getJSONObject("(config)toaster");
297 assertNotNull("(config)toaster JSON object missing", configToaster);
298 // without module prefix
299 containsProperties(configToaster, "toasterSlot");
301 JSONObject toasterSlot = topLevelJson.getJSONObject("(config)toasterSlot");
302 assertNotNull("(config)toasterSlot JSON object missing", toasterSlot);
303 // with module prefix
304 containsProperties(toasterSlot, "toaster-augmented:slotInfo");
306 } catch (JSONException e) {
307 fail("Json exception while reading JSON object. Original message " + e.getMessage());
311 private void containsProperties(final JSONObject jsonObject, final String... properties) throws JSONException {
312 for (String property : properties) {
313 JSONObject propertiesObject = jsonObject.getJSONObject("properties");
314 assertNotNull("Properties object missing in ", propertiesObject);
315 JSONObject concretePropertyObject = propertiesObject.getJSONObject(property);
316 assertNotNull(property + " is missing", concretePropertyObject);