@Test public void testFileStatusPipeFile() throws Exception { RawLocalFileSystem origFs = new RawLocalFileSystem(); RawLocalFileSystem fs = spy(origFs); Configuration conf = mock(Configuration.class); fs.setConf(conf); Whitebox.setInternalState(fs, "useDeprecatedFileStatus", false); Path path = new Path("/foo"); File pipe = mock(File.class); when(pipe.isFile()).thenReturn(false); when(pipe.isDirectory()).thenReturn(false); when(pipe.exists()).thenReturn(true); FileStatus stat = mock(FileStatus.class); doReturn(pipe).when(fs).pathToFile(path); doReturn(stat).when(fs).getFileStatus(path); FileStatus[] stats = fs.listStatus(path); assertTrue(stats != null && stats.length == 1 && stats[0] == stat); }
private HttpServer2 checkBindAddress(String host, int port, boolean findPort) throws Exception { HttpServer2 server = createServer(host, port); try { // not bound, ephemeral should return requested port (0 for ephemeral) List<?> listeners = (List<?>) Whitebox.getInternalState(server, "listeners"); Connector listener = (Connector) listeners.get(0); assertEquals(port, listener.getPort()); // verify hostname is what was given server.openListeners(); assertEquals(host, server.getConnectorAddress(0).getHostName()); int boundPort = server.getConnectorAddress(0).getPort(); if (port == 0) { assertTrue(boundPort != 0); // ephemeral should now return bound port } else if (findPort) { assertTrue(boundPort > port); } } catch (Exception e) { server.stop(); throw e; } return server; }
@Test public void isBtcTxHashAlreadyProcessed_normalFlow() throws IOException { Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR); bridge.init(null, null, null, null, null, null); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock); Set<Sha256Hash> hashes = new HashSet<>(); when(bridgeSupportMock.isBtcTxHashAlreadyProcessed(any(Sha256Hash.class))).then((InvocationOnMock invocation) -> hashes.contains(invocation.getArgumentAt(0, Sha256Hash.class))); hashes.add(Sha256Hash.of("hash_1".getBytes())); hashes.add(Sha256Hash.of("hash_2".getBytes())); hashes.add(Sha256Hash.of("hash_3".getBytes())); hashes.add(Sha256Hash.of("hash_4".getBytes())); for (Sha256Hash hash : hashes) { Assert.assertTrue(bridge.isBtcTxHashAlreadyProcessed(new Object[]{hash.toString()})); verify(bridgeSupportMock).isBtcTxHashAlreadyProcessed(hash); } Assert.assertFalse(bridge.isBtcTxHashAlreadyProcessed(new Object[]{Sha256Hash.of("anything".getBytes()).toString()})); Assert.assertFalse(bridge.isBtcTxHashAlreadyProcessed(new Object[]{Sha256Hash.of("yetanotheranything".getBytes()).toString()})); }
@Test public void isBtcTxHashAlreadyProcessed_exception() throws IOException { Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR); bridge.init(null, null, null, null, null, null); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock); boolean thrown = false; try { bridge.isBtcTxHashAlreadyProcessed(new Object[]{"notahash"}); } catch (RuntimeException e) { thrown = true; } Assert.assertTrue(thrown); verify(bridgeSupportMock, never()).isBtcTxHashAlreadyProcessed(any()); }
@Before public void setUp() { // not sure why, but adapter does not get injected properly, hence a workaround here: Whitebox.setInternalState(governor, "bluetoothObject", adapter); when(adapter.isPowered()).thenReturn(POWERED); when(adapter.isDiscovering()).thenReturn(DISCOVERING); when(adapter.getAlias()).thenReturn(ALIAS); when(adapter.getName()).thenReturn(NAME); doNothing().when(adapter).enablePoweredNotifications(poweredCaptor.capture()); doNothing().when(adapter).enableDiscoveringNotifications(discoveringCaptor.capture()); governor.addAdapterListener(listener); when(adapter.getURL()).thenReturn(URL); PowerMockito.mockStatic(BluetoothObjectFactoryProvider.class); when(BluetoothObjectFactoryProvider.getFactory(any())).thenReturn(bluetoothObjectFactory); when(bluetoothObjectFactory.getAdapter(URL)).thenReturn(adapter); when(adapter.getDevices()).thenReturn(DEVICES); }
@Test public void getBtcTxHashProcessedHeight_exception() throws IOException { Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR); bridge.init(null, null, null, null, null, null); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock); boolean thrown = false; try { bridge.getBtcTxHashProcessedHeight(new Object[]{"notahash"}); } catch (RuntimeException e) { thrown = true; } Assert.assertTrue(thrown); verify(bridgeSupportMock, never()).getBtcTxHashProcessedHeight(any()); }
/** * If region open fails with IOException in openRegion() while doing tableDescriptors.get() * the region should not add into regionsInTransitionInRS map * @throws Exception */ @Test public void testRegionOpenFailsDueToIOException() throws Exception { HRegionInfo REGIONINFO = new HRegionInfo(TableName.valueOf("t"), HConstants.EMPTY_START_ROW, HConstants.EMPTY_START_ROW); HRegionServer regionServer = TEST_UTIL.getHBaseCluster().getRegionServer(0); TableDescriptors htd = Mockito.mock(TableDescriptors.class); Object orizinalState = Whitebox.getInternalState(regionServer,"tableDescriptors"); Whitebox.setInternalState(regionServer, "tableDescriptors", htd); Mockito.doThrow(new IOException()).when(htd).get((TableName) Mockito.any()); try { ProtobufUtil.openRegion(null, regionServer.getRSRpcServices(), regionServer.getServerName(), REGIONINFO); fail("It should throw IOException "); } catch (IOException e) { } Whitebox.setInternalState(regionServer, "tableDescriptors", orizinalState); assertFalse("Region should not be in RIT", regionServer.getRegionsInTransitionInRS().containsKey(REGIONINFO.getEncodedNameAsBytes())); }
@Test public void testMetaFile() throws Exception { RaftStorage storage = new RaftStorage(storageDir, StartupOption.FORMAT); File m = storage.getStorageDir().getMetaFile(); Assert.assertTrue(m.exists()); MetaFile metaFile = new MetaFile(m); Assert.assertEquals(MetaFile.DEFAULT_TERM, metaFile.getTerm()); Assert.assertEquals(MetaFile.EMPTY_VOTEFOR, metaFile.getVotedFor()); metaFile.set(123, "peer1"); metaFile.readFile(); Assert.assertEquals(123, metaFile.getTerm()); Assert.assertEquals("peer1", metaFile.getVotedFor()); MetaFile metaFile2 = new MetaFile(m); Assert.assertFalse((Boolean) Whitebox.getInternalState(metaFile2, "loaded")); Assert.assertEquals(123, metaFile.getTerm()); Assert.assertEquals("peer1", metaFile.getVotedFor()); storage.close(); }
@BeforeMethod public void setupMethod() throws Exception { this.evaluationService = new PolicyEvaluationServiceImpl(); MockitoAnnotations.initMocks(this); Whitebox.setInternalState(this.policyMatcher, "attributeReaderFactory", this.attributeReaderFactory); Whitebox.setInternalState(this.evaluationService, "policyMatcher", this.policyMatcher); Whitebox.setInternalState(this.evaluationService, "policySetValidator", this.policySetValidator); when(this.zoneResolver.getZoneEntityOrFail()).thenReturn(new ZoneEntity(0L, "testzone")); when(this.cache.get(any(PolicyEvaluationRequestCacheKey.class))).thenReturn(null); when(this.attributeReaderFactory.getResourceAttributeReader()).thenReturn(this.externalResourceAttributeReader); when(this.attributeReaderFactory.getSubjectAttributeReader()).thenReturn(this.externalSubjectAttributeReader); PolicySet policySet = new ObjectMapper().readValue( new File("src/test/resources/policy-set-with-one-policy-one-condition-using-res-attributes.json"), PolicySet.class); when(this.policyService.getAllPolicySets()).thenReturn(Collections.singletonList(policySet)); }
/** * The close() method of DFSOutputStream should never throw the same exception * twice. See HDFS-5335 for details. */ @Test public void testCloseTwice() throws IOException { DistributedFileSystem fs = cluster.getFileSystem(); FSDataOutputStream os = fs.create(new Path("/test")); DFSOutputStream dos = (DFSOutputStream) Whitebox.getInternalState(os, "wrappedStream"); @SuppressWarnings("unchecked") AtomicReference<IOException> ex = (AtomicReference<IOException>) Whitebox .getInternalState(dos, "lastException"); Assert.assertEquals(null, ex.get()); dos.close(); IOException dummy = new IOException("dummy"); ex.set(dummy); try { dos.close(); } catch (IOException e) { Assert.assertEquals(e, dummy); } Assert.assertEquals(null, ex.get()); dos.close(); }
@Test public void testGetRemoteToken() throws IOException, URISyntaxException { Configuration conf = new Configuration(); DummyFs fs = spy(new DummyFs()); Token<TokenIdentifier> token = new Token<TokenIdentifier>(new byte[0], new byte[0], DummyFs.TOKEN_KIND, new Text("127.0.0.1:1234")); doReturn(token).when(fs).getDelegationToken(anyString()); doReturn(token).when(fs).getRenewToken(); fs.initialize(new URI("dummyfs://127.0.0.1:1234"), conf); fs.tokenAspect.ensureTokenInitialized(); // Select a token, store and renew it verify(fs).setDelegationToken(token); assertNotNull(Whitebox.getInternalState(fs.tokenAspect, "dtRenewer")); assertNotNull(Whitebox.getInternalState(fs.tokenAspect, "action")); }
@Override public void run() { try { Thread.sleep(1000); LOG.info("Deleting" + path); final FSDirectory fsdir = cluster.getNamesystem().dir; INode fileINode = fsdir.getINode4Write(path.toString()); INodeMap inodeMap = (INodeMap) Whitebox.getInternalState(fsdir, "inodeMap"); fs.delete(path, false); // after deletion, add the inode back to the inodeMap inodeMap.put(fileINode); LOG.info("Deleted" + path); } catch (Exception e) { LOG.info(e); } }
@Test public void testInternalNameService() throws Exception { Configuration conf = new Configuration(); conf.set(DFSConfigKeys.DFS_NAMESERVICES, "ns1,ns2,ns3"); addNN(conf, "ns1", "mock1:8020"); addNN(conf, "ns2", "mock1:8020"); addNN(conf, "ns3", "mock1:8020"); conf.set(DFSConfigKeys.DFS_INTERNAL_NAMESERVICES_KEY, "ns1"); bpm.refreshNamenodes(conf); assertEquals("create #1\n", log.toString()); @SuppressWarnings("unchecked") Map<String, BPOfferService> map = (Map<String, BPOfferService>) Whitebox .getInternalState(bpm, "bpByNameserviceId"); Assert.assertFalse(map.containsKey("ns2")); Assert.assertFalse(map.containsKey("ns3")); Assert.assertTrue(map.containsKey("ns1")); log.setLength(0); }
@Test public void testUpdateNotReadyToReady() throws Exception { // conditions Whitebox.setInternalState(governor, "bluetoothObject", null); governor.addGovernorListener(governorListener); governor.update(); InOrder inOrder = inOrder(governor, governorListener, bluetoothManager); inOrder.verify(bluetoothManager).getBluetoothObject(URL); inOrder.verify(governor).init(bluetoothObject); inOrder.verify(governorListener).ready(true); inOrder.verify(governor).update(bluetoothObject); inOrder.verify(governorListener, never()).lastUpdatedChanged(any()); governor.updateLastChanged(); governor.update(); inOrder.verify(governorListener).lastUpdatedChanged(any()); inOrder.verifyNoMoreInteractions(); }
@Test(timeout=3000) public void testPutMetrics() throws IOException, InterruptedException { final StatsDSink sink = new StatsDSink(); List<MetricsTag> tags = new ArrayList<MetricsTag>(); tags.add(new MetricsTag(MsInfo.Hostname, "host")); tags.add(new MetricsTag(MsInfo.Context, "jvm")); tags.add(new MetricsTag(MsInfo.ProcessName, "process")); Set<AbstractMetric> metrics = new HashSet<AbstractMetric>(); metrics.add(makeMetric("foo1", 1.25, MetricType.COUNTER)); metrics.add(makeMetric("foo2", 2.25, MetricType.GAUGE)); final MetricsRecord record = new MetricsRecordImpl(MsInfo.Context, (long) 10000, tags, metrics); try (DatagramSocket sock = new DatagramSocket()) { sock.setReceiveBufferSize(8192); final StatsDSink.StatsD mockStatsD = new StatsD(sock.getLocalAddress().getHostName(), sock.getLocalPort()); Whitebox.setInternalState(sink, "statsd", mockStatsD); final DatagramPacket p = new DatagramPacket(new byte[8192], 8192); sink.putMetrics(record); sock.receive(p); String result =new String(p.getData(), 0, p.getLength(), Charset.forName("UTF-8")); assertTrue( "Received data did not match data sent", result.equals("host.process.jvm.Context.foo1:1.25|c") || result.equals("host.process.jvm.Context.foo2:2.25|g")); } finally { sink.close(); } }
@Test(timeout=3000) public void testPutMetrics2() throws IOException { StatsDSink sink = new StatsDSink(); List<MetricsTag> tags = new ArrayList<MetricsTag>(); tags.add(new MetricsTag(MsInfo.Hostname, null)); tags.add(new MetricsTag(MsInfo.Context, "jvm")); tags.add(new MetricsTag(MsInfo.ProcessName, "process")); Set<AbstractMetric> metrics = new HashSet<AbstractMetric>(); metrics.add(makeMetric("foo1", 1, MetricType.COUNTER)); metrics.add(makeMetric("foo2", 2, MetricType.GAUGE)); MetricsRecord record = new MetricsRecordImpl(MsInfo.Context, (long) 10000, tags, metrics); try (DatagramSocket sock = new DatagramSocket()) { sock.setReceiveBufferSize(8192); final StatsDSink.StatsD mockStatsD = new StatsD(sock.getLocalAddress().getHostName(), sock.getLocalPort()); Whitebox.setInternalState(sink, "statsd", mockStatsD); final DatagramPacket p = new DatagramPacket(new byte[8192], 8192); sink.putMetrics(record); sock.receive(p); String result = new String(p.getData(), 0, p.getLength(), Charset.forName("UTF-8")); assertTrue("Received data did not match data sent", result.equals("process.jvm.Context.foo1:1|c") || result.equals("process.jvm.Context.foo2:2|g")); } finally { sink.close(); } }
@Test public void testPutMetrics() { GraphiteSink sink = new GraphiteSink(); List<MetricsTag> tags = new ArrayList<MetricsTag>(); tags.add(new MetricsTag(MsInfo.Context, "all")); tags.add(new MetricsTag(MsInfo.Hostname, "host")); Set<AbstractMetric> metrics = new HashSet<AbstractMetric>(); metrics.add(makeMetric("foo1", 1.25)); metrics.add(makeMetric("foo2", 2.25)); MetricsRecord record = new MetricsRecordImpl(MsInfo.Context, (long) 10000, tags, metrics); ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class); final GraphiteSink.Graphite mockGraphite = makeGraphite(); Whitebox.setInternalState(sink, "graphite", mockGraphite); sink.putMetrics(record); try { verify(mockGraphite).write(argument.capture()); } catch (IOException e) { e.printStackTrace(); } String result = argument.getValue(); assertEquals(true, result.equals("null.all.Context.Context=all.Hostname=host.foo1 1.25 10\n" + "null.all.Context.Context=all.Hostname=host.foo2 2.25 10\n") || result.equals("null.all.Context.Context=all.Hostname=host.foo2 2.25 10\n" + "null.all.Context.Context=all.Hostname=host.foo1 1.25 10\n")); }
@Test public void testPutMetrics2() { GraphiteSink sink = new GraphiteSink(); List<MetricsTag> tags = new ArrayList<MetricsTag>(); tags.add(new MetricsTag(MsInfo.Context, "all")); tags.add(new MetricsTag(MsInfo.Hostname, null)); Set<AbstractMetric> metrics = new HashSet<AbstractMetric>(); metrics.add(makeMetric("foo1", 1)); metrics.add(makeMetric("foo2", 2)); MetricsRecord record = new MetricsRecordImpl(MsInfo.Context, (long) 10000, tags, metrics); ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class); final GraphiteSink.Graphite mockGraphite = makeGraphite(); Whitebox.setInternalState(sink, "graphite", mockGraphite); sink.putMetrics(record); try { verify(mockGraphite).write(argument.capture()); } catch (IOException e) { e.printStackTrace(); } String result = argument.getValue(); assertEquals(true, result.equals("null.all.Context.Context=all.foo1 1 10\n" + "null.all.Context.Context=all.foo2 2 10\n") || result.equals("null.all.Context.Context=all.foo2 2 10\n" + "null.all.Context.Context=all.foo1 1 10\n")); }
@Test public void testFailureAndPutMetrics() throws IOException { GraphiteSink sink = new GraphiteSink(); List<MetricsTag> tags = new ArrayList<MetricsTag>(); tags.add(new MetricsTag(MsInfo.Context, "all")); tags.add(new MetricsTag(MsInfo.Hostname, "host")); Set<AbstractMetric> metrics = new HashSet<AbstractMetric>(); metrics.add(makeMetric("foo1", 1.25)); metrics.add(makeMetric("foo2", 2.25)); MetricsRecord record = new MetricsRecordImpl(MsInfo.Context, (long) 10000, tags, metrics); final GraphiteSink.Graphite mockGraphite = makeGraphite(); Whitebox.setInternalState(sink, "graphite", mockGraphite); // throw exception when first try doThrow(new IOException("IO exception")).when(mockGraphite).write(anyString()); sink.putMetrics(record); verify(mockGraphite).write(anyString()); verify(mockGraphite).close(); // reset mock and try again reset(mockGraphite); when(mockGraphite.isConnected()).thenReturn(false); ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class); sink.putMetrics(record); verify(mockGraphite).write(argument.capture()); String result = argument.getValue(); assertEquals(true, result.equals("null.all.Context.Context=all.Hostname=host.foo1 1.25 10\n" + "null.all.Context.Context=all.Hostname=host.foo2 2.25 10\n") || result.equals("null.all.Context.Context=all.Hostname=host.foo2 2.25 10\n" + "null.all.Context.Context=all.Hostname=host.foo1 1.25 10\n")); }
@Test public void getFederationSize() throws IOException { Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR); bridge.init(null, null, null, null, null, null); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock); when(bridgeSupportMock.getFederationSize()).thenReturn(1234); Assert.assertEquals(1234, bridge.getFederationSize(new Object[]{}).intValue()); }
@Test public void getFederationThreshold() throws IOException { Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR); bridge.init(null, null, null, null, null, null); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock); when(bridgeSupportMock.getFederationThreshold()).thenReturn(5678); Assert.assertEquals(5678, bridge.getFederationThreshold(new Object[]{}).intValue()); }
@Test public void getFederationCreationTime() throws IOException { Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR); bridge.init(null, null, null, null, null, null); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock); when(bridgeSupportMock.getFederationCreationTime()).thenReturn(Instant.ofEpochMilli(5000)); Assert.assertEquals(5000, bridge.getFederationCreationTime(new Object[]{}).intValue()); }
@Test public void getFederationCreationBlockNumber() throws IOException { Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock); when(bridgeSupportMock.getFederationCreationBlockNumber()).thenReturn(42L); Assert.assertThat(bridge.getFederationCreationBlockNumber(new Object[]{}), is(42L)); }
@Test public void getFederatorPublicKey() throws IOException { Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR); bridge.init(null, null, null, null, null, null); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock); when(bridgeSupportMock.getFederatorPublicKey(any(int.class))).then((InvocationOnMock invocation) -> BigInteger.valueOf(invocation.getArgumentAt(0, int.class)).toByteArray()); Assert.assertTrue(Arrays.equals(new byte[]{10}, bridge.getFederatorPublicKey(new Object[]{BigInteger.valueOf(10)}))); Assert.assertTrue(Arrays.equals(new byte[]{20}, bridge.getFederatorPublicKey(new Object[]{BigInteger.valueOf(20)}))); Assert.assertTrue(Arrays.equals(new byte[]{1, 0}, bridge.getFederatorPublicKey(new Object[]{BigInteger.valueOf(256)}))); }
@Test public void getRetiringFederationSize() throws IOException { Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR); bridge.init(null, null, null, null, null, null); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock); when(bridgeSupportMock.getRetiringFederationSize()).thenReturn(1234); Assert.assertEquals(1234, bridge.getRetiringFederationSize(new Object[]{}).intValue()); }
@Test public void getRetiringFederationThreshold() throws IOException { Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR); bridge.init(null, null, null, null, null, null); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock); when(bridgeSupportMock.getRetiringFederationThreshold()).thenReturn(5678); Assert.assertEquals(5678, bridge.getRetiringFederationThreshold(new Object[]{}).intValue()); }
@Test public void regionAndProxyShouldBeReflectedInClient(){ AwsKmsClientBuilder clientBuilder = new AwsKmsClientBuilder(); clientBuilder.region("eu-west-1").proxyHost("host").proxyPort(8080); AWSKMSClient amazonKmsClient = clientBuilder.build(); { ClientConfiguration configuration = (ClientConfiguration) Whitebox.getInternalState(amazonKmsClient,"clientConfiguration"); assertThat(configuration.getProxyHost()).isEqualTo("host"); assertThat(configuration.getProxyPort()).isEqualTo(8080); } }
private HttpServer checkBindAddress(String host, int port, boolean findPort) throws Exception { HttpServer server = createServer(host, port); try { // not bound, ephemeral should return requested port (0 for ephemeral) List<?> listeners = (List<?>) Whitebox.getInternalState(server, "listeners"); Connector listener = (Connector) Whitebox.getInternalState( listeners.get(0), "listener"); assertEquals(port, listener.getPort()); // verify hostname is what was given server.openListeners(); assertEquals(host, server.getConnectorAddress(0).getHostName()); int boundPort = server.getConnectorAddress(0).getPort(); if (port == 0) { assertTrue(boundPort != 0); // ephemeral should now return bound port } else if (findPort) { assertTrue(boundPort > port); // allow a little wiggle room to prevent random test failures if // some consecutive ports are already in use assertTrue(boundPort - port < 8); } } catch (Exception e) { server.stop(); throw e; } return server; }
@Test public void getRetiringFederatorPublicKey() throws IOException { Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR); bridge.init(null, null, null, null, null, null); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock); when(bridgeSupportMock.getRetiringFederatorPublicKey(any(int.class))).then((InvocationOnMock invocation) -> BigInteger.valueOf(invocation.getArgumentAt(0, int.class)).toByteArray()); Assert.assertTrue(Arrays.equals(new byte[]{10}, bridge.getRetiringFederatorPublicKey(new Object[]{BigInteger.valueOf(10)}))); Assert.assertTrue(Arrays.equals(new byte[]{20}, bridge.getRetiringFederatorPublicKey(new Object[]{BigInteger.valueOf(20)}))); Assert.assertTrue(Arrays.equals(new byte[]{1, 0}, bridge.getRetiringFederatorPublicKey(new Object[]{BigInteger.valueOf(256)}))); }
@Test public void testRunValidInputWithInvalidFolders() throws Exception { String[] args = {"-i=foo", "-o=?x/bar.xml", "-s=foo"}; JunitXmlParser parser = new JunitXmlParser(); parser.run(args); Boolean hasFileNotFoundErrors = (Boolean) Whitebox.getInternalState(parser, "hasFileNotFoundErrors"); assertTrue(hasFileNotFoundErrors); }
@Test public void getPendingFederatorPublicKey() throws IOException { Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR); bridge.init(null, null, null, null, null, null); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock); when(bridgeSupportMock.getPendingFederatorPublicKey(any(int.class))).then((InvocationOnMock invocation) -> BigInteger.valueOf(invocation.getArgumentAt(0, int.class)).toByteArray()); Assert.assertTrue(Arrays.equals(new byte[]{10}, bridge.getPendingFederatorPublicKey(new Object[]{BigInteger.valueOf(10)}))); Assert.assertTrue(Arrays.equals(new byte[]{20}, bridge.getPendingFederatorPublicKey(new Object[]{BigInteger.valueOf(20)}))); Assert.assertTrue(Arrays.equals(new byte[]{1, 0}, bridge.getPendingFederatorPublicKey(new Object[]{BigInteger.valueOf(256)}))); }
@Test public void createFederation() throws IOException { Transaction txMock = mock(Transaction.class); Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR); bridge.init(txMock, null, null, null, null, null); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock); when(bridgeSupportMock.voteFederationChange(txMock, new ABICallSpec("create", new byte[][]{}))).thenReturn(123); Assert.assertEquals(123, bridge.createFederation(new Object[]{}).intValue()); }
@Test public void addFederatorPublicKey_ok() throws IOException { Transaction txMock = mock(Transaction.class); Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR); bridge.init(txMock, null, null, null, null, null); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock); when(bridgeSupportMock.voteFederationChange(txMock, new ABICallSpec("add", new byte[][] { Hex.decode("aabbccdd") }))) .thenReturn(123); Assert.assertEquals(123, bridge.addFederatorPublicKey(new Object[]{Hex.decode("aabbccdd")}).intValue()); }
@Test public void addFederatorPublicKey_wrongParameterType() throws IOException { Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR); bridge.init(null, null, null, null, null, null); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock); Assert.assertEquals(-10, bridge.addFederatorPublicKey(new Object[]{ "i'm not a byte array" }).intValue()); verify(bridgeSupportMock, never()).voteFederationChange(any(), any()); }
@Test public void commitFederation_wrongParameterType() throws IOException { Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR); bridge.init(null, null, null, null, null, null); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock); Assert.assertEquals(-10, bridge.commitFederation(new Object[]{ "i'm not a byte array" }).intValue()); verify(bridgeSupportMock, never()).voteFederationChange(any(), any()); }
@Test public void rollbackFederation() throws IOException { Transaction txMock = mock(Transaction.class); Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR); bridge.init(txMock, null, null, null, null, null); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock); when(bridgeSupportMock.voteFederationChange(txMock, new ABICallSpec("rollback", new byte[][]{}))).thenReturn(456); Assert.assertEquals(456, bridge.rollbackFederation(new Object[]{}).intValue()); }
@Test public void getLockWhitelistSize() throws IOException { Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR); bridge.init(null, null, null, null, null, null); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock); when(bridgeSupportMock.getLockWhitelistSize()).thenReturn(1234); Assert.assertEquals(1234, bridge.getLockWhitelistSize(new Object[]{}).intValue()); }
@Test public void getLockWhitelistAddress() throws IOException { Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR); bridge.init(null, null, null, null, null, null); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock); when(bridgeSupportMock.getLockWhitelistAddress(any(int.class))).then((InvocationOnMock invocation) -> BigInteger.valueOf(invocation.getArgumentAt(0, int.class)).toString()); Assert.assertEquals("10", bridge.getLockWhitelistAddress(new Object[]{BigInteger.valueOf(10)})); Assert.assertEquals("20", bridge.getLockWhitelistAddress(new Object[]{BigInteger.valueOf(20)})); }
@Test public void testNotifyLastChangedException() { Date date = new Date(); Whitebox.setInternalState(governor, "lastActivity", date); governor.addGovernorListener(governorListener); doThrow(Exception.class).when(governorListener).lastUpdatedChanged(any()); governor.notifyLastChanged(); verify(governorListener, times(1)).lastUpdatedChanged(date); }
@Test public void getFeePerKb() { Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR); BridgeSupport bridgeSupportMock = mock(BridgeSupport.class); Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock); when(bridgeSupportMock.getFeePerKb()) .thenReturn(Coin.valueOf(12345678901234L)); Assert.assertEquals(12345678901234L, bridge.getFeePerKb(new Object[]{})); }