Simplify RestconfInvokeOperationsServiceImpl
[netconf.git] / restconf / restconf-nb / src / test / java / org / opendaylight / restconf / nb / rfc8040 / rests / services / impl / RestconfInvokeOperationsServiceImplTest.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  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.rests.services.impl;
9
10 import static org.hamcrest.CoreMatchers.instanceOf;
11 import static org.hamcrest.MatcherAssert.assertThat;
12 import static org.junit.Assert.assertEquals;
13 import static org.junit.Assert.assertNull;
14 import static org.junit.Assert.assertSame;
15 import static org.junit.Assert.assertThrows;
16 import static org.junit.Assert.assertTrue;
17 import static org.mockito.Mockito.doReturn;
18 import static org.mockito.Mockito.mock;
19 import static org.mockito.Mockito.verify;
20 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFailedFluentFuture;
21 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
22
23 import java.util.Collection;
24 import java.util.List;
25 import java.util.Optional;
26 import java.util.concurrent.ExecutionException;
27 import javax.ws.rs.WebApplicationException;
28 import javax.ws.rs.container.AsyncResponse;
29 import javax.ws.rs.core.Response.Status;
30 import javax.ws.rs.core.UriInfo;
31 import org.junit.Before;
32 import org.junit.BeforeClass;
33 import org.junit.Test;
34 import org.junit.runner.RunWith;
35 import org.mockito.ArgumentCaptor;
36 import org.mockito.Mock;
37 import org.mockito.junit.MockitoJUnitRunner;
38 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
39 import org.opendaylight.mdsal.dom.api.DOMRpcException;
40 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
41 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
42 import org.opendaylight.mdsal.dom.api.DOMRpcService;
43 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
44 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
45 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
46 import org.opendaylight.restconf.nb.rfc8040.TestRestconfUtils;
47 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
48 import org.opendaylight.yangtools.yang.common.ErrorTag;
49 import org.opendaylight.yangtools.yang.common.ErrorType;
50 import org.opendaylight.yangtools.yang.common.QName;
51 import org.opendaylight.yangtools.yang.common.RpcError;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
53 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
55 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
56 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
57 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
58 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
59 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
60
61 @RunWith(MockitoJUnitRunner.StrictStubs.class)
62 public class RestconfInvokeOperationsServiceImplTest {
63     private static final QName RPC = QName.create("ns", "2015-02-28", "test-rpc");
64     private static final ContainerNode INPUT = Builders.containerBuilder()
65         .withNodeIdentifier(new NodeIdentifier(QName.create(RPC, "input")))
66         .withChild(ImmutableNodes.leafNode(QName.create(RPC, "content"), "test"))
67         .build();
68     private static final ContainerNode OUTPUT = Builders.containerBuilder()
69         .withNodeIdentifier(new NodeIdentifier(QName.create(RPC, "output")))
70         .withChild(ImmutableNodes.leafNode(QName.create(RPC, "content"), "operation result"))
71         .build();
72
73     private static EffectiveModelContext CONTEXT;
74
75     @Mock
76     private DOMRpcService rpcService;
77     @Mock
78     private DOMMountPoint mountPoint;
79     private RestconfInvokeOperationsServiceImpl invokeOperationsService;
80
81     @BeforeClass
82     public static void beforeClass() throws Exception {
83         CONTEXT = YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles("/invoke-rpc"));
84     }
85
86     @Before
87     public void setup() {
88         invokeOperationsService = new RestconfInvokeOperationsServiceImpl(rpcService);
89     }
90
91     @Test
92     public void testInvokeRpcWithNonEmptyOutput() {
93         final ContainerNode result = mock(ContainerNode.class);
94         doReturn(false).when(result).isEmpty();
95
96         final AsyncResponse ar = mock(AsyncResponse.class);
97         final ArgumentCaptor<NormalizedNodePayload> response = ArgumentCaptor.forClass(NormalizedNodePayload.class);
98         invokeOperationsService.invokeRpc("invoke-rpc-module:rpcTest", prepNNC(result), mock(UriInfo.class), ar);
99         verify(ar).resume(response.capture());
100
101         assertSame(result, response.getValue().getData());
102     }
103
104     @Test
105     public void testInvokeRpcWithEmptyOutput() {
106         final ContainerNode result = mock(ContainerNode.class);
107         doReturn(true).when(result).isEmpty();
108
109         final AsyncResponse ar = mock(AsyncResponse.class);
110         final ArgumentCaptor<Throwable> response = ArgumentCaptor.forClass(Throwable.class);
111         invokeOperationsService.invokeRpc("invoke-rpc-module:rpcTest", prepNNC(result), mock(UriInfo.class), ar);
112         verify(ar).resume(response.capture());
113
114         final Throwable failure = response.getValue();
115         assertThat(failure, instanceOf(WebApplicationException.class));
116         assertEquals(Status.NO_CONTENT.getStatusCode(), ((WebApplicationException) failure).getResponse().getStatus());
117     }
118
119     @Test
120     public void invokeRpcTest() throws InterruptedException, ExecutionException {
121         final DOMRpcResult mockResult = new DefaultDOMRpcResult(OUTPUT, List.of());
122         doReturn(immediateFluentFuture(mockResult)).when(rpcService).invokeRpc(RPC, INPUT);
123         final DOMRpcResult rpcResult = RestconfInvokeOperationsServiceImpl.invokeRpc(INPUT, RPC, rpcService).get();
124         assertTrue(rpcResult.getErrors().isEmpty());
125         assertEquals(OUTPUT, rpcResult.getResult());
126     }
127
128     @Test
129     public void invokeRpcErrorsAndCheckTestTest() throws InterruptedException, ExecutionException {
130         final QName errorRpc = QName.create(RPC, "error-rpc");
131         final DOMRpcException exception = new DOMRpcImplementationNotAvailableException(
132                 "No implementation of RPC " + errorRpc + " available.");
133         doReturn(immediateFailedFluentFuture(exception)).when(rpcService).invokeRpc(errorRpc, INPUT);
134         final DOMRpcResult rpcResult = RestconfInvokeOperationsServiceImpl.invokeRpc(INPUT, errorRpc, rpcService).get();
135         assertNull(rpcResult.getResult());
136         final Collection<? extends RpcError> errorList = rpcResult.getErrors();
137         assertEquals(1, errorList.size());
138         final RpcError actual = errorList.iterator().next();
139         assertEquals("No implementation of RPC " + errorRpc + " available.", actual.getMessage());
140         assertEquals(ErrorTag.OPERATION_FAILED, actual.getTag());
141         assertEquals(ErrorType.RPC, actual.getErrorType());
142     }
143
144     @Test
145     public void invokeRpcViaMountPointTest() throws InterruptedException, ExecutionException {
146         doReturn(Optional.ofNullable(rpcService)).when(mountPoint).getService(DOMRpcService.class);
147         final DOMRpcResult mockResult = new DefaultDOMRpcResult(OUTPUT, List.of());
148         doReturn(immediateFluentFuture(mockResult)).when(rpcService).invokeRpc(RPC, INPUT);
149         final DOMRpcResult rpcResult = RestconfInvokeOperationsServiceImpl.invokeRpc(INPUT, RPC, mountPoint).get();
150         assertTrue(rpcResult.getErrors().isEmpty());
151         assertEquals(OUTPUT, rpcResult.getResult());
152     }
153
154     @Test
155     public void invokeRpcMissingMountPointServiceTest() {
156         doReturn(Optional.empty()).when(mountPoint).getService(DOMRpcService.class);
157         assertThrows(RestconfDocumentedException.class,
158             () -> RestconfInvokeOperationsServiceImpl.invokeRpc(INPUT, RPC, mountPoint));
159     }
160
161     @Test
162     public void checkResponseTest() throws InterruptedException, ExecutionException {
163         doReturn(immediateFluentFuture(new DefaultDOMRpcResult(OUTPUT, List.of())))
164             .when(rpcService).invokeRpc(RPC, INPUT);
165         final DOMRpcResult rpcResult = RestconfInvokeOperationsServiceImpl.invokeRpc(INPUT, RPC, rpcService).get();
166         assertTrue(rpcResult.getErrors().isEmpty());
167         assertEquals(OUTPUT, rpcResult.getResult());
168     }
169
170     private NormalizedNodePayload prepNNC(final NormalizedNode result) {
171         final QName qname = QName.create("invoke:rpc:module", "2013-12-03", "rpc-test");
172         final RpcDefinition schemaNode = CONTEXT.getOperations().stream().filter(rpc -> rpc.getQName().equals(qname))
173             .findFirst()
174             .orElseThrow();
175
176         final NormalizedNode data = mock(NormalizedNode.class);
177         final DOMRpcResult domRpcResult = mock(DOMRpcResult.class);
178         doReturn(immediateFluentFuture(domRpcResult)).when(rpcService).invokeRpc(qname, data);
179         doReturn(result).when(domRpcResult).getResult();
180         return NormalizedNodePayload.of(
181             InstanceIdentifierContext.ofRpcInput(CONTEXT, schemaNode, null), data);
182     }
183 }