Bug 8153: Enforce check-style rules for netconf - sal-netconf-connector
[netconf.git] / netconf / sal-netconf-connector / src / test / java / org / opendaylight / netconf / sal / connect / netconf / NetconfStateSchemasTest.java
1 /*
2  * Copyright (c) 2014, 2015 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
9 package org.opendaylight.netconf.sal.connect.netconf;
10
11 import static org.hamcrest.CoreMatchers.hasItem;
12 import static org.junit.Assert.assertEquals;
13 import static org.junit.Assert.assertThat;
14 import static org.mockito.Matchers.any;
15 import static org.mockito.Matchers.eq;
16 import static org.mockito.Mockito.mock;
17 import static org.mockito.Mockito.when;
18 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_QNAME;
19 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
20
21 import com.google.common.util.concurrent.CheckedFuture;
22 import com.google.common.util.concurrent.Futures;
23 import com.google.common.util.concurrent.ListenableFuture;
24 import java.net.InetSocketAddress;
25 import java.util.Collections;
26 import java.util.Set;
27 import java.util.concurrent.ExecutionException;
28 import java.util.concurrent.Executors;
29 import java.util.concurrent.Future;
30 import java.util.concurrent.TimeUnit;
31 import org.junit.Assert;
32 import org.junit.Before;
33 import org.junit.Test;
34 import org.mockito.Mock;
35 import org.mockito.MockitoAnnotations;
36 import org.opendaylight.controller.config.util.xml.XmlUtil;
37 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
38 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
39 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
40 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
41 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
42 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
43 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
44 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
45 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
46 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
48 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Schemas;
49 import org.opendaylight.yangtools.yang.common.QName;
50 import org.opendaylight.yangtools.yang.common.RpcError;
51 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
53 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
54 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
55 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
56 import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParser;
57 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
58 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63 import org.w3c.dom.Document;
64 import org.w3c.dom.Element;
65
66 public class NetconfStateSchemasTest {
67
68     private static final Logger LOG = LoggerFactory.getLogger(NetconfStateSchemasTest.class);
69
70     private static final NetconfSessionPreferences CAPS = NetconfSessionPreferences.fromStrings(Collections.singleton(
71         "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04"));
72     private final RemoteDeviceId deviceId = new RemoteDeviceId("device", new InetSocketAddress(99));
73     private final int numberOfSchemas = 73;
74     private final int numberOfLegalSchemas = numberOfSchemas - 3;
75     private ContainerNode compositeNodeSchemas;
76
77     @Mock
78     private DOMRpcService rpc;
79
80     @Before
81     public void setUp() throws Exception {
82         MockitoAnnotations.initMocks(this);
83         final SchemaContext schemaContext = BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext();
84         final DataSchemaNode schemasNode =
85                 ((ContainerSchemaNode) schemaContext
86                         .getDataChildByName(NetconfState.QNAME)).getDataChildByName(Schemas.QNAME);
87         final Document schemasXml =
88                 XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/netconf-state.schemas.payload.xml"));
89         final ToNormalizedNodeParser<Element, ContainerNode, ContainerSchemaNode> containerNodeParser =
90                 DomToNormalizedNodeParserFactory
91                     .getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, false).getContainerNodeParser();
92         compositeNodeSchemas = containerNodeParser
93                 .parse(Collections.singleton(schemasXml.getDocumentElement()), (ContainerSchemaNode) schemasNode);
94
95     }
96
97     @Test
98     public void testCreate() throws Exception {
99         final NetconfStateSchemas schemas = NetconfStateSchemas.create(deviceId, compositeNodeSchemas);
100
101         final Set<QName> availableYangSchemasQNames = schemas.getAvailableYangSchemasQNames();
102         assertEquals(numberOfLegalSchemas, availableYangSchemasQNames.size());
103
104         assertThat(availableYangSchemasQNames,
105                 hasItem(QName.create("urn:TBD:params:xml:ns:yang:network-topology", "2013-07-12", "network-topology")));
106     }
107
108     @Test
109     public void testCreate2() throws Exception {
110         final ContainerNode netconfState = Builders.containerBuilder()
111                 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfState.QNAME))
112                 .withChild(compositeNodeSchemas)
113                 .build();
114         final ContainerNode data = Builders.containerBuilder()
115                 .withNodeIdentifier(new YangInstanceIdentifier
116                         .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME))
117                 .withChild(netconfState)
118                 .build();
119         final ContainerNode rpcReply = Builders.containerBuilder()
120                 .withNodeIdentifier(new YangInstanceIdentifier
121                         .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
122                 .withChild(data)
123                 .build();
124         when(rpc.invokeRpc(eq(toPath(NETCONF_GET_QNAME)), any()))
125                 .thenReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(rpcReply)));
126         final NetconfStateSchemas stateSchemas = NetconfStateSchemas.create(rpc, CAPS, deviceId);
127         final Set<QName> availableYangSchemasQNames = stateSchemas.getAvailableYangSchemasQNames();
128         assertEquals(numberOfLegalSchemas, availableYangSchemasQNames.size());
129
130         assertThat(availableYangSchemasQNames,
131                 hasItem(QName.create("urn:TBD:params:xml:ns:yang:network-topology", "2013-07-12", "network-topology")));
132     }
133
134     @Test
135     public void testCreateMonitoringNotSupported() throws Exception {
136         final NetconfSessionPreferences caps = NetconfSessionPreferences.fromStrings(Collections.emptySet());
137         final NetconfStateSchemas stateSchemas = NetconfStateSchemas.create(rpc, caps, deviceId);
138         final Set<QName> availableYangSchemasQNames = stateSchemas.getAvailableYangSchemasQNames();
139         Assert.assertTrue(availableYangSchemasQNames.isEmpty());
140     }
141
142     @Test
143     public void testCreateFail() throws Exception {
144         final CheckedFuture<DOMRpcResult, DOMRpcException> resultFuture =
145                 Futures.immediateFailedCheckedFuture(new DOMRpcImplementationNotAvailableException("not available"));
146         when(rpc.invokeRpc(eq(toPath(NETCONF_GET_QNAME)), any())).thenReturn(resultFuture);
147         final NetconfStateSchemas stateSchemas = NetconfStateSchemas.create(rpc, CAPS, deviceId);
148         final Set<QName> availableYangSchemasQNames = stateSchemas.getAvailableYangSchemasQNames();
149         Assert.assertTrue(availableYangSchemasQNames.isEmpty());
150     }
151
152     @Test
153     public void testCreateRpcError() throws Exception {
154         final RpcError rpcError = RpcResultBuilder.newError(RpcError.ErrorType.RPC, "fail", "fail");
155         when(rpc.invokeRpc(eq(toPath(NETCONF_GET_QNAME)), any()))
156                 .thenReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(rpcError)));
157         final NetconfStateSchemas stateSchemas = NetconfStateSchemas.create(rpc, CAPS, deviceId);
158         final Set<QName> availableYangSchemasQNames = stateSchemas.getAvailableYangSchemasQNames();
159         Assert.assertTrue(availableYangSchemasQNames.isEmpty());
160     }
161
162     @SuppressWarnings("checkstyle:IllegalThrows")
163     @Test(expected = RuntimeException.class)
164     public void testCreateInterrupted() throws Throwable {
165         //NetconfStateSchemas.create calls Thread.currentThread().interrupt(), so it must run in its own thread
166         final Future<?> testFuture = Executors.newSingleThreadExecutor().submit(() -> {
167             final ListenableFuture interruptedFuture = mock(ListenableFuture.class);
168             try {
169                 when(interruptedFuture.get()).thenThrow(new InterruptedException("interrupted"));
170                 final CheckedFuture checkedFuture = Futures.makeChecked(interruptedFuture, ReadFailedException.MAPPER);
171                 when(rpc.invokeRpc(eq(toPath(NETCONF_GET_QNAME)), any())).thenReturn(checkedFuture);
172                 NetconfStateSchemas.create(rpc, CAPS, deviceId);
173             } catch (final InterruptedException | ExecutionException e) {
174                 LOG.info("Operation failed.", e);
175             }
176
177         });
178         try {
179             testFuture.get(3, TimeUnit.SECONDS);
180         } catch (final ExecutionException e) {
181             throw e.getCause();
182         }
183     }
184
185     @Test
186     public void testRemoteYangSchemaEquals() throws Exception {
187         final NetconfStateSchemas.RemoteYangSchema schema1 =
188                 new NetconfStateSchemas.RemoteYangSchema(NetconfState.QNAME);
189         final NetconfStateSchemas.RemoteYangSchema schema2 =
190                 new NetconfStateSchemas.RemoteYangSchema(NetconfState.QNAME);
191         final NetconfStateSchemas.RemoteYangSchema schema3 =
192                 new NetconfStateSchemas.RemoteYangSchema(Schemas.QNAME);
193         Assert.assertEquals(schema1, schema2);
194         Assert.assertEquals(schema2, schema1);
195         Assert.assertNotEquals(schema1, schema3);
196         Assert.assertNotEquals(schema2, schema3);
197
198     }
199 }