Java Code Examples for org.powermock.reflect.Whitebox#getInternalState()

The following examples show how to use org.powermock.reflect.Whitebox#getInternalState() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CentralizedRuleTest.java    From aws-xray-sdk-java with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 2
Source File: DataReaderTest.java    From xbee-java with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Test method for {@link com.digi.xbee.api.DataReader#addExplicitDataReceiveListener(com.digi.xbee.api.listeners.IExplicitDataReceiveListener)}. 
 */
@Test
public final void testAddExplicitDataeReceiveListenerExistingListener() {
	// Setup the resources for the test.
	IExplicitDataReceiveListener l = Mockito.mock(IExplicitDataReceiveListener.class);
	DataReader reader = new DataReader(testCI, OperatingMode.API, mockDevice);
	
	reader.addExplicitDataReceiveListener(l);
	
	ArrayList<IExplicitDataReceiveListener> list = Whitebox.getInternalState(reader, "explicitDataReceiveListeners");
	assertThat(list.size(), is(equalTo(1)));
	assertThat(list.contains(l), is(equalTo(true)));
	
	// Call the method under test.
	reader.addExplicitDataReceiveListener(l);
	
	// Verify the result.
	list = Whitebox.getInternalState(reader, "explicitDataReceiveListeners");
	assertThat(list.size(), is(equalTo(1)));
	assertThat(list.contains(l), is(equalTo(true)));
}
 
Example 3
Source File: CentralizedRuleTest.java    From aws-xray-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testRuleUpdateWithoutInvalidation() {
    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", 300, 10, 0.0)
            .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.assertFalse(invalidate);
}
 
Example 4
Source File: SubscriptionTest.java    From nsq-j with MIT License 6 votes vote down vote up
private void testLowFlight(Subscriber subscriber, Subscription sub, int maxInflight, int numCons) throws Exception {
    sub.setMaxInFlight(maxInflight);
    checkHosts(sub, numCons);
    assertTrue(sub.isLowFlight());
    Map<HostAndPort, SubConnection> conMap = Whitebox.getInternalState(sub, "connectionMap");

    Set<SubConnection> ready = getReady(conMap.values());
    Set<SubConnection> paused = Sets.difference(new HashSet<SubConnection>(conMap.values()), ready);

    assertEquals(maxInflight, ready.size());
    assertEquals(numCons - maxInflight, paused.size());

    Whitebox.invokeMethod(sub, "rotateLowFlight");

    Set<SubConnection> nextReady = getReady(conMap.values());
    Set<SubConnection> nextPaused = Sets.difference(new HashSet<SubConnection>(conMap.values()), nextReady);

    assertEquals(maxInflight, nextReady.size());
    assertEquals(numCons - maxInflight, nextPaused.size());
    assertEquals(1, Sets.difference(ready, nextReady).size());
    assertEquals(1, Sets.difference(paused, nextPaused).size());
}
 
Example 5
Source File: DataReaderTest.java    From xbee-java with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Test method for {@link com.digi.xbee.api.DataReader#removeIPDataReceiveListener(com.digi.xbee.api.listeners.IIPDataReceiveListener)}. 
 */
@Test
public final void testRemoveIPDataReceiveListener() {
	// Setup the resources for the test.
	IIPDataReceiveListener l = Mockito.mock(IIPDataReceiveListener.class);
	DataReader reader = new DataReader(testCI, OperatingMode.API, mockDevice);
	
	reader.addIPDataReceiveListener(l);
	
	// Call the method under test.
	reader.removeIPDataReceiveListener(l);
	
	// Verify the result.
	ArrayList<IIPDataReceiveListener> list = Whitebox.getInternalState(reader, "ipDataReceiveListeners");
	assertThat(list.size(), is(equalTo(0)));
	assertThat(list.contains(l), is(equalTo(false)));
}
 
Example 6
Source File: XBeeNetworkDiscoverDevicesListenerTest.java    From xbee-java with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Test method for {@link com.digi.xbee.api.XBeeNetwork#removeDiscoveryListener(IDiscoveryListener)}.
 */
@Test
public void testRemoveDiscoveryListener() {
	// Setup the resources for the test.
	IDiscoveryListener listener = PowerMockito.mock(IDiscoveryListener.class);
	
	// Add the listener.
	network.addDiscoveryListener(listener);
	
	// Verify that the listener has been added successfully.
	List<IDiscoveryListener> internalListenersList = Whitebox.<List<IDiscoveryListener>> getInternalState(network, "discoveryListeners");
	assertEquals(internalListenersList.size(), 1);
	assertEquals(internalListenersList.get(0), listener);
	
	// Call the method under test.
	network.removeDiscoveryListener(listener);
	
	// Verify that the listener has been removed successfully.
	assertEquals(internalListenersList.size(), 0);
}
 
Example 7
Source File: TestTajoClient.java    From tajo with Apache License 2.0 6 votes vote down vote up
@Test
public void testClientRPCInterference() throws Exception {
  TajoClient client = cluster.newTajoClient();
  TajoClient client2 = cluster.newTajoClient();


  NettyClientBase rpcClient = Whitebox.getInternalState(client, NettyClientBase.class);
  assertNotNull(rpcClient);

  NettyClientBase rpcClient2 = Whitebox.getInternalState(client2, NettyClientBase.class);
  assertNotNull(rpcClient);

  assertNotEquals(rpcClient.getChannel().eventLoop(), rpcClient2.getChannel().eventLoop());

  client.close();
  client2.close();

  rpcClient.getChannel().eventLoop().terminationFuture().sync();
  assertTrue(rpcClient.getChannel().eventLoop().isTerminated());

  rpcClient2.getChannel().eventLoop().terminationFuture().sync();
  assertTrue(rpcClient2.getChannel().eventLoop().isTerminated());
}
 
Example 8
Source File: DataReaderTest.java    From xbee-java with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Test method for {@link com.digi.xbee.api.DataReader#addDataReceiveListener(com.digi.xbee.api.listeners.IDataReceiveListener)}. 
 */
@Test
public final void testAddDataReceiveListener() {
	// Setup the resources for the test.
	IDataReceiveListener l = Mockito.mock(IDataReceiveListener.class);
	DataReader reader = new DataReader(testCI, OperatingMode.API, mockDevice);
	
	// Call the method under test.
	reader.addDataReceiveListener(l);
	
	// Verify the result.
	ArrayList<IDataReceiveListener> list = Whitebox.getInternalState(reader, "dataReceiveListeners");
	assertThat(list.size(), is(equalTo(1)));
	assertThat(list.contains(l), is(equalTo(true)));
}
 
Example 9
Source File: ExecutableStageDoFnOperatorTest.java    From beam with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testEnsureStateCleanupWithKeyedInput() throws Exception {
  TupleTag<Integer> mainOutput = new TupleTag<>("main-output");
  DoFnOperator.MultiOutputOutputManagerFactory<Integer> outputManagerFactory =
      new DoFnOperator.MultiOutputOutputManagerFactory(mainOutput, VarIntCoder.of());
  VarIntCoder keyCoder = VarIntCoder.of();
  ExecutableStageDoFnOperator<Integer, Integer> operator =
      getOperator(
          mainOutput,
          Collections.emptyList(),
          outputManagerFactory,
          WindowingStrategy.globalDefault(),
          keyCoder,
          WindowedValue.getFullCoder(keyCoder, GlobalWindow.Coder.INSTANCE));

  KeyedOneInputStreamOperatorTestHarness<Integer, WindowedValue<Integer>, WindowedValue<Integer>>
      testHarness =
          new KeyedOneInputStreamOperatorTestHarness(
              operator, val -> val, new CoderTypeInformation<>(keyCoder));

  RemoteBundle bundle = Mockito.mock(RemoteBundle.class);
  when(bundle.getInputReceivers())
      .thenReturn(
          ImmutableMap.<String, FnDataReceiver<WindowedValue>>builder()
              .put("input", Mockito.mock(FnDataReceiver.class))
              .build());
  when(stageBundleFactory.getBundle(any(), any(), any(), any())).thenReturn(bundle);

  testHarness.open();

  Object doFnRunner = Whitebox.getInternalState(operator, "doFnRunner");
  assertThat(doFnRunner, instanceOf(DoFnRunnerWithMetricsUpdate.class));

  // There should be a StatefulDoFnRunner installed which takes care of clearing state
  Object statefulDoFnRunner = Whitebox.getInternalState(doFnRunner, "delegate");
  assertThat(statefulDoFnRunner, instanceOf(StatefulDoFnRunner.class));
}
 
Example 10
Source File: XBeeNetworkConfigurationTest.java    From xbee-java with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Test method for {@link com.digi.xbee.api.XBeeNetwork#clearDeviceList()}.
 * 
 * Clear non-empty network.
 */
@Test
public final void testClear() {
	// Setup the resources for the test.
	List<RemoteXBeeDevice> list = new ArrayList<RemoteXBeeDevice>(0);
	for (int i = 0; i < 3; i++)
		list.add(new RemoteXBeeDevice(deviceMock, 
				new XBee64BitAddress("0013A20040A9E78"+i), 
				XBee16BitAddress.UNKNOWN_ADDRESS, "id"+i));
	
	network.addRemoteDevices(list);
	
	Map<XBee64BitAddress, RemoteXBeeDevice> add64Map = Whitebox.<Map<XBee64BitAddress, RemoteXBeeDevice>> getInternalState(network, "remotesBy64BitAddr");
	Map<XBee16BitAddress, RemoteXBeeDevice> add16Map = Whitebox.<Map<XBee16BitAddress, RemoteXBeeDevice>> getInternalState(network, "remotesBy16BitAddr");
	
	assertThat(add64Map.size(), is(equalTo(3)));
	assertThat(add16Map.size(), is(equalTo(0)));
	
	assertThat("There must be " + list.size() + " devices in the network", network.getNumberOfDevices(), is(equalTo(list.size())));
	
	// Call the method under test.
	network.clearDeviceList();
	
	// Verify the result.
	assertThat(add64Map.size(), is(equalTo(0)));
	assertThat(add16Map.size(), is(equalTo(0)));
	
	assertThat("The network must be empty", network.getNumberOfDevices(), is(equalTo(0)));
}
 
Example 11
Source File: SerializableMockitoMethodProxyTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldCreateCorrectCreationInfo() throws Exception {
    // given
    MethodProxy proxy = MethodProxy.create(String.class, Integer.class, "", "", "");
    SerializableMockitoMethodProxy serializableMockitoMethodProxy = new SerializableMockitoMethodProxy(proxy);

    // when
    Object methodProxy = Whitebox.invokeMethod(serializableMockitoMethodProxy, "getMethodProxy",  new Object[0]);

    // then
    Object info = Whitebox.getInternalState(methodProxy, "createInfo");
    assertEquals(String.class, Whitebox.getInternalState(info, "c1"));
    assertEquals(Integer.class, Whitebox.getInternalState(info, "c2"));
}
 
Example 12
Source File: BasicValidatorTest.java    From AwesomeValidation with MIT License 5 votes vote down vote up
public void testValidationCallbackExecute() {
    ValidationCallback validationCallback = Whitebox.getInternalState(mSpiedBasicValidator, "mValidationCallback");
    Matcher mockMatcher = PowerMockito.mock(Matcher.class);
    EditText mockEditText = mock(EditText.class);
    String mockErrMsg = PowerMockito.mock(String.class);
    when(mMockValidationHolder.getEditText()).thenReturn(mockEditText);
    when(mMockValidationHolder.getErrMsg()).thenReturn(mockErrMsg);
    doNothing().when(mockEditText).setError(mockErrMsg);
    validationCallback.execute(mMockValidationHolder, mockMatcher);
    verify(mockEditText).setError(mockErrMsg);
}
 
Example 13
Source File: XBeeNetworkDiscoverDevicesListenerTest.java    From xbee-java with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Test method for {@link com.digi.xbee.api.XBeeNetwork#addDiscoveryListener(IDiscoveryListener)}.
 */
@Test
public void testAddDiscoveryListener() {
	// Setup the resources for the test.
	IDiscoveryListener listener = PowerMockito.mock(IDiscoveryListener.class);
	
	// Call the method under test.
	network.addDiscoveryListener(listener);
	
	// Verify that the listener has been added successfully.
	List<IDiscoveryListener> internalListenersList = Whitebox.<List<IDiscoveryListener>> getInternalState(network, "discoveryListeners");
	assertEquals(internalListenersList.size(), 1);
	assertEquals(internalListenersList.get(0), listener);
}
 
Example 14
Source File: SimpleFrameVisitorTest.java    From amazon-kinesis-video-streams-parser-library with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithMkvVideo() throws Exception {
    streamingMkvReader = StreamingMkvReader.createDefault(getClustersByteSource("clusters.mkv"));
    streamingMkvReader.apply(frameVisitor);

    Assert.assertEquals(SIMPLE_BLOCKS_COUNT_MKV, frameProcessCount);
    Assert.assertEquals(nullFrameCount, 0);
    MkvElementVisitor internal =  Whitebox.getInternalState(frameVisitor, "frameVisitorInternal");
    long timeCode = Whitebox.getInternalState(internal, "clusterTimeCode");
    long timeCodeScale = Whitebox.getInternalState(internal, "timeCodeScale");
    Assert.assertNotEquals(-1, timeCode);
    Assert.assertNotEquals(-1, timeCodeScale);
}
 
Example 15
Source File: XBeeNetworkConfigurationTest.java    From xbee-java with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Test method for {@link com.digi.xbee.api.XBeeNetwork#addRemoteDevices(java.util.List)}.
 * 
 * Add a list of devices to not empty network and a already existing device.
 */
@Test
public final void testAddRemoteDevices16BitToNetworkWithAlreadyExistingDevices() {
	// Setup the resources for the test.
	List<RemoteXBeeDevice> list = new ArrayList<RemoteXBeeDevice>(0);
	for (int i = 0; i < 3; i++)
		list.add(new RemoteXBeeDevice(deviceMock, 
				XBee64BitAddress.UNKNOWN_ADDRESS, 
				new XBee16BitAddress("123"+i), "id"+i));
	
	RemoteXBeeDevice deviceAlreadyInNetwork = PowerMockito.spy(
			new RemoteXBeeDevice(deviceMock, 
			XBee64BitAddress.UNKNOWN_ADDRESS, 
			new XBee16BitAddress("1230"), "id0_old"));
	network.addRemoteDevice(deviceAlreadyInNetwork);
	
	// Call the method under test.
	List<RemoteXBeeDevice> added = network.addRemoteDevices(list);
	
	// Verify the result.
	Map<XBee64BitAddress, RemoteXBeeDevice> add64Map = Whitebox.<Map<XBee64BitAddress, RemoteXBeeDevice>> getInternalState(network, "remotesBy64BitAddr");
	Map<XBee16BitAddress, RemoteXBeeDevice> add16Map = Whitebox.<Map<XBee16BitAddress, RemoteXBeeDevice>> getInternalState(network, "remotesBy16BitAddr");
	
	assertThat(add64Map.size(), is(equalTo(0)));
	assertThat(add16Map.size(), is(equalTo(3)));
	
	Mockito.verify(network, Mockito.times(list.size() + 1 /*We are adding in the setup*/)).addRemoteDevice(Mockito.any(RemoteXBeeDevice.class));
	
	assertThat("Returned list must contain " + list.size(), added.size(), is(equalTo(list.size())));
	assertThat("The network must contain " + list.size(), network.getNumberOfDevices(), is(equalTo(list.size())));
	assertThat("The added reference and the returned must be the different", list == added, is(equalTo(false)));
	
	Mockito.verify(deviceAlreadyInNetwork, Mockito.times(1)).updateDeviceDataFrom(list.get(0));
	assertThat("The reference of existing device in the network and in the list to add must be different", 
			list.get(0) == added.get(0), is(equalTo(false)));
	for (int i = 1; i < list.size(); i++)
		assertThat("The device reference in the network and in the list to add must be the same", 
				list.get(i) == added.get(i), is(equalTo(true)));
}
 
Example 16
Source File: ITClusterModuleEtcdProviderFunctionalTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Test
public void unregisterRemoteOfCluster() throws Exception {
    final String serviceName = "unregister_remote_cluster";
    ModuleProvider providerA = createProvider(serviceName);
    ModuleProvider providerB = createProvider(serviceName);

    Address addressA = new Address("127.0.0.4", 1000, true);
    Address addressB = new Address("127.0.0.5", 1000, true);

    RemoteInstance instanceA = new RemoteInstance(addressA);
    RemoteInstance instanceB = new RemoteInstance(addressB);

    getClusterRegister(providerA).registerRemote(instanceA);
    getClusterRegister(providerB).registerRemote(instanceB);

    List<RemoteInstance> remoteInstancesOfA = queryRemoteNodes(providerA, 2);
    validateServiceInstance(addressA, addressB, remoteInstancesOfA);

    List<RemoteInstance> remoteInstancesOfB = queryRemoteNodes(providerB, 2);
    validateServiceInstance(addressB, addressA, remoteInstancesOfB);

    // unregister A
    EtcdClient client = Whitebox.getInternalState(providerA, "client");
    client.close();

    // only B
    remoteInstancesOfB = queryRemoteNodes(providerB, 1, 120);
    assertEquals(1, remoteInstancesOfB.size());
    Address address = remoteInstancesOfB.get(0).getAddress();
    assertEquals(address, addressB);
    assertTrue(addressB.isSelf());
}
 
Example 17
Source File: TestTableOrderProvider.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testTableOrderStrategy() throws Exception {
  List<String> expectedStrategyOrderedTables = expectedOrderOrNullIfError;
  if (expectedOrderOrNullIfError == null) {
    try {
      tableOrderProvider.initialize(tableContextsMap);
      Assert.fail("Table Order Provider initialization should have failed");
    } catch (StageException e) {
      //Expected
      LOG.info("Expected Error:", e);
    }
  } else {
    tableOrderProvider.initialize(tableContextsMap);
    Map<String, TableContext> tableContextMap = Whitebox.getInternalState(tableOrderProvider, "tableContextMap");

    Multimap<String, String> referredTablesMap = referredTablesTestRelation.getReferredTableMap();
    int totalNumberOfTables = Sets.union(referredTablesMap.keySet(), new HashSet<>(referredTablesMap.values())).size();
    Assert.assertEquals(totalNumberOfTables, tableContextMap.size());

    List<String> actualOrder = new LinkedList<>(tableOrderProvider.getOrderedTables());

    LOG.debug("Expected Order: {}", JOINER.join(expectedOrderOrNullIfError));
    LOG.debug("Actual Order: {}", JOINER.join(actualOrder));

    for (int i = 0; i < expectedStrategyOrderedTables.size(); i++) {
      String expectedTable = expectedStrategyOrderedTables.get(i);
      String actualTable = actualOrder.get(i);
      Assert.assertEquals("Table order seems to be wrong", expectedTable, actualTable);
    }
  }
}
 
Example 18
Source File: CGLIBHackerTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldSetMockitoNamingPolicyEvenIfMethodProxyIsProxied() throws Exception {
    //given
    MockitoMethodProxy proxiedMethodProxy = spy(new MethodProxyBuilder().build());
    
    //when
    new CGLIBHacker().setMockitoNamingPolicy(proxiedMethodProxy);
    
    //then
    Object realMethodProxy = Whitebox.invokeMethod(proxiedMethodProxy, "getMethodProxy", new Object[0]);
    Object createInfo = Whitebox.getInternalState(realMethodProxy, "createInfo");
    NamingPolicy namingPolicy = (NamingPolicy) Whitebox.getInternalState(createInfo, "namingPolicy");
    assertEquals(MockitoNamingPolicy.INSTANCE, namingPolicy);
}
 
Example 19
Source File: SimpleFrameVisitorTest.java    From amazon-kinesis-video-streams-parser-library with Apache License 2.0 5 votes vote down vote up
@Test(expected = MkvElementVisitException.class)
public void testWhenNoTimeCode() throws Exception {
    MkvElementVisitor internal =  Whitebox.getInternalState(frameVisitor, "frameVisitorInternal");
    Whitebox.setInternalState(internal, "timeCodeScale", 1);
    PowerMockito.when(mockDataElement.getElementMetaData()).thenReturn(mockElementMetaData);
    PowerMockito.when(mockElementMetaData.getTypeInfo()).thenReturn(MkvTypeInfos.SIMPLEBLOCK);
    internal.visit(mockDataElement);

}
 
Example 20
Source File: UnderlabelValidatorTest.java    From AwesomeValidation with MIT License 5 votes vote down vote up
public void testValidationCallbackExecute() throws Exception {
    ValidationCallback validationCallback = Whitebox.getInternalState(mSpiedUnderlabelValidator, "mValidationCallback");
    Whitebox.setInternalState(mSpiedUnderlabelValidator, "mHasFailed", false);
    TextView mockTextView = mock(TextView.class);
    Matcher mockMatcher = PowerMockito.mock(Matcher.class);
    Drawable mockDrawable = mock(Drawable.class);
    when(mMockValidationHolder.getEditText().getBackground()).thenReturn(mockDrawable);
    doNothing().when(mockDrawable).setColorFilter(anyInt(), any(PorterDuff.Mode.class));
    PowerMockito.doReturn(mockTextView).when(mSpiedUnderlabelValidator, "replaceView", mMockValidationHolder);
    validationCallback.execute(mMockValidationHolder, mockMatcher);
}