145140011e7e61c52724f4fb746fd78d9003c303
[netconf.git] / netconf / netconf-topology-singleton / src / test / java / org / opendaylight / netconf / topology / singleton / impl / NetconfNodeActorTest.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.netconf.topology.singleton.impl;
9
10 import static java.nio.charset.StandardCharsets.UTF_8;
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertNull;
13 import static org.junit.Assert.assertTrue;
14 import static org.mockito.ArgumentMatchers.any;
15 import static org.mockito.ArgumentMatchers.anyCollection;
16 import static org.mockito.ArgumentMatchers.argThat;
17 import static org.mockito.ArgumentMatchers.eq;
18 import static org.mockito.Mockito.after;
19 import static org.mockito.Mockito.doAnswer;
20 import static org.mockito.Mockito.doNothing;
21 import static org.mockito.Mockito.doReturn;
22 import static org.mockito.Mockito.mock;
23 import static org.mockito.Mockito.reset;
24 import static org.mockito.Mockito.timeout;
25 import static org.mockito.Mockito.times;
26 import static org.mockito.Mockito.verify;
27 import static org.mockito.Mockito.verifyNoMoreInteractions;
28 import static org.mockito.MockitoAnnotations.initMocks;
29
30 import akka.actor.ActorRef;
31 import akka.actor.ActorSystem;
32 import akka.actor.Props;
33 import akka.actor.Status.Failure;
34 import akka.actor.Status.Success;
35 import akka.pattern.AskTimeoutException;
36 import akka.pattern.Patterns;
37 import akka.testkit.TestActorRef;
38 import akka.testkit.javadsl.TestKit;
39 import akka.util.Timeout;
40 import com.google.common.collect.ImmutableList;
41 import com.google.common.collect.Lists;
42 import com.google.common.io.ByteSource;
43 import com.google.common.net.InetAddresses;
44 import com.google.common.util.concurrent.Futures;
45 import com.google.common.util.concurrent.SettableFuture;
46 import java.io.InputStream;
47 import java.net.InetSocketAddress;
48 import java.util.ArrayList;
49 import java.util.Collections;
50 import java.util.List;
51 import java.util.Scanner;
52 import java.util.concurrent.ExecutionException;
53 import java.util.concurrent.TimeUnit;
54 import org.junit.After;
55 import org.junit.Before;
56 import org.junit.Rule;
57 import org.junit.Test;
58 import org.junit.rules.ExpectedException;
59 import org.mockito.ArgumentCaptor;
60 import org.mockito.Mock;
61 import org.opendaylight.controller.cluster.schema.provider.impl.YangTextSchemaSourceSerializationProxy;
62 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
63 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
64 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
65 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
66 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
67 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
68 import org.opendaylight.mdsal.dom.api.DOMNotificationService;
69 import org.opendaylight.mdsal.dom.api.DOMRpcException;
70 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
71 import org.opendaylight.mdsal.dom.api.DOMRpcService;
72 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
73 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
74 import org.opendaylight.netconf.topology.singleton.impl.actors.NetconfNodeActor;
75 import org.opendaylight.netconf.topology.singleton.impl.utils.ClusteringRpcException;
76 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
77 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup.NetconfTopologySetupBuilder;
78 import org.opendaylight.netconf.topology.singleton.messages.AskForMasterMountPoint;
79 import org.opendaylight.netconf.topology.singleton.messages.CreateInitialMasterActorData;
80 import org.opendaylight.netconf.topology.singleton.messages.MasterActorDataInitialized;
81 import org.opendaylight.netconf.topology.singleton.messages.NotMasterException;
82 import org.opendaylight.netconf.topology.singleton.messages.RefreshSetupMasterActorData;
83 import org.opendaylight.netconf.topology.singleton.messages.RegisterMountPoint;
84 import org.opendaylight.netconf.topology.singleton.messages.UnregisterSlaveMountPoint;
85 import org.opendaylight.yangtools.concepts.ObjectRegistration;
86 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
87 import org.opendaylight.yangtools.yang.common.QName;
88 import org.opendaylight.yangtools.yang.common.RpcError;
89 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
90 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
91 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
92 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
93 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
94 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
95 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
96 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
97 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
98 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
99 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
100 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
101 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
102 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
103 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
104 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
105 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
106 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
107 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
108 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToASTTransformer;
109 import scala.concurrent.Await;
110 import scala.concurrent.Future;
111 import scala.concurrent.duration.Duration;
112
113 public class NetconfNodeActorTest {
114
115     private static final Timeout TIMEOUT = new Timeout(Duration.create(5, "seconds"));
116     private static final RevisionSourceIdentifier SOURCE_IDENTIFIER1 = RevisionSourceIdentifier.create("yang1");
117     private static final RevisionSourceIdentifier SOURCE_IDENTIFIER2 = RevisionSourceIdentifier.create("yang2");
118
119     private ActorSystem system = ActorSystem.create();
120     private final TestKit testKit = new TestKit(system);
121
122     @Rule
123     public final ExpectedException exception = ExpectedException.none();
124
125     private ActorRef masterRef;
126     private RemoteDeviceId remoteDeviceId;
127     private final SharedSchemaRepository masterSchemaRepository = new SharedSchemaRepository("master");
128
129     @Mock
130     private DOMRpcService mockDOMRpcService;
131
132     @Mock
133     private DOMMountPointService mockMountPointService;
134
135     @Mock
136     private DOMMountPointService.DOMMountPointBuilder mockMountPointBuilder;
137
138     @Mock
139     private ObjectRegistration<DOMMountPoint> mockMountPointReg;
140
141     @Mock
142     private DOMDataBroker mockDOMDataBroker;
143
144     @Mock
145     private SchemaSourceRegistration<?> mockSchemaSourceReg1;
146
147     @Mock
148     private SchemaSourceRegistration<?> mockSchemaSourceReg2;
149
150     @Mock
151     private SchemaSourceRegistry mockRegistry;
152
153     @Mock
154     private EffectiveModelContextFactory mockSchemaContextFactory;
155
156     @Mock
157     private SchemaRepository mockSchemaRepository;
158
159     @Mock
160     private EffectiveModelContext mockSchemaContext;
161
162     @Before
163     public void setup() {
164         initMocks(this);
165
166         remoteDeviceId = new RemoteDeviceId("netconf-topology",
167                 new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9999));
168
169         masterSchemaRepository.registerSchemaSourceListener(
170                 TextToASTTransformer.create(masterSchemaRepository, masterSchemaRepository));
171
172         final NetconfTopologySetup setup = NetconfTopologySetupBuilder.create().setActorSystem(system)
173                 .setIdleTimeout(Duration.apply(1, TimeUnit.SECONDS)).build();
174
175         final Props props = NetconfNodeActor.props(setup, remoteDeviceId, masterSchemaRepository,
176                 masterSchemaRepository, TIMEOUT, mockMountPointService);
177
178         masterRef = TestActorRef.create(system, props, "master_messages");
179
180         resetMountPointMocks();
181
182         doReturn(mockMountPointBuilder).when(mockMountPointService).createMountPoint(any());
183
184         doReturn(mockSchemaSourceReg1).when(mockRegistry).registerSchemaSource(any(), withSourceId(SOURCE_IDENTIFIER1));
185         doReturn(mockSchemaSourceReg2).when(mockRegistry).registerSchemaSource(any(), withSourceId(SOURCE_IDENTIFIER2));
186
187         doReturn(mockSchemaContextFactory).when(mockSchemaRepository)
188                 .createEffectiveModelContextFactory();
189     }
190
191     @After
192     public void teardown() {
193         TestKit.shutdownActorSystem(system, true);
194         system = null;
195     }
196
197     @Test
198     public void testInitializeAndRefreshMasterData() {
199
200         // Test CreateInitialMasterActorData.
201
202         initializeMaster(new ArrayList<>());
203
204         // Test RefreshSetupMasterActorData.
205
206         final RemoteDeviceId newRemoteDeviceId = new RemoteDeviceId("netconf-topology2",
207                 new InetSocketAddress(InetAddresses.forString("127.0.0.2"), 9999));
208
209         final NetconfTopologySetup newSetup = NetconfTopologySetupBuilder.create().setActorSystem(system).build();
210
211         masterRef.tell(new RefreshSetupMasterActorData(newSetup, newRemoteDeviceId), testKit.getRef());
212
213         testKit.expectMsgClass(MasterActorDataInitialized.class);
214     }
215
216     @Test
217     public void tesAskForMasterMountPoint() {
218
219         // Test with master not setup yet.
220
221         final TestKit kit = new TestKit(system);
222
223         masterRef.tell(new AskForMasterMountPoint(kit.getRef()), kit.getRef());
224
225         final Failure failure = kit.expectMsgClass(Failure.class);
226         assertTrue(failure.cause() instanceof NotMasterException);
227
228         // Now initialize - master should send the RegisterMountPoint message.
229
230         List<SourceIdentifier> sourceIdentifiers = Lists.newArrayList(RevisionSourceIdentifier.create("testID"));
231         initializeMaster(sourceIdentifiers);
232
233         masterRef.tell(new AskForMasterMountPoint(kit.getRef()), kit.getRef());
234
235         final RegisterMountPoint registerMountPoint = kit.expectMsgClass(RegisterMountPoint.class);
236
237         assertEquals(sourceIdentifiers, registerMountPoint.getSourceIndentifiers());
238     }
239
240     @Test
241     public void testRegisterAndUnregisterMountPoint() throws Exception {
242
243         ActorRef slaveRef = registerSlaveMountPoint();
244
245         // Unregister
246
247         slaveRef.tell(new UnregisterSlaveMountPoint(), testKit.getRef());
248
249         verify(mockMountPointReg, timeout(5000)).close();
250         verify(mockSchemaSourceReg1, timeout(1000)).close();
251         verify(mockSchemaSourceReg2, timeout(1000)).close();
252
253         // Test registration with another interleaved registration that completes while the first registration
254         // is resolving the schema context.
255
256         reset(mockSchemaSourceReg1, mockRegistry, mockSchemaRepository);
257         resetMountPointMocks();
258
259         doReturn(mockSchemaSourceReg1).when(mockRegistry).registerSchemaSource(any(), withSourceId(SOURCE_IDENTIFIER1));
260
261         doReturn(mockSchemaContextFactory).when(mockSchemaRepository)
262                 .createEffectiveModelContextFactory();
263
264         final SchemaSourceRegistration<?> newMockSchemaSourceReg = mock(SchemaSourceRegistration.class);
265
266         final EffectiveModelContextFactory newMockSchemaContextFactory = mock(EffectiveModelContextFactory.class);
267         doReturn(Futures.immediateFuture(mockSchemaContext))
268                 .when(newMockSchemaContextFactory).createEffectiveModelContext(anyCollection());
269
270         doAnswer(unused -> {
271             SettableFuture<SchemaContext> future = SettableFuture.create();
272             new Thread(() -> {
273                 doReturn(newMockSchemaSourceReg).when(mockRegistry).registerSchemaSource(any(),
274                         withSourceId(SOURCE_IDENTIFIER1));
275
276                 doReturn(newMockSchemaContextFactory).when(mockSchemaRepository)
277                         .createEffectiveModelContextFactory();
278
279                 slaveRef.tell(new RegisterMountPoint(ImmutableList.of(SOURCE_IDENTIFIER1), masterRef),
280                         testKit.getRef());
281
282                 future.set(mockSchemaContext);
283             }).start();
284             return future;
285         }).when(mockSchemaContextFactory).createEffectiveModelContext(anyCollection());
286
287         doReturn(mockSchemaContextFactory).when(mockSchemaRepository)
288                 .createEffectiveModelContextFactory();
289
290         slaveRef.tell(new RegisterMountPoint(ImmutableList.of(SOURCE_IDENTIFIER1), masterRef), testKit.getRef());
291
292         verify(mockMountPointBuilder, timeout(5000)).register();
293         verify(mockMountPointBuilder, after(500)).addInitialSchemaContext(mockSchemaContext);
294         verify(mockMountPointBuilder).addService(eq(DOMDataBroker.class), any());
295         verify(mockMountPointBuilder).addService(eq(DOMRpcService.class), any());
296         verify(mockMountPointBuilder).addService(eq(DOMNotificationService.class), any());
297         verify(mockSchemaSourceReg1).close();
298         verify(mockRegistry, times(2)).registerSchemaSource(any(), withSourceId(SOURCE_IDENTIFIER1));
299         verify(mockSchemaRepository, times(2)).createEffectiveModelContextFactory();
300         verifyNoMoreInteractions(mockMountPointBuilder, newMockSchemaSourceReg);
301
302         // Stop the slave actor and verify schema source registrations are closed.
303
304         final Future<Boolean> stopFuture = Patterns.gracefulStop(slaveRef, TIMEOUT.duration());
305         Await.result(stopFuture, TIMEOUT.duration());
306
307         verify(mockMountPointReg).close();
308         verify(newMockSchemaSourceReg).close();
309     }
310
311     @SuppressWarnings("unchecked")
312     @Test
313     public void testRegisterMountPointWithSchemaFailures() throws Exception {
314         final NetconfTopologySetup setup = NetconfTopologySetupBuilder.create().setActorSystem(system).build();
315
316         final ActorRef slaveRef = system.actorOf(NetconfNodeActor.props(setup, remoteDeviceId, mockRegistry,
317                 mockSchemaRepository, TIMEOUT, mockMountPointService));
318
319         // Test unrecoverable failure.
320
321         doReturn(Futures.immediateFailedFuture(new SchemaResolutionException("mock")))
322                 .when(mockSchemaContextFactory).createEffectiveModelContext(anyCollection());
323
324         slaveRef.tell(new RegisterMountPoint(ImmutableList.of(SOURCE_IDENTIFIER1, SOURCE_IDENTIFIER2),
325                 masterRef), testKit.getRef());
326
327         testKit.expectMsgClass(Success.class);
328
329         verify(mockRegistry, timeout(5000)).registerSchemaSource(any(), withSourceId(SOURCE_IDENTIFIER1));
330         verify(mockRegistry, timeout(5000)).registerSchemaSource(any(), withSourceId(SOURCE_IDENTIFIER2));
331
332         verify(mockMountPointBuilder, after(1000).never()).register();
333         verify(mockSchemaSourceReg1, timeout(1000)).close();
334         verify(mockSchemaSourceReg2, timeout(1000)).close();
335
336         // Test recoverable AskTimeoutException - schema context resolution should be retried.
337
338         reset(mockSchemaSourceReg1, mockSchemaSourceReg2);
339
340         doReturn(Futures.immediateFailedFuture(new SchemaResolutionException("mock",
341                 new AskTimeoutException("timeout"))))
342             .doReturn(Futures.immediateFuture(mockSchemaContext))
343             .when(mockSchemaContextFactory).createEffectiveModelContext(anyCollection());
344
345         slaveRef.tell(new RegisterMountPoint(ImmutableList.of(SOURCE_IDENTIFIER1, SOURCE_IDENTIFIER2),
346                 masterRef), testKit.getRef());
347
348         testKit.expectMsgClass(Success.class);
349
350         verify(mockMountPointBuilder, timeout(5000)).register();
351         verifyNoMoreInteractions(mockSchemaSourceReg1, mockSchemaSourceReg2);
352
353         // Test AskTimeoutException with an interleaved successful registration. The first schema context resolution
354         // attempt should not be retried.
355
356         reset(mockSchemaSourceReg1, mockSchemaSourceReg2, mockSchemaRepository, mockSchemaContextFactory);
357         resetMountPointMocks();
358
359         final EffectiveModelContextFactory mockSchemaContextFactorySuccess = mock(EffectiveModelContextFactory.class);
360         doReturn(Futures.immediateFuture(mockSchemaContext))
361                 .when(mockSchemaContextFactorySuccess).createEffectiveModelContext(anyCollection());
362
363         doAnswer(unused -> {
364             SettableFuture<SchemaContext> future = SettableFuture.create();
365             new Thread(() -> {
366                 doReturn(mockSchemaContextFactorySuccess).when(mockSchemaRepository)
367                     .createEffectiveModelContextFactory();
368
369                 slaveRef.tell(new RegisterMountPoint(ImmutableList.of(SOURCE_IDENTIFIER1, SOURCE_IDENTIFIER2),
370                         masterRef), testKit.getRef());
371
372                 future.setException(new SchemaResolutionException("mock", new AskTimeoutException("timeout")));
373             }).start();
374             return future;
375         }).when(mockSchemaContextFactory).createEffectiveModelContext(anyCollection());
376
377         doReturn(mockSchemaContextFactory).when(mockSchemaRepository).createEffectiveModelContextFactory();
378
379         slaveRef.tell(new RegisterMountPoint(ImmutableList.of(SOURCE_IDENTIFIER1, SOURCE_IDENTIFIER2),
380                 masterRef), testKit.getRef());
381
382         verify(mockMountPointBuilder, timeout(5000)).register();
383         verify(mockSchemaRepository, times(2)).createEffectiveModelContextFactory();
384     }
385
386     @Test
387     public void testYangTextSchemaSourceRequest() throws Exception {
388         final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create("testID");
389
390         final ProxyYangTextSourceProvider proxyYangProvider =
391                 new ProxyYangTextSourceProvider(masterRef, system.dispatcher(), TIMEOUT);
392
393         final YangTextSchemaSource yangTextSchemaSource = YangTextSchemaSource.delegateForByteSource(sourceIdentifier,
394                 ByteSource.wrap("YANG".getBytes(UTF_8)));
395
396         // Test success.
397
398         final SchemaSourceRegistration<YangTextSchemaSource> schemaSourceReg = masterSchemaRepository
399                 .registerSchemaSource(id -> Futures.immediateFuture(yangTextSchemaSource),
400                      PotentialSchemaSource.create(sourceIdentifier, YangTextSchemaSource.class, 1));
401
402         final Future<YangTextSchemaSourceSerializationProxy> resolvedSchemaFuture =
403                 proxyYangProvider.getYangTextSchemaSource(sourceIdentifier);
404
405         final YangTextSchemaSourceSerializationProxy success = Await.result(resolvedSchemaFuture, TIMEOUT.duration());
406
407         assertEquals(sourceIdentifier, success.getRepresentation().getIdentifier());
408         assertEquals("YANG", convertStreamToString(success.getRepresentation().openStream()));
409
410         // Test missing source failure.
411
412         exception.expect(MissingSchemaSourceException.class);
413
414         schemaSourceReg.close();
415
416         final Future<YangTextSchemaSourceSerializationProxy> failedSchemaFuture =
417                 proxyYangProvider.getYangTextSchemaSource(sourceIdentifier);
418
419         Await.result(failedSchemaFuture, TIMEOUT.duration());
420     }
421
422     @Test
423     @SuppressWarnings({"checkstyle:AvoidHidingCauseException", "checkstyle:IllegalThrows"})
424     public void testSlaveInvokeRpc() throws Throwable {
425
426         final List<SourceIdentifier> sourceIdentifiers =
427                 Lists.newArrayList(RevisionSourceIdentifier.create("testID"));
428
429         initializeMaster(sourceIdentifiers);
430         registerSlaveMountPoint();
431
432         ArgumentCaptor<DOMRpcService> domRPCServiceCaptor = ArgumentCaptor.forClass(DOMRpcService.class);
433         verify(mockMountPointBuilder).addService(eq(DOMRpcService.class), domRPCServiceCaptor.capture());
434
435         final DOMRpcService slaveDomRPCService = domRPCServiceCaptor.getValue();
436         assertTrue(slaveDomRPCService instanceof ProxyDOMRpcService);
437
438         final QName testQName = QName.create("", "TestQname");
439         final SchemaPath schemaPath = SchemaPath.create(true, testQName);
440         final NormalizedNode<?, ?> outputNode = ImmutableContainerNodeBuilder.create()
441                 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(testQName))
442                 .withChild(ImmutableNodes.leafNode(testQName, "foo")).build();
443         final RpcError rpcError = RpcResultBuilder.newError(RpcError.ErrorType.RPC, null, "Rpc invocation failed.");
444
445         // RPC with no response output.
446
447         doReturn(FluentFutures.immediateNullFluentFuture()).when(mockDOMRpcService).invokeRpc(any(), any());
448
449         DOMRpcResult result = slaveDomRPCService.invokeRpc(schemaPath, outputNode).get(2, TimeUnit.SECONDS);
450
451         assertEquals(null, result);
452
453         // RPC with response output.
454
455         doReturn(FluentFutures.immediateFluentFuture(new DefaultDOMRpcResult(outputNode)))
456                 .when(mockDOMRpcService).invokeRpc(any(), any());
457
458         result = slaveDomRPCService.invokeRpc(schemaPath, outputNode).get(2, TimeUnit.SECONDS);
459
460         assertEquals(outputNode, result.getResult());
461         assertTrue(result.getErrors().isEmpty());
462
463         // RPC with response error.
464
465         doReturn(FluentFutures.immediateFluentFuture(new DefaultDOMRpcResult(rpcError)))
466                 .when(mockDOMRpcService).invokeRpc(any(), any());
467
468         result = slaveDomRPCService.invokeRpc(schemaPath, outputNode).get(2, TimeUnit.SECONDS);
469
470         assertNull(result.getResult());
471         assertEquals(rpcError, result.getErrors().iterator().next());
472
473         // RPC with response output and error.
474
475         doReturn(FluentFutures.immediateFluentFuture(new DefaultDOMRpcResult(outputNode, rpcError)))
476                 .when(mockDOMRpcService).invokeRpc(any(), any());
477
478         final DOMRpcResult resultOutputError =
479                 slaveDomRPCService.invokeRpc(schemaPath, outputNode).get(2, TimeUnit.SECONDS);
480
481         assertEquals(outputNode, resultOutputError.getResult());
482         assertEquals(rpcError, resultOutputError.getErrors().iterator().next());
483
484         // RPC failure.
485
486         exception.expect(DOMRpcException.class);
487
488         doReturn(FluentFutures.immediateFailedFluentFuture(new ClusteringRpcException("mock")))
489                 .when(mockDOMRpcService).invokeRpc(any(), any());
490
491         try {
492             slaveDomRPCService.invokeRpc(schemaPath, outputNode).get(2, TimeUnit.SECONDS);
493         } catch (ExecutionException e) {
494             throw e.getCause();
495         }
496     }
497
498     @Test
499     public void testSlaveNewTransactionRequests() {
500
501         doReturn(mock(DOMDataTreeReadTransaction.class)).when(mockDOMDataBroker).newReadOnlyTransaction();
502         doReturn(mock(DOMDataTreeReadWriteTransaction.class)).when(mockDOMDataBroker).newReadWriteTransaction();
503         doReturn(mock(DOMDataTreeWriteTransaction.class)).when(mockDOMDataBroker).newWriteOnlyTransaction();
504
505         initializeMaster(Collections.emptyList());
506         registerSlaveMountPoint();
507
508         ArgumentCaptor<DOMDataBroker> domDataBrokerCaptor = ArgumentCaptor.forClass(DOMDataBroker.class);
509         verify(mockMountPointBuilder).addService(eq(DOMDataBroker.class), domDataBrokerCaptor.capture());
510
511         final DOMDataBroker slaveDOMDataBroker = domDataBrokerCaptor.getValue();
512         assertTrue(slaveDOMDataBroker instanceof ProxyDOMDataBroker);
513
514         slaveDOMDataBroker.newReadOnlyTransaction();
515         verify(mockDOMDataBroker).newReadOnlyTransaction();
516
517         slaveDOMDataBroker.newReadWriteTransaction();
518         verify(mockDOMDataBroker).newReadWriteTransaction();
519
520         slaveDOMDataBroker.newWriteOnlyTransaction();
521         verify(mockDOMDataBroker).newWriteOnlyTransaction();
522     }
523
524     private ActorRef registerSlaveMountPoint() {
525         final ActorRef slaveRef = system.actorOf(NetconfNodeActor.props(
526                 NetconfTopologySetupBuilder.create().setActorSystem(system).build(), remoteDeviceId, mockRegistry,
527                 mockSchemaRepository, TIMEOUT, mockMountPointService));
528
529         doReturn(Futures.immediateFuture(mockSchemaContext))
530                 .when(mockSchemaContextFactory).createEffectiveModelContext(anyCollection());
531
532         slaveRef.tell(new RegisterMountPoint(ImmutableList.of(SOURCE_IDENTIFIER1, SOURCE_IDENTIFIER2),
533                 masterRef), testKit.getRef());
534
535         verify(mockMountPointBuilder, timeout(5000)).register();
536         verify(mockMountPointBuilder).addInitialSchemaContext(mockSchemaContext);
537         verify(mockMountPointBuilder).addService(eq(DOMDataBroker.class), any());
538         verify(mockMountPointBuilder).addService(eq(DOMRpcService.class), any());
539         verify(mockMountPointBuilder).addService(eq(DOMNotificationService.class), any());
540
541         testKit.expectMsgClass(Success.class);
542
543         return slaveRef;
544     }
545
546     private void initializeMaster(final List<SourceIdentifier> sourceIdentifiers) {
547         masterRef.tell(new CreateInitialMasterActorData(mockDOMDataBroker, sourceIdentifiers,
548                 mockDOMRpcService), testKit.getRef());
549
550         testKit.expectMsgClass(MasterActorDataInitialized.class);
551     }
552
553     private void resetMountPointMocks() {
554         reset(mockMountPointReg, mockMountPointBuilder);
555
556         doNothing().when(mockMountPointReg).close();
557
558         doReturn(mockMountPointBuilder).when(mockMountPointBuilder).addInitialSchemaContext(any());
559         doReturn(mockMountPointBuilder).when(mockMountPointBuilder).addService(any(), any());
560         doReturn(mockMountPointReg).when(mockMountPointBuilder).register();
561     }
562
563     private static PotentialSchemaSource<?> withSourceId(final SourceIdentifier identifier) {
564         return argThat(argument -> identifier.equals(argument.getSourceIdentifier()));
565     }
566
567     private static String convertStreamToString(final InputStream is) {
568         try (Scanner scanner = new Scanner(is)) {
569             return scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
570         }
571     }
572 }