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