aboutsummaryrefslogtreecommitdiffstats
path: root/sdnr/wt/netconfnode-state-service/provider/src/test/java/org/onap/ccsdk/features/sdnr/wt/netconfnodestateservice/test/TestNetconfNodeStateService.java
blob: ee1f721588c810d5d2c00003b8129b0f50d7fbca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
/*
 * ============LICENSE_START=======================================================
 * ONAP : ccsdk features
 * ================================================================================
 * Copyright (C) 2020 highstreet technologies GmbH Intellectual Property.
 * All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */
package org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.test;

import com.google.common.util.concurrent.ListenableFuture;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.ExecutionException;
import org.eclipse.jdt.annotation.NonNull;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.IEntityDataProvider;
import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.NetconfAccessor;
import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.NetconfNodeConnectListener;
import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.NetconfNodeStateListener;
import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.VesNotificationListener;
import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.impl.NetconfNodeStateServiceImpl;
import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.impl.rpc.NetconfnodeStateServiceRpcApiImpl;
import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.test.example.ExampleConfig;
import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.test.example.TestNetconfHelper;
import org.opendaylight.mdsal.binding.api.ClusteredDataTreeChangeListener;
import org.opendaylight.mdsal.binding.api.DataBroker;
import org.opendaylight.mdsal.binding.api.DataObjectModification;
import org.opendaylight.mdsal.binding.api.DataObjectModification.ModificationType;
import org.opendaylight.mdsal.binding.api.DataTreeChangeListener;
import org.opendaylight.mdsal.binding.api.DataTreeModification;
import org.opendaylight.mdsal.binding.api.MountPointService;
import org.opendaylight.mdsal.binding.api.NotificationPublishService;
import org.opendaylight.mdsal.binding.api.RpcProviderService;
import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
import org.opendaylight.mdsal.binding.dom.codec.impl.BindingCodecContext;
import org.opendaylight.mdsal.binding.runtime.spi.BindingRuntimeHelpers;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev221225.ConnectionOper.ConnectionStatus;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev221225.NetconfNode;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev221225.NetconfNodeBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconfnode.state.rev191011.AttributeChangeNotification;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconfnode.state.rev191011.AttributeChangeNotificationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconfnode.state.rev191011.FaultNotification;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconfnode.state.rev191011.FaultNotificationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconfnode.state.rev191011.GetStatusInputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconfnode.state.rev191011.GetStatusOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconfnode.state.rev191011.GetStatusOutputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconfnode.state.rev191011.PushAttributeChangeNotificationInputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconfnode.state.rev191011.PushAttributeChangeNotificationOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconfnode.state.rev191011.PushFaultNotificationInputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconfnode.state.rev191011.PushFaultNotificationOutput;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.parser.api.YangParserException;
import org.opendaylight.yangtools.yang.parser.api.YangParserFactory;
import org.opendaylight.yangtools.yang.parser.impl.DefaultYangParserFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class TestNetconfNodeStateService extends Mockito {

    private static Path KARAF_ETC = Paths.get("etc");
    private static NetconfNodeStateServiceImpl netconfStateService;
    //private static DataBrokerNetconfMock dataBrokerNetconf;
    private static DataBroker dataBrokerNetconf;
    private @NonNull static DataTreeChangeListener<Node> listener;
    private @NonNull static ClusteredDataTreeChangeListener<Node> listenerClustered;


    private static final Logger LOG = LoggerFactory.getLogger(TestNetconfNodeStateService.class);

    @SuppressWarnings("unchecked")
    @BeforeClass
    public static <T extends DataObject, L extends DataTreeChangeListener<T>> void before()
            throws InterruptedException, IOException {

        System.out.println("Logger: " + LOG.getClass().getName() + " " + LOG.getName());
        // Call System property to get the classpath value
        Path etc = KARAF_ETC;
        delete(etc);

        System.out.println("Create empty:" + etc.toString());
        Files.createDirectories(etc);

        // Create mocks
        //dataBrokerNetconf = new DataBrokerNetconfMock();
        //dataBrokerNetconf.newReadWriteTransaction();
        dataBrokerNetconf = mock(DataBroker.class);
        when(dataBrokerNetconf.registerDataTreeChangeListener(any(), any())).thenAnswer(invocation -> {
            Object pListener = invocation.getArguments()[1];
            System.out.println("Register " + pListener.getClass().getName());
            if (pListener instanceof ClusteredDataTreeChangeListener) {
                System.out.println("Clustered listener");
                listenerClustered = (ClusteredDataTreeChangeListener<Node>) pListener;
            } else if (pListener instanceof DataTreeChangeListener) {
                System.out.println("Listener");
                listener = (DataTreeChangeListener<Node>) pListener;
            }
            return new ListenerRegistration<L>() {
                @Override
                public L getInstance() {
                    return (L) pListener;
                }

                @Override
                public void close() {}
            };

        });
        ClusterSingletonServiceProvider clusterSingletonService = mock(ClusterSingletonServiceProvider.class);
        MountPointService mountPointService = mock(MountPointService.class);
        NotificationPublishService notificationPublishService = mock(NotificationPublishService.class);
        RpcProviderService rpcProviderRegistry = mock(RpcProviderService.class);
        IEntityDataProvider entityProviderMock = mock(IEntityDataProvider.class);
        YangParserFactory yangParserFactory = new DefaultYangParserFactory();
        BindingNormalizedNodeSerializer bindingNormalizedNodeSerializer =
                new BindingCodecContext(BindingRuntimeHelpers.createRuntimeContext());
        // start using blueprint interface
        netconfStateService = new NetconfNodeStateServiceImpl();

        netconfStateService.setDataBroker(dataBrokerNetconf);
        netconfStateService.setMountPointService(mountPointService);
        netconfStateService.setNotificationPublishService(notificationPublishService);
        netconfStateService.setRpcProviderRegistry(rpcProviderRegistry);
        netconfStateService.setClusterSingletonService(clusterSingletonService);
        netconfStateService.setEntityDataProvider(entityProviderMock);
        netconfStateService.setYangParserFactory(yangParserFactory);
        netconfStateService.setBindingNormalizedNodeSerializer(bindingNormalizedNodeSerializer);
        netconfStateService.init();
        System.out.println("Initialization done");
    }

    @AfterClass
    public static void after() throws InterruptedException, IOException {
        System.out.println("Start shutdown");
        // close using blueprint interface
        if(netconfStateService!=null) {
        	netconfStateService.close();
        }
        delete(KARAF_ETC);

    }

    @Test
    public void test1() {

        System.out.println("Test1: Verify init state");
        assertTrue("Devicemanager not initialized", netconfStateService.isInitializationSuccessful());
    }


    @Test
    public void test2() {

        System.out.println("Test2: Register state listener");

        NetconfNodeStateListener nSL = mock(NetconfNodeStateListener.class);
        ListenerRegistration<NetconfNodeStateListener> res = netconfStateService.registerNetconfNodeStateListener(nSL);
        assertNotNull("Result should be null", res);
        res.getInstance();
        res.close();
    }

    @Test
    public void test3() {

        System.out.println("Test3: Register connect listener");

        NetconfNodeConnectListener nCL = mock(NetconfNodeConnectListener.class);
        ListenerRegistration<NetconfNodeConnectListener> res =
                netconfStateService.registerNetconfNodeConnectListener(nCL);
        assertNotNull("Result should be null", res);
        res.getInstance();
        res.close();
    }

    @Test
    public void test4() {
        System.out.println("Test4: Get status listener");
        GetStatusInputBuilder inputBuilder = new GetStatusInputBuilder();
        GetStatusOutputBuilder res = netconfStateService.getStatus(inputBuilder.build());
        assertNotNull("Result should be null", res);
    }

    @SuppressWarnings("unchecked")
    @Test
    public void test5OnConnect() throws InterruptedException {
        System.out.println("Test5: On Connect");
        String nodeIdString = "Test";
        String capabilityStringForNetworkElement = "network-element";
        NodeId nodeId = new NodeId(nodeIdString);
        Node rootNode = TestNetconfHelper.getTestNode(nodeId, capabilityStringForNetworkElement);

        DataObjectModification<Node> dom = mock(DataObjectModification.class);
        when(dom.getDataAfter()).thenReturn(rootNode);
        when(dom.getModificationType()).thenReturn(ModificationType.WRITE);

        DataTreeModification<Node> ntn = mock(DataTreeModification.class);
        when(ntn.getRootNode()).thenReturn(dom);

        NetconfNodeConnectListener nCL = mock(NetconfNodeConnectListener.class);
        netconfStateService.registerNetconfNodeConnectListener(nCL);

        Collection<DataTreeModification<Node>> changes = Arrays.asList(ntn);
        sendClusteredChanges(changes);
        sendChanges(changes);
        Thread.sleep(300);
        //verify that it was called one time and nodeId is the expected
        ArgumentCaptor<NetconfAccessor> varArgs = ArgumentCaptor.forClass(NetconfAccessor.class);
        verify(nCL).onEnterConnected(varArgs.capture());
        NetconfAccessor accessor = varArgs.getValue();
        System.out.println("Accessor " + accessor.getNodeId());
        assertEquals(nodeIdString, accessor.getNodeId().getValue());
    }

    @SuppressWarnings("unchecked")
    @Test
    public void test6Update() {
        System.out.println("Test6: OnChange");
        NetconfNodeBuilder netconfNodeBuilder = new NetconfNodeBuilder();
        netconfNodeBuilder.setConnectionStatus(ConnectionStatus.Connected);
        NetconfNode rootNodeNetconf = netconfNodeBuilder.build();

        NodeBuilder nodeBuilder = new NodeBuilder();
        nodeBuilder.addAugmentation(rootNodeNetconf);
        nodeBuilder.setNodeId(new NodeId("Test"));
        Node rootNodeAfter = nodeBuilder.build();

        DataObjectModification<Node> dom = mock(DataObjectModification.class);
        when(dom.getDataBefore()).thenReturn(rootNodeAfter);
        when(dom.getDataAfter()).thenReturn(rootNodeAfter);
        when(dom.getModificationType()).thenReturn(ModificationType.WRITE);

        DataTreeModification<Node> ntn = mock(DataTreeModification.class);
        when(ntn.getRootNode()).thenReturn(dom);

        Collection<DataTreeModification<Node>> changes = Arrays.asList(ntn);
        sendClusteredChanges(changes);
        sendChanges(changes);
    }

    @Test
    public void test7ApiStatus() throws InterruptedException, ExecutionException {

        NetconfnodeStateServiceRpcApiImpl api = netconfStateService.getNetconfnodeStateServiceRpcApiImpl();

        GetStatusInputBuilder statusInput = new GetStatusInputBuilder();
        ListenableFuture<RpcResult<GetStatusOutput>> statusOutput = api.getStatus(statusInput.build());
        RpcResult<GetStatusOutput> res = statusOutput.get();
        GetStatusOutput output = res.getResult();
        System.out.println("Output " + output);
    }


    @Test
    public void test8ApiPushFault() throws InterruptedException, ExecutionException {

        NetconfnodeStateServiceRpcApiImpl api = netconfStateService.getNetconfnodeStateServiceRpcApiImpl();

        VesNotificationListener vNL = mock(VesNotificationListener.class);
        ListenerRegistration<VesNotificationListener> registration = netconfStateService.registerVesNotifications(vNL);

        FaultNotificationBuilder faultBuilder = new FaultNotificationBuilder();
        faultBuilder.setProblem("problem1");
        FaultNotification fault = faultBuilder.build();
        PushFaultNotificationInputBuilder statusInput = new PushFaultNotificationInputBuilder();
        statusInput.fieldsFrom(fault);
        ListenableFuture<RpcResult<PushFaultNotificationOutput>> rpcOutput =
                api.pushFaultNotification(statusInput.build());
        RpcResult<PushFaultNotificationOutput> res = rpcOutput.get();
        PushFaultNotificationOutput output = res.getResult();

        //verify that it was called one time
        verify(vNL, times(1)).onNotification(fault);

        registration.close();
        System.out.println("Output " + output);
    }

    @Test
    public void test9ApiPushNotifiction() throws InterruptedException, ExecutionException {

        NetconfnodeStateServiceRpcApiImpl api = netconfStateService.getNetconfnodeStateServiceRpcApiImpl();

        VesNotificationListener vNL = mock(VesNotificationListener.class);
        ListenerRegistration<VesNotificationListener> registration = netconfStateService.registerVesNotifications(vNL);

        AttributeChangeNotificationBuilder changeBuilder = new AttributeChangeNotificationBuilder();
        changeBuilder.setAttributeName("attribute1");
        AttributeChangeNotification change = changeBuilder.build();
        PushAttributeChangeNotificationInputBuilder statusInput = new PushAttributeChangeNotificationInputBuilder();
        statusInput.fieldsFrom(change);
        ListenableFuture<RpcResult<PushAttributeChangeNotificationOutput>> rpcOutput =
                api.pushAttributeChangeNotification(statusInput.build());
        RpcResult<PushAttributeChangeNotificationOutput> res = rpcOutput.get();
        PushAttributeChangeNotificationOutput output = res.getResult();

        //verify that it was called one time
        verify(vNL, times(1)).onNotification(change);

        registration.close();
        System.out.println("Output " + output);
    }

    @Test
    public void test10ApiPushNotifiction() throws YangParserException, IOException {
        ExampleConfig.exampleConfig(netconfStateService.getDomContext());
    }

    @Test
    public void test10NetconfAccessorClone() {

    }

    // ------- private section

    private static void delete(Path etc) throws IOException {
        if (Files.exists(etc)) {
            System.out.println("Found and remove:" + etc.toString());
            delete(etc.toFile());
        }
    }

    private static void delete(File f) throws IOException {
        if (f.isDirectory()) {
            for (File c : f.listFiles()) {
                delete(c);
            }
        }
        if (!f.delete()) {
            throw new FileNotFoundException("Failed to delete file: " + f);
        }
    }

    public void sendChanges(Collection<DataTreeModification<Node>> changes) {
        listener.onDataTreeChanged(changes);
    }

    public void sendClusteredChanges(Collection<DataTreeModification<Node>> changes) {
        listenerClustered.onDataTreeChanged(changes);
    }


}