src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
BridgeSupport { public boolean increaseLockingCap(Transaction tx, Coin newCap) { AddressBasedAuthorizer authorizer = bridgeConstants.getIncreaseLockingCapAuthorizer(); if (!authorizer.isAuthorized(tx)) { logger.warn("not authorized address tried to increase locking cap. Address: {}", tx.getSender()); return false; } Co...
@Test public void increaseLockingCap_unauthorized() { AddressBasedAuthorizer authorizer = mock(AddressBasedAuthorizer.class); when(authorizer.isAuthorized(any(Transaction.class))).thenReturn(false); BridgeConstants constants = mock(BridgeConstants.class); when(constants.getIncreaseLockingCapAuthorizer()).thenReturn(aut...
BridgeSupport { public Boolean isBtcTxHashAlreadyProcessed(Sha256Hash btcTxHash) throws IOException { return provider.getHeightIfBtcTxhashIsAlreadyProcessed(btcTxHash).isPresent(); } BridgeSupport( BridgeConstants bridgeConstants, BridgeStorageProvider provider, BridgeEventLogger eve...
@Test public void isBtcTxHashAlreadyProcessed() throws IOException { BridgeConstants bridgeConstants = BridgeRegTestConstants.getInstance(); ActivationConfig.ForBlock activations = ActivationConfigsForTest.all().forBlock(0l); Sha256Hash hash1 = Sha256Hash.ZERO_HASH; Sha256Hash hash2 = Sha256Hash.wrap("00000000000000000...
BridgeSupport { public Long getBtcTxHashProcessedHeight(Sha256Hash btcTxHash) throws IOException { return provider.getHeightIfBtcTxhashIsAlreadyProcessed(btcTxHash).orElse(-1L); } BridgeSupport( BridgeConstants bridgeConstants, BridgeStorageProvider provider, BridgeEventLogger eventL...
@Test public void getBtcTxHashProcessedHeight() throws IOException { BridgeConstants bridgeConstants = BridgeRegTestConstants.getInstance(); ActivationConfig.ForBlock activations = ActivationConfigsForTest.all().forBlock(0l); Sha256Hash hash1 = Sha256Hash.ZERO_HASH; Sha256Hash hash2 = Sha256Hash.wrap("00000000000000000...
BridgeSupport { public void registerBtcTransaction(Transaction rskTx, byte[] btcTxSerialized, int height, byte[] pmtSerialized) throws IOException, BlockStoreException { Context.propagate(btcContext); Sha256Hash btcTxHash = BtcTransactionFormatUtils.calculateBtcTxHash(btcTxSerialized); try { if (isAlreadyBtcTxHashProce...
@Test public void eventLoggerLogLockBtc_before_rskip_146_activation() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP146)).thenReturn(false); BridgeEventLogger mockedEventLogger = mock(BridgeEventLogger.class); BridgeStorage...
BridgeSupport { public void updateCollections(Transaction rskTx) throws IOException { Context.propagate(btcContext); eventLogger.logUpdateCollections(rskTx); processFundsMigration(rskTx); processReleaseRequests(); processReleaseTransactions(rskTx); } BridgeSupport( BridgeConstants bridgeConstants, ...
@Test public void rskTxWaitingForSignature_uses_updateCollection_rskTxHash_before_rskip_146_activation() throws IOException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP146)).thenReturn(false); BridgeConstants spiedBridgeConstants = spy(Br...
Value { public String toString() { StringBuilder stringBuilder = new StringBuilder(); if (isList()) { Object[] list = (Object[]) value; if (list.length == 2) { stringBuilder.append("[ "); Value key = new Value(list[0]); byte[] keyNibbles = CompactEncoder.binToNibblesNoTerminator(key.asBytes()); String keyString = ByteU...
@Test public void toString_Empty() { Value val = new Value(null); String str = val.toString(); assertEquals("", str); } @Test public void toString_SameString() { Value val = new Value("hello"); String str = val.toString(); assertEquals("hello", str); } @Test public void toString_Array() { Value val = new Value(new Stri...
BridgeSupport { @VisibleForTesting protected boolean isBlockMerkleRootValid(Sha256Hash merkleRoot, BtcBlock blockHeader) { boolean isValid = false; if (blockHeader.getMerkleRoot().equals(merkleRoot)) { logger.trace("block merkle root is valid"); isValid = true; } else { if (activations.isActive(ConsensusRule.RSKIP143))...
@Test public void isBlockMerkleRootValid_equal_merkle_roots() { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(false); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, mock(BridgeStorageProvider.class), mock(Re...
BridgeSupport { public Integer getBtcTransactionConfirmations(Sha256Hash btcTxHash, Sha256Hash btcBlockHash, MerkleBranch merkleBranch) throws BlockStoreException, IOException { Context.propagate(btcContext); this.ensureBtcBlockChain(); StoredBlock block = btcBlockStore.getFromCache(btcBlockHash); if (block == null) { ...
@Test public void getBtcTransactionConfirmations_rejects_tx_with_witness_before_rskip_143() throws Exception { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(false); BtcTransaction tx1 = new BtcTransaction(btcParams); tx1.addO...
BridgeSupport { public void registerBtcCoinbaseTransaction(byte[] btcTxSerialized, Sha256Hash blockHash, byte[] pmtSerialized, Sha256Hash witnessMerkleRoot, byte[] witnessReservedValue) throws IOException, BlockStoreException { Context.propagate(btcContext); this.ensureBtcBlockStore(); Sha256Hash btcTxHash = BtcTransac...
@Test(expected = BridgeIllegalArgumentException.class) public void when_RegisterBtcCoinbaseTransaction_wrong_witnessReservedValue_noSent() throws BlockStoreException, AddressFormatException, IOException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusR...
BridgeSupport { public boolean hasBtcBlockCoinbaseTransactionInformation(Sha256Hash blockHash) { CoinbaseInformation coinbaseInformation = provider.getCoinbaseInformation(blockHash); return coinbaseInformation != null; } BridgeSupport( BridgeConstants bridgeConstants, BridgeStorageProvider provi...
@Test public void hasBtcCoinbaseTransaction_before_rskip_143_activation() throws AddressFormatException { ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class); when(activations.isActive(ConsensusRule.RSKIP143)).thenReturn(false); Repository repository = createRepository(); BridgeStorageProvider...
BridgeSupport { public boolean isAlreadyBtcTxHashProcessed(Sha256Hash btcTxHash) throws IOException { if (getBtcTxHashProcessedHeight(btcTxHash) > -1L) { logger.warn("Supplied Btc Tx {} was already processed", btcTxHash); return true; } return false; } BridgeSupport( BridgeConstants bridgeConstants, ...
@Test public void isAlreadyBtcTxHashProcessedHeight_true() throws IOException { Repository repository = createRepository(); BtcTransaction btcTransaction = new BtcTransaction(btcParams); BridgeStorageProvider provider = new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR, bridgeConstants, activations...
BridgeSupport { @VisibleForTesting protected boolean validationsForRegisterBtcTransaction(Sha256Hash btcTxHash, int height, byte[] pmtSerialized, byte[] btcTxSerialized) throws BlockStoreException, VerificationException.EmptyInputsOrOutputs, BridgeIllegalArgumentException { try { int acceptableConfirmationsAmount = bri...
@Test public void validationsForRegisterBtcTransaction_negative_height() throws BlockStoreException { BtcTransaction tx = new BtcTransaction(btcParams); Repository repository = createRepository(); BridgeStorageProvider provider = new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR, bridgeConstants, a...
BridgeSupport { public void addSignature(BtcECKey federatorPublicKey, List<byte[]> signatures, byte[] rskTxHash) throws Exception { Context.propagate(btcContext); Federation retiringFederation = getRetiringFederation(); Federation activeFederation = getActiveFederation(); Federation federation = activeFederation.hasBtc...
@Test public void addSignature_fedPubKey_no_belong_to_active_federation_no_existing_retiring_fed() throws Exception { BridgeStorageProvider provider = mock(BridgeStorageProvider.class); BridgeSupport bridgeSupport = getBridgeSupport( bridgeConstants, provider, mock(Repository.class), mock(BridgeEventLogger.class), mock...
BridgeSupport { protected TxType getTransactionType(BtcTransaction btcTx) { if (BridgeUtils.isLockTx(btcTx, getLiveFederations(), btcContext, bridgeConstants)) { return TxType.PEGIN; } if (BridgeUtils.isMigrationTx(btcTx, getActiveFederation(), getRetiringFederation(), btcContext, bridgeConstants)) { return TxType.MIGR...
@Test public void getTransactionType_lock_tx() { BridgeSupport bridgeSupport = getBridgeSupport(bridgeConstants, mock(BridgeStorageProvider.class)); BtcTransaction btcTx = new BtcTransaction(btcParams); btcTx.addOutput(Coin.COIN.multiply(10), bridgeConstants.getGenesisFederation().getAddress()); btcTx.addInput(PegTestU...
AddressBasedAuthorizer { public boolean isAuthorized(RskAddress sender) { return authorizedAddresses.stream() .anyMatch(address -> Arrays.equals(address, sender.getBytes())); } AddressBasedAuthorizer(List<ECKey> authorizedKeys, MinimumRequiredCalculation requiredCalculation); boolean isAuthorized(RskAddress sender); bo...
@Test public void isAuthorized() { AddressBasedAuthorizer auth = new AddressBasedAuthorizer(Arrays.asList( ECKey.fromPrivate(BigInteger.valueOf(100L)), ECKey.fromPrivate(BigInteger.valueOf(101L)), ECKey.fromPrivate(BigInteger.valueOf(102L)) ), AddressBasedAuthorizer.MinimumRequiredCalculation.MAJORITY); for (long n = 1...
BridgeSerializationUtils { public static byte[] serializeMapOfHashesToLong(Map<Sha256Hash, Long> map) { byte[][] bytes = new byte[map.size() * 2][]; int n = 0; List<Sha256Hash> sortedHashes = new ArrayList<>(map.keySet()); Collections.sort(sortedHashes); for (Sha256Hash hash : sortedHashes) { Long value = map.get(hash)...
@Test public void serializeMapOfHashesToLong() throws Exception { Map<Sha256Hash, Long> sample = new HashMap<>(); sample.put(Sha256Hash.wrap(charNTimes('b', 64)), 1L); sample.put(Sha256Hash.wrap(charNTimes('d', 64)), 2L); sample.put(Sha256Hash.wrap(charNTimes('a', 64)), 3L); sample.put(Sha256Hash.wrap(charNTimes('c', 6...
BridgeSerializationUtils { public static Map<Sha256Hash, Long> deserializeMapOfHashesToLong(byte[] data) { Map<Sha256Hash, Long> map = new HashMap<>(); if (data == null || data.length == 0) { return map; } RLPList rlpList = (RLPList) RLP.decode2(data).get(0); if (rlpList.size() % 2 != 0) { throw new RuntimeException("d...
@Test public void deserializeMapOfHashesToLong_emptyOrNull() throws Exception { assertEquals(BridgeSerializationUtils.deserializeMapOfHashesToLong(null), new HashMap<>()); assertEquals(BridgeSerializationUtils.deserializeMapOfHashesToLong(new byte[]{}), new HashMap<>()); } @Test public void deserializeMapOfHashesToLong...
BridgeSerializationUtils { public static byte[] serializeFederationOnlyBtcKeys(Federation federation) { return serializeFederationWithSerializer(federation, federationMember -> federationMember.getBtcPublicKey().getPubKeyPoint().getEncoded(true)); } private BridgeSerializationUtils(); static byte[] serializeMap(Sorted...
@Test public void serializeFederationOnlyBtcKeys() throws Exception { byte[][] publicKeyBytes = new byte[][]{ BtcECKey.fromPrivate(BigInteger.valueOf(100)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(200)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(300)).getPubKey(), BtcECKey.fromPrivate(BigInteger.v...
BridgeSerializationUtils { public static Federation deserializeFederationOnlyBtcKeys(byte[] data, NetworkParameters networkParameters) { return deserializeFederationWithDesserializer(data, networkParameters, (pubKeyBytes -> FederationMember.getFederationMemberFromKey(BtcECKey.fromPublicOnly(pubKeyBytes)))); } private ...
@Test public void deserializeFederationOnlyBtcKeys_ok() throws Exception { byte[][] publicKeyBytes = Arrays.asList(100, 200, 300, 400, 500, 600).stream() .map(k -> BtcECKey.fromPrivate(BigInteger.valueOf(k))) .sorted(BtcECKey.PUBKEY_COMPARATOR) .map(k -> k.getPubKey()) .toArray(byte[][]::new); byte[][] rlpKeys = new by...
BridgeSerializationUtils { public static byte[] serializeFederation(Federation federation) { return serializeFederationWithSerializer(federation, BridgeSerializationUtils::serializeFederationMember); } private BridgeSerializationUtils(); static byte[] serializeMap(SortedMap<Keccak256, BtcTransaction> map); static Sort...
@Test public void serializeFederation_serializedKeysAreCompressedAndThree() { final int NUM_MEMBERS = 10; final int EXPECTED_NUM_KEYS = 3; final int EXPECTED_PUBLICKEY_SIZE = 33; List<FederationMember> members = new ArrayList<>(); for (int j = 0; j < NUM_MEMBERS; j++) { members.add(new FederationMember(new BtcECKey(), ...
BridgeSerializationUtils { public static Federation deserializeFederation(byte[] data, NetworkParameters networkParameters) { return deserializeFederationWithDesserializer(data, networkParameters, BridgeSerializationUtils::deserializeFederationMember); } private BridgeSerializationUtils(); static byte[] serializeMap(S...
@Test public void deserializeFederation_wrongListSize() { byte[] serialized = RLP.encodeList(RLP.encodeElement(new byte[0]), RLP.encodeElement(new byte[0])); try { BridgeSerializationUtils.deserializeFederation(serialized, NetworkParameters.fromID(NetworkParameters.ID_REGTEST)); Assert.fail(); } catch (RuntimeException...
BridgeSerializationUtils { public static byte[] serializePendingFederation(PendingFederation pendingFederation) { List<byte[]> encodedMembers = pendingFederation.getMembers().stream() .sorted(FederationMember.BTC_RSK_MST_PUBKEYS_COMPARATOR) .map(BridgeSerializationUtils::serializeFederationMember) .collect(Collectors.t...
@Test public void serializePendingFederation_serializedKeysAreCompressedAndThree() { final int NUM_MEMBERS = 10; final int EXPECTED_NUM_KEYS = 3; final int EXPECTED_PUBLICKEY_SIZE = 33; List<FederationMember> members = new ArrayList<>(); for (int j = 0; j < NUM_MEMBERS; j++) { members.add(new FederationMember(new BtcEC...
BridgeSerializationUtils { public static PendingFederation deserializePendingFederation(byte[] data) { RLPList rlpList = (RLPList)RLP.decode2(data).get(0); List<FederationMember> members = new ArrayList<>(); for (int k = 0; k < rlpList.size(); k++) { RLPElement element = rlpList.get(k); FederationMember member = deseri...
@Test public void deserializePendingFederation_invalidFederationMember() { byte[] serialized = RLP.encodeList( RLP.encodeList(RLP.encodeElement(new byte[0]), RLP.encodeElement(new byte[0])) ); try { BridgeSerializationUtils.deserializePendingFederation(serialized); Assert.fail(); } catch (RuntimeException e) { Assert.a...
BridgeSerializationUtils { public static byte[] serializePendingFederationOnlyBtcKeys(PendingFederation pendingFederation) { return serializeBtcPublicKeys(pendingFederation.getBtcPublicKeys()); } private BridgeSerializationUtils(); static byte[] serializeMap(SortedMap<Keccak256, BtcTransaction> map); static SortedMap<...
@Test public void serializePendingFederationOnlyBtcKeys() throws Exception { byte[][] publicKeyBytes = new byte[][]{ BtcECKey.fromPrivate(BigInteger.valueOf(100)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(200)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(300)).getPubKey(), BtcECKey.fromPrivate(BigIn...
BridgeSerializationUtils { public static PendingFederation deserializePendingFederationOnlyBtcKeys(byte[] data) { List<FederationMember> members = deserializeBtcPublicKeys(data).stream().map(pk -> FederationMember.getFederationMemberFromKey(pk) ).collect(Collectors.toList()); return new PendingFederation(members); } pr...
@Test public void deserializePendingFederationOnlyBtcKeys() throws Exception { byte[][] publicKeyBytes = Arrays.asList(100, 200, 300, 400, 500, 600).stream() .map(k -> BtcECKey.fromPrivate(BigInteger.valueOf(k))) .sorted(BtcECKey.PUBKEY_COMPARATOR) .map(k -> k.getPubKey()) .toArray(byte[][]::new); byte[][] rlpBytes = n...
BridgeSerializationUtils { public static byte[] serializeElection(ABICallElection election) { byte[][] bytes = new byte[election.getVotes().size() * 2][]; int n = 0; Map<ABICallSpec, List<RskAddress>> votes = election.getVotes(); ABICallSpec[] specs = votes.keySet().toArray(new ABICallSpec[0]); Arrays.sort(specs, ABICa...
@Test public void serializeElection() throws Exception { AddressBasedAuthorizer authorizer = getTestingAddressBasedAuthorizer(); Map<ABICallSpec, List<RskAddress>> sampleVotes = new HashMap<>(); sampleVotes.put( new ABICallSpec("one-function", new byte[][]{}), Arrays.asList(createAddress("8899"), createAddress("aabb"))...
BridgeSerializationUtils { public static ABICallElection deserializeElection(byte[] data, AddressBasedAuthorizer authorizer) { if (data == null || data.length == 0) { return new ABICallElection(authorizer); } RLPList rlpList = (RLPList) RLP.decode2(data).get(0); if (rlpList.size() % 2 != 0) { throw new RuntimeException...
@Test public void deserializeElection_emptyOrNull() throws Exception { AddressBasedAuthorizer authorizer = getTestingAddressBasedAuthorizer(); ABICallElection election; election = BridgeSerializationUtils.deserializeElection(null, authorizer); Assert.assertEquals(0, election.getVotes().size()); election = BridgeSeriali...
Web3Impl implements Web3 { @Override public String web3_clientVersion() { String clientVersion = baseClientVersion + "/" + config.projectVersion() + "/" + System.getProperty("os.name") + "/Java1.8/" + config.projectVersionModifier() + "-" + buildInfo.getBuildHash(); if (logger.isDebugEnabled()) { logger.debug("web3_cli...
@Test public void web3_clientVersion() throws Exception { Web3 web3 = createWeb3(); String clientVersion = web3.web3_clientVersion(); assertTrue("client version is not including rsk!", clientVersion.toLowerCase().contains("rsk")); }
TransportAsync implements Transport { public synchronized void handleConnected() { if (!this.state) { this.state = true; fireEvent(true, this.listener); } } TransportAsync(final Executor executor); synchronized void handleConnected(); synchronized void handleDisconnected(); @Override void state(final Consumer<Boolean> ...
@Test public void test1() throws InterruptedException { final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); try { final TransportAsync transport = new TransportAsync(executor); final Instant start = Instant.now(); executor.schedule(() -> { transport.handleConnected(); }, 100, TimeUni...
Topic { public Stream<String> stream() { return segments.stream(); } private Topic(final List<String> segments); List<String> getSegments(); Stream<String> stream(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static Topic split(String path); static Topic of(final List<...
@Test public void testStream() { final String result = Topic.split("foo/bar").stream().collect(Collectors.joining()); assertEquals("foobar", result); }
Payload { public static Payload of(final String key, final Object value) { Objects.requireNonNull(key); return new Payload(now(), singletonMap(key, value), false); } private Payload(final Instant timestamp, final Map<String, ?> values, final boolean cloneValues); Instant getTimestamp(); Map<String, ?> getValues(); @Ov...
@Test(expected = NullPointerException.class) public void testNull1() { Payload.of((String) null, null); } @Test(expected = NullPointerException.class) public void testNull2() { Payload.of(null); } @Test(expected = NullPointerException.class) public void testNull3() { Payload.of(null, null, null); } @Test(expected = Nul...
Errors { public static ErrorHandler<RuntimeException> ignore() { return IGNORE; } private Errors(); static ErrorHandler<RuntimeException> ignore(); static ErrorHandler<RuntimeException> handle(final BiConsumer<Throwable, Optional<Payload>> handler); static void ignore(final Throwable e, final Optional<Payload> payload...
@Test public void test1() { Errors.ignore().handleError(new Exception(), Optional.empty()); }
Errors { public static ErrorHandler<RuntimeException> handle(final BiConsumer<Throwable, Optional<Payload>> handler) { return new ErrorHandler<RuntimeException>() { @Override public void handleError(final Throwable e, final Optional<Payload> payload) throws RuntimeException { handler.accept(e, payload); } }; } private ...
@Test public void test2() { Errors.handle((error, payload) -> { }).handleError(new Exception(), Optional.empty()); } @Test public void test3() { Errors.handle(Errors::ignore).handleError(new Exception(), Optional.empty()); }
JksServerConfigurator implements HttpServerConfigurator { private int getPort(ServerConfiguration configuration) { return configuration.getInteger(ConfigKies.HTTPS_PORT, ConfigKies.DEFAULT_HTTPS_PORT); } @Override void configureHttpServer(VertxContext context, HttpServerOptions options); }
@Test public void givenSslEnabledInConfiguration_whenHttpsPortIsMissingInConfiguration_thenShouldUseDefaultHttpsPort() throws Exception { configuration.put(SSL_CONFIGURATION_KEY, TRUE); configuration.remove(HTTPS_PORT); configureServer(); assertThat(options.getPort()).isEqualTo(DEFAULT_HTTPS_PORT); } @Test public void ...
HttpServiceDiscovery { public void getWebClient(Function<Record, Boolean> filter, Handler<AsyncResult<WebClient>> handler) { HttpEndpoint.getWebClient(serviceDiscovery, filter, handler); } HttpServiceDiscovery(ServiceDiscovery serviceDiscovery); void publish(HttpEndpointConfiguration configuration, Handler<AsyncResult<...
@Test public void givenServiceDiscovery_whenPublishHttpServiceAndAskingForItsWebClientByJsonWithConfiguration_thenShouldGetTheClient(TestContext context) throws Exception { publishHttpEndpoint(httpEndpointConfiguration.metadata(metadata)); getWebClient(jsonFilter, metadata, context.asyncAssertSuccess(Assert::assertNotN...
MessageSourceServiceDiscovery { public <T> void getConsumer(Function<Record, Boolean> filter, Handler<AsyncResult<MessageConsumer<T>>> handler) { MessageSource.getConsumer(serviceDiscovery, filter, handler); } MessageSourceServiceDiscovery(ServiceDiscovery serviceDiscovery); void publish(MessageSourceConfiguration conf...
@Test public void givenServiceDiscovery_whenPublishingMessageSourceAndAskingForItsConsumer_thenShouldGetTheConsumer(TestContext context) throws Exception { publishMessageSourceService(messageSourceConfiguration); vertxServiceDiscovery.messageSource().getConsumer(record -> record.getName().equals(SERVICE_NAME), context....
RedisServiceDiscovery { public void getClient(Function<Record, Boolean> filter, Handler<AsyncResult<RedisClient>> handler) { RedisDataSource.getRedisClient(serviceDiscovery, filter, handler); } RedisServiceDiscovery(ServiceDiscovery serviceDiscovery); void publish(DataSourceServiceConfiguration configuration, Handler<A...
@Test public void givenServiceDiscovery_whenPublishingRedisDataSourceAndAskingForItsClient_thenShouldGetTheClient(TestContext context) throws Exception { publishRedisDataSourceService(dataSourceConfiguration); vertxServiceDiscovery.redis().getClient(filter(), context.asyncAssertSuccess()); } @Test public void givenServ...
EventBusServiceDiscovery { public <T> void getProxy(Class<T> serviceClass, Handler<AsyncResult<T>> handler) { EventBusService.getProxy(serviceDiscovery, serviceClass, handler); } EventBusServiceDiscovery(ServiceDiscovery serviceDiscovery); void publish(EventBusServiceConfiguration configuration, Handler<AsyncResult<Rec...
@Test public void givenServiceDiscovery_whenPublishEventBusServiceAndAskingForItsProxy_thenShouldGetTheService(TestContext context) throws Exception { publishEventBusService(eventBusConfiguration); vertxServiceDiscovery.eventBus().getProxy(TestService.class, context.asyncAssertSuccess(Assert::assertNotNull)); }
EventBusServiceDiscovery { public <T> void getServiceProxy(Function<Record, Boolean> filter, Class<T> serviceClass, Handler<AsyncResult<T>> handler) { EventBusService.getServiceProxy(serviceDiscovery, filter, serviceClass, handler); } EventBusServiceDiscovery(ServiceDiscovery serviceDiscovery); void publish(EventBusSer...
@Test public void givenServiceDiscovery_whenPublishEventBusServiceAndAskingForItsServiceProxy_thenShouldGetTheService(TestContext context) throws Exception { publishEventBusService(eventBusConfiguration); vertxServiceDiscovery.eventBus().getServiceProxy(record -> record.getName().equals(SERVICE_NAME), TestService.class...
JDBCServiceDiscovery { public void getClient(Function<Record, Boolean> filter, Handler<AsyncResult<JDBCClient>> handler) { JDBCDataSource.getJDBCClient(serviceDiscovery, filter, handler); } JDBCServiceDiscovery(ServiceDiscovery serviceDiscovery); void publish(DataSourceServiceConfiguration configuration, Handler<AsyncR...
@Test public void givenServiceDiscovery_whenPublishingMessageSourceAndAskingForItsClient_thenShouldGetTheClient(TestContext context) throws Exception { publishJDBCDataSourceService(dataSourceConfiguration); vertxServiceDiscovery.jdbc().getClient(filter(), context.asyncAssertSuccess()); } @Test public void givenServiceD...
MongoServiceDiscovery { public void getClient(Function<Record, Boolean> filter, Handler<AsyncResult<MongoClient>> handler) { MongoDataSource.getMongoClient(serviceDiscovery, filter, handler); } MongoServiceDiscovery(ServiceDiscovery serviceDiscovery); void publish(DataSourceServiceConfiguration configuration, Handler<A...
@Test public void givenServiceDiscovery_whenPublishingRedisDataSourceAndAskingForItsClient_thenShouldGetTheClient(TestContext context) throws Exception { publishMongoDataSourceService(dataSourceConfiguration); vertxServiceDiscovery.mongo().getClient(filter(), context.asyncAssertSuccess()); } @Test public void givenServ...
VertxServiceDiscovery { public void publishRecord(Record record, Handler<AsyncResult<Record>> handler) { serviceDiscovery.publish(record, handler); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageSourceServiceDiscovery m...
@Test public void givenServiceDiscovery_whenPublishingRecord_thenTheRecordShouldBePublished(TestContext context) throws Exception { vertxServiceDiscovery.publishRecord(record, context.asyncAssertSuccess()); }
VertxServiceDiscovery { public void lookup(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler) { lookup(filter, false, handler); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageSourceServiceDiscovery ...
@Test(expected = InvalidFilterException.class) public void givenServiceDiscovery_whenLookupForARecordWithNullFilter_thenShouldThrowException() throws Exception { lookup(null, ar -> { }); } @Test public void givenServiceDiscovery_whenLookupForARecordUnmatchingPredicate_thenShouldGetNullRecord(TestContext context) throws...
JksServerConfigurator implements HttpServerConfigurator { private String getPath(ServerConfiguration configuration) { return configuration.getString(ConfigKies.SSL_JKS_PATH); } @Override void configureHttpServer(VertxContext context, HttpServerOptions options); }
@Test public void givenSslEnabledInConfigurationWithJksPathAndPassword_whenConfiguringServer_thenHttpOptionSslShouldBeEnabledAndConfiguredWithThePathAndPassword() throws Exception { configuration.put(SSL_CONFIGURATION_KEY, TRUE); configureServer(); assertThat(options.isSsl()).isTrue(); assertThat(options.getKeyStoreOpt...
VertxServiceDiscovery { public void lookupIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<Record>> handler) { lookup(filter, true, handler); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageSourc...
@Test(expected = InvalidFilterException.class) public void givenServiceDiscovery_whenLookupForARecordIncludingOutOfServicePassingNullFilter_thenShouldThrowException(TestContext context) throws Exception { lookupIncludeOutOfService(null, ar -> { }); } @Test public void givenServiceDiscovery_whenLookupForARecordIncluding...
VertxServiceDiscovery { public void lookupByJson(JsonObject jsonFilter, Handler<AsyncResult<Record>> handler) { serviceDiscovery.getRecord(jsonFilter, handler); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageSourceServi...
@Test public void givenServiceDiscovery_whenLookupByJsonForARecordPassingNull_thenShouldGetTheRecord(TestContext context) throws Exception { publishTestRecord(record); lookupByJson(null, context.asyncAssertSuccess(record -> { context.assertEquals(SERVICE_NAME, record.getName()); })); } @Test public void givenServiceDis...
VertxServiceDiscovery { public void lookupAll(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler) { lookupAll(filter, false, handler); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageSourceServi...
@Test(expected = InvalidFilterException.class) public void givenServiceDiscovery_whenLookupForAllRecordsPassingNullFilter_thenShouldThrowException() throws Exception { lookupAll(null, ar -> { }); } @Test public void givenServiceDiscovery_whenLookupForAllRecordsWithUnmatchingPredicate_thenShouldNotGetAnyRecord(TestConte...
VertxServiceDiscovery { public void lookupAllIncludeOutOfService(Function<Record, Boolean> filter, Handler<AsyncResult<List<Record>>> handler) { lookupAll(filter, true, handler); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); ...
@Test(expected = InvalidFilterException.class) public void givenServiceDiscovery_whenLookupForAllRecordsIncludingOutOfServicePassingNullFilter_thenShouldThrowException(TestContext context) throws Exception { lookupAllIncludeOutOfService(null, ar -> { }); } @Test public void givenServiceDiscovery_whenLookupForAllRecords...
HttpServiceDiscovery { public void getHttpClient(Function<Record, Boolean> filter, Handler<AsyncResult<HttpClient>> handler) { HttpEndpoint.getClient(serviceDiscovery, filter, handler); } HttpServiceDiscovery(ServiceDiscovery serviceDiscovery); void publish(HttpEndpointConfiguration configuration, Handler<AsyncResult<R...
@Test public void givenServiceDiscovery_whenPublishHttpServiceAndAskingForItsHttpClientByFilter_thenShouldGetTheClient(TestContext context) throws Exception { publishHttpEndpoint(httpEndpointConfiguration); getHttpClient(record -> record.getName().equals(SERVICE_NAME), context.asyncAssertSuccess(Assert::assertNotNull))...
VertxServiceDiscovery { public void lookupAllByJson(JsonObject jsonFilter, Handler<AsyncResult<List<Record>>> handler) { serviceDiscovery.getRecords(jsonFilter, handler); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageS...
@Test public void givenServiceDiscovery_whenLookupForAllRecordsByJsonPassingNull_thenShouldGetAllRecords(TestContext context) throws Exception { publishTestRecord(record); publishTestRecord(otherRecord); lookupAllByJson(null, context.asyncAssertSuccess(records -> { context.assertEquals(2, records.size()); })); } @Test ...
VertxServiceDiscovery { public ServiceReference lookupForAReference(Record record) { return serviceDiscovery.getReference(record); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusServiceDiscovery eventBus(); MessageSourceServiceDiscovery messageSource(); J...
@Test public void givenServiceDiscovery_whenPublishServiceAndLookupForItsServiceReference_thenShouldGetTheReference(TestContext context) throws Exception { publishTestRecord(record, context.asyncAssertSuccess(record -> { assertNotNull(vertxServiceDiscovery.lookupForAReference(record)); })); }
VertxServiceDiscovery { public ServiceReference lookupForAReferenceWithConfiguration(Record record, JsonObject configuration) { return serviceDiscovery.getReferenceWithConfiguration(record, configuration); } VertxServiceDiscovery(Vertx vertx); ServiceDiscovery serviceDiscovery(); HttpServiceDiscovery http(); EventBusSe...
@Test public void givenServiceDiscovery_whenPublishServiceWithMetadataAndLookupForItsServiceReferencePassingConfiguration_thenShouldGetTheReferenceUponTheseConfigurations(TestContext context) throws Exception { publishTestRecord(record, context.asyncAssertSuccess(record -> { ServiceReference reference = vertxServiceDis...
ListItemsUniqueModel extends AbstractValueModel { public void setValue(Object newValue) { throw new UnsupportedOperationException("ListItemsUniqueModel is read-only"); } ListItemsUniqueModel(ObservableList<E> list, Class<E> beanClass, String propertyName); Object getValue(); boolean calculate(); void setValue(Object ne...
@Test public void testEventsOnPropertyChange() { ObservableList<ValueHolder> list = new ArrayListModel<ValueHolder>(); ValueHolder v1 = new ValueHolder("A"); list.add(v1); ValueHolder v2 = new ValueHolder("B"); list.add(v2); ListItemsUniqueModel<ValueHolder> unique = new ListItemsUniqueModel<ValueHolder>(list, ValueHol...
CollectionUtil { public static <E> E getElementAtIndex(Collection<E> set, int idx) { if (idx >= set.size() || idx < 0) { throw new IndexOutOfBoundsException(); } Iterator<E> it = set.iterator(); for (int i = 0; i < idx; ++i) { it.next(); } return it.next(); } static E getElementAtIndex(Collection<E> set, int idx); sta...
@Test public void testGetElementAtIndex() { assertEquals("A", CollectionUtil.getElementAtIndex(d_set, 0)); assertEquals("B", CollectionUtil.getElementAtIndex(d_set, 1)); } @Test(expected=IndexOutOfBoundsException.class) public void testGetElementAtIndexTooHigh() { CollectionUtil.getElementAtIndex(d_set, 2); } @Test(exp...
CollectionUtil { public static <E> int getIndexOfElement(Collection<E> set, Object child) { int i = 0; for (E e : set) { if (e.equals(child)) { return i; } ++i; } return -1; } static E getElementAtIndex(Collection<E> set, int idx); static int getIndexOfElement(Collection<E> set, Object child); static boolean containsA...
@Test public void testGetIndexOfElement() { assertEquals(0, CollectionUtil.getIndexOfElement(d_set, "A")); assertEquals(1, CollectionUtil.getIndexOfElement(d_set, "B")); assertEquals(-1, CollectionUtil.getIndexOfElement(d_set, "C")); }
CollectionUtil { public static boolean nextLexicographicElement(int x[], int c[]) { assert(x.length == c.length); final int l = x.length; if (l < 1) { return false; } for (int i = l - 1; i >= 0; --i) { ++x[i]; if (x[i] == c[i]) { x[i] = 0; } else { return true; } } return false; } static E getElementAtIndex(Collection...
@Test public void testNextLexicographicElement() { int c[] = new int[] {1, 2, 3, 1}; int x[] = new int[] {0, 0, 0, 0}; assertTrue(CollectionUtil.nextLexicographicElement(x, c)); assertArrayEquals(new int[] {0, 0, 1, 0}, x); assertTrue(CollectionUtil.nextLexicographicElement(x, c)); assertArrayEquals(new int[] {0, 0, 2,...
GuardedObservableList extends AbstractObservableList<E> { @Override public void add(int index, E element) { check(element); d_nested.add(index, element); } GuardedObservableList(ObservableList<E> nested, Predicate<? super E> predicate); @Override E get(int index); @Override int size(); @Override void add(int index, E e...
@Test(expected=IllegalArgumentException.class) public void testConstructionWithNonEmptyList() { ObservableList<Integer> list = new ArrayListModel<Integer>(); list.add(1); d_list = new GuardedObservableList<Integer>(list, new Predicate<Number>() { public boolean evaluate(Number object) { return object.doubleValue() > 0....
GuardedObservableList extends AbstractObservableList<E> { @Override public E set(int index, E element) { check(element); return d_nested.set(index, element); } GuardedObservableList(ObservableList<E> nested, Predicate<? super E> predicate); @Override E get(int index); @Override int size(); @Override void add(int index,...
@Test(expected=IllegalArgumentException.class) public void testSetBadValue() { d_list.set(1, -1); }
FilteredObservableList extends AbstractObservableList<E> { @Override public void add(final int index, final E element) { if(!d_filter.evaluate(element)) throw new IllegalArgumentException("Cannot add " + element + ", it does not pass the filter of " + this); if(index < d_indices.size()) { d_inner.add(d_indices.get(inde...
@Test public void testContentsUpdateAddNone() { ListDataListener mock = createStrictMock(ListDataListener.class); replay(mock); d_outer.addListDataListener(mock); d_inner.add(2, "Haank"); assertEquals(Arrays.asList("Gert", "Jan"), d_outer); verify(mock); } @Test public void testSublistUpdating() { ObservableList<String...
FilteredObservableList extends AbstractObservableList<E> { private void intervalAdded(final int lower, final int upper) { final int delta = upper - lower + 1; final int first = firstAtLeast(lower); updateIndices(first, delta); final int oldSize = d_indices.size(); for(int i = upper; i >= lower; --i) { if (d_filter.eval...
@Test public void testContentsUpdateAddAllIndex() { ListDataListener mock = createStrictMock(ListDataListener.class); mock.intervalAdded(ListDataEventMatcher.eqListDataEvent(new ListDataEvent(d_outer, ListDataEvent.INTERVAL_ADDED, 1, 2))); replay(mock); d_outer.addListDataListener(mock); d_inner.addAll(2, Arrays.asList...
ListMinimumSizeModel extends AbstractValueModel { public Boolean getValue() { return d_val; } ListMinimumSizeModel(ListModel list, int minSize); Boolean getValue(); void setValue(Object value); }
@Test public void testInitialValues() { assertFalse(new ListMinimumSizeModel(new ArrayListModel<String>(), 1).getValue()); assertTrue(new ListMinimumSizeModel(new ArrayListModel<String>(Arrays.asList("Test")), 1).getValue()); assertFalse(new ListMinimumSizeModel(new ArrayListModel<String>(Arrays.asList("Test")), 2).get...
FilteredObservableList extends AbstractObservableList<E> { @Override public E remove(final int index) { return d_inner.remove((int) d_indices.get(index)); } FilteredObservableList(final ObservableList<E> inner, final Predicate<E> filter); void setFilter(final Predicate<E> filter); @Override E get(final int index); @Ove...
@Test public void testContentsUpdateRemoveNone() { ListDataListener mock = createStrictMock(ListDataListener.class); replay(mock); d_outer.addListDataListener(mock); d_inner.remove("Daan"); assertEquals(Arrays.asList("Gert", "Jan"), d_outer); verify(mock); }
FilteredObservableList extends AbstractObservableList<E> { private void intervalRemoved(final int lower, final int upper) { final int first = firstAtLeast(lower); if (first >= d_indices.size()) { return; } final int last = firstOver(upper); d_indices.removeAll(new ArrayList<Integer>(d_indices.subList(first, last))); fi...
@Test public void testContentsUpdateRemoveAll() { ListDataListener mock = createStrictMock(ListDataListener.class); mock.intervalRemoved(ListDataEventMatcher.eqListDataEvent(new ListDataEvent(d_outer, ListDataEvent.INTERVAL_REMOVED, 0, 1))); replay(mock); d_outer.addListDataListener(mock); d_inner.clear(); assertEquals...
FilteredObservableList extends AbstractObservableList<E> { @Override public E set(final int index, final E element) { if(!d_filter.evaluate(element)) throw new IllegalArgumentException("Cannot add " + element + ", it does not pass the filter."); return d_inner.set(d_indices.get(index), element); } FilteredObservableLis...
@Test public void testContentsUpdateFirstElement() { d_inner.set(0, "Gaart"); assertEquals(Arrays.asList("Jan"), d_outer); d_inner.set(0, "Gert"); assertEquals(Arrays.asList("Gert", "Jan"), d_outer); } @Test public void testContentsUpdateLastElement() { d_inner.set(3, "Klees"); assertEquals(Arrays.asList("Gert", "Jan",...
FilteredObservableList extends AbstractObservableList<E> { public void setFilter(final Predicate<E> filter) { d_filter = filter; final int oldSize = size(); if(!isEmpty()) { d_indices.clear(); fireIntervalRemoved(0, oldSize - 1); } initializeIndices(); if(!isEmpty()) { fireIntervalAdded(0, size() - 1); } } FilteredObse...
@Test public void testSetFilter() { ListDataListener mock = createStrictMock(ListDataListener.class); mock.intervalRemoved(ListDataEventMatcher.eqListDataEvent(new ListDataEvent(d_outer, ListDataEvent.INTERVAL_REMOVED, 0, 1))); mock.intervalAdded(ListDataEventMatcher.eqListDataEvent(new ListDataEvent(d_outer, ListDataE...
ListMinimumSizeModel extends AbstractValueModel { public void setValue(Object value) { throw new UnsupportedOperationException(); } ListMinimumSizeModel(ListModel list, int minSize); Boolean getValue(); void setValue(Object value); }
@Test(expected=UnsupportedOperationException.class) public void testSetValueNotSupported() { new ListMinimumSizeModel(new ArrayListModel<String>(), 2).setValue(true); }
SortedSetModel extends AbstractList<E> implements ObservableList<E> { @Override public E remove(int index) { if (index >= 0 && index < size()) { E e = get(index); d_set.remove(e); d_listenerManager.fireIntervalRemoved(index, index); return e; } throw new IndexOutOfBoundsException(); } SortedSetModel(); SortedSetModel(...
@Test public void testRemoving() { assertTrue(d_filledList.remove("Daan")); assertEquals(Arrays.asList("Gert", "Margreth"), d_filledList); assertEquals("Gert", d_filledList.remove(0)); assertEquals(Arrays.asList("Margreth"), d_filledList); resetFilledList(); d_filledList.clear(); assertEquals(Collections.emptyList(), d...
SortedSetModel extends AbstractList<E> implements ObservableList<E> { @Override public void add(int index, E element) { if (!d_set.contains(element)) { d_set.add(element); int idx = indexOf(element); d_listenerManager.fireIntervalAdded(idx, idx); } } SortedSetModel(); SortedSetModel(Comparator<? super E> comparator); ...
@Test public void testAdding() { SortedSetModel<String> ssm = new SortedSetModel<String>(); ssm.add(0, "Gert"); assertEquals(Arrays.asList("Gert"), ssm); ssm.add(0, "Margreth"); assertEquals(Arrays.asList("Gert", "Margreth"), ssm); }
SortedSetModel extends AbstractList<E> implements ObservableList<E> { public SortedSet<E> getSet() { return new TreeSet<E>(d_set); } SortedSetModel(); SortedSetModel(Comparator<? super E> comparator); SortedSetModel(Collection<? extends E> c); @Override int size(); @Override E get(int index); @Override void add(int i...
@Test public void testGetSet() { assertEquals(new TreeSet<String>(d_filledList), d_filledList.getSet()); }
ValueEqualsModel extends AbstractConverter { public void setValue(final Object newValue) { throw new UnsupportedOperationException(getClass().getSimpleName() + " is read-only"); } ValueEqualsModel(final ValueModel model, final Object expectedValue); void setValue(final Object newValue); Object convertFromSubject(final ...
@Test public void testEqualsExpected() { ValueHolder valueModel = new ValueHolder("name"); ValueEqualsModel equalsModel = new ValueEqualsModel(valueModel, "name"); assertEquals(Boolean.TRUE, equalsModel.getValue()); PropertyChangeListener listener = EasyMock.createStrictMock(PropertyChangeListener.class); listener.prop...
ValueEqualsModel extends AbstractConverter { public void setExpected(Object expectedValue) { Object oldVal = getValue(); d_expectedValue = expectedValue; firePropertyChange("value", oldVal, getValue()); } ValueEqualsModel(final ValueModel model, final Object expectedValue); void setValue(final Object newValue); Object ...
@Test public void testChangeExpected() { ValueHolder valueModel = new ValueHolder("name"); ValueEqualsModel equalsModel = new ValueEqualsModel(valueModel, "name"); assertEquals(Boolean.TRUE, equalsModel.getValue()); PropertyChangeListener listener = EasyMock.createStrictMock(PropertyChangeListener.class); listener.prop...
DateUtil { public static Date getCurrentDateWithoutTime() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.AM_PM, Calendar.AM); Date date = cal.getTime(); return date; } static Date getCurren...
@SuppressWarnings("deprecation") @Test public void testGetCurrentDateWithoutTime() { Date now = new Date(); Date woTime = DateUtil.getCurrentDateWithoutTime(); assertEquals(now.getYear(), woTime.getYear()); assertEquals(now.getMonth(), woTime.getMonth()); assertEquals(now.getDay(), woTime.getDay()); assertEquals(0, woT...
Statistics { public static EstimateWithPrecision meanDifference( double m0, double s0, double n0, double m1, double s1, double n1) { double md = m1 - m0; double se = Math.sqrt((s0 * s0) / n0 + (s1 * s1) / n1); return new EstimateWithPrecision(md, se); } private Statistics(); static double logit(double p); static doubl...
@Test public void testMeanDifference() { EstimateWithPrecision e = Statistics.meanDifference( -2.5, 1.6, 177, -2.6, 1.5, 176); assertEquals(-0.1, e.getPointEstimate(), EPSILON); assertEquals(0.1650678, e.getStandardError(), EPSILON); }
SimpleSuspendableTask implements SimpleTask { public boolean wakeUp() { return d_suspendable.wakeUp(); } SimpleSuspendableTask(Suspendable suspendable, String str); SimpleSuspendableTask(Runnable runnable, String str); SimpleSuspendableTask(Runnable runnable); SimpleSuspendableTask(Suspendable suspendable); void add...
@Test public void wakeUpWakesNested() { Suspendable mockSuspendable = createStrictMock(Suspendable.class); expect(mockSuspendable.wakeUp()).andReturn(true); replay(mockSuspendable); SimpleTask task = new SimpleSuspendableTask(mockSuspendable); task.wakeUp(); verify(mockSuspendable); }
SimpleSuspendableTask implements SimpleTask { public boolean abort() { return d_suspendable.abort(); } SimpleSuspendableTask(Suspendable suspendable, String str); SimpleSuspendableTask(Runnable runnable, String str); SimpleSuspendableTask(Runnable runnable); SimpleSuspendableTask(Suspendable suspendable); void addTa...
@Test public void wakeUpAbortsNested() { Suspendable mockSuspendable = createStrictMock(Suspendable.class); expect(mockSuspendable.abort()).andReturn(true); replay(mockSuspendable); SimpleTask task = new SimpleSuspendableTask(mockSuspendable); task.abort(); verify(mockSuspendable); }
DecisionTransition implements Transition { public List<Task> transition() { if (!isReady()) { throw new RuntimeException("Not ready for transition."); } if (d_condition.evaluate()) { return Collections.singletonList(d_ifTask); } else { return Collections.singletonList(d_elTask); } } DecisionTransition(Task source, Task...
@Test public void testTrueCondition() { MockTask source = new MockTask(); Task ifTask = new MockTask(); Task elTask = new MockTask(); Condition condition = createStrictMock(Condition.class); expect(condition.evaluate()).andReturn(true); replay(condition); Transition trans = new DecisionTransition(source, ifTask, elTask...
StringNotEmptyModel extends AbstractValueModel { public Boolean getValue() { return d_val; } StringNotEmptyModel(ValueModel nested); Boolean getValue(); void setValue(Object value); }
@Test public void testInitialValues() { assertFalse(new StringNotEmptyModel(new ValueHolder(null)).getValue()); assertFalse(new StringNotEmptyModel(new ValueHolder(new Object())).getValue()); assertFalse(new StringNotEmptyModel(new ValueHolder("")).getValue()); assertTrue(new StringNotEmptyModel(new ValueHolder("Test")...
ActivityModel { public Set<Task> getNextStates() { if (isFinished()) { return Collections.emptySet(); } return findAccessibleStates(d_start); } ActivityModel(Task start, Task end, Collection<? extends Transition> transitions); Set<Task> getNextStates(); boolean isFinished(); Task getStartState(); Task getEndState(); Se...
@Test public void testInitialState() { MockTask start = new MockTask(); start.start(); MockTask end = new MockTask(); Transition trans = new DirectTransition(start, end); ActivityModel model = new ActivityModel(start, end, Collections.singleton(trans)); assertEquals(Collections.singleton(start), model.getNextStates());...
ActivityModel { public boolean isFinished() { return d_end.isFinished(); } ActivityModel(Task start, Task end, Collection<? extends Transition> transitions); Set<Task> getNextStates(); boolean isFinished(); Task getStartState(); Task getEndState(); Set<Task> getStates(); Task getStateByName(String name); Set<Transition...
@Test public void testIsFinished() { MockTask start = new MockTask(); start.start(); MockTask end = new MockTask(); Transition trans = new DirectTransition(start, end); ActivityModel model = new ActivityModel(start, end, Collections.singleton(trans)); start.finish(); end.start(); end.finish(); assertTrue(model.isFinish...
IterativeTask extends SimpleSuspendableTask { public void setReportingInterval(int interval) { ((IterativeSuspendable)d_suspendable).setReportingInterval(interval); } IterativeTask(IterativeComputation computation, String str); IterativeTask(IterativeComputation computation); void setReportingInterval(int interval); @...
@Test public void testNotifyProgress() { IterativeComputation comp = new ShortComputation(10); IterativeTask task = new IterativeTask(comp); task.setReportingInterval(3); TaskListener listener = createStrictMock(TaskListener.class); listener.taskEvent(new TaskStartedEvent(task)); listener.taskEvent(new TaskProgressEven...
StringNotEmptyModel extends AbstractValueModel { public void setValue(Object value) { throw new UnsupportedOperationException(); } StringNotEmptyModel(ValueModel nested); Boolean getValue(); void setValue(Object value); }
@Test(expected=UnsupportedOperationException.class) public void testSetValueNotSupported() { new StringNotEmptyModel(new ValueHolder(null)).setValue(true); } @Test public void testEventChaining() { ValueHolder holder = new ValueHolder(null); StringNotEmptyModel model = new StringNotEmptyModel(holder); PropertyChangeLis...
StudentTTable { public static double getT(int v) { if (v < 1) { throw new IllegalArgumentException("student T distribution defined only for positive degrees of freedom"); } TDistribution dist = new TDistribution(v); return dist.inverseCumulativeProbability(0.975); } static double getT(int v); }
@Test public void testTable() { assertEquals(12.706, StudentTTable.getT(1), 0.001); assertEquals(1.998, StudentTTable.getT(63), 0.001); assertEquals(1.96, StudentTTable.getT(1000), 0.01); assertEquals(1.96, StudentTTable.getT(2000), 0.01); assertEquals(StudentTTable.getT(160) / 2 + StudentTTable.getT(140) / 2, StudentT...
Interval { public double getLength() { return d_upperBound.doubleValue() - d_lowerBound.doubleValue(); } Interval(N lowerBound, N upperBound); N getLowerBound(); N getUpperBound(); double getLength(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void testGetLength() { Interval<Double> in = new Interval<Double>(1.0, 6.0); assertEquals(5.0, in.getLength(), 0.00001); }
Interval { @Override public boolean equals(Object o) { if (o instanceof Interval<?>) { Interval<?> other = (Interval<?>) o; if (other.canEqual(this)) { if (other.getLowerBound().getClass().equals(getLowerBound().getClass())) { return ((getLowerBound().equals(other.getLowerBound())) && (getUpperBound().equals(other.getU...
@Test public void testEquals() { Interval<Double> in = new Interval<Double>(1.0, 6.0); Interval<Integer> in2 = new Interval<Integer>(1, 6); assertNotEquals(in, in2); Double d = new Double(1.0); Integer i = new Integer(6); assertNotEquals(d, in); assertNotEquals(i, in2); Interval<Double> in3 = new Interval<Double>(1.0, ...
Interval { @Override public String toString() { return getLowerBound().toString() + "-" + getUpperBound().toString(); } Interval(N lowerBound, N upperBound); N getLowerBound(); N getUpperBound(); double getLength(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void testToString() { Interval<Double> in = new Interval<Double>(1.0, 6.0); assertEquals("1.0-6.0", in.toString()); }
LogstashLayout implements Layout<String> { @PluginBuilderFactory @SuppressWarnings("WeakerAccess") public static Builder newBuilder() { return new Builder(); } private LogstashLayout(Builder builder); @Override String toSerializable(LogEvent event); @Override byte[] toByteArray(LogEvent event); @Override void encode(L...
@Test public void test_lineSeparator_suffix() { SimpleMessage message = new SimpleMessage("Hello, World!"); LogEvent logEvent = Log4jLogEvent .newBuilder() .setLoggerName(LogstashLayoutTest.class.getSimpleName()) .setLevel(Level.INFO) .setMessage(message) .build(); test_lineSeparator_suffix(logEvent, true); test_lineSe...
MainActivity extends AppCompatActivity { @VisibleForTesting void initViews() { EditText weightText = (EditText)findViewById(R.id.text_weight); EditText heightText = (EditText)findViewById(R.id.text_height); TextView resultText = (TextView)findViewById(R.id.text_result); mCalcButton = (Button)findViewById(R.id.button_ca...
@Test public void initViews를호출하면버튼의Listener가설정된다() { EditText weightText = mock(EditText.class); EditText heightText = mock(EditText.class); TextView resultText = mock(TextView.class); Button resultButton = mock(Button.class); View.OnClickListener buttonListener = mock(View.OnClickListener.class); MainActivity activity...
SaveBmiService extends IntentService { public static void start(Context context, BmiValue bmiValue) { Intent intent = new Intent(context, SaveBmiService.class); intent.putExtra(PARAM_KEY_BMI_VALUE, bmiValue); context.startService(intent); } SaveBmiService(); @Override void onCreate(); static void start(Context context,...
@Test public void static인start메소드를호출하면startService된다() { Context context = mock(Context.class); SaveBmiService.start(context, mock(BmiValue.class)); verify(context, times(1)).startService((Intent) any()); }
SaveBmiService extends IntentService { @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Serializable extra = intent.getSerializableExtra(PARAM_KEY_BMI_VALUE); if (extra == null || !(extra instanceof BmiValue)) { return; } BmiValue bmiValue = (BmiValue)extra; boolean result = save...
@Test public void onHandleIntentにnull을전달하면아무것도하지않는다() { SaveBmiService service = spy(new SaveBmiService()); service.onHandleIntent(null); verify(service, never()).sendLocalBroadcast(anyBoolean()); verify(service, never()).saveToRemoteServer((BmiValue) any()); } @Test public void onHandleIntent에파라미터없는Intent를전달하면아무것도하지않는...
BmiCalculator { public BmiValue calculate(float heightInMeter, float weightInKg) { if (heightInMeter < 0 || weightInKg < 0) { throw new RuntimeException("키와 몸무게는 양수로 지정해주세요"); } float bmiValue = weightInKg / (heightInMeter * heightInMeter); return createValueObj(bmiValue); } BmiValue calculate(float heightInMeter, flo...
@Test(expected = RuntimeException.class) public void 신장에음수값을넘기면예외가발생한다() { calculator.calculate(-1f, 60.0f);
BmiValue implements Serializable { public float toFloat() { int rounded = Math.round(mValue * 100); return rounded / 100f; } BmiValue(float value); float toFloat(); String getMessage(); }
@Test public void 생성시에전달한Float값을소수점2자리까지반올림해반환한다() { BmiValue bmiValue = new BmiValue(20.00511f); Assert.assertEquals(20.01f, bmiValue.toFloat()); } @Test public void 생성시에전달한Float값을소수점2자리까지버림해반환한다() { BmiValue bmiValue = new BmiValue(20.00499f); Assert.assertEquals(20.00f, bmiValue.toFloat()); }
DriverSettings extends AbstractPropSettings { public String getGeckcoDriverPath() { return getProperty("GeckoDriverPath", geckoDriverPath); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String...
@Test public void testGetGeckcoDriverPath() { String expResult; if (isWin) { expResult = "./lib/Drivers/geckodriver.exe"; } else { expResult = "./lib/Drivers/geckodriver"; } String result = ds.getGeckcoDriverPath(); assertEquals(result, expResult); }
FParser { public static Object eval(String s) { String func = FN(s); s = s.replaceFirst(func, ""); String[] params = {}; if (s.length() >= 2) { String param = s.substring(1, s.lastIndexOf(")")); params = param.split(RX, -1); } return String.valueOf(EXE(func, params)); } static List<String> getFuncList(); static Object...
@Test public void testEval_DateTest() { System.out.println("eval date fn"); String s; Object result; s = "Date(0,\"MM-dd-yy\")"; result = FParser.eval(s); assertTrue(result.toString().matches("(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])-\\d{2}"), "date " + result); s = "Date(0,\"MM dd yyyy\")"; result = FParser.eval(s); a...
FParser { public static String evaljs(String script) { try { return JS.eval("JSON.stringify(" + script + ")").toString(); } catch (ScriptException ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } return "undefined"; } static List<String> getFuncList(); static Object eval(String s); static String evaljs(String scrip...
@Test(invocationCount = 10) public void testEvaljs() { System.out.println("Evaljs"); String script = "floor(100 + random() * 900)"; String result = FParser.evaljs(script); assertTrue(result.matches("[0-9]{3}"), "Test random "); script = "'test'+ floor(100 + random() * 900)+'vt@gmail.com'"; result = (String) JSONValue.p...
KeyMap { public static String resolveContextVars(String in, Map<?,?> vMap) { return replaceKeys(in, CONTEXT_VARS, true, 1, vMap); } static Map<Object, Object> getSystemVars(); static String resolveContextVars(String in, Map<?,?> vMap); static String resolveEnvVars(String in); static String replaceKeys(String in, Patte...
@Test public void testResolveContextVars() { System.out.println("resolveContextVars"); String in = "this is a {scenario}/{testset} -> {testset}/{release} for {project}.{release}.{testcase} "; String expResult = "this is a myscn/ts -> ts/rel for pro.rel.tc "; String result = KeyMap.resolveContextVars(in, vMap); assertEq...
KeyMap { public static String resolveEnvVars(String in) { return replaceKeys(in, ENV_VARS); } static Map<Object, Object> getSystemVars(); static String resolveContextVars(String in, Map<?,?> vMap); static String resolveEnvVars(String in); static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int ...
@Test public void testResolveEnvVars() { System.out.println("resolveEnvVars"); String in = "${val.1}-${var.1}-${val.2}-${val.1}-${val.3}-${val.4}-${var.4}-${var.1}-${var.2}-"; String expResult = "1-x-b-1-c-val.4-var.4-x-y-"; String result = KeyMap.resolveEnvVars(in); assertEquals(expResult, result); }
KeyMap { public static String replaceKeys(String in, Pattern pattern, boolean preserveKeys, int passes, Map<?,?>... maps) { String out = in; for (int pass = 1; pass <= passes; pass++) { Matcher m = pattern.matcher(in); String match, key; while (m.find()) { match = m.group(); key = m.group(1); Boolean resolved = false; ...
@Test public void testReplaceKeysUserVariables() { System.out.println("replaceKeys"); String in = "this is a %scenario%/%testset% -> %testset%/%release% for %project%.%testcase%/%%release%%. "; boolean preserveKeys = true; String result; String expResult = "this is a myscn/ts -> ts/rel for pro.tc/%rel%. "; result = Key...
ChromeEmulators { public static String getPrefLocation() { if (SystemUtils.IS_OS_WINDOWS) { return SystemUtils.getUserHome().getAbsolutePath() + "/AppData/Local/Google/Chrome/User Data/Default"; } if (SystemUtils.IS_OS_MAC_OSX) { return SystemUtils.getUserHome().getAbsolutePath()+"/Library/Application Support/Google/Ch...
@Test(enabled = false) public void testGetPrefLocation() { System.out.println("getPrefLocation"); File file = new File(ChromeEmulators.getPrefLocation(), "Preferences"); if (!file.exists()) { System.out.println(file.getAbsolutePath()); System.out.println("------------------------"); Stream.of(file.listFiles()) .map(Fil...
ChromeEmulators { public static void sync() { try { LOG.info("Trying to load emulators from Chrome Installation"); File file = new File(getPrefLocation(), "Preferences"); if (file.exists()) { Map map = MAPPER.readValue(file, Map.class); Map devtools = (Map) map.get("devtools"); Map prefs = (Map) devtools.get("preferenc...
@Test(enabled = false) public void testSync() { System.out.println("sync"); ChromeEmulators.sync(); assertTrue(!ChromeEmulators.getEmulatorsList().isEmpty(), "EmulatorsList is Empty"); }
ChromeEmulators { public static List<String> getEmulatorsList() { load(); return EMULATORS; } static void sync(); static String getPrefLocation(); static List<String> getEmulatorsList(); }
@Test(enabled = false) public void testGetEmulatorsList() { System.out.println("getEmulatorsList"); List<String> result = ChromeEmulators.getEmulatorsList(); assertTrue(Stream.of("Nexus 5", "Galaxy S5", "Nexus 6P", "iPhone 5", "iPhone 6 Plus") .allMatch(result::contains), "Some/all emulators missing in the EmulatorsLis...