import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.MockitoAnnotations.initMocks;
import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFailedFluentFuture;
import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.XMLUnit;
import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier;
+import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
+import org.junit.runner.RunWith;
import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
import org.opendaylight.mdsal.dom.api.DOMRpcAvailabilityListener;
import org.opendaylight.mdsal.dom.api.DOMRpcException;
import org.opendaylight.mdsal.dom.api.DOMRpcResult;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
+@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class RuntimeRpcTest {
private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpcTest.class);
private static final String SESSION_ID_FOR_REPORTING = "netconf-test-session1";
@Before
public void setUp() throws Exception {
- initMocks(this);
doNothing().when(registration).close();
- doReturn(listener).when(registration).getInstance();
- doReturn(null).when(schemaService).getGlobalContext();
- doReturn(null).when(schemaService).getSessionContext();
doAnswer(invocationOnMock -> {
((EffectiveModelContextListener) invocationOnMock.getArguments()[0]).onModelContextUpdated(SCHEMA_CONTEXT);
return registration;
this.currentSchemaContext = new CurrentSchemaContext(schemaService, sourceProvider);
}
+ @After
+ public void tearDown() {
+ currentSchemaContext.close();
+ }
+
@Test
public void testVoidOutputRpc() throws Exception {
final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER);
package org.opendaylight.netconf.mdsal.connector.ops;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyZeroInteractions;
-import static org.mockito.MockitoAnnotations.initMocks;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.opendaylight.netconf.mdsal.connector.ops.AbstractNetconfOperationTest.RPC_REPLY_OK;
import static org.opendaylight.netconf.mdsal.connector.ops.AbstractNetconfOperationTest.SESSION_ID_FOR_REPORTING;
import static org.opendaylight.netconf.mdsal.connector.ops.AbstractNetconfOperationTest.executeOperation;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Before;
import org.junit.Test;
+import org.junit.runner.RunWith;
import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
import org.opendaylight.mdsal.dom.api.DOMDataBroker;
import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
import org.opendaylight.netconf.api.DocumentedException;
import org.opendaylight.yangtools.util.concurrent.FluentFutures;
import org.w3c.dom.Document;
+@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class ValidateTest {
@Mock
private DOMDataTransactionValidator noopValidator;
private DOMDataBroker dataBroker;
@Before
- public void setUp() throws Exception {
- initMocks(this);
+ public void setUp() {
doReturn(FluentFutures.immediateNullFluentFuture()).when(noopValidator).validate(any());
doReturn(FluentFutures.immediateFailedFluentFuture(new ValidationFailedException("invalid data")))
.when(failingValidator).validate(any());
@Test
public void testValidateUnsupported() throws Exception {
whenValidatorIsNotDefined();
- try {
- validate("messages/mapping/validate/validate.xml");
- fail("Should have failed - <validate> not supported");
- } catch (final DocumentedException e) {
- assertEquals(DocumentedException.ErrorSeverity.ERROR, e.getErrorSeverity());
- assertEquals(DocumentedException.ErrorTag.OPERATION_NOT_SUPPORTED, e.getErrorTag());
- assertEquals(DocumentedException.ErrorType.PROTOCOL, e.getErrorType());
- }
+ final DocumentedException e = assertThrows(DocumentedException.class,
+ () -> validate("messages/mapping/validate/validate.xml"));
+ assertEquals(DocumentedException.ErrorSeverity.ERROR, e.getErrorSeverity());
+ assertEquals(DocumentedException.ErrorTag.OPERATION_NOT_SUPPORTED, e.getErrorTag());
+ assertEquals(DocumentedException.ErrorType.PROTOCOL, e.getErrorType());
}
@Test
public void testSourceMissing() throws Exception {
whenUsingValidator(noopValidator);
- try {
- validate("messages/mapping/validate/validate_no_source.xml");
- fail("Should have failed - <source> element is missing");
- } catch (final DocumentedException e) {
- assertEquals(DocumentedException.ErrorSeverity.ERROR, e.getErrorSeverity());
- assertEquals(DocumentedException.ErrorTag.MISSING_ELEMENT, e.getErrorTag());
- assertEquals(DocumentedException.ErrorType.PROTOCOL, e.getErrorType());
- }
+ final DocumentedException e = assertThrows(DocumentedException.class,
+ () -> validate("messages/mapping/validate/validate_no_source.xml"));
+ assertEquals(DocumentedException.ErrorSeverity.ERROR, e.getErrorSeverity());
+ assertEquals(DocumentedException.ErrorTag.MISSING_ELEMENT, e.getErrorTag());
+ assertEquals(DocumentedException.ErrorType.PROTOCOL, e.getErrorType());
}
@Test
public void testSourceRunning() throws Exception {
whenUsingValidator(noopValidator);
- try {
- validate("messages/mapping/validate/validate_running.xml");
- fail("Should have failed - <running/> is not supported");
- } catch (final DocumentedException e) {
- assertEquals(DocumentedException.ErrorSeverity.ERROR, e.getErrorSeverity());
- assertEquals(DocumentedException.ErrorTag.OPERATION_NOT_SUPPORTED, e.getErrorTag());
- assertEquals(DocumentedException.ErrorType.PROTOCOL, e.getErrorType());
- }
+ final DocumentedException e = assertThrows(DocumentedException.class,
+ () -> validate("messages/mapping/validate/validate_running.xml"));
+ assertEquals(DocumentedException.ErrorSeverity.ERROR, e.getErrorSeverity());
+ assertEquals(DocumentedException.ErrorTag.OPERATION_NOT_SUPPORTED, e.getErrorTag());
+ assertEquals(DocumentedException.ErrorType.PROTOCOL, e.getErrorType());
}
@Test
public void testValidateEmptyTx() throws Exception {
whenUsingValidator(noopValidator);
verifyResponse(validate("messages/mapping/validate/validate.xml"), RPC_REPLY_OK);
- verifyZeroInteractions(noopValidator);
+ verifyNoMoreInteractions(noopValidator);
}
@Test
public void testValidateFailed() throws Exception {
whenUsingValidator(failingValidator);
final TransactionProvider transactionProvider = initCandidateTransaction();
- try {
- validate("messages/mapping/validate/validate.xml", transactionProvider);
- fail("Should have failed - operation failed");
- } catch (final DocumentedException e) {
- assertEquals(DocumentedException.ErrorSeverity.ERROR, e.getErrorSeverity());
- assertEquals(DocumentedException.ErrorTag.OPERATION_FAILED, e.getErrorTag());
- assertEquals(DocumentedException.ErrorType.APPLICATION, e.getErrorType());
- }
+ final DocumentedException e = assertThrows(DocumentedException.class,
+ () -> validate("messages/mapping/validate/validate.xml", transactionProvider));
+ assertEquals(DocumentedException.ErrorSeverity.ERROR, e.getErrorSeverity());
+ assertEquals(DocumentedException.ErrorTag.OPERATION_FAILED, e.getErrorTag());
+ assertEquals(DocumentedException.ErrorType.APPLICATION, e.getErrorType());
}
private void whenValidatorIsNotDefined() {
return transactionProvider;
}
- private Document validate(final String resource, final TransactionProvider transactionProvider) throws Exception {
+ private static Document validate(final String resource, final TransactionProvider transactionProvider)
+ throws Exception {
final Validate validate = new Validate(SESSION_ID_FOR_REPORTING, transactionProvider);
return executeOperation(validate, resource);
}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.netconf.mdsal.notification.impl.ops;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
-import org.hamcrest.CoreMatchers;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import org.junit.runner.RunWith;
import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
+import org.mockito.junit.MockitoJUnitRunner;
import org.opendaylight.netconf.api.NetconfSession;
import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlUtil;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.StreamNameType;
import org.w3c.dom.Element;
+@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class CreateSubscriptionTest {
private static final String CREATE_SUBSCRIPTION_XML = "<create-subscription\n"
private NetconfNotificationRegistry notificationRegistry;
@Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
+ public void setUp() {
doReturn(true).when(notificationRegistry).isStreamAvailable(any(StreamNameType.class));
doReturn(mock(NotificationListenerRegistration.class)).when(notificationRegistry)
.registerNotificationListener(any(StreamNameType.class), any(NetconfNotificationListener.class));
final Element element =
createSubscription.handleWithNoSubsequentOperations(XmlUtil.newDocument(), operationElement);
- Assert.assertThat(XmlUtil.toString(element), CoreMatchers.containsString("ok"));
+ assertThat(XmlUtil.toString(element), containsString("ok"));
}
}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.netconf.messagebus.eventsources.netconf;
import static org.hamcrest.CoreMatchers.hasItems;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.verify;
import java.util.Collection;
import java.util.Set;
import javax.xml.transform.dom.DOMSource;
-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.dom.api.DOMNotification;
import org.opendaylight.mdsal.dom.api.DOMNotificationListener;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.TopicId;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
+@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class ConnectionNotificationTopicRegistrationTest {
private ConnectionNotificationTopicRegistration registration;
private DOMNotificationListener listener;
@Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
+ public void setUp() {
registration = new ConnectionNotificationTopicRegistration("candidate", listener);
}
public void testClose() throws Exception {
registration.setActive(true);
registration.close();
- Assert.assertFalse(registration.isActive());
+ assertFalse(registration.isActive());
checkStatus(listener, EventSourceStatus.Deactive);
}
final TopicId topic3 = registerTopic("topic3");
final Set<TopicId> notificationTopicIds =
registration.getTopicsForNotification(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH);
- Assert.assertNotNull(notificationTopicIds);
- Assert.assertThat(notificationTopicIds, hasItems(topic1, topic2, topic3));
+ assertNotNull(notificationTopicIds);
+ assertThat(notificationTopicIds, hasItems(topic1, topic2, topic3));
registration.unRegisterNotificationTopic(topic3);
final Set<TopicId> afterUnregister =
registration.getTopicsForNotification(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH);
- Assert.assertNotNull(afterUnregister);
- Assert.assertThat(afterUnregister, hasItems(topic1, topic2));
- Assert.assertFalse(afterUnregister.contains(topic3));
+ assertNotNull(afterUnregister);
+ assertThat(afterUnregister, hasItems(topic1, topic2));
+ assertFalse(afterUnregister.contains(topic3));
}
private TopicId registerTopic(final String value) {
ArgumentCaptor<DOMNotification> notificationCaptor = ArgumentCaptor.forClass(DOMNotification.class);
verify(listener).onNotification(notificationCaptor.capture());
final DOMNotification value = notificationCaptor.getValue();
- Assert.assertEquals(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH, value.getType());
+ assertEquals(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH, value.getType());
final Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> body = value.getBody()
.getValue();
- Assert.assertEquals(1, body.size());
+ assertEquals(1, body.size());
final DOMSource source = (DOMSource) body.iterator().next().getValue();
final String statusNodeValue = source.getNode().getFirstChild().getFirstChild().getNodeValue();
- Assert.assertEquals(status.toString(), statusNodeValue);
+ assertEquals(status.toString(), statusNodeValue);
}
}
\ No newline at end of file
package org.opendaylight.netconf.messagebus.eventsources.netconf;
import static org.hamcrest.CoreMatchers.hasItems;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
import java.time.Instant;
import java.util.Optional;
import java.util.Set;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import org.junit.runner.RunWith;
import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
+import org.mockito.junit.MockitoJUnitRunner;
import org.opendaylight.mdsal.dom.api.DOMNotificationListener;
import org.opendaylight.mdsal.dom.api.DOMNotificationService;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.TopicId;
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;
+@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class StreamNotificationTopicRegistrationTest {
private static final String STREAM_NAME = "stream-1";
@Before
public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
-
Node node = new NodeBuilder().setNodeId(NodeId.getDefaultInstance("node-id")).build();
when(mount.getNode()).thenReturn(node);
when(mount.registerNotificationListener(source, ConnectionNotificationTopicRegistration
@Test
public void testActivateNotificationSource() throws Exception {
registration.activateNotificationSource();
- Assert.assertTrue(registration.isActive());
+ assertTrue(registration.isActive());
verify(mount).invokeCreateSubscription(stream);
}
registration.setActive(true);
registration.reActivateNotificationSource();
- Assert.assertTrue(registration.isActive());
+ assertTrue(registration.isActive());
verify(mount).invokeCreateSubscription(stream, Optional.empty());
}
registration.setLastEventTime(lastEventTime);
registration.reActivateNotificationSource();
- Assert.assertTrue(registration.isActive());
+ assertTrue(registration.isActive());
verify(mount).invokeCreateSubscription(stream, Optional.of(lastEventTime));
}
public void testClose() throws Exception {
registration.setActive(true);
registration.close();
- Assert.assertFalse(registration.isActive());
+ assertFalse(registration.isActive());
}
@Test
final TopicId topic3 = registerTopic("topic3");
final Set<TopicId> notificationTopicIds =
registration.getTopicsForNotification(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH);
- Assert.assertNotNull(notificationTopicIds);
- Assert.assertThat(notificationTopicIds, hasItems(topic1, topic2, topic3));
+ assertNotNull(notificationTopicIds);
+ assertThat(notificationTopicIds, hasItems(topic1, topic2, topic3));
registration.unRegisterNotificationTopic(topic3);
final Set<TopicId> afterUnregister =
registration.getTopicsForNotification(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH);
- Assert.assertNotNull(afterUnregister);
- Assert.assertThat(afterUnregister, hasItems(topic1, topic2));
- Assert.assertFalse(afterUnregister.contains(topic3));
+ assertNotNull(afterUnregister);
+ assertThat(afterUnregister, hasItems(topic1, topic2));
+ assertFalse(afterUnregister.contains(topic3));
}
private TopicId registerTopic(final String value) {
import static org.hamcrest.CoreMatchers.both;
import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import java.util.Map;
+import java.util.Map.Entry;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
XmlElement.fromDomElementWithExpected(element, "top");
XmlElement.fromDomElementWithExpected(element, "top", "namespace");
- try {
- XmlElement.fromString("notXml");
- fail();
- } catch (final DocumentedException e) {
- // expected
- }
-
- try {
- XmlElement.fromDomElementWithExpected(element, "notTop");
- fail();
- } catch (final DocumentedException e) {
- // expected
- }
-
- try {
- XmlElement.fromDomElementWithExpected(element, "top", "notNamespace");
- fail();
- } catch (final DocumentedException e) {
- // expected
- }
+ assertThrows(DocumentedException.class, () -> XmlElement.fromString("notXml"));
+ assertThrows(DocumentedException.class, () -> XmlElement.fromDomElementWithExpected(element, "notTop"));
+ assertThrows(DocumentedException.class,
+ () -> XmlElement.fromDomElementWithExpected(element, "top", "notNamespace"));
}
@Test
final XmlElement noNamespaceElement = XmlElement.fromString("<noNamespace/>");
assertFalse(noNamespaceElement.hasNamespace());
- try {
- noNamespaceElement.getNamespace();
- fail();
- } catch (final MissingNameSpaceException e) {
- // expected
- }
+
+ assertThrows(MissingNameSpaceException.class, () -> noNamespaceElement.getNamespace());
final XmlElement inner = xmlElement.getOnlyChildElement("inner");
final XmlElement deepInner = inner.getOnlyChildElementWithSameNamespaceOptionally().get();
@Test
public void testExtractNamespaces() throws Exception {
final XmlElement innerPrefixed = xmlElement.getOnlyChildElement("innerPrefixed");
- Map.Entry<String, String> namespaceOfTextContent = innerPrefixed.findNamespaceOfTextContent();
+ Entry<String, String> namespaceOfTextContent = innerPrefixed.findNamespaceOfTextContent();
assertNotNull(namespaceOfTextContent);
assertEquals("b", namespaceOfTextContent.getKey());
xmlElement.checkUnrecognisedElements(xmlElement.getOnlyChildElement("inner"),
xmlElement.getOnlyChildElement("innerPrefixed"), xmlElement.getOnlyChildElement("innerNamespace"));
- try {
- xmlElement.checkUnrecognisedElements(xmlElement.getOnlyChildElement("inner"));
- fail();
- } catch (final DocumentedException e) {
- assertThat(e.getMessage(), both(containsString("innerNamespace")).and(containsString("innerNamespace")));
- }
+ final DocumentedException e = assertThrows(DocumentedException.class,
+ () -> xmlElement.checkUnrecognisedElements(xmlElement.getOnlyChildElement("inner")));
+ assertThat(e.getMessage(), both(containsString("innerNamespace")).and(containsString("innerNamespace")));
}
}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.netconf.client;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyObject;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
channelFuture = mock(ChannelPromise.class);
mockEventLoop();
doReturn(channelFuture).when(channel).newPromise();
- doReturn(channelFuture).when(channel).writeAndFlush(anyObject());
- doReturn(channelFuture).when(channel).writeAndFlush(anyObject(), any(ChannelPromise.class));
+ doReturn(channelFuture).when(channel).writeAndFlush(any());
+ doReturn(channelFuture).when(channel).writeAndFlush(any(), any(ChannelPromise.class));
doReturn(channelFuture).when(channelFuture).addListener(any(GenericFutureListener.class));
caps = Sets.newSet("a", "b");
helloMessage = NetconfHelloMessage.createServerHello(caps, 10);
SimpleNetconfClientSessionListener simpleListener = new SimpleNetconfClientSessionListener();
final Future<NetconfMessage> promise = simpleListener.sendRequest(message);
simpleListener.onSessionUp(clientSession);
- verify(channel, times(1)).writeAndFlush(anyObject(), anyObject());
+ verify(channel, times(1)).writeAndFlush(any(), any());
simpleListener.onSessionDown(clientSession, new Exception());
assertFalse(promise.isSuccess());
SimpleNetconfClientSessionListener simpleListener = new SimpleNetconfClientSessionListener();
final Future<NetconfMessage> promise = simpleListener.sendRequest(message);
simpleListener.onSessionUp(clientSession);
- verify(channel, times(1)).writeAndFlush(anyObject(), anyObject());
+ verify(channel, times(1)).writeAndFlush(any(), any());
simpleListener.sendRequest(message);
assertFalse(promise.isSuccess());
SimpleNetconfClientSessionListener simpleListener = new SimpleNetconfClientSessionListener();
final Future<NetconfMessage> promise = simpleListener.sendRequest(message);
simpleListener.onSessionUp(clientSession);
- verify(channel, times(1)).writeAndFlush(anyObject(), anyObject());
+ verify(channel, times(1)).writeAndFlush(any(), any());
simpleListener.onMessage(clientSession, message);
assertTrue(promise.isSuccess());
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.netconf.impl.mapping.operations;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyObject;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
return null;
}).when(sendFuture).addListener(any(GenericFutureListener.class));
doReturn(sendFuture).when(channel).newPromise();
- doReturn(sendFuture).when(channel).writeAndFlush(anyObject(), anyObject());
+ doReturn(sendFuture).when(channel).writeAndFlush(any(), any());
doReturn(true).when(sendFuture).isSuccess();
final NetconfServerSessionListener listener = mock(NetconfServerSessionListener.class);
doNothing().when(listener).onSessionTerminated(any(NetconfServerSession.class),
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.netconf.impl.util;
-import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.anyObject;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
doReturn(channel).when(context).channel();
channelFuture = mock(ChannelFuture.class);
doReturn(channelFuture).when(channelFuture).addListener(any(GenericFutureListener.class));
- doReturn(channelFuture).when(channel).writeAndFlush(anyObject());
+ doReturn(channelFuture).when(channel).writeAndFlush(any());
}
@Test
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.mockito.Mockito.verifyZeroInteractions;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoop;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
-import io.netty.util.concurrent.GenericFutureListener;
import java.util.Collections;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
+import org.junit.runner.RunWith;
import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
+import org.mockito.junit.MockitoJUnitRunner;
import org.opendaylight.netconf.api.NetconfMessage;
import org.opendaylight.netconf.api.NetconfSessionListener;
import org.opendaylight.netconf.api.NetconfTerminationReason;
import org.opendaylight.netconf.nettyutil.handler.exi.EXIParameters;
import org.opendaylight.netconf.nettyutil.handler.exi.NetconfStartExiMessage;
+@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class AbstractNetconfSessionTest {
@Mock
@Before
public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
doNothing().when(listener).onMessage(any(TestingNetconfSession.class), any(NetconfMessage.class));
doNothing().when(listener).onSessionUp(any(TestingNetconfSession.class));
doNothing().when(listener).onSessionDown(any(TestingNetconfSession.class), any(Exception.class));
doNothing().when(listener).onSessionTerminated(any(TestingNetconfSession.class),
any(NetconfTerminationReason.class));
- doReturn(writeFuture).when(writeFuture).addListener(any(GenericFutureListener.class));
-
doReturn(writeFuture).when(channel).newPromise();
- doReturn(writeFuture).when(channel).writeAndFlush(any(NetconfMessage.class));
doReturn(writeFuture).when(channel).writeAndFlush(any(NetconfMessage.class), any(ChannelPromise.class));
doReturn(pipeline).when(channel).pipeline();
- doReturn("mockChannel").when(channel).toString();
doReturn(mock(ChannelFuture.class)).when(channel).close();
doReturn(null).when(pipeline).replace(anyString(), anyString(), any(ChannelHandler.class));
public void testReplaceHandlers() throws Exception {
final TestingNetconfSession testingNetconfSession = new TestingNetconfSession(listener, channel, 1L);
final ChannelHandler mock = mock(ChannelHandler.class);
- doReturn("handler").when(mock).toString();
testingNetconfSession.replaceMessageDecoder(mock);
verify(pipeline).replace(AbstractChannelInitializer.NETCONF_MESSAGE_DECODER,
public void testEndOfInput() throws Exception {
final TestingNetconfSession testingNetconfSession = new TestingNetconfSession(listener, channel, 1L);
testingNetconfSession.endOfInput();
- verifyZeroInteractions(listener);
+ verifyNoMoreInteractions(listener);
testingNetconfSession.sessionUp();
testingNetconfSession.endOfInput();
verify(listener).onSessionDown(any(TestingNetconfSession.class), any(Exception.class));
testingNetconfSession.sendMessage(hello);
verify(channel).writeAndFlush(hello, writeFuture);
}
-
}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.netconf.nettyutil.handler;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.not;
-import static org.junit.Assert.assertThat;
+import static org.hamcrest.MatcherAssert.assertThat;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
*/
package org.opendaylight.netconf.nettyutil.handler;
+import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import com.google.common.collect.Iterables;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
-import static org.mockito.ArgumentMatchers.anyObject;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
doReturn(channel).when(ctx).channel();
doReturn(ctx).when(ctx).fireChannelActive();
doReturn(ctx).when(ctx).fireChannelInactive();
- doReturn(ctx).when(ctx).fireChannelRead(anyObject());
+ doReturn(ctx).when(ctx).fireChannelRead(any());
doReturn(mock(ChannelFuture.class)).when(ctx).disconnect(any(ChannelPromise.class));
doReturn(getMockedPromise()).when(ctx).newPromise();
}
doReturn(ioWriteFuture).when(asyncIn).writePacket(any(Buffer.class));
- verifyZeroInteractions(firstWritePromise, secondWritePromise);
+ verifyNoMoreInteractions(firstWritePromise, secondWritePromise);
// make first write stop pending
firstWriteListener.operationComplete(ioWriteFuture);
package org.opendaylight.netconf.util;
import static org.hamcrest.CoreMatchers.containsString;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertThrows;
import java.util.Collections;
import javax.xml.transform.dom.DOMResult;
public void testConflictingVersionDetection() throws Exception {
final Document document = XmlUtil.readXmlToDocument(getClass()
.getResourceAsStream("/netconfMessages/conflictingversion/conflictingVersionResponse.xml"));
- try {
- NetconfUtil.checkIsMessageOk(document);
- fail();
- } catch (final IllegalStateException e) {
- assertThat(e.getMessage(), containsString("Optimistic lock failed. Expected parent version 21, was 18"));
- }
+
+ final IllegalStateException e = assertThrows(IllegalStateException.class,
+ () -> NetconfUtil.checkIsMessageOk(document));
+ assertThat(e.getMessage(), containsString("Optimistic lock failed. Expected parent version 21, was 18"));
}
@Test
package org.opendaylight.netconf.sal.connect.netconf;
import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
-import org.junit.Assert;
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
verifySchemas(libraryModulesSchemas);
}
-
private static void verifySchemas(final LibraryModulesSchemas libraryModulesSchemas) throws MalformedURLException {
final Map<SourceIdentifier, URL> resolvedModulesSchema = libraryModulesSchemas.getAvailableModels();
- Assert.assertThat(resolvedModulesSchema.size(), is(3));
+ assertThat(resolvedModulesSchema.size(), is(3));
- Assert.assertTrue(resolvedModulesSchema.containsKey(RevisionSourceIdentifier.create("module-with-revision",
+ assertTrue(resolvedModulesSchema.containsKey(RevisionSourceIdentifier.create("module-with-revision",
Revision.of("2014-04-08"))));
- Assert.assertThat(resolvedModulesSchema.get(
+ assertThat(resolvedModulesSchema.get(
RevisionSourceIdentifier.create("module-with-revision", Revision.of("2014-04-08"))),
is(new URL("http://localhost:8181/yanglib/schemas/module-with-revision/2014-04-08")));
- Assert.assertTrue(resolvedModulesSchema.containsKey(
+ assertTrue(resolvedModulesSchema.containsKey(
RevisionSourceIdentifier.create("another-module-with-revision", Revision.of("2013-10-21"))));
- Assert.assertThat(resolvedModulesSchema.get(
+ assertThat(resolvedModulesSchema.get(
RevisionSourceIdentifier.create("another-module-with-revision", Revision.of("2013-10-21"))),
is(new URL("http://localhost:8181/yanglib/schemas/another-module-with-revision/2013-10-21")));
- Assert.assertTrue(resolvedModulesSchema.containsKey(
+ assertTrue(resolvedModulesSchema.containsKey(
RevisionSourceIdentifier.create("module-without-revision")));
- Assert.assertThat(resolvedModulesSchema.get(
+ assertThat(resolvedModulesSchema.get(
RevisionSourceIdentifier.create("module-without-revision")),
is(new URL("http://localhost:8181/yanglib/schemas/module-without-revision/")));
}
LibraryModulesSchemas.create(getClass().getResource("/yang-library-fail.xml").toString());
final Map<SourceIdentifier, URL> resolvedModulesSchema = libraryModulesSchemas.getAvailableModels();
- Assert.assertThat(resolvedModulesSchema.size(), is(1));
+ assertThat(resolvedModulesSchema.size(), is(1));
- Assert.assertFalse(resolvedModulesSchema.containsKey(
- RevisionSourceIdentifier.create("module-with-bad-url")));
+ assertFalse(resolvedModulesSchema.containsKey(RevisionSourceIdentifier.create("module-with-bad-url")));
//See BUG 8071 https://bugs.opendaylight.org/show_bug.cgi?id=8071
- //Assert.assertFalse(resolvedModulesSchema.containsKey(
+ //assertFalse(resolvedModulesSchema.containsKey(
// RevisionSourceIdentifier.create("module-with-bad-revision", "bad-revision")));
- Assert.assertTrue(resolvedModulesSchema.containsKey(
- RevisionSourceIdentifier.create("good-ol-module")));
+ assertTrue(resolvedModulesSchema.containsKey(RevisionSourceIdentifier.create("good-ol-module")));
}
-
@Test
public void testCreateFromInvalidAll() throws Exception {
// test bad yang lib url
LibraryModulesSchemas libraryModulesSchemas = LibraryModulesSchemas.create("ObviouslyBadUrl");
- Assert.assertThat(libraryModulesSchemas.getAvailableModels(), is(Collections.emptyMap()));
+ assertThat(libraryModulesSchemas.getAvailableModels(), is(Collections.emptyMap()));
// TODO test also fail on json and xml parsing. But can we fail not on runtime exceptions?
}
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyCollectionOf;
+import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.after;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.concurrent.Executors;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
-import org.mockito.Mockito;
import org.opendaylight.mdsal.dom.api.DOMActionService;
import org.opendaylight.mdsal.dom.api.DOMNotification;
import org.opendaylight.mdsal.dom.api.DOMRpcResult;
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
import org.xml.sax.SAXException;
-@SuppressWarnings("checkstyle:IllegalCatch")
public class NetconfDeviceTest extends AbstractTestModelTest {
private static final NetconfMessage NOTIFICATION;
- private static final ContainerNode COMPOSITE_NODE;
+ private static final ContainerNode COMPOSITE_NODE = mockClass(ContainerNode.class);
static {
- try {
- COMPOSITE_NODE = mockClass(ContainerNode.class);
- } catch (final Exception e) {
- throw new RuntimeException(e);
- }
try {
NOTIFICATION = new NetconfMessage(XmlUtil
.readXmlToDocument(NetconfDeviceTest.class.getResourceAsStream("/notification-payload.xml")));
} else {
return Futures.immediateFuture(SCHEMA_CONTEXT);
}
- }).when(schemaFactory).createEffectiveModelContext(anyCollectionOf(SourceIdentifier.class));
+ }).when(schemaFactory).createEffectiveModelContext(anyCollection());
final NetconfDeviceSchemasResolver stateSchemasResolver = (deviceRpc, remoteSessionCapabilities, id,
schemaContext) -> {
getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
device.onRemoteSessionUp(sessionCaps, listener);
- Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(MountPointContext.class),
+ verify(facade, timeout(5000)).onDeviceConnected(any(MountPointContext.class),
any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class), isNull());
- Mockito.verify(schemaFactory, times(2)).createEffectiveModelContext(anyCollectionOf(SourceIdentifier.class));
+ verify(schemaFactory, times(2)).createEffectiveModelContext(anyCollection());
}
@Test
= new SchemaResolutionException("fail first",
Collections.emptyList(), HashMultimap.create());
doReturn(Futures.immediateFailedFuture(schemaResolutionException))
- .when(schemaFactory).createEffectiveModelContext(anyCollectionOf(SourceIdentifier.class));
+ .when(schemaFactory).createEffectiveModelContext(anyCollection());
final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice
.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, STATE_SCHEMAS_RESOLVER);
final NetconfSessionPreferences sessionCaps = getSessionCaps(false, capList);
device.onRemoteSessionUp(sessionCaps, listener);
- Mockito.verify(facade, Mockito.timeout(5000)).onDeviceDisconnected();
- Mockito.verify(listener, Mockito.timeout(5000)).close();
- Mockito.verify(schemaFactory, times(1)).createEffectiveModelContext(anyCollectionOf(SourceIdentifier.class));
+ verify(facade, timeout(5000)).onDeviceDisconnected();
+ verify(listener, timeout(5000)).close();
+ verify(schemaFactory, times(1)).createEffectiveModelContext(anyCollection());
}
@Test
} else {
return Futures.immediateFuture(SCHEMA_CONTEXT);
}
- }).when(schemaFactory).createEffectiveModelContext(anyCollectionOf(SourceIdentifier.class));
+ }).when(schemaFactory).createEffectiveModelContext(anyCollection());
final NetconfDeviceSchemasResolver stateSchemasResolver = (deviceRpc, remoteSessionCapabilities, id,
schemaContext) -> {
getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
device.onRemoteSessionUp(sessionCaps, listener);
- Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(MountPointContext.class),
+ verify(facade, timeout(5000)).onDeviceConnected(any(MountPointContext.class),
any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class), isNull());
- Mockito.verify(schemaFactory, times(1)).createEffectiveModelContext(anyCollectionOf(SourceIdentifier.class));
+ verify(schemaFactory, times(1)).createEffectiveModelContext(anyCollection());
}
private static SchemaSourceRegistry getSchemaRegistry() {
.setSalFacade(facade)
.setBaseSchemas(BASE_SCHEMAS)
.build();
- final NetconfDevice netconfSpy = Mockito.spy(device);
+ final NetconfDevice netconfSpy = spy(device);
final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION));
.setSalFacade(facade)
.setBaseSchemas(BASE_SCHEMAS)
.build();
- final NetconfDevice netconfSpy = Mockito.spy(device);
+ final NetconfDevice netconfSpy = spy(device);
final NetconfSessionPreferences sessionCaps = getSessionCaps(false,
Lists.newArrayList(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0));
.setSalFacade(facade)
.setBaseSchemas(BASE_SCHEMAS)
.build();
- final NetconfDevice netconfSpy = Mockito.spy(device);
+ final NetconfDevice netconfSpy = spy(device);
final NetconfSessionPreferences sessionCaps = getSessionCaps(false,
Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION));
.setSalFacade(facade)
.setBaseSchemas(BASE_SCHEMAS)
.build();
- final NetconfDevice netconfSpy = Mockito.spy(device);
+ final NetconfDevice netconfSpy = spy(device);
final NetconfSessionPreferences sessionCaps = getSessionCaps(false, Collections.emptyList());
private static <T> T mockClass(final Class<T> remoteDeviceHandlerClass) {
final T mock = mock(remoteDeviceHandlerClass);
- Mockito.doReturn(remoteDeviceHandlerClass.getSimpleName()).when(mock).toString();
+ doReturn(remoteDeviceHandlerClass.getSimpleName()).when(mock).toString();
return mock;
}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.netconf.sal.connect.netconf.listener;
import static org.hamcrest.CoreMatchers.hasItem;
+import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import com.google.common.collect.Lists;
*/
package org.opendaylight.netconf.sal.connect.netconf.schema.mapping;
+import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT;
import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-import com.google.common.util.concurrent.FluentFuture;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
final NetconfMessage ok = new NetconfMessage(XmlUtil.readXmlToDocument(okStream));
final NetconfMessage data = new NetconfMessage(XmlUtil.readXmlToDocument(dataStream));
when(listener.sendRequest(any(), eq(NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME)))
- .thenReturn(FluentFuture.from(RpcResultBuilder.success(data).buildFuture()));
+ .thenReturn(RpcResultBuilder.success(data).buildFuture());
when(listener.sendRequest(any(), eq(NetconfMessageTransformUtil.NETCONF_GET_QNAME)))
- .thenReturn(FluentFuture.from(RpcResultBuilder.success(data).buildFuture()));
+ .thenReturn(RpcResultBuilder.success(data).buildFuture());
when(listener.sendRequest(any(), eq(NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)))
- .thenReturn(FluentFuture.from(RpcResultBuilder.success(ok).buildFuture()));
+ .thenReturn(RpcResultBuilder.success(ok).buildFuture());
when(listener.sendRequest(any(), eq(NetconfMessageTransformUtil.NETCONF_COPY_CONFIG_QNAME)))
- .thenReturn(FluentFuture.from(RpcResultBuilder.success(ok).buildFuture()));
+ .thenReturn(RpcResultBuilder.success(ok).buildFuture());
when(listener.sendRequest(any(), eq(NetconfMessageTransformUtil.NETCONF_DISCARD_CHANGES_QNAME)))
- .thenReturn(FluentFuture.from(RpcResultBuilder.success(ok).buildFuture()));
+ .thenReturn(RpcResultBuilder.success(ok).buildFuture());
when(listener.sendRequest(any(), eq(NetconfMessageTransformUtil.NETCONF_VALIDATE_QNAME)))
- .thenReturn(FluentFuture.from(RpcResultBuilder.success(ok).buildFuture()));
+ .thenReturn(RpcResultBuilder.success(ok).buildFuture());
when(listener.sendRequest(any(), eq(NetconfMessageTransformUtil.NETCONF_LOCK_QNAME)))
- .thenReturn(FluentFuture.from(RpcResultBuilder.success(ok).buildFuture()));
+ .thenReturn(RpcResultBuilder.success(ok).buildFuture());
when(listener.sendRequest(any(), eq(NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME)))
- .thenReturn(FluentFuture.from(RpcResultBuilder.success(ok).buildFuture()));
+ .thenReturn(RpcResultBuilder.success(ok).buildFuture());
when(listener.sendRequest(any(), eq(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME)))
- .thenReturn(FluentFuture.from(RpcResultBuilder.success(ok).buildFuture()));
+ .thenReturn(RpcResultBuilder.success(ok).buildFuture());
final MessageTransformer<NetconfMessage> transformer = new NetconfMessageTransformer(
new EmptyMountPointContext(SCHEMA_CONTEXT), true, BASE_SCHEMAS.getBaseSchema());
final DOMRpcService rpc = new NetconfDeviceRpc(SCHEMA_CONTEXT, listener, transformer);