Merge "Fix exception when netconf device provides YIN schemas"
[controller.git] / opendaylight / md-sal / sal-rest-docgen / src / test / java / org / opendaylight / controller / sal / rest / doc / impl / ApiDocGeneratorTest.java
1 package org.opendaylight.controller.sal.rest.doc.impl;
2
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;
7
8 import com.google.common.base.Preconditions;
9 import java.io.File;
10 import java.util.Arrays;
11 import java.util.HashSet;
12 import java.util.Map.Entry;
13 import java.util.Set;
14 import java.util.TreeSet;
15 import javax.ws.rs.core.UriInfo;
16 import junit.framework.Assert;
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.Resource;
27 import org.opendaylight.controller.sal.rest.doc.swagger.ResourceList;
28 import org.opendaylight.yangtools.yang.model.api.Module;
29 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
30 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
31
32 /**
33  *
34  */
35 public class ApiDocGeneratorTest {
36
37     public static final String HTTP_HOST = "http://host";
38     private ApiDocGenerator generator;
39     private DocGenTestHelper helper;
40     private SchemaContext schemaContext;
41
42     @Before
43     public void setUp() throws Exception {
44         generator = new ApiDocGenerator();
45         helper = new DocGenTestHelper();
46         helper.setUp();
47         schemaContext = new YangParserImpl().resolveSchemaContext(new HashSet<Module>(helper.getModules().values()));
48     }
49
50     @After
51     public void after() throws Exception {
52     }
53
54     /**
55      * Method: getApiDeclaration(String module, String revision, UriInfo
56      * uriInfo)
57      */
58     @Test
59     public void testGetModuleDoc() throws Exception {
60         Preconditions.checkArgument(helper.getModules() != null, "No modules found");
61
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(),
65                         "http://localhost:8080/restconf", "",schemaContext);
66                 validateToaster(doc);
67                 validateTosterDocContainsModulePrefixes(doc);
68                 Assert.assertNotNull(doc);
69             }
70         }
71     }
72
73     @Test
74     public void testEdgeCases() throws Exception {
75         Preconditions.checkArgument(helper.getModules() != null, "No modules found");
76
77         for (Entry<File, Module> m : helper.getModules().entrySet()) {
78             if (m.getKey().getAbsolutePath().endsWith("toaster.yang")) {
79                 ApiDeclaration doc = generator.getSwaggerDocSpec(m.getValue(),
80                         "http://localhost:8080/restconf", "",schemaContext);
81                 Assert.assertNotNull(doc);
82
83                 //testing bugs.opendaylight.org bug 1290. UnionType model type.
84                 String jsonString = doc.getModels().toString();
85                 assertTrue(
86                         jsonString.contains( "testUnion\":{\"type\":\"integer or string\",\"required\":false}" ) );
87             }
88         }
89     }
90
91     /**
92      * Tests whether from yang files are generated all required paths for HTTP operations (GET, DELETE, PUT, POST)
93      *
94      * If container | list is augmented then in path there should be specified module name followed with collon (e. g.
95      * "/config/module1:element1/element2/module2:element3")
96      *
97      * @param doc
98      * @throws Exception
99      */
100     private void validateToaster(ApiDeclaration doc) throws Exception {
101         Set<String> expectedUrls = new TreeSet<>(Arrays.asList(new String[] {
102                 "/config/toaster2:toaster/", "/operational/toaster2:toaster/",
103                 "/operations/toaster2:cancel-toast", "/operations/toaster2:make-toast",
104                 "/operations/toaster2:restock-toaster",
105                 "/config/toaster2:toaster/toasterSlot/{slotId}/toaster-augmented:slotInfo/" }));
106
107         Set<String> actualUrls = new TreeSet<>();
108
109         Api configApi = null;
110         for (Api api : doc.getApis()) {
111             actualUrls.add(api.getPath());
112             if (api.getPath().contains("/config/toaster2:toaster/")) {
113                 configApi = api;
114             }
115         }
116
117         boolean containsAll = actualUrls.containsAll(expectedUrls);
118         if (!containsAll) {
119             expectedUrls.removeAll(actualUrls);
120             fail("Missing expected urls: " + expectedUrls);
121         }
122
123         Set<String> expectedConfigMethods = new TreeSet<>(Arrays.asList(new String[] { "GET",
124                 "PUT", "DELETE" }));
125         Set<String> actualConfigMethods = new TreeSet<>();
126         for (Operation oper : configApi.getOperations()) {
127             actualConfigMethods.add(oper.getMethod());
128         }
129
130         containsAll = actualConfigMethods.containsAll(expectedConfigMethods);
131         if (!containsAll) {
132             expectedConfigMethods.removeAll(actualConfigMethods);
133             fail("Missing expected method on config API: " + expectedConfigMethods);
134         }
135
136         // TODO: we should really do some more validation of the
137         // documentation...
138         /**
139          * Missing validation: Explicit validation of URLs, and their methods
140          * Input / output models.
141          */
142     }
143
144     @Test
145     public void testGetResourceListing() throws Exception {
146         UriInfo info = helper.createMockUriInfo(HTTP_HOST);
147         SchemaService mockSchemaService = helper.createMockSchemaService(schemaContext);
148
149         generator.setSchemaService(mockSchemaService);
150
151         ResourceList resourceListing = generator.getResourceListing(info);
152
153         Resource toaster = null;
154         Resource toaster2 = null;
155         for (Resource r : resourceListing.getApis()) {
156             String path = r.getPath();
157             if (path.contains("toaster2")) {
158                 toaster2 = r;
159             } else if (path.contains("toaster")) {
160                 toaster = r;
161             }
162         }
163
164         assertNotNull(toaster2);
165         assertNotNull(toaster);
166
167         assertEquals(HTTP_HOST + "/toaster(2009-11-20)", toaster.getPath());
168         assertEquals(HTTP_HOST + "/toaster2(2009-11-20)", toaster2.getPath());
169     }
170
171     private void validateTosterDocContainsModulePrefixes(ApiDeclaration doc) {
172         JSONObject topLevelJson = doc.getModels();
173         try {
174             JSONObject configToaster = topLevelJson.getJSONObject("(config)toaster");
175             assertNotNull("(config)toaster JSON object missing", configToaster);
176             //without module prefix
177             containsProperties(configToaster, "toasterSlot");
178
179             JSONObject toasterSlot = topLevelJson.getJSONObject("(config)toasterSlot");
180             assertNotNull("(config)toasterSlot JSON object missing", toasterSlot);
181             //with module prefix
182             containsProperties(toasterSlot, "toaster-augmented:slotInfo");
183
184         } catch (JSONException e) {
185             fail("Json exception while reading JSON object. Original message "+e.getMessage());
186         }
187     }
188
189     private void containsProperties(final JSONObject jsonObject,final String...properties) throws JSONException {
190         for (String property : properties) {
191             JSONObject propertiesObject = jsonObject.getJSONObject("properties");
192             assertNotNull("Properties object missing in ", propertiesObject);
193             JSONObject concretePropertyObject = propertiesObject.getJSONObject(property);
194             assertNotNull(property + " is missing",concretePropertyObject);
195         }
196     }
197 }