Add DatabindContext and its wiring
[netconf.git] / restconf / restconf-nb / src / test / java / org / opendaylight / restconf / nb / rfc8040 / jersey / providers / errors / RestconfDocumentedExceptionMapperTest.java
1 /*
2  * Copyright © 2019 FRINX s.r.o. All rights reserved.
3  *
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
7  */
8 package org.opendaylight.restconf.nb.rfc8040.jersey.providers.errors;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assume.assumeTrue;
12 import static org.mockito.Mockito.doReturn;
13 import static org.mockito.Mockito.mock;
14
15 import java.util.Arrays;
16 import java.util.List;
17 import javax.ws.rs.core.HttpHeaders;
18 import javax.ws.rs.core.MediaType;
19 import javax.ws.rs.core.Response;
20 import javax.ws.rs.core.Response.Status;
21 import org.json.JSONException;
22 import org.json.JSONObject;
23 import org.json.XML;
24 import org.junit.BeforeClass;
25 import org.junit.Test;
26 import org.junit.runner.RunWith;
27 import org.junit.runners.Parameterized;
28 import org.junit.runners.Parameterized.Parameter;
29 import org.junit.runners.Parameterized.Parameters;
30 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
31 import org.opendaylight.restconf.common.errors.RestconfError;
32 import org.opendaylight.restconf.nb.rfc8040.MediaTypes;
33 import org.opendaylight.restconf.nb.rfc8040.databind.DatabindContext;
34 import org.opendaylight.yangtools.yang.common.ErrorTag;
35 import org.opendaylight.yangtools.yang.common.ErrorType;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.common.QNameModule;
38 import org.opendaylight.yangtools.yang.common.Revision;
39 import org.opendaylight.yangtools.yang.common.XMLNamespace;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
41 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
42 import org.skyscreamer.jsonassert.JSONAssert;
43
44 @RunWith(Parameterized.class)
45 public class RestconfDocumentedExceptionMapperTest {
46
47     private static final String EMPTY_XML = "<errors xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\"></errors>";
48     private static final String EMPTY_JSON = "{}";
49     private static final QNameModule MONITORING_MODULE_INFO = QNameModule.create(
50         XMLNamespace.of("instance:identifier:patch:module"), Revision.of("2015-11-21"));
51
52     private static RestconfDocumentedExceptionMapper exceptionMapper;
53
54     @BeforeClass
55     public static void setupExceptionMapper() {
56         final var schemaContext = YangParserTestUtils.parseYangResources(
57                 RestconfDocumentedExceptionMapperTest.class, "/restconf/impl/ietf-restconf@2017-01-26.yang",
58                 "/instanceidentifier/yang/instance-identifier-patch-module.yang");
59         exceptionMapper = new RestconfDocumentedExceptionMapper(() -> DatabindContext.ofModel(schemaContext));
60     }
61
62     /**
63      * Testing entries 0 - 6: testing of media types and empty responses.
64      * Testing entries 7 - 8: testing of deriving of status codes from error entries.
65      * Testing entries 9 - 10: testing of serialization of different optional fields of error entries (JSON/XML).
66      *
67      * @return Testing data for parametrized test.
68      */
69     @Parameters(name = "{index}: {0}: {1}")
70     public static Iterable<Object[]> data() {
71         final RestconfDocumentedException sampleComplexError =
72             new RestconfDocumentedException("general message", new IllegalStateException("cause"), List.of(
73                 new RestconfError(ErrorType.APPLICATION, ErrorTag.BAD_ATTRIBUTE, "message 1", "app tag #1"),
74                 new RestconfError(ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED,
75                     "message 2", "app tag #2", "my info"),
76                 new RestconfError(ErrorType.RPC, ErrorTag.DATA_MISSING,
77                     "message 3", " app tag #3", "my error info", YangInstanceIdentifier.builder()
78                     .node(QName.create(MONITORING_MODULE_INFO, "patch-cont"))
79                     .node(QName.create(MONITORING_MODULE_INFO, "my-list1"))
80                     .nodeWithKey(QName.create(MONITORING_MODULE_INFO, "my-list1"),
81                         QName.create(MONITORING_MODULE_INFO, "name"), "sample")
82                     .node(QName.create(MONITORING_MODULE_INFO, "my-leaf12"))
83                     .build())));
84
85         return Arrays.asList(new Object[][] {
86             {
87                 "Mapping of the exception without any errors and XML output derived from content type",
88                 new RestconfDocumentedException(Status.BAD_REQUEST),
89                 mockHttpHeaders(MediaType.APPLICATION_XML_TYPE, List.of()),
90                 Response.status(Status.BAD_REQUEST)
91                         .type(MediaTypes.APPLICATION_YANG_DATA_XML_TYPE)
92                         .entity(EMPTY_XML)
93                         .build()
94             },
95             {
96                 "Mapping of the exception without any errors and JSON output derived from unsupported content type",
97                 new RestconfDocumentedException(Status.INTERNAL_SERVER_ERROR),
98                 mockHttpHeaders(MediaType.APPLICATION_FORM_URLENCODED_TYPE, List.of()),
99                 Response.status(Status.INTERNAL_SERVER_ERROR)
100                         .type(MediaTypes.APPLICATION_YANG_DATA_JSON_TYPE)
101                         .entity(EMPTY_JSON)
102                         .build()
103             },
104             {
105                 "Mapping of the exception without any errors and JSON output derived from missing content type "
106                         + "and accepted media types",
107                 new RestconfDocumentedException(Status.NOT_IMPLEMENTED),
108                 mockHttpHeaders(null, List.of()),
109                 Response.status(Status.NOT_IMPLEMENTED)
110                         .type(MediaTypes.APPLICATION_YANG_DATA_JSON_TYPE)
111                         .entity(EMPTY_JSON)
112                         .build()
113             },
114             {
115                 "Mapping of the exception without any errors and JSON output derived from expected types - both JSON"
116                         + "and XML types are accepted, but server should prefer JSON format",
117                 new RestconfDocumentedException(Status.INTERNAL_SERVER_ERROR),
118                 mockHttpHeaders(MediaType.APPLICATION_JSON_TYPE, List.of(
119                         MediaType.APPLICATION_FORM_URLENCODED_TYPE, MediaType.APPLICATION_XML_TYPE,
120                         MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_OCTET_STREAM_TYPE)),
121                 Response.status(Status.INTERNAL_SERVER_ERROR)
122                         .type(MediaTypes.APPLICATION_YANG_DATA_JSON_TYPE)
123                         .entity(EMPTY_JSON)
124                         .build()
125             },
126             {
127                 "Mapping of the exception without any errors and JSON output derived from expected types - there"
128                         + "is only a wildcard type that should be mapped to default type",
129                 new RestconfDocumentedException(Status.NOT_FOUND),
130                 mockHttpHeaders(null, List.of(MediaType.WILDCARD_TYPE)),
131                 Response.status(Status.NOT_FOUND)
132                         .type(MediaTypes.APPLICATION_YANG_DATA_JSON_TYPE)
133                         .entity(EMPTY_JSON)
134                         .build()
135             },
136             {
137                 "Mapping of the exception without any errors and XML output derived from expected types - "
138                         + "we should choose the most specific and supported type",
139                 new RestconfDocumentedException(Status.NOT_FOUND),
140                 mockHttpHeaders(null, List.of(MediaType.valueOf("*/yang-data+json"),
141                         MediaType.valueOf("application/yang-data+xml"), MediaType.WILDCARD_TYPE)),
142                 Response.status(Status.NOT_FOUND)
143                         .type(MediaTypes.APPLICATION_YANG_DATA_XML_TYPE)
144                         .entity(EMPTY_XML)
145                         .build()
146             },
147             {
148                 "Mapping of the exception without any errors and XML output derived from expected types - "
149                         + "we should choose the most specific and supported type",
150                 new RestconfDocumentedException(Status.NOT_FOUND),
151                 mockHttpHeaders(null, List.of(MediaType.valueOf("*/unsupported"),
152                         MediaType.valueOf("application/*"), MediaType.WILDCARD_TYPE)),
153                 Response.status(Status.NOT_FOUND)
154                         .type(MediaTypes.APPLICATION_YANG_DATA_JSON_TYPE)
155                         .entity(EMPTY_JSON)
156                         .build()
157             },
158             {
159                 "Mapping of the exception with one error entry but null status code. This status code should"
160                         + "be derived from single error entry; JSON output",
161                 new RestconfDocumentedException("Sample error message"),
162                 mockHttpHeaders(MediaType.APPLICATION_JSON_TYPE, List.of(MediaTypes.APPLICATION_YANG_PATCH_JSON_TYPE)),
163                 Response.status(Status.INTERNAL_SERVER_ERROR)
164                         .type(MediaTypes.APPLICATION_YANG_DATA_JSON_TYPE)
165                         .entity("{\n"
166                                 + "  \"errors\": {\n"
167                                 + "    \"error\": [\n"
168                                 + "      {\n"
169                                 + "        \"error-tag\": \"operation-failed\",\n"
170                                 + "        \"error-message\": \"Sample error message\",\n"
171                                 + "        \"error-type\": \"application\"\n"
172                                 + "      }\n"
173                                 + "    ]\n"
174                                 + "  }\n"
175                                 + "}")
176                         .build()
177             },
178             {
179                 "Mapping of the exception with two error entries but null status code. This status code should"
180                         + "be derived from the first error entry that is specified; XML output",
181                 new RestconfDocumentedException("general message", new IllegalStateException("cause"), List.of(
182                                 new RestconfError(ErrorType.APPLICATION, ErrorTag.BAD_ATTRIBUTE, "message 1"),
183                                 new RestconfError(ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "message 2"))),
184                 mockHttpHeaders(MediaType.APPLICATION_JSON_TYPE, List.of(MediaTypes.APPLICATION_YANG_PATCH_XML_TYPE)),
185                 Response.status(Status.BAD_REQUEST)
186                         .type(MediaTypes.APPLICATION_YANG_DATA_XML_TYPE)
187                         .entity("<errors xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\">\n"
188                                 + "<error>\n"
189                                 + "<error-message>message 1</error-message>\n"
190                                 + "<error-tag>bad-attribute</error-tag>\n"
191                                 + "<error-type>application</error-type>\n"
192                                 + "</error>\n"
193                                 + "<error>\n"
194                                 + "<error-message>message 2</error-message>\n"
195                                 + "<error-tag>operation-failed</error-tag>\n"
196                                 + "<error-type>application</error-type>\n"
197                                 + "</error>\n"
198                                 + "</errors>")
199                         .build()
200             },
201             {
202                 "Mapping of the exception with three entries and optional entries set: error app tag (the first error),"
203                         + " error info (the second error), and error path (the last error); JSON output",
204                 sampleComplexError, mockHttpHeaders(MediaType.APPLICATION_JSON_TYPE, List.of(
205                         MediaType.APPLICATION_JSON_TYPE)),
206                 Response.status(Status.BAD_REQUEST)
207                         .type(MediaTypes.APPLICATION_YANG_DATA_JSON_TYPE)
208                         .entity("{\n"
209                                 + "  \"errors\": {\n"
210                                 + "    \"error\": [\n"
211                                 + "      {\n"
212                                 + "        \"error-tag\": \"bad-attribute\",\n"
213                                 + "        \"error-app-tag\": \"app tag #1\",\n"
214                                 + "        \"error-message\": \"message 1\",\n"
215                                 + "        \"error-type\": \"application\"\n"
216                                 + "      },\n"
217                                 + "      {\n"
218                                 + "        \"error-tag\": \"operation-failed\",\n"
219                                 + "        \"error-app-tag\": \"app tag #2\",\n"
220                                 + "        \"error-info\": \"my info\",\n"
221                                 + "        \"error-message\": \"message 2\",\n"
222                                 + "        \"error-type\": \"application\"\n"
223                                 + "      },\n"
224                                 + "      {\n"
225                                 + "        \"error-tag\": \"data-missing\",\n"
226                                 + "        \"error-app-tag\": \" app tag #3\",\n"
227                                 + "        \"error-info\": \"my error info\",\n"
228                                 + "        \"error-message\": \"message 3\",\n"
229                                 + "        \"error-path\": \"/instance-identifier-patch-module:patch-cont/"
230                                 + "my-list1[name='sample']/my-leaf12\",\n"
231                                 + "        \"error-type\": \"rpc\"\n"
232                                 + "      }\n"
233                                 + "    ]\n"
234                                 + "  }\n"
235                                 + "}")
236                         .build()
237             },
238             {
239                 "Mapping of the exception with three entries and optional entries set: error app tag (the first error),"
240                         + " error info (the second error), and error path (the last error); XML output",
241                 sampleComplexError, mockHttpHeaders(MediaTypes.APPLICATION_YANG_PATCH_JSON_TYPE,
242                         List.of(MediaTypes.APPLICATION_YANG_DATA_XML_TYPE)),
243                 Response.status(Status.BAD_REQUEST)
244                         .type(MediaTypes.APPLICATION_YANG_DATA_XML_TYPE)
245                         .entity("<errors xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\">\n"
246                                 + "<error>\n"
247                                 + "<error-type>application</error-type>\n"
248                                 + "<error-message>message 1</error-message>\n"
249                                 + "<error-tag>bad-attribute</error-tag>\n"
250                                 + "<error-app-tag>app tag #1</error-app-tag>\n"
251                                 + "</error>\n"
252                                 + "<error>\n"
253                                 + "<error-type>application</error-type>\n"
254                                 + "<error-message>message 2</error-message>\n"
255                                 + "<error-tag>operation-failed</error-tag>\n"
256                                 + "<error-app-tag>app tag #2</error-app-tag>\n"
257                                 + "<error-info>my info</error-info></error>\n"
258                                 + "<error>\n"
259                                 + "<error-type>rpc</error-type>\n"
260                                 + "<error-path xmlns:a=\"instance:identifier:patch:module\">/a:patch-cont/"
261                                 + "a:my-list1[a:name='sample']/a:my-leaf12</error-path>\n"
262                                 + "<error-message>message 3</error-message>\n"
263                                 + "<error-tag>data-missing</error-tag>\n"
264                                 + "<error-app-tag> app tag #3</error-app-tag>\n"
265                                 + "<error-info>my error info</error-info>\n"
266                                 + "</error>\n"
267                                 + "</errors>")
268                         .build()
269             }
270         });
271     }
272
273     @Parameter
274     public String testDescription;
275     @Parameter(1)
276     public RestconfDocumentedException thrownException;
277     @Parameter(2)
278     public HttpHeaders httpHeaders;
279     @Parameter(3)
280     public Response expectedResponse;
281
282     @Test
283     public void testMappingOfExceptionToResponse() throws JSONException {
284         exceptionMapper.setHttpHeaders(httpHeaders);
285         final Response response = exceptionMapper.toResponse(thrownException);
286         compareResponseWithExpectation(expectedResponse, response);
287     }
288
289     @Test
290     public void testFormatingJson() throws JSONException {
291         assumeTrue(expectedResponse.getMediaType().equals(MediaTypes.APPLICATION_YANG_DATA_JSON_TYPE));
292
293         exceptionMapper.setHttpHeaders(httpHeaders);
294         final Response response = exceptionMapper.toResponse(thrownException);
295         assertEquals(expectedResponse.getEntity().toString(), response.getEntity().toString());
296     }
297
298     private static HttpHeaders mockHttpHeaders(final MediaType contentType, final List<MediaType> acceptedTypes) {
299         final HttpHeaders httpHeaders = mock(HttpHeaders.class);
300         doReturn(contentType).when(httpHeaders).getMediaType();
301         doReturn(acceptedTypes).when(httpHeaders).getAcceptableMediaTypes();
302         return httpHeaders;
303     }
304
305     private static void compareResponseWithExpectation(final Response expectedResponse, final Response actualResponse)
306             throws JSONException {
307         final String errorMessage = String.format("Actual response %s doesn't equal to expected response %s",
308                 actualResponse, expectedResponse);
309         assertEquals(errorMessage, expectedResponse.getStatus(), actualResponse.getStatus());
310         assertEquals(errorMessage, expectedResponse.getMediaType(), actualResponse.getMediaType());
311         if (MediaTypes.APPLICATION_YANG_DATA_JSON_TYPE.equals(expectedResponse.getMediaType())) {
312             JSONAssert.assertEquals(expectedResponse.getEntity().toString(),
313                     actualResponse.getEntity().toString(), true);
314         } else {
315             final JSONObject expectedResponseInJson = XML.toJSONObject(expectedResponse.getEntity().toString());
316             final JSONObject actualResponseInJson = XML.toJSONObject(actualResponse.getEntity().toString());
317             JSONAssert.assertEquals(expectedResponseInJson, actualResponseInJson, true);
318         }
319     }
320 }