InstanceIdentifierContext does not take generics
[netconf.git] / restconf / restconf-nb-rfc8040 / src / test / java / org / opendaylight / restconf / nb / rfc8040 / rests / services / impl / RestconfInvokeOperationsServiceImplTest.java
index 57e8017970c926f14bbdc08b851b6c387c78314f..93996cd7b6d5767ffebc7e57064fdb52d37e7eff 100644 (file)
  */
 package org.opendaylight.restconf.nb.rfc8040.rests.services.impl;
 
+import static org.hamcrest.CoreMatchers.instanceOf;
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.verify;
+import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFailedFluentFuture;
 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
 
-import java.util.Collections;
+import java.util.Collection;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.ExecutionException;
 import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.Response;
+import javax.ws.rs.container.AsyncResponse;
+import javax.ws.rs.core.Response.Status;
 import javax.ws.rs.core.UriInfo;
-import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
 import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
+import org.mockito.junit.MockitoJUnitRunner;
 import org.opendaylight.mdsal.common.api.CommitInfo;
+import org.opendaylight.mdsal.dom.api.DOMDataBroker;
 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
+import org.opendaylight.mdsal.dom.api.DOMMountPoint;
+import org.opendaylight.mdsal.dom.api.DOMRpcException;
+import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
 import org.opendaylight.mdsal.dom.api.DOMRpcService;
 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
-import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
+import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
-import org.opendaylight.restconf.common.context.NormalizedNodeContext;
+import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
 import org.opendaylight.restconf.nb.rfc8040.TestRestconfUtils;
-import org.opendaylight.restconf.nb.rfc8040.handlers.RpcServiceHandler;
 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
-import org.opendaylight.restconf.nb.rfc8040.handlers.TransactionChainHandler;
-import org.opendaylight.restconf.nb.rfc8040.references.SchemaContextRef;
+import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
 import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.RpcError;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
 
+@RunWith(MockitoJUnitRunner.StrictStubs.class)
 public class RestconfInvokeOperationsServiceImplTest {
-
     private static final String PATH_FOR_NEW_SCHEMA_CONTEXT = "/invoke-rpc";
 
-    private RestconfInvokeOperationsServiceImpl invokeOperationsService;
-
-    @Mock
-    private RpcServiceHandler rpcServiceHandler;
+    private static final QName RPC = QName.create("ns", "2015-02-28", "test-rpc");
+    private static final ContainerNode INPUT = Builders.containerBuilder()
+        .withNodeIdentifier(new NodeIdentifier(QName.create(RPC, "input")))
+        .withChild(ImmutableNodes.leafNode(QName.create(RPC, "content"), "test"))
+        .build();
+    private static final ContainerNode OUTPUT = Builders.containerBuilder()
+        .withNodeIdentifier(new NodeIdentifier(QName.create(RPC, "output")))
+        .withChild(ImmutableNodes.leafNode(QName.create(RPC, "content"), "operation result"))
+        .build();
 
     @Mock
     private DOMRpcService rpcService;
+    @Mock
+    private DOMMountPoint mountPoint;
+    private RestconfInvokeOperationsServiceImpl invokeOperationsService;
 
     @Before
     public void setup() throws Exception {
-        MockitoAnnotations.initMocks(this);
-        final SchemaContextRef contextRef = new SchemaContextRef(
-                YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT)));
-        final TransactionChainHandler txHandler = mock(TransactionChainHandler.class);
-        final DOMTransactionChain domTx = mock(DOMTransactionChain.class);
-        when(txHandler.get()).thenReturn(domTx);
+        final EffectiveModelContext contextRef =
+                YangParserTestUtils.parseYangFiles(TestRestconfUtils.loadFiles(PATH_FOR_NEW_SCHEMA_CONTEXT));
+        final DOMDataBroker dataBroker = mock(DOMDataBroker.class);
         final DOMDataTreeWriteTransaction wTx = mock(DOMDataTreeWriteTransaction.class);
-        when(domTx.newWriteOnlyTransaction()).thenReturn(wTx);
+        doReturn(wTx).when(dataBroker).newWriteOnlyTransaction();
         doReturn(CommitInfo.emptyFluentFuture()).when(wTx).commit();
-        final SchemaContextHandler schemaContextHandler = SchemaContextHandler.newInstance(txHandler,
+        final SchemaContextHandler schemaContextHandler = new SchemaContextHandler(dataBroker,
             mock(DOMSchemaService.class));
-        schemaContextHandler.onModelContextUpdated(contextRef.get());
-        this.invokeOperationsService =
-                new RestconfInvokeOperationsServiceImpl(this.rpcServiceHandler, schemaContextHandler);
-        when(this.rpcServiceHandler.get()).thenReturn(this.rpcService);
+        schemaContextHandler.onModelContextUpdated(contextRef);
+        invokeOperationsService =
+                new RestconfInvokeOperationsServiceImpl(rpcService, schemaContextHandler);
     }
 
     @Test
     public void testInvokeRpcWithNonEmptyOutput() {
-        final String identifier = "invoke-rpc-module:rpcTest";
         final ContainerNode result = mock(ContainerNode.class);
-        final LeafNode outputChild = mock(LeafNode.class);
-        when(result.getValue()).thenReturn(Collections.singleton(outputChild));
+        doReturn(false).when(result).isEmpty();
 
-        final NormalizedNodeContext payload = prepNNC(result);
-        final UriInfo uriInfo = mock(UriInfo.class);
+        final AsyncResponse ar = mock(AsyncResponse.class);
+        final ArgumentCaptor<NormalizedNodePayload> response = ArgumentCaptor.forClass(NormalizedNodePayload.class);
+        invokeOperationsService.invokeRpc("invoke-rpc-module:rpcTest", prepNNC(result), mock(UriInfo.class), ar);
+        verify(ar).resume(response.capture());
 
-        final NormalizedNodeContext rpc = this.invokeOperationsService.invokeRpc(identifier, payload, uriInfo);
-        assertEquals(result, rpc.getData());
+        assertSame(result, response.getValue().getData());
     }
 
     @Test
     public void testInvokeRpcWithEmptyOutput() {
-        final String identifier = "invoke-rpc-module:rpcTest";
         final ContainerNode result = mock(ContainerNode.class);
+        doReturn(true).when(result).isEmpty();
+
+        final AsyncResponse ar = mock(AsyncResponse.class);
+        final ArgumentCaptor<Throwable> response = ArgumentCaptor.forClass(Throwable.class);
+        invokeOperationsService.invokeRpc("invoke-rpc-module:rpcTest", prepNNC(result), mock(UriInfo.class), ar);
+        verify(ar).resume(response.capture());
+
+        final Throwable failure = response.getValue();
+        assertThat(failure, instanceOf(WebApplicationException.class));
+        assertEquals(Status.NO_CONTENT.getStatusCode(), ((WebApplicationException) failure).getResponse().getStatus());
+    }
+
+    @Test
+    public void invokeRpcTest() throws InterruptedException, ExecutionException {
+        final DOMRpcResult mockResult = new DefaultDOMRpcResult(OUTPUT, List.of());
+        doReturn(immediateFluentFuture(mockResult)).when(rpcService).invokeRpc(RPC, INPUT);
+        final DOMRpcResult rpcResult = RestconfInvokeOperationsServiceImpl.invokeRpc(INPUT, RPC, rpcService).get();
+        assertTrue(rpcResult.getErrors().isEmpty());
+        assertEquals(OUTPUT, rpcResult.getResult());
+    }
+
+    @Test
+    public void invokeRpcErrorsAndCheckTestTest() throws InterruptedException, ExecutionException {
+        final QName errorRpc = QName.create(RPC, "error-rpc");
+        final DOMRpcException exception = new DOMRpcImplementationNotAvailableException(
+                "No implementation of RPC " + errorRpc + " available.");
+        doReturn(immediateFailedFluentFuture(exception)).when(rpcService).invokeRpc(errorRpc, INPUT);
+        final DOMRpcResult rpcResult = RestconfInvokeOperationsServiceImpl.invokeRpc(INPUT, errorRpc, rpcService).get();
+        assertNull(rpcResult.getResult());
+        final Collection<? extends RpcError> errorList = rpcResult.getErrors();
+        assertEquals(1, errorList.size());
+        final RpcError actual = errorList.iterator().next();
+        assertEquals("No implementation of RPC " + errorRpc + " available.", actual.getMessage());
+        assertEquals("operation-failed", actual.getTag());
+        assertEquals(RpcError.ErrorType.RPC, actual.getErrorType());
+    }
 
-        final NormalizedNodeContext payload = prepNNC(result);
-        final UriInfo uriInfo = mock(UriInfo.class);
+    @Test
+    public void invokeRpcViaMountPointTest() throws InterruptedException, ExecutionException {
+        doReturn(Optional.ofNullable(rpcService)).when(mountPoint).getService(DOMRpcService.class);
+        final DOMRpcResult mockResult = new DefaultDOMRpcResult(OUTPUT, List.of());
+        doReturn(immediateFluentFuture(mockResult)).when(rpcService).invokeRpc(RPC, INPUT);
+        final DOMRpcResult rpcResult = RestconfInvokeOperationsServiceImpl.invokeRpc(INPUT, RPC, mountPoint).get();
+        assertTrue(rpcResult.getErrors().isEmpty());
+        assertEquals(OUTPUT, rpcResult.getResult());
+    }
 
-        WebApplicationException exceptionToBeThrown = null;
-        try {
-            this.invokeOperationsService.invokeRpc(identifier, payload, uriInfo);
-        } catch (final WebApplicationException exception) {
-            exceptionToBeThrown = exception;
+    @Test
+    public void invokeRpcMissingMountPointServiceTest() {
+        doReturn(Optional.empty()).when(mountPoint).getService(DOMRpcService.class);
+        assertThrows(RestconfDocumentedException.class,
+            () -> RestconfInvokeOperationsServiceImpl.invokeRpc(INPUT, RPC, mountPoint));
+    }
 
-        }
-        Assert.assertNotNull("WebApplicationException with status code 204 is expected.", exceptionToBeThrown);
-        Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), exceptionToBeThrown.getResponse().getStatus());
+    @Test
+    public void checkResponseTest() throws InterruptedException, ExecutionException {
+        doReturn(immediateFluentFuture(new DefaultDOMRpcResult(OUTPUT, List.of())))
+            .when(rpcService).invokeRpc(RPC, INPUT);
+        final DOMRpcResult rpcResult = RestconfInvokeOperationsServiceImpl.invokeRpc(INPUT, RPC, rpcService).get();
+        assertTrue(rpcResult.getErrors().isEmpty());
+        assertEquals(OUTPUT, rpcResult.getResult());
     }
 
-    private NormalizedNodeContext prepNNC(final NormalizedNode<?, ?> result) {
-        final InstanceIdentifierContext<?> context = mock(InstanceIdentifierContext.class);
+    private NormalizedNodePayload prepNNC(final NormalizedNode result) {
+        final InstanceIdentifierContext context = mock(InstanceIdentifierContext.class);
         final RpcDefinition schemaNode = mock(RpcDefinition.class);
         final QName qname = QName.create("invoke:rpc:module", "2013-12-03", "rpcTest");
-        final SchemaPath schemaPath = SchemaPath.create(true, qname);
-        when(schemaNode.getPath()).thenReturn(schemaPath);
-        when(schemaNode.getQName()).thenReturn(qname);
+        doReturn(qname).when(schemaNode).getQName();
         doReturn(schemaNode).when(context).getSchemaNode();
-        final NormalizedNode<?, ?> data = mock(NormalizedNode.class);
+        final NormalizedNode data = mock(NormalizedNode.class);
         final DOMRpcResult domRpcResult = mock(DOMRpcResult.class);
-        doReturn(immediateFluentFuture(domRpcResult)).when(this.rpcService).invokeRpc(schemaPath, data);
+        doReturn(immediateFluentFuture(domRpcResult)).when(rpcService).invokeRpc(qname, data);
         doReturn(result).when(domRpcResult).getResult();
-        return new NormalizedNodeContext(context, data);
+        return NormalizedNodePayload.of(context, data);
     }
 }