下面列出了org.apache.http.impl.io.EmptyInputStream#org.powermock.reflect.Whitebox 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void test_populateStaticParameters_justdomain()
{
String url = "http://EXAMPLE.com";
EasyMock.expect(requestMock.getHeader(ModelBuilder.BASE_MODEL_URL_PATH_HEADER)).andReturn(url);
Map<String, String> mapStaticParams = new HashMap<String, String>();
mapStaticParams.put(WPBModel.GLOBAL_PROTOCOL, "http");
mapStaticParams.put(WPBModel.GLOBAL_DOMAIN, "example.com");
mapStaticParams.put(WPBModel.GLOBAL_CONTEXT_PATH, "");
mapStaticParams.put(WPBModel.GLOBAL_BASE_URL, "http://EXAMPLE.com");
InternalModel model = new InternalModel();
EasyMock.replay(requestMock, configurationMock);
modelBuilder = new ModelBuilder(cacheInstancesMock);
try
{
Whitebox.invokeMethod(modelBuilder, "populateStaticParameters", requestMock, model);
} catch (Exception e)
{
assertTrue(false);
}
EasyMock.verify(requestMock, configurationMock);
assertTrue(model.getCmsModel().get(WPBModel.REQUEST_KEY).equals(mapStaticParams));
}
/**
* Test method for {@link com.digi.xbee.api.listeners.IDataReceiveListener#dataReceived(XBeeMessage)} and
* {@link com.digi.xbee.api.DataReader#packetReceived(XBeePacket)}.
*
* <p>Verify that if the listener is not subscribed to receive data, the callback is not
* executed although a data packet is received.</p>
*
* @throws Exception
*/
@Test
public void testDataReceiveNotSubscribed() throws Exception {
// Whenever a new remote XBee device needs to be instantiated, return the mocked one.
PowerMockito.whenNew(RemoteXBeeDevice.class).withAnyArguments().thenReturn(remoteXBeeDevice);
// Fire the private packetReceived method of the dataReader with a receive packet.
Whitebox.invokeMethod(dataReader, PACKET_RECEIVED_METHOD, receivePacket);
// Verify that the notifyDataReceived private method was called.
PowerMockito.verifyPrivate(dataReader, Mockito.times(1)).invoke(NOTIFY_DATA_RECEIVED_METHOD,
Mockito.any(XBeeMessage.class));
// As the receiveDataListener was not subscribed in the DataReceiveListeners of the dataReader object, the
// address and data of the receiveDataListener should be null.
assertNull(receiveDataListener.get64BitAddress());
assertNull(receiveDataListener.getData());
assertFalse(receiveDataListener.isBroadcast());
}
@Test
public void run() throws Exception {
// Given
DataObserversManager dataObserversManager = Mockito.spy(new DataObserversManager());
PowerMockito.mockStatic(Database.class);
Database database = PowerMockito.mock(Database.class);
PowerMockito.when(database, "dbReference").thenReturn(firDatabaseReference);
Whitebox.setInternalState(database, "dbReference", firDatabaseReference);
Whitebox.setInternalState(database, "databasePath", "/test");
QueryOnDataChange query = new QueryOnDataChange(database, "/test");
Class dataType = String.class;
// When
query.with(mock(ConverterPromise.class)).withArgs(dataType).execute();
// Then
Mockito.verify(firDatabaseReference, VerificationModeFactory.times(1)).observeEventTypeWithBlockWithCancelBlock(Mockito.anyLong(), Mockito.any(FIRDatabaseQuery.Block_observeEventTypeWithBlockWithCancelBlock_1.class), Mockito.any(FIRDatabaseQuery.Block_observeEventTypeWithBlockWithCancelBlock_2.class));
}
@Test
public void testSendTraceSegmentWithException() throws InvalidProtocolBufferException {
grpcServerRule.getServiceRegistry().addService(serviceImplBase);
AbstractSpan firstEntrySpan = ContextManager.createEntrySpan("/testFirstEntry", null);
firstEntrySpan.setComponent(ComponentsDefine.TOMCAT);
Tags.HTTP.METHOD.set(firstEntrySpan, "GET");
Tags.URL.set(firstEntrySpan, "127.0.0.1:8080");
SpanLayer.asHttp(firstEntrySpan);
ContextManager.stopSpan();
grpcServerRule.getServer().shutdownNow();
serviceClient.consume(storage.getTraceSegments());
assertThat(upstreamSegments.size(), is(0));
boolean reconnect = Whitebox.getInternalState(
ServiceManager.INSTANCE.findService(GRPCChannelManager.class), "reconnect");
assertThat(reconnect, is(true));
}
@Test
public void testExpiredReservoirPositiveBernoulliSample() {
Clock clock = Clock.fixed(Instant.ofEpochSecond(1500000000), ZoneId.systemDefault());
SamplingRule input = createInput("r1", 300, 0, 0.5);
CentralizedRule rule = new CentralizedRule(input, rand);
SamplingTargetDocument target = createTarget(0, 0.5, 1499999999);
rule.update(target, clock.instant());
Mockito.when(rand.next()).thenReturn(0.2);
// BernoulliSample() from expired reservoir
SamplingResponse response = rule.sample(clock.instant());
Mockito.verify(rand).next();
Assert.assertTrue(response.isSampled());
Assert.assertEquals("r1", response.getRuleName().get());
Statistics s = Whitebox.getInternalState(rule, "statistics", CentralizedRule.class);
Assert.assertEquals(1, s.getSampled());
Assert.assertEquals(1, s.getRequests());
Assert.assertEquals(0, s.getBorrowed());
}
/**
* Test method for {@link com.digi.xbee.api.connection.DataReader#addPacketReceiveListener(IPacketReceiveListener, int))}.
*/
@Test
public final void testAddPacketReceiveListenerFrameID() {
// Setup the resources for the test.
IPacketReceiveListener l = Mockito.mock(IPacketReceiveListener.class);
DataReader reader = new DataReader(testCI, OperatingMode.API, mockDevice);
int frameID = 1;
// Call the method under test.
reader.addPacketReceiveListener(l, frameID);
// Verify the result.
HashMap<IPacketReceiveListener, Integer> map = Whitebox.getInternalState(reader, "packetReceiveListeners");
assertThat(map.size(), is(equalTo(1)));
assertThat(map.containsKey(l), is(equalTo(true)));
assertThat(map.get(l), is(equalTo(frameID)));
}
@SuppressWarnings("unchecked")
@Test
public void buildMimeMessagePreparator() throws Exception {
//MimeMessage mockMessage = PowerMockito.mock(MimeMessage.class);
MimeMessageHelper mockMessageHelper = PowerMockito.mock(MimeMessageHelper.class);
PowerMockito.whenNew(MimeMessageHelper.class).withArguments(any(MimeMessage.class), anyBoolean()).thenReturn(mockMessageHelper);
when(mailContentBuilderService.buildPlainTextMail(anyString(), anyMap())).thenReturn("content");
mailService = PowerMockito.spy(new MailService(mailSender, mailContentBuilderService));
String from = "from";
List<String> to = Lists.newArrayList();
to.add("[email protected]");
String subject = "subject";
String mailMessageUrlOrBody = "mailMessageUrlOrBody";
Map<String, Object> placeholderValues = Maps.newHashMap();
placeholderValues.put("name", "134");
final String attachmentUrl = "www.test.com";
final Boolean isPlainMessage = true;
final MailService classUnderTest = PowerMockito.spy(new MailService(mailSender, mailContentBuilderService));
Whitebox.invokeMethod(classUnderTest, "buildMimeMessagePreparator", from, to, subject, mailMessageUrlOrBody,
placeholderValues, attachmentUrl, isPlainMessage);
}
@Test
@SuppressWarnings("unchecked")
public void prepare() throws Exception {
PowerMockito.mockStatic(EtcdUtils.class);
ClusterModuleEtcdConfig etcdConfig = new ClusterModuleEtcdConfig();
etcdConfig.setHostPort("10.0.0.1:1000,10.0.0.2:1001");
Whitebox.setInternalState(provider, "config", etcdConfig);
provider.prepare();
List<URI> uris = mock(List.class);
PowerMockito.when(EtcdUtils.parse(etcdConfig)).thenReturn(uris);
ArgumentCaptor<ClusterModuleEtcdConfig> addressCaptor = ArgumentCaptor.forClass(ClusterModuleEtcdConfig.class);
PowerMockito.verifyStatic();
EtcdUtils.parse(addressCaptor.capture());
ClusterModuleEtcdConfig cfg = addressCaptor.getValue();
assertEquals(etcdConfig.getHostPort(), cfg.getHostPort());
}
@Before
public void setUp() throws Exception {
mockFactory = new MetaverseObjectFactory();
when( mockBuilder.getMetaverseObjectFactory() ).thenReturn( mockFactory );
when( mockNamespace.getParentNamespace() ).thenReturn( mockNamespace );
analyzer = new JsonOutputAnalyzer() {};
analyzer.setMetaverseBuilder( mockBuilder );
when( mockJsonOutput.getStepMetaInterface() ).thenReturn( meta );
when( mockJsonOutput.getStepMeta() ).thenReturn( mockStepMeta );
when( mockStepMeta.getStepMetaInterface() ).thenReturn( meta );
Whitebox.setInternalState( ExternalResourceCache.getInstance(), "transMap", new ConcurrentHashMap() );
Whitebox.setInternalState( ExternalResourceCache.getInstance(), "resourceMap", new ConcurrentHashMap() );
}
@Test
public void testAccumulatorRegistrationOnOperatorClose() throws Exception {
DoFnOperator doFnOperator = getOperatorForCleanupInspection();
OneInputStreamOperatorTestHarness<WindowedValue<String>, WindowedValue<String>> testHarness =
new OneInputStreamOperatorTestHarness<>(doFnOperator);
testHarness.open();
String metricContainerFieldName = "flinkMetricContainer";
FlinkMetricContainer monitoredContainer =
Mockito.spy(
(FlinkMetricContainer)
Whitebox.getInternalState(doFnOperator, metricContainerFieldName));
Whitebox.setInternalState(doFnOperator, metricContainerFieldName, monitoredContainer);
// Closes and disposes the operator
testHarness.close();
// Ensure that dispose has the metrics code
doFnOperator.dispose();
Mockito.verify(monitoredContainer, Mockito.times(2)).registerMetricsForPipelineResult();
}
@Test
public void test_getPageModelProvider_not_exists_in_map()
{
String controllerClass = "com.webpagebytes.cms.engine.DummyPageModelProvider";
try
{
WPBPageModelProvider result = Whitebox.invokeMethod(pageContentBuilder, "getPageModelProvider", controllerClass);
assertTrue (result != null);
Map<String, WPBPageModelProvider> controllers = Whitebox.getInternalState(pageContentBuilder, "customControllers");
assertTrue (controllers.get(controllerClass) != null);
} catch (Exception e)
{
assertTrue (false);
}
}
@Test
public void testExpiredReservoirNegativeBernoulliSample() {
Clock clock = Clock.fixed(Instant.ofEpochSecond(1500000000), ZoneId.systemDefault());
SamplingRule input = createInput("r1", 300, 0, 0.2);
CentralizedRule rule = new CentralizedRule(input, rand);
SamplingTargetDocument target = createTarget(0, 0.2, 1499999999);
rule.update(target, clock.instant());
Mockito.when(rand.next()).thenReturn(0.4);
SamplingResponse response = rule.sample(clock.instant());
Assert.assertFalse(response.isSampled());
Assert.assertEquals("r1", response.getRuleName().get());
Statistics s = Whitebox.getInternalState(rule, "statistics", CentralizedRule.class);
Assert.assertEquals(0, s.getSampled());
Assert.assertEquals(1, s.getRequests());
Assert.assertEquals(0, s.getBorrowed());
}
@Test
public void testDeleteShellThrowsFaultException() throws Exception {
mockExecuteRequest();
PowerMockito.mockStatic(WSManUtils.class);
Mockito.when(WSManUtils.isSpecificResponseAction(RESPONSE_BODY, DELETE_RESPONSE_ACTION)).thenReturn(false);
Mockito.when(WSManUtils.isFaultResponse(RESPONSE_BODY)).thenReturn(true);
Mockito.when(WSManUtils.getResponseFault(RESPONSE_BODY)).thenReturn(FAULT_MESSAGE);
thrownException.expectMessage(FAULT_MESSAGE);
Whitebox.invokeMethod(wsManRemoteShellServiceSpy, WSManRemoteShellServiceTest.DELETE_SHELL_METHOD, csHttpClientMock, httpClientInputsMock, SHELL_UUID, wsManRequestInputs);
verifyStatic();
WSManUtils.isSpecificResponseAction(RESPONSE_BODY, DELETE_RESPONSE_ACTION);
WSManUtils.isFaultResponse(RESPONSE_BODY);
WSManUtils.getResponseFault(RESPONSE_BODY);
}
@Test
public void testNegativeSample() {
Clock clock = Clock.fixed(Instant.ofEpochSecond(1500000000), ZoneId.systemDefault());
SamplingRule input = createInput("r1", 300, 10, 0.0);
CentralizedRule rule = new CentralizedRule(input, rand);
SamplingTargetDocument target = createTarget(0, 0.0, 1500000010);
rule.update(target, clock.instant());
SamplingResponse response = rule.sample(clock.instant());
Assert.assertFalse(response.isSampled());
Assert.assertEquals("r1", response.getRuleName().get());
Statistics s = Whitebox.getInternalState(rule, "statistics", CentralizedRule.class);
Assert.assertEquals(0, s.getSampled());
Assert.assertEquals(1, s.getRequests());
Assert.assertEquals(0, s.getBorrowed());
}
/**
* Test method for {@link com.digi.xbee.api.DataReader#addIPDataReceiveListener(com.digi.xbee.api.listeners.IIPDataReceiveListener)}.
*/
@Test
public final void testAddIPDataReceiveListenerExistingListener() {
// Setup the resources for the test.
IIPDataReceiveListener l = Mockito.mock(IIPDataReceiveListener.class);
DataReader reader = new DataReader(testCI, OperatingMode.API, mockDevice);
reader.addIPDataReceiveListener(l);
ArrayList<IIOSampleReceiveListener> list = Whitebox.getInternalState(reader, "ipDataReceiveListeners");
assertThat(list.size(), is(equalTo(1)));
assertThat(list.contains(l), is(equalTo(true)));
// Call the method under test.
reader.addIPDataReceiveListener(l);
// Verify the result.
list = Whitebox.getInternalState(reader, "ipDataReceiveListeners");
assertThat(list.size(), is(equalTo(1)));
assertThat(list.contains(l), is(equalTo(true)));
}
@Test
public void testPrintMessageFiltered() {
LogLevel logLevelFil = PowerMockito.mock( LogLevel.class );
Whitebox.setInternalState( logLevelFil, "name", "Error" );
Whitebox.setInternalState( logLevelFil, "ordinal", 1 );
when( logLevelFil.isError() ).thenReturn( false );
ILogMessage logMsgInterfaceFil = mock( ILogMessage.class );
Mockito.when( logMsgInterfaceFil.getLevel() ).thenReturn( logLevelFil );
Mockito.when( logMsgInterfaceFil.toString() ).thenReturn( "a" );
PowerMockito.mockStatic( Utils.class );
when( Utils.isEmpty( anyString() ) ).thenReturn( false );
when( logLevelFil.isVisible( any( LogLevel.class ) ) ).thenReturn( true );
logChannel.setFilter( "b" );
logChannel.println( logMsgInterfaceFil, LogLevel.BASIC );
verify( logChFileWriterBuffer, times( 0 ) ).addEvent( any( HopLoggingEvent.class ) );
}
/**
* Test method for {@link com.digi.xbee.api.listeners.IDataReceiveListener#dataReceived(XBeeMessage)} and
* {@link com.digi.xbee.api.DataReader#packetReceived(XBeePacket)}.
*
* <p>Verify that, when subscribed to receive data and a packet that does not correspond to
* data, the callback of the listener is not executed.</p>
*
* @throws Exception
*/
@Test
public void testDataReceiveSubscribedInvalid() throws Exception {
// Subscribe to listen for data.
dataReader.addDataReceiveListener(receiveDataListener);
// Fire the private packetReceived method of the dataReader with an invalid packet.
Whitebox.invokeMethod(dataReader, PACKET_RECEIVED_METHOD, invalidPacket);
// Verify that the notifyDataReceived private method was not called.
PowerMockito.verifyPrivate(dataReader, Mockito.never()).invoke(NOTIFY_DATA_RECEIVED_METHOD,
Mockito.any(XBeeMessage.class));
// Verify that the callback of the listener was not executed
Mockito.verify(receiveDataListener, Mockito.never()).dataReceived(Mockito.any(XBeeMessage.class));
// All the parameters of our listener should be empty.
assertNull(receiveDataListener.get64BitAddress());
assertNull(receiveDataListener.getData());
assertFalse(receiveDataListener.isBroadcast());
}
@Test
public void testSimpleTimer() {
// Creating a simplify timer
final SkywalkingMeterRegistry registry = new SkywalkingMeterRegistry();
final Timer timer = registry.timer("test_simple_timer", "skywalking", "test");
// Check Skywalking type
Assert.assertTrue(timer instanceof SkywalkingTimer);
final List<MeterId.Tag> tags = Arrays.asList(new MeterId.Tag("skywalking", "test"));
// Multiple record data
timer.record(10, TimeUnit.MILLISECONDS);
timer.record(20, TimeUnit.MILLISECONDS);
timer.record(3, TimeUnit.MILLISECONDS);
// Check micrometer data
Assert.assertEquals(3, timer.count());
Assert.assertEquals(33d, timer.totalTime(TimeUnit.MILLISECONDS), 0.0);
Assert.assertEquals(20d, timer.max(TimeUnit.MILLISECONDS), 0.0);
// Check Skywalking data
assertCounter(Whitebox.getInternalState(timer, "counter"), "test_simple_timer_count", tags, 3d);
assertCounter(Whitebox.getInternalState(timer, "sum"), "test_simple_timer_sum", tags, 33d);
assertGauge(Whitebox.getInternalState(timer, "max"), "test_simple_timer_max", tags, 20d);
assertHistogramNull(Whitebox.getInternalState(timer, "histogram"));
}
@SuppressWarnings("unchecked")
@Test
public void testUpdateVlanMode() throws Exception {
Port port = mock(Port.class);
Column<GenericTableSchema, Set<String>> column = mock(Column.class);
when(port.getVlanModeColumn()).thenReturn(column);
Set<String> set = new HashSet<>();
set.add(VLAN_MODE_ACCESS);
when(column.getData()).thenReturn(set);
OvsdbTerminationPointAugmentationBuilder ovsdbTerminationPointBuilder = mock(
OvsdbTerminationPointAugmentationBuilder.class);
when(ovsdbTerminationPointBuilder.setVlanMode(OvsdbPortInterfaceAttributes.VlanMode.Access))
.thenReturn(ovsdbTerminationPointBuilder);
Whitebox.invokeMethod(ovsdbPortUpdateCommand, "updateVlanMode", port, ovsdbTerminationPointBuilder);
verify(ovsdbTerminationPointBuilder).setVlanMode(any(VlanMode.class));
}
/**
* Tests that reading an XStream file with the proto attribute converts to the scheme attribute.
* Jenkins behaves a bit differently than XStream does out of the box, so it isn't a fully comparable test.
*
* @throws IOException if so.
*/
@Test
public void testProtoToScheme() throws IOException {
//Provider = "Default", "review", "29418", "ssh", "http://review:8080/", "2.6"
XStream x = new XStream();
x.aliasPackage("com.sonyericsson.hudson.plugins.gerrit.gerritevents",
"com.sonymobile.tools.gerrit.gerritevents");
PatchsetCreated event = (PatchsetCreated)x.fromXML(getClass()
.getResourceAsStream("DeserializeProviderTest.xml"));
Provider provider = event.getProvider();
assertNotNull(provider);
assertEquals("ssh", provider.getScheme()); //The important test
assertEquals("Default", provider.getName());
assertNull(Whitebox.getInternalState(provider, "proto"));
}
protected boolean doNextAsyncTaskRunBackgroundEvenIfCancelled(Queue<AsyncTaskHolder> asyncTasks) throws Exception {
if (asyncTasks.size() > 0) {
AsyncTaskHolder holder = asyncTasks.peek();
AsyncTask asyncTask = holder.asyncTask;
Object res = Whitebox.invokeMethod(asyncTask, "doInBackground", holder.params);
asyncTasks.poll();
if (holder.canceled) {
Whitebox.invokeMethod(asyncTask, "onCancelled");
return false;
} else {
Whitebox.invokeMethod(asyncTask, "onPostExecute", res);
}
return true;
}
return false;
}
/**
* Test method for {@link com.digi.xbee.api.models.XBeePacketsQueue#isDataPacket(XBeePacket)}.
*
* <p>Verify that the {@code isDataPacket} method of the {@code XBeePacketsQueue} class works
* successfully for data packets.</p>
*
* @throws Exception
*/
@Test
public void testIsDataPacketTrue() throws Exception {
ArrayList<XBeePacket> dataPackets = new ArrayList<XBeePacket>();
// Fill the list of data packets.
dataPackets.add(mockedReceivePacket);
dataPackets.add(mockedRx64Packet);
dataPackets.add(mockedRx16Packet);
// Create an XBeePacketsQueue.
XBeePacketsQueue xbeePacketsQueue = PowerMockito.spy(new XBeePacketsQueue());
// Verify that packets contained in the data packets list are actually data packets.
for (XBeePacket packet:dataPackets)
assertTrue((Boolean)Whitebox.invokeMethod(xbeePacketsQueue, METHOD_IS_DATA_PACKET, packet));
}
@Test
public void Test_marshall() throws Exception {
String imageID = "ami-1";
String instanceType = InstanceType.C1_MEDIUM.getName();
int minCount = 1;
int maxCount = 1;
MockEC2QueryHandler handler = MockEC2QueryHandler.getInstance();
RunInstancesResponseType runInstancesResponseType = Whitebox.invokeMethod(handler,
"runInstances", imageID,
instanceType, minCount, maxCount);
String xml = JAXBUtil.marshall(runInstancesResponseType, "RunInstancesResponse",
"2012-02-10");
Assert.assertTrue(xml != null && !xml.isEmpty());
Assert.assertTrue(xml.contains("<imageId>ami-1</imageId>"));
Assert.assertTrue(xml.contains("<instanceType>c1.medium</instanceType>"));
}
@Test
public void testProcessCommandExecutionResponse() throws Exception {
doReturn(RECEIVE_RESULT).when(resultMock).get(RETURN_RESULT);
PowerMockito.doReturn(STDOUT_VALUE).when(wsManRemoteShellServiceSpy, BUILD_RESULT_FROM_RESPONSE_STREAMS_METHOD, RECEIVE_RESULT, OutputStream.STDOUT);
PowerMockito.doReturn(STDERR_VALUE).when(wsManRemoteShellServiceSpy, BUILD_RESULT_FROM_RESPONSE_STREAMS_METHOD, RECEIVE_RESULT, OutputStream.STDERR);
PowerMockito.mockStatic(WSManUtils.class);
PowerMockito.when(WSManUtils.getScriptExitCode(RECEIVE_RESULT)).thenReturn(SCRIPT_EXIT_CODE_ZERO);
Map<String, String> result = Whitebox.invokeMethod(wsManRemoteShellServiceSpy, PROCESS_COMMAND_EXECUTION_RESPONSE_METHOD, resultMock);
assertEquals(STDOUT_VALUE, result.get(RETURN_RESULT));
assertEquals(STDERR_VALUE, result.get(STDERR));
assertEquals(SCRIPT_EXIT_CODE_ZERO, result.get(SCRIPT_EXIT_CODE));
verify(resultMock, times(3)).get(RETURN_RESULT);
verifyStatic();
WSManUtils.getScriptExitCode(RECEIVE_RESULT);
}
/**
* Test method for {@link com.digi.xbee.api.listeners.IModemStatusReceiveListener#modemStatusEventReceived(ModemStatusEvent)}
* and {@link com.digi.xbee.api.DataReader#packetReceived(XBeePacket)}.
*
* <p>Verify that, when subscribed to receive Modem Status events and a ModemStatusPacket is received,
* the callback of the listener is executed.</p>
*
* @throws Exception
*/
@Test
public void testModemStatusReceiveSubscribed() throws Exception {
// Subscribe to listen for Modem Status events.
dataReader.addModemStatusReceiveListener(receiveModemStatusListener);
// Fire the private packetReceived method of the dataReader with a ModemStatusPacket.
Whitebox.invokeMethod(dataReader, PACKET_RECEIVED_METHOD, modemStatusPacket);
// Verify that the notifyModemStatusReceived private method was called with the correct Modem Status event.
PowerMockito.verifyPrivate(dataReader, Mockito.times(1)).invoke(NOTIFY_MODEM_STATUS_RECEIVED_METHOD, MODEM_STATUS_EVENT);
// Verify that the listener callback was executed one time.
Mockito.verify(receiveModemStatusListener, Mockito.times(1)).modemStatusEventReceived(Mockito.any(ModemStatusEvent.class));
assertEquals(MODEM_STATUS_EVENT, receiveModemStatusListener.getModemStatus());
}
@Test
public void testPutandGetInstanceIdentifier() throws Exception {
ConnectionInfo key = mock(ConnectionInfo.class);
ConnectionInfo connectionInfo = mock(ConnectionInfo.class);
PowerMockito.mockStatic(SouthboundMapper.class);
when(SouthboundMapper.suppressLocalIpPort(key)).thenReturn(connectionInfo);
instanceIdentifiers = new ConcurrentHashMap<>();
field(OvsdbConnectionManager.class, "instanceIdentifiers").set(ovsdbConnManager, instanceIdentifiers);
//Test putInstanceIdentifier()
Whitebox.invokeMethod(ovsdbConnManager, "putInstanceIdentifier", key, iid);
Map<ConnectionInfo, OvsdbConnectionInstance> testIids = Whitebox.getInternalState(ovsdbConnManager,
"instanceIdentifiers");
assertEquals("Error, size of the hashmap is incorrect", 1, testIids.size());
//Test getInstanceIdentifier()
assertEquals("Error returning correct InstanceIdentifier object", iid,
ovsdbConnManager.getInstanceIdentifier(key));
//Test removeInstanceIdentifier()
Whitebox.invokeMethod(ovsdbConnManager, "removeInstanceIdentifier", key);
Map<ConnectionInfo, OvsdbConnectionInstance> testRemoveIids = Whitebox.getInternalState(ovsdbConnManager,
"instanceIdentifiers");
assertEquals("Error, size of the hashmap is incorrect", 0, testRemoveIids.size());
}
@Test
@PrepareOnlyThisForTest( { NioDatagramSession.class, NioProcessor.class, AbstractIoSession.class })
public void assertThatPrepareOnlyThisForTestWorks() throws Exception {
final String scheduleRemoveMethodName = "scheduleRemove";
Executor executor = createMock(Executor.class);
NioProcessor objectUnderTest = createPartialMock(NioProcessor.class, new String[] { scheduleRemoveMethodName }, executor);
NioDatagramSession session = createMock(NioDatagramSession.class);
expect(session.isConnected()).andReturn(false);
expectPrivate(objectUnderTest, scheduleRemoveMethodName, session).once();
replay(objectUnderTest, executor, session);
assertFalse(Whitebox.<Boolean> invokeMethod(objectUnderTest, "flushNow", session, 20L));
verify(objectUnderTest, executor, session);
}
@Test
public void testRuleUpdateWithInvalidation() {
SamplingRule input = createInput("r1", 300, 10, 0.0)
.withHTTPMethod("POST")
.withServiceName("s1")
.withURLPath("/foo/bar");
CentralizedRule r = new CentralizedRule(input, new RandImpl());
SamplingRule update = createInput("r1", 301, 5, 0.5)
.withHTTPMethod("GET")
.withServiceName("s2")
.withURLPath("/bar/foo");
boolean invalidate = r.update(update);
Matchers m = Whitebox.getInternalState(r, "matchers", CentralizedRule.class);
Assert.assertEquals("GET", Whitebox.getInternalState(m, "method", Matchers.class));
Assert.assertEquals("s2", Whitebox.getInternalState(m, "service", Matchers.class));
Assert.assertEquals("/bar/foo", Whitebox.getInternalState(m, "url", Matchers.class));
Assert.assertTrue(invalidate);
}
/**
* Test method for {@link com.digi.xbee.api.DataReader#removeModemStatusReceiveListener(com.digi.xbee.api.listeners.IModemStatusReceiveListener)}.
*/
@Test
public final void testRemoveModemStatusReceiveListener() {
// Setup the resources for the test.
IModemStatusReceiveListener l = Mockito.mock(IModemStatusReceiveListener.class);
DataReader reader = new DataReader(testCI, OperatingMode.API, mockDevice);
reader.addModemStatusReceiveListener(l);
// Call the method under test.
reader.removeModemStatusReceiveListener(l);
// Verify the result.
ArrayList<IModemStatusReceiveListener> list = Whitebox.getInternalState(reader, "modemStatusListeners");
assertThat(list.size(), is(equalTo(0)));
assertThat(list.contains(l), is(equalTo(false)));
}
@SuppressWarnings("unchecked")
@Test
public void testUpdateManagers() throws Exception {
Map<UUID, OpenVSwitch> updatedOpenVSwitchRows = new HashMap<>();
OpenVSwitch openVSwitch = mock(OpenVSwitch.class);
updatedOpenVSwitchRows.put(mock(UUID.class), openVSwitch);
PowerMockito.mockStatic(SouthboundMapper.class);
List<ManagerEntry> managerEntries = new ArrayList<>();
managerEntries.add(mock(ManagerEntry.class));
when(SouthboundMapper.createManagerEntries(any(OpenVSwitch.class), any(Map.class))).thenReturn(managerEntries);
// mock getManagerEntryIid()
ReadWriteTransaction transaction = mock(ReadWriteTransaction.class);
Map<UUID, Manager> updatedManagerRows = new HashMap<>();
PowerMockito.doReturn(mock(InstanceIdentifier.class)).when(ovsdbManagersUpdateCommand, "getManagerEntryIid",
any(ManagerEntry.class));
doNothing().when(transaction).merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class),
any(ManagerEntry.class));
Whitebox.invokeMethod(ovsdbManagersUpdateCommand, "updateManagers", transaction, updatedManagerRows,
updatedOpenVSwitchRows);
verify(transaction).merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class),
any(ManagerEntry.class));
}